@octocodeai/octocode-tools-core 16.6.0 → 16.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +179 -249
  2. package/dist/direct.js +37 -35
  3. package/dist/errors/localToolErrors.d.ts +1 -0
  4. package/dist/github/pullRequestSearch.d.ts +1 -0
  5. package/dist/index.d.ts +6 -4
  6. package/dist/index.js +39 -44
  7. package/dist/oql/adapters/graphProof.d.ts +6 -0
  8. package/dist/oql/adapters/graphView.d.ts +28 -0
  9. package/dist/oql/adapters/local.d.ts +1 -0
  10. package/dist/oql/adapters/resultMap.d.ts +7 -0
  11. package/dist/oql/adapters/runner.d.ts +7 -0
  12. package/dist/oql/envelope.d.ts +2 -0
  13. package/dist/oql/index.d.ts +2 -1
  14. package/dist/oql/index.js +37 -34
  15. package/dist/oql/schema.d.ts +24 -8
  16. package/dist/oql/schemeText.d.ts +27 -10
  17. package/dist/oql/transformers/github/common.d.ts +7 -1
  18. package/dist/oql/types.d.ts +19 -2
  19. package/dist/responses.d.ts +4 -35
  20. package/dist/schema.d.ts +1 -1
  21. package/dist/schema.js +2 -1
  22. package/dist/scheme/pagination.d.ts +51 -0
  23. package/dist/scheme/responseEnvelope.d.ts +67 -1
  24. package/dist/shared/config/index.d.ts +1 -8
  25. package/dist/shared/config/index.js +1 -2
  26. package/dist/shared/credentials/index.d.ts +1 -1
  27. package/dist/shared/credentials/index.js +2 -1
  28. package/dist/shared/credentials/storage.d.ts +0 -2
  29. package/dist/shared/credentials/testing.js +1 -1
  30. package/dist/shared/credentials/types.d.ts +1 -1
  31. package/dist/shared/paths.d.ts +6 -1
  32. package/dist/shared/paths.js +1 -1
  33. package/dist/shared/session/index.js +1 -1
  34. package/dist/tools/directToolCatalog.exec.d.ts +5 -0
  35. package/dist/tools/directToolCatalog.meta.d.ts +1 -0
  36. package/dist/tools/github_clone_repo/scheme.d.ts +0 -1
  37. package/dist/tools/github_fetch_content/scheme.d.ts +6 -89
  38. package/dist/tools/github_search_code/scheme.d.ts +4 -6
  39. package/dist/tools/github_search_pull_requests/scheme.d.ts +0 -1
  40. package/dist/tools/github_search_repos/execution.d.ts +58 -0
  41. package/dist/tools/github_search_repos/scheme.d.ts +3 -6
  42. package/dist/tools/github_view_repo_structure/scheme.d.ts +0 -1
  43. package/dist/tools/local_binary_inspect/binaryInspector.d.ts +0 -4
  44. package/dist/tools/local_binary_inspect/scheme.d.ts +97 -0
  45. package/dist/tools/local_fetch_content/scheme.d.ts +66 -0
  46. package/dist/tools/local_find_files/scheme.d.ts +49 -0
  47. package/dist/tools/local_ripgrep/scheme.d.ts +75 -0
  48. package/dist/tools/local_view_structure/scheme.d.ts +52 -0
  49. package/dist/tools/lsp/semantic_content/scheme.d.ts +8 -22
  50. package/dist/tools/lsp/shared/readiness.d.ts +17 -0
  51. package/dist/tools/lsp/shared/semanticTypes.d.ts +2 -2
  52. package/dist/tools/package_search/execution.d.ts +23 -0
  53. package/dist/tools/package_search/scheme.d.ts +10 -4
  54. package/dist/tools/toolNames.d.ts +2 -1
  55. package/dist/types/server.d.ts +1 -1
  56. package/dist/utils/response/bulk.d.ts +1 -0
  57. package/dist/utils/response/groupedFinalizer.d.ts +7 -2
  58. package/package.json +7 -3
  59. package/dist/oql/adapters/v2.d.ts +0 -32
  60. package/dist/oql/v2params.d.ts +0 -22
  61. package/dist/shared/config/defaults.d.ts +0 -14
  62. package/dist/shared/config/loader.d.ts +0 -7
  63. package/dist/shared/config/resolver.d.ts +0 -2
  64. package/dist/shared/config/resolverCache.d.ts +0 -12
  65. package/dist/shared/config/resolverSections.d.ts +0 -10
  66. package/dist/shared/config/runtimeSurface.d.ts +0 -21
  67. package/dist/shared/config/types.d.ts +0 -92
  68. package/dist/shared/config/validator.d.ts +0 -2
  69. package/dist/shared/credentials/envTokens.d.ts +0 -9
package/dist/direct.js CHANGED
@@ -5,47 +5,49 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- var US=Object.defineProperty;var y=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var $S=(e,t)=>{for(var n in t)US(e,n,{get:t[n],enumerable:!0})};import{completeMetadata as jS}from"@octocodeai/octocode-core";var $,we,Wt,$M,To=y(()=>{"use strict";$=jS.toolNames,we=$.LSP_GET_SEMANTIC_CONTENT,Wt="oqlSearch",$M=new Set([$.LOCAL_RIPGREP,$.LOCAL_FETCH_CONTENT,$.LOCAL_FIND_FILES,$.LOCAL_VIEW_STRUCTURE,$.LOCAL_BINARY_INSPECT,we])});function Kt(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function ea(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var Uu,yn=y(()=>{"use strict";To();Uu=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});var fe=y(()=>{"use strict"});import{z as Eo}from"zod";function G(e,t){return Eo.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Eo.number().int().min(e).max(t))}function te(e,t={}){let{maxQueries:n=5}=t;return Eo.object({queries:Eo.array(e).min(1).max(n).describe("Parallel queries."),...VS}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var oe,bn,Rn,VS,Ne=y(()=>{"use strict";fe();oe=G(1,1e3).optional().default(1),bn=G(0,100).optional(),Rn=G(1,1e9).optional(),VS={responseCharOffset:G(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:G(1,5e4).optional().describe("Full-response char window.")}});import{z as $u}from"zod";function WS(e,t){return e?.description&&!t.description?t.describe(e.description):t}function ju(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=WS(e.shape[r],o);return n}function KS(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function qu(e,t){if(!t?.length)return e;let n=new Set(t);return $u.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function ae(e,t={},n={}){let r=qu(e,n.omit),o=KS(r,ju(r,t));return n.strict?o.strict():o}function de(e,t={},n={}){let r=qu(e,n.omit),o=$u.object({...r.shape,...ju(r,t)});return n.strict?o.strict():o}var Ke=y(()=>{"use strict"});import{z as xe}from"zod";var YS,Ge,kt=y(()=>{"use strict";YS=xe.object({currentPage:xe.number(),totalPages:xe.number(),hasMore:xe.boolean(),charOffset:xe.number(),charLength:xe.number(),totalChars:xe.number(),nextCharOffset:xe.number().optional()}).optional(),Ge={hints:xe.array(xe.string()).optional(),base:xe.string().optional(),shared:xe.record(xe.string(),xe.union([xe.string(),xe.number(),xe.boolean()])).optional(),responsePagination:YS}});import{CloneRepoQuerySchema as XS}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as JS}from"@octocodeai/octocode-core/schemas/outputs";var or,ko,aD,na=y(()=>{"use strict";Ne();Ke();kt();or=ae(XS),ko=te(or),aD=JS.extend(Ge)});import{z as T}from"zod";import{FileContentQuerySchema as Ku}from"@octocodeai/octocode-core/schemas";var ZS,eC,Vu,Wu,Yu,tC,Sn,Oo,gD,vo=y(()=>{"use strict";fe();Ne();Ke();kt();ZS=T.enum(["none","standard","symbols"]).optional().default("standard"),eC=T.object({currentPage:T.number(),totalPages:T.number(),hasMore:T.boolean(),nextPage:T.number().optional(),nextMatchPage:T.number().optional(),charOffset:T.number().optional(),charLength:T.number().optional(),totalChars:T.number().optional(),nextCharOffset:T.number().optional(),filesPerPage:T.number().optional(),totalFiles:T.number().optional(),entriesPerPage:T.number().optional(),totalEntries:T.number().optional(),matchesPerPage:T.number().optional(),totalMatches:T.number().optional()}),Vu=T.object({path:T.string(),content:T.string(),localPath:T.string().optional(),repoRoot:T.string().optional(),contentView:T.enum(["none","standard","symbols"]).optional(),isSkeleton:T.boolean().optional(),totalLines:T.number().optional(),sourceChars:T.number().optional(),sourceBytes:T.number().optional(),resolvedBranch:T.string().optional(),pagination:eC.optional(),isPartial:T.boolean().optional(),startLine:T.number().optional(),endLine:T.number().optional(),matchRanges:T.array(T.object({start:T.number(),end:T.number()})).optional(),lastModified:T.string().optional(),lastModifiedBy:T.string().optional(),warnings:T.array(T.string()).optional(),matchNotFound:T.boolean().optional(),searchedFor:T.string().optional(),cached:T.boolean().optional()}),Wu=T.object({path:T.string(),localPath:T.string(),repoRoot:T.string().optional(),fileCount:T.number(),totalSize:T.number(),complete:T.boolean().optional(),directoryEntryCount:T.number().optional(),eligibleFileCount:T.number().optional(),savedFileCount:T.number().optional(),skipped:T.object({nonFile:T.number(),missingDownloadUrl:T.number(),oversized:T.number(),binary:T.number(),fileLimit:T.number(),fetchFailed:T.number(),totalSizeLimit:T.number(),pathTraversal:T.number()}).optional(),limits:T.object({maxDirectoryFiles:T.number(),maxTotalSize:T.number(),maxFileSize:T.number()}).optional(),warnings:T.array(T.string()).optional(),files:T.array(T.object({path:T.string(),size:T.number(),type:T.string()})).optional(),cached:T.boolean().optional(),resolvedBranch:T.string().optional()}),Yu={startLine:Rn,endLine:Rn,contextLines:bn,charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:ZS},tC=de(Ku,Yu),Sn=ae(Ku,Yu),Oo=te(tC),gD=T.object({base:T.string().optional(),shared:T.record(T.string(),T.union([T.string(),T.number(),T.boolean()])).optional(),responsePagination:Ge.responsePagination,results:T.array(T.object({id:T.string(),owner:T.string(),repo:T.string(),files:T.array(Vu).optional(),directories:T.array(Wu).optional(),data:T.object({owner:T.string(),repo:T.string(),files:T.array(Vu).optional(),directories:T.array(Wu).optional()}).optional()})),errors:T.array(T.object({id:T.string(),owner:T.string().optional(),repo:T.string().optional(),path:T.string().optional(),error:T.string()})).optional()})});import{z as N}from"zod";import{GitHubCodeSearchQuerySchema as Xu}from"@octocodeai/octocode-core/schemas";var Ju,Ao,Lo,wD,ra=y(()=>{"use strict";fe();Ne();Ke();kt();Ju={limit:G(1,100).optional(),page:oe.default(1)},Ao=ae(Xu,Ju),Lo=te(de(Xu,Ju)),wD=N.object({base:N.string().optional(),shared:N.record(N.string(),N.union([N.string(),N.number(),N.boolean()])).optional(),responsePagination:Ge.responsePagination,results:N.array(N.object({id:N.string(),data:N.object({files:N.array(N.object({owner:N.string(),repo:N.string(),path:N.string(),queryId:N.string().optional(),matches:N.array(N.object({value:N.string().optional(),pathOnly:N.boolean().optional(),matchIndices:N.array(N.object({start:N.number(),end:N.number(),lineOffset:N.number()})).optional(),url:N.string().optional()}))})),pagination:N.object({currentPage:N.number(),totalPages:N.number(),perPage:N.number(),totalMatches:N.number(),reportedTotalMatches:N.number().optional(),reachableTotalMatches:N.number().optional(),totalMatchesKind:N.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:N.boolean().optional(),hasMore:N.boolean(),nextPage:N.number().optional(),uniqueFileCount:N.number().optional()}).optional()})})),emptyQueries:N.array(N.object({id:N.string(),nonExistentScope:N.literal(!0).optional(),incompleteResults:N.literal(!0).optional()})).optional(),warnings:N.array(N.string()).optional(),errors:N.array(N.object({id:N.string(),error:N.string()})).optional()})});import{z as Yt}from"zod";import{GitHubPullRequestSearchQuerySchema as Zu}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as rC}from"@octocodeai/octocode-core/schemas/outputs";var ed,oC,Pn,_o,_D,Io=y(()=>{"use strict";fe();Ne();Ke();kt();ed={perPage:G(1,100).optional().default(30),prNumber:G(1,1e9).optional(),limit:G(1,100).optional().default(30),page:oe.default(1),filePage:oe.optional(),commentPage:oe.optional(),commitPage:oe.optional(),itemsPerPage:G(1,100).optional().default(20),charOffset:G(0,1e8).optional(),commentBodyOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional()},oC=de(Zu,ed),Pn=ae(Zu,ed),_o=te(oC),_D=rC.extend({results:Yt.array(Yt.object({id:Yt.string().optional(),status:Yt.string().optional(),data:Yt.object({pull_requests:Yt.array(Yt.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Ge})});import{z as V}from"zod";import{GitHubReposSearchSingleQuerySchema as td}from"@octocodeai/octocode-core/schemas";var nd,Fo,Mo,iC,sC,aC,zD,oa=y(()=>{"use strict";fe();Ne();Ke();kt();nd={limit:G(1,100).optional(),page:oe.default(1)},Fo=ae(td,nd),Mo=te(de(td,nd)),iC=V.object({owner:V.string(),repo:V.string(),stars:V.number().optional(),forks:V.number().optional(),openIssuesCount:V.number().optional(),language:V.string().optional(),license:V.string().optional(),description:V.string().optional(),homepage:V.string().optional(),pushedAt:V.string().optional(),createdAt:V.string().optional(),defaultBranch:V.string().optional(),topics:V.array(V.string()).optional(),visibility:V.string().optional(),url:V.string().optional(),updatedAt:V.string().optional()}),sC=V.object({currentPage:V.number(),totalPages:V.number(),hasMore:V.boolean(),perPage:V.number().optional(),totalMatches:V.number().optional(),reportedTotalMatches:V.number().optional(),reachableTotalMatches:V.number().optional(),totalMatchesKind:V.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:V.boolean().optional(),nextPage:V.number().optional()}).optional(),aC=V.object({repositories:V.array(V.union([V.string(),iC])).optional(),pagination:sC}).passthrough(),zD=V.object({results:V.array(V.object({id:V.string().optional(),status:V.string().optional(),data:aC.optional()}).passthrough()).optional()}).extend(Ge)});import{GitHubViewRepoStructureQuerySchema as rd}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as lC}from"@octocodeai/octocode-core/schemas/outputs";var od,Do,No,KD,ia=y(()=>{"use strict";fe();fe();Ne();Ke();kt();od={maxDepth:G(0,20).optional(),page:oe.default(1),itemsPerPage:G(1,200).optional()},Do=ae(rd,od),No=te(de(rd,od)),KD=lC.extend(Ge)});import{z as ee}from"zod";import{NpmPackageQuerySchema as id}from"@octocodeai/octocode-core/schemas";var sd,Go,Ho,nN,sa=y(()=>{"use strict";Ne();Ke();kt();sd={page:oe,mode:ee.enum(["lean","full"]).optional()},Go=ae(id,sd),Ho=te(de(id,sd,{strict:!0}),{maxQueries:5}),nN=ee.object({results:ee.array(ee.looseObject({id:ee.string(),data:ee.looseObject({packages:ee.array(ee.object({name:ee.string(),version:ee.string().optional(),description:ee.string().optional(),license:ee.string().optional(),downloads:ee.number().optional(),repository:ee.string().optional(),repositoryDirectory:ee.string().optional(),next:ee.record(ee.string(),ee.unknown()).optional()}).passthrough()).optional(),pagination:ee.object({currentPage:ee.number(),totalPages:ee.number(),perPage:ee.number(),totalFound:ee.number(),returned:ee.number(),hasMore:ee.boolean(),nextPage:ee.number().optional()}).optional()}).optional(),status:ee.string().optional()})).optional()}).extend(Ge)});import{z as uC}from"zod";import{FetchContentQuerySchema as ad}from"@octocodeai/octocode-core/schemas";var dC,cd,pC,wn,zo,Bo=y(()=>{"use strict";fe();Ne();Ke();dC=uC.enum(["none","standard","symbols"]).optional().default("standard"),cd={startLine:Rn,endLine:Rn,contextLines:bn.default(5),charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:dC},pC=de(ad,cd),wn=ae(ad,cd),zo=te(pC,{maxQueries:5})});import{z as fC}from"zod";import{FindFilesQuerySchema as mC}from"@octocodeai/octocode-core/schemas";function gC(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 ld,ud,hC,xn,Qo,Uo=y(()=>{"use strict";fe();Ne();Ke();ld={maxDepth:G(0,100).optional(),minDepth:G(0,100).optional(),limit:G(1,1e4).optional(),page:oe.default(1),itemsPerPage:G(1,50).optional()},ud=fC.object(Object.fromEntries(Object.entries(mC.shape).filter(([e])=>e!=="regexType")));hC=de(ud,ld),xn=ae(ud,ld).superRefine(gC),Qo=te(hC,{maxQueries:5})});import{z as Tn}from"zod";import{RipgrepQuerySchema as dd}from"@octocodeai/octocode-core/schemas";var yC,bC,pd,RC,SC,CC,Ot,$o,ar=y(()=>{"use strict";fe();Ne();Ke();yC=["paginated","discovery","detailed","structural"],bC=["semanticRanking"],pd={mode:Tn.enum(yC).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters.'),pattern:Tn.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:Tn.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:bn,matchContentLength:G(1,1e5).optional().default(500),maxMatchesPerFile:G(1,1e5).optional(),maxFiles:G(1,1e5).optional(),matchPage:oe.optional(),itemsPerPage:G(1,1e3).optional(),page:oe.default(1),unique:Tn.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:Tn.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},RC={...pd,semanticRanking:Tn.never().optional()},SC=de(dd,RC),CC=ae(dd,pd,{strict:!0,omit:bC}),Ot=CC.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),$o=te(SC,{maxQueries:5})});import{ViewStructureQuerySchema as fd}from"@octocodeai/octocode-core/schemas";var md,PC,En,jo,qo=y(()=>{"use strict";fe();Ne();Ke();md={maxDepth:G(0,20).optional(),limit:G(1,1e4).optional(),page:oe.default(1),itemsPerPage:G(1,50).optional()},PC=de(fd,md),En=ae(fd,md),jo=te(PC,{maxQueries:5})});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as yd}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as wC}from"@octocodeai/octocode-core/schemas/outputs";var xC,TC,EC,bd,kC,Ko,Yo,gd,OC,vC,Vo,Wo,AC,LC,Rd,kn,_C,IC,FC,Sd,MC,DC,NC,GC,HC,zC,BC,hd,FN,la=y(()=>{"use strict";fe();Ne();Ke();yn();xC=G(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),TC=G(0,1e5).optional(),EC=["structured","compact"],bd={type:R.enum(Uu).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:R.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:xC.optional(),orderHint:TC,depth:G(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:oe,itemsPerPage:G(1,100).optional(),contextLines:G(0,100).optional(),format:R.enum(EC).optional().default("structured")},kC=de(yd,bd),Ko=ae(yd,bd),Yo=te(kC,{maxQueries:5}),gd=R.object({line:R.number(),character:R.number()}),OC=R.object({start:gd,end:gd}),vC=R.object({startLine:R.number(),endLine:R.number()}),Vo=R.object({uri:R.string(),content:R.string().optional(),displayRange:vC.optional(),isDefinition:R.boolean().optional()}),Wo=R.string(),AC=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),LC=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),Rd=R.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),kn=R.object({category:Rd,reason:R.string()}),_C=R.object({currentPage:R.number(),totalPages:R.number(),totalResults:R.number(),hasMore:R.boolean(),itemsPerPage:R.number(),nextPage:R.number().optional()}),IC=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),FC=R.string(),Sd=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),MC=R.string(),DC=R.object({direction:R.enum(["incoming","outgoing"]),item:Sd,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),NC=R.string(),GC=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),HC=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),zC=R.string(),BC=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([Vo,Wo]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([Vo,Wo]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([Vo,Wo]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([Vo,Wo])).optional(),byFile:R.array(R.union([HC,zC])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:kn.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([Sd,MC]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([DC,NC])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:GC,empty:kn.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:OC.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([IC,FC])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:kn.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:kn.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:kn.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:kn.optional()}),R.object({kind:R.literal("empty"),category:Rd,reason:R.string()})]),hd=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:AC.optional(),lsp:LC,payload:BC,pagination:_C.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),FN=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:hd}),R.object({id:R.string().min(1),status:R.literal("error"),data:wC}),R.object({id:R.string().min(1),data:hd})]))})});import{z as Cd}from"zod";import{LocalBinaryInspectQuerySchema as QC}from"@octocodeai/octocode-core/schemas";var UC,Pd,On,Xo,Jo=y(()=>{"use strict";Ne();UC={entryPageNumber:oe.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:G(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:G(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:oe.default(1).describe("1-based page for paginated entry/content listings."),detailed:Cd.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Pd=Cd.object({...QC.shape,...UC}),On=Pd.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),Xo=te(Pd,{maxQueries:5})});function xd(e){return Array.isArray(e.queries)}function Td(e){return Array.isArray(e.queries)}function Ed(e){return Array.isArray(e.children)}var vt,Zo,wd,cr=y(()=>{"use strict";vt=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],Zo=["fixes","dataflow"],wd=["packages","repositories"]});import{z as h}from"zod";var da,ua,$C,kd,Od,jC,qC,vn,vd,VC,WC,Jt,Ad,Ld,_d,Id,ei,KC,UN,YC,XC,Fd,pa,ti,Md,Dd,An,lr=y(()=>{"use strict";cr();da=h.lazy(()=>h.union([h.strictObject({kind:h.literal("local"),path:h.string().min(1)}),h.strictObject({kind:h.literal("github"),repo:h.string().min(1).optional(),owner:h.string().min(1).optional(),ref:h.string().min(1).optional()}),h.strictObject({kind:h.literal("materialized"),localPath:h.string().min(1),source:da.optional()}),h.strictObject({kind:h.literal("npm")})])),ua=h.union([h.string(),h.array(h.string()).max(100)]),$C=h.strictObject({path:ua.optional(),language:ua.optional(),include:h.array(h.string()).max(100).optional(),exclude:h.array(h.string()).max(100).optional(),excludeDir:h.array(h.string()).max(100).optional(),hidden:h.boolean().optional(),noIgnore:h.boolean().optional(),minDepth:h.number().int().min(0).max(64).optional(),maxDepth:h.number().int().min(0).max(64).optional()}).optional(),kd=h.enum(["smart","sensitive","insensitive"]),Od=h.string().max(1e4),jC=h.strictObject({id:h.string().optional(),kind:h.literal("text"),value:Od,case:kd.optional(),wholeWord:h.boolean().optional()}),qC=h.strictObject({id:h.string().optional(),kind:h.literal("regex"),value:Od,dialect:h.enum(["rust","pcre2","provider"]).optional(),case:kd.optional(),wholeWord:h.boolean().optional(),multiline:h.boolean().optional(),dotAll:h.boolean().optional()}),vn=h.lazy(()=>h.strictObject({pattern:h.string().optional(),kind:h.string().optional(),inside:vn.optional(),has:vn.optional(),not:vn.optional(),all:h.array(vn).optional(),any:h.array(vn).optional(),stopBy:h.literal("end").optional()})),vd=h.union([vn,h.string().min(1)]),VC=h.strictObject({id:h.string().optional(),kind:h.literal("structural"),lang:h.string().min(1),pattern:h.string().optional(),rule:vd.optional()}),WC=h.strictObject({id:h.string().optional(),kind:h.literal("field"),field:h.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:h.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:h.unknown().optional()}),Jt=h.lazy(()=>h.discriminatedUnion("kind",[h.strictObject({kind:h.literal("all"),id:h.string().optional(),of:h.array(Jt).min(1)}),h.strictObject({kind:h.literal("any"),id:h.string().optional(),of:h.array(Jt).min(1)}),h.strictObject({kind:h.literal("not"),id:h.string().optional(),predicate:Jt}),jC,qC,VC,WC])),Ad=h.strictObject({mode:h.enum(["never","auto","required"]),strategy:h.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:h.boolean().optional(),forceRefresh:h.boolean().optional()}),Ld=h.strictObject({content:h.strictObject({range:h.strictObject({startLine:h.number().int().min(1).optional(),endLine:h.number().int().min(1).optional(),contextLines:h.number().int().min(0).max(100).optional()}).optional(),match:h.strictObject({text:h.string(),regex:h.boolean().optional(),caseSensitive:h.boolean().optional()}).optional(),contentView:h.enum(["exact","compact","symbols"]).optional(),charOffset:h.number().int().min(0).max(1e8).optional(),charLength:h.number().int().min(1).max(5e4).optional(),fullContent:h.boolean().optional()}).optional(),tree:h.strictObject({maxDepth:h.number().int().min(0).max(64).optional(),pattern:h.string().optional(),includeSizes:h.boolean().optional(),extensions:h.array(h.string()).optional(),filesOnly:h.boolean().optional(),directoriesOnly:h.boolean().optional(),sortBy:h.enum(["name","size","time","extension"]).optional(),reverse:h.boolean().optional()}).optional()}),_d=h.strictObject({search:h.strictObject({countLinesPerFile:h.boolean().optional(),countMatchesPerFile:h.boolean().optional(),onlyMatching:h.boolean().optional(),unique:h.boolean().optional(),countUnique:h.boolean().optional(),contextLines:h.number().int().min(0).max(100).optional(),invertMatch:h.boolean().optional(),matchWindow:h.number().int().min(0).optional(),matchContentLength:h.number().int().min(1).optional(),maxMatchesPerFile:h.number().int().min(1).optional(),matchPage:h.number().int().min(1).optional(),sort:h.enum(["relevance","matchCount","path","modified","accessed","created"]).optional(),sortReverse:h.boolean().optional(),rankingProfile:h.string().optional(),debugRanking:h.boolean().optional()}).optional(),budget:h.strictObject({maxFiles:h.number().int().min(1).optional(),maxCandidates:h.number().int().min(1).optional(),maxBytes:h.number().int().min(1).optional(),maxMaterializedBytes:h.number().int().min(1).optional(),maxPlanNodes:h.number().int().min(1).optional(),maxBooleanExpansion:h.number().int().min(1).optional(),timeoutMs:h.number().int().min(1).optional()}).optional()}),Id=h.enum(["discovery","paginated","detailed"]),ei=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),target:h.enum(vt),from:da.optional(),scope:$C,where:Jt.optional(),materialize:Ad.optional(),fetch:Ld.optional(),select:h.array(h.string()).optional(),view:Id.optional(),controls:_d.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional()}),KC=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),queries:h.array(ei).min(1).max(5),combine:h.enum(["independent","merge"]).optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),explain:h.boolean().optional()}),UN=h.union([ei,KC]),YC=vt,XC=[...vt,...Zo],Fd={schema:h.literal("oql").optional(),id:h.string().optional(),mainResearchGoal:h.string().optional(),researchGoal:h.string().optional(),reasoning:h.string().optional()},pa={...Fd,target:h.enum(XC).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:da.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:Jt.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:h.union([Ad,h.enum(["never","auto","required"])]).optional(),fetch:Ld.optional(),select:h.array(h.string()).optional(),view:Id.optional(),controls:_d.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional(),repo:h.string().optional(),owner:h.string().optional(),ref:h.string().optional(),path:ua.optional(),text:h.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:h.string().optional(),pattern:h.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:vd.optional(),lang:h.string().optional(),and:h.array(h.unknown()).optional(),or:h.array(h.unknown()).optional(),xor:h.array(h.unknown()).optional(),noneOf:h.array(h.unknown()).optional(),oneOf:h.array(h.unknown()).optional(),invert:h.unknown().optional(),filesOnly:h.boolean().optional(),filesWithoutMatch:h.boolean().optional(),verbose:h.boolean().optional()},ti=h.object({...pa,target:h.enum(YC).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes.")}).catchall(h.unknown()),Md=h.object(pa).catchall(h.unknown()),Dd=h.object({...Fd,queries:h.array(h.unknown()).min(1)}).catchall(h.unknown()),An=h.object({...pa,queries:h.array(h.unknown()).min(1).max(5).optional(),combine:h.enum(["independent","merge"]).optional()}).catchall(h.unknown())});import{z as fa}from"zod";function dr(e){return Qd.find(t=>t.name===e)}function ur(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===$.PACKAGE_SEARCH?"Package":"Other"}function eP(e){return[...e].sort((t,n)=>{let r=ma.indexOf(ur(t)),o=ma.indexOf(ur(n));if(r!==o)return r-o;let i=Nd.get(t)??Number.MAX_SAFE_INTEGER,s=Nd.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function tP(e){let t=dr(e);if(!t)return"{}";try{return JSON.stringify(fa.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(fa.toJSONSchema(t.schema),null,2)}}function nP(e){return JSON.stringify(e??{},null,2)}function rP(e){let t=ur(e),n=[...ZC];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function oP(){return Bd.map(e=>({...e}))}function iP(){return JSON.stringify(Object.fromEntries(Bd.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function sP(e,t){return t?.tools?.[e]?.description??e}function Sa(e){let t=dr(e);if(!t)return[];let n=fa.toJSONSchema(t.schema);if(!Ln(n))return[];let r=At(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Ra.has(i)&&!ba(r[i])):[]);return ya(r,o)}function Gd(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function aP(e){let t=uP(e);if(t.length>0)return t.map(r=>({...r,command:Gd(e,r.query)}));let n=lP(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:Gd(e,n)}]}function cP(e){return aP(e)[0]?.query??{}}function lP(e){if(!dr(e))return{};let t=Sa(e),n=t.filter(i=>!i.name.includes(".")),r=bP(n),o={};for(let i of r)o[i.name]=PP(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===we&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function uP(e){return e===Wt?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===$.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"facebook",repo:"react",keywordsToSearch:["useState"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"facebook",repo:"react",path:"packages/react/src",since:"2024-01-01T00:00:00Z",perPage:5}}]:e===$.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"facebook",repo:"react",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["useState"],owner:"facebook",repo:"react",extension:"js",limit:5}}]:e===$.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"facebook",concise:!0,limit:5}}]:e===$.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"facebook",repo:"react",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===$.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"facebook",repo:"react",sparsePath:"packages/react"}}]:e===$.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:e===$.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"src/index.ts",startLine:1,endLine:40,minify:"none"}},{label:"matched slice",query:{path:"src/index.ts",matchString:"registerTool",contextLines:8,minify:"standard"}}]:e===$.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:".",names:["*.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/**",entryType:"f",itemsPerPage:20}}]:e===$.LOCAL_BINARY_INSPECT?[{label:"archive listing",query:{path:"archive.zip",mode:"list",entriesPerPage:50}},{label:"binary strings",query:{path:"dist/app.node",mode:"strings",minLength:8,charLength:2e3}}]:e===we?[{label:"semantic definition",query:{uri:"/path/to/file.ts",type:"definition",symbolName:"myFunction",lineHint:42}},{label:"symbol outline",query:{uri:"/path/to/file.ts",type:"documentSymbols"}}]:[]}function dP(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new ct("Tool input must be valid JSON.")}return Ud(e,r,n)}function Ud(e,t,n={}){let r=fP(e,t,n),o=dr(e);if(!o)throw new ct(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new ct("Tool input does not match the expected schema.",pP(i.error));return i.data}function pP(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function fP(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(At(t)&&Array.isArray(t.queries))r=t.queries;else if(At(t))r=[t];else throw new ct('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new ct("At least one query is required.");let o=At(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,l)=>{i=!0,n.onUnknownFields?.(c,l)}},a=r.map((c,l)=>mP(e,l,hP(e,c,l,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new ct("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function mP(e,t,n,r){let o={...n},i=ur(e),s=r.sourceLabel??"direct tool execution",a=gP(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 gP(e,t){return`Execute ${e} via ${t}`}function hP(e,t,n,r={}){if(!At(t))throw new ct("Tool input must be a JSON object or an array of objects.");let o=new Set([...Sa(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Ra]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function yP(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 ga(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Ln(e.items)?e.items:void 0;return`array<${n?ga(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Ln).map(ga).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 bP(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&&RP(i)).sort(SP),o=Math.max(Hd,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=>!$d.has(i.name)).filter(i=>i.type!=="boolean").slice(0,Hd)}function RP(e){return $d.has(e.name)||e.type==="boolean"?!1:CP(e)?ha.has(e.name):!0}function SP(e,t){let n=ha.get(e.name)??Number.MAX_SAFE_INTEGER,r=ha.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function CP(e){return e.constraints?.includes("default ")===!0}function ya(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Ra.has(o))continue;let s=Ln(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:ga(s),constraints:yP(s),description:typeof s.description=="string"?s.description:void 0}),At(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!ba(s.properties?.[u]):!1):[]);r.push(...ya(s.properties,l,a))}let c=s.type==="array"&&Ln(s.items)?s.items:void 0;if(c&&At(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!ba(c.properties?.[u]):!1):[]);r.push(...ya(c.properties,l,a))}}return r}function PP(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[zd(e,n)]}return zd(e,t)}function zd(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"facebook";case"repo":return"react";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"react";default:return e}}function At(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ln(e){return At(e)}function ba(e){return Ln(e)&&"default"in e}var ma,Nd,ct,JC,Ra,ZC,Bd,Qd,Hd,ha,$d,Ca=y(()=>{"use strict";To();yn();na();vo();ra();Io();oa();ia();sa();Bo();Uo();ar();qo();la();Jo();lr();ma=["GitHub","Local Code","Package","Other"],Nd=new Map([$.GITHUB_SEARCH_CODE,$.GITHUB_SEARCH_REPOSITORIES,$.GITHUB_SEARCH_PULL_REQUESTS,$.GITHUB_FETCH_CONTENT,$.GITHUB_VIEW_REPO_STRUCTURE,$.GITHUB_CLONE_REPO,$.LOCAL_RIPGREP,$.LOCAL_FIND_FILES,$.LOCAL_FETCH_CONTENT,$.LOCAL_VIEW_STRUCTURE,we,$.PACKAGE_SEARCH,Wt].map((e,t)=>[e,t])),ct=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},JC=["id","mainResearchGoal","researchGoal","reasoning"],Ra=new Set([...JC]),ZC=["id","researchGoal","reasoning"],Bd=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],Qd=[{name:$.GITHUB_SEARCH_CODE,schema:Ao,inputSchema:Lo},{name:$.GITHUB_FETCH_CONTENT,schema:Sn,inputSchema:Oo},{name:$.GITHUB_VIEW_REPO_STRUCTURE,schema:Do,inputSchema:No},{name:$.GITHUB_SEARCH_REPOSITORIES,schema:Fo,inputSchema:Mo},{name:$.GITHUB_SEARCH_PULL_REQUESTS,schema:Pn,inputSchema:_o},{name:$.PACKAGE_SEARCH,schema:Go,inputSchema:Ho},{name:$.GITHUB_CLONE_REPO,schema:or,inputSchema:ko},{name:$.LOCAL_RIPGREP,schema:Ot,inputSchema:$o},{name:$.LOCAL_VIEW_STRUCTURE,schema:En,inputSchema:jo},{name:$.LOCAL_FIND_FILES,schema:xn,inputSchema:Qo},{name:$.LOCAL_FETCH_CONTENT,schema:wn,inputSchema:zo},{name:we,schema:Ko,inputSchema:Yo},{name:$.LOCAL_BINARY_INSPECT,schema:On,inputSchema:Xo},{name:Wt,schema:ti,inputSchema:An}];Hd=4,ha=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]]),$d=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});function Lt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function _n(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 ni(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var ri=y(()=>{"use strict"});function xP(e){let t=Lt(e),n=pr.get(t);return!n||Date.now()-n.cachedAt>=wP?!1:n.credentials?!_n(n.credentials):!0}function Pa(e){e?pr.delete(Lt(e)):pr.clear()}function jd(e){let t=Lt(e);if(xP(t))return pr.get(t).credentials}function qd(e,t){let n=Lt(e);pr.set(n,{credentials:t,cachedAt:Date.now()})}var pr,wP,Vd=y(()=>{"use strict";ri();pr=new Map,wP=300*1e3});import oi from"node:os";import TP from"node:path";function xa(){return ii?process.env.APPDATA||TP.join(In,"AppData","Roaming"):In}var ii,wa,EP,In,Wd=y(()=>{"use strict";ii=oi.platform()==="win32",wa=oi.platform()==="darwin",EP=oi.platform()==="linux",In=oi.homedir()});var Ta=y(()=>{"use strict";Wd()});import{existsSync as kP,mkdirSync as OP}from"node:fs";import{join as Ee}from"node:path";function AP(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function LP(){return ii?Ee(xa(),Ea):wa?Ee(In,Ea):Ee(AP("XDG_CONFIG_HOME")??Ee(In,".config"),Ea)}function Kd(){kP(Le.home)||OP(Le.home,{recursive:!0,mode:vP})}var Ea,vP,He,Le,Fn=y(()=>{"use strict";Ta();Ea=".octocode",vP=448;He=LP(),Le={home:He,config:Ee(He,".octocoderc"),credentials:Ee(He,"credentials.json"),key:Ee(He,".key"),session:Ee(He,"session.json"),stats:Ee(He,"stats.json"),tmp:Ee(He,"tmp"),clone:Ee(He,"tmp","clone"),tree:Ee(He,"tmp","tree"),binary:Ee(He,"tmp","binary"),repos:Ee(He,"tmp","clone"),unzip:Ee(He,"tmp","unzip"),cliConfig:Ee(He,"config.json"),lspConfig:Ee(He,"lsp-servers.json")}});import{z as Se}from"zod";var _P,IP,Yd,Xd=y(()=>{"use strict";_P=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()}),IP=Se.object({hostname:Se.string(),username:Se.string(),token:_P,gitProtocol:Se.enum(["ssh","https"]),createdAt:Se.string(),updatedAt:Se.string()}),Yd=Se.object({version:Se.number(),credentials:Se.record(Se.string(),IP)})});import{existsSync as Jd,readFileSync as Zd,writeFileSync as ep,unlinkSync as kG,statSync as FP,chmodSync as MP}from"node:fs";import{createCipheriv as DP,createDecipheriv as NP,randomBytes as tp}from"node:crypto";function en(){Kd()}function op(){if(en(),Jd(Zt))return FP(Zt).mode&511&63&&MP(Zt,384),Buffer.from(Zd(Zt,"utf8"),"hex");let e=tp(32);return ep(Zt,e.toString("hex"),{mode:384}),e}function ka(e){let t=op(),n=tp(GP),r=DP(rp,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 Oa(e){let t=op(),[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=NP(rp,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function si(){if(en(),!Jd(fr))return{version:1,credentials:{}};try{let e=Zd(fr,"utf8"),t=Oa(e),n=JSON.parse(t),r=Yd.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function ip(e){en();let t=ka(JSON.stringify(e,null,2));ep(fr,t,{mode:384})}var np,fr,Zt,rp,GP,sp=y(()=>{"use strict";Fn();Xd();np=Le.home,fr=Le.credentials,Zt=Le.key,rp="aes-256-gcm",GP=16});var mr,Mn,va=y(()=>{"use strict";mr="178c6fc778ccc68e1d6a",Mn="github.com"});import{refreshToken as HP}from"@octokit/oauth-methods";import{request as zP}from"@octokit/request";function BP(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 QP(e){return e==="github.com"||e===Mn?"https://api.github.com":`https://${e}/api/v3`}async function ap(e,t=Mn,n=mr){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(ni(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await HP({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:zP.defaults({baseUrl:QP(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?BP(o.message):"Token refresh failed"}}}async function cp(e,t=Mn,n=mr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!_n(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await ap(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var lp=y(()=>{"use strict";ri();va()});function up(){for(let e of Aa){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}var Aa,La=y(()=>{"use strict";Aa=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN"]});import{execFile as UP}from"child_process";function _a(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=$P.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;UP("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var $P,Ia=y(()=>{"use strict";$P=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function dp(e){Fa=e}function jP(){if(!Fa)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Fa}async function ai(e){let t=e?.hostname??Mn,n=e?.clientId??mr,r=e?.getGhCliToken??_a,o=up();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await jP().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch{}return null}var Fa,pp=y(()=>{"use strict";La();Ia();va();Fa=null});async function fp(e){let t=Lt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=si();return r.credentials[t]=n,ip(r),Pa(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Ma(e="github.com",t){let n=Lt(e);if(!t?.bypassCache){let i=jd(n);if(i!==void 0)return i}let o=si().credentials[n]||null;return qd(n,o),o}async function mp(e,t){let n=await Ma(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await fp(n),!0):!1}async function gp(e,t){return cp({getCredentials:Ma,updateToken:mp},e,t)}var Da=y(()=>{"use strict";Vd();sp();lp();pp();La();ri();dp({getTokenWithRefresh:gp})});var hp=y(()=>{"use strict";Da();Ia()});import{z as W}from"zod";var JP,ZP,ci,ew,li,yp,bp,Rp=y(()=>{"use strict";JP=W.object({rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),calls:W.number()}),ZP=W.object({hits:W.record(W.string(),W.number()).default({}),rateLimits:W.number().default(0)}),ci=W.record(W.string(),W.number()).default({}),ew=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:ci,rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),charSavingsCalls:W.number(),githubCacheHits:W.number(),githubCacheRateLimits:W.number(),packageRegistryFailures:W.number().default(0),packageRegistryFailuresByRegistry:ci}),li=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:ci,charsSavedByTool:W.record(W.string(),JP).default({}),githubCacheHits:ZP.default({hits:{},rateLimits:0}),packageRegistryFailures:ci,totalUsage:ew.optional()}),yp=W.object({version:W.literal(1),sessionId:W.string(),createdAt:W.string(),lastActiveAt:W.string(),stats:li.optional()}),bp=W.object({version:W.literal(1),stats:li})});function Sp(e){return Object.values(e).reduce((t,n)=>t+n,0)}function tw(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:Sp(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Sp(o),packageRegistryFailuresByRegistry:o}}function Rt(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:tw(t)}}function Na(){return Rt({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Ga=y(()=>{"use strict"});import{existsSync as Pp,readFileSync as wp,writeFileSync as nw,unlinkSync as bH,renameSync as rw}from"node:fs";function Cp(e,t){let n=`${e}.tmp`;nw(n,JSON.stringify(t,null,2),{mode:384}),rw(n,e)}function ow(e){let{stats:t,...n}=e;return n}function iw(e){let t=JSON.parse(e),n=bp.safeParse(t);if(n.success)return Rt(n.data.stats);let r=li.safeParse(t);return r.success?Rt(r.data):null}function sw(e){let t=e?Rt(e):Na();if(!Pp(hr))return t;try{let n=wp(hr,"utf8"),r=iw(n);return r||t}catch{return t}}function Ha(e){en(),Cp(hr,{version:e.version,stats:Rt(e.stats)}),Cp(gr,ow(e))}function xp(){if(!Pp(gr))return null;try{let e=wp(gr,"utf8"),t=JSON.parse(e),n=yp.safeParse(t);return n.success?{...n.data,stats:sw(n.data.stats)}:null}catch{return null}}var gr,hr,ui=y(()=>{"use strict";Da();Fn();Rp();Ga();gr=Le.session,hr=Le.stats});function cw(){Tp||(Tp=!0,Ep=()=>{di()},kp=()=>{di()},Op=()=>{di()},process.on("exit",Ep),process.on("SIGINT",kp),process.on("SIGTERM",Op))}function lw(){za||(za=setInterval(()=>{yr&&_t&&(Ha(_t),yr=!1)},aw),za.unref())}function vp(){if(_t)return _t;let e=xp();return e&&(_t=e),e}function Ap(e){_t=e,yr=!0,cw(),lw()}function di(){if(!Ba&&yr&&_t){Ba=!0;try{Ha(_t),yr=!1}catch{}finally{Ba=!1}}}var aw,_t,yr,za,Tp,Ep,kp,Op,Ba,Lp=y(()=>{"use strict";ui();aw=6e4,_t=null,yr=!1,za=null,Tp=!1,Ep=null,kp=null,Op=null,Ba=!1});import{randomUUID as IH}from"node:crypto";function uw(e){return Rt(e)}function dw(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 _p(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 pw(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 It(e){let t=vp();if(!t)return{success:!1,session:null};let n=uw(t.stats),r=Rt({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:_p(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:dw(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:pw(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:_p(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Ap(o),{success:!0,session:o}}function Qa(e=1){return It({rateLimits:e})}function Ua(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return It({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function $a(e,t=1){return It({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ja(e=1){return It({githubCacheHits:{hits:{},rateLimits:e}})}var br=y(()=>{"use strict";ui();Ga();Lp();ui()});var Ip=y(()=>{"use strict";br();br();br();br()});var qa=y(()=>{"use strict"});var pi,tn,Dn,Rr,fi,Ft,Va,Sr,Cr,Pr,wr,xr,Tr,Er=y(()=>{"use strict";pi={apiUrl:"https://api.github.com"},tn={enabled:!1,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},Dn={enabled:null,enableAdditional:null,disabled:null},Rr={timeout:3e4,maxRetries:3},fi={configPath:void 0},Ft={format:"yaml",pagination:{defaultCharLength:2e4}},Va={version:1,github:pi,local:tn,tools:Dn,network:Rr,lsp:fi,output:Ft},Sr=5e3,Cr=3e5,Pr=0,wr=10,xr=1e3,Tr=5e4});import{z as me}from"zod";var Wa,Ka=y(()=>{"use strict";Wa=me.looseObject({$schema:me.string().optional(),version:me.number().int().optional(),github:me.record(me.string(),me.unknown()).optional(),local:me.record(me.string(),me.unknown()).optional(),tools:me.record(me.string(),me.unknown()).optional(),network:me.record(me.string(),me.unknown()).optional(),lsp:me.record(me.string(),me.unknown()).optional(),output:me.record(me.string(),me.unknown()).optional()})});import{existsSync as fw,readFileSync as mw}from"node:fs";function gw(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
9
- `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t=t.replace(/,(\s*[}\]])/g,"$1"),t}function hw(e){let t=gw(e);return JSON.parse(t)}function Ya(){let e=Fp;if(!fw(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=mw(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=hw(t),r=Wa.safeParse(n);return r.success?{success:!0,config:r.data,path:e}:{success:!1,error:`Config file has invalid structure: ${r.error.issues[0]?.message??"unknown error"}`,path:e}}catch(t){return{success:!1,error:`Failed to parse config file: ${t instanceof Error?t.message:"Unknown error"}`,path:e}}}function Nn(){return Le.home}var Fp,mi=y(()=>{"use strict";Fn();Ka();Fp=Le.config});function yw(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function Za(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Mp(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function Dp(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function bw(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function Xa(e,t){return e===void 0||e===null?null:Dp(e,t)}function Np(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function Rw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=yw(e.apiUrl,"github.apiUrl");r&&t.push(r)}function Sw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Mp(n.enabled,"local.enabled");r&&t.push(r);let o=Mp(n.enableClone,"local.enableClone");o&&t.push(o);let i=Dp(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=bw(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=Np(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function Cw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=Xa(n.enabled,"tools.enabled");r&&t.push(r);let o=Xa(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=Xa(n.disabled,"tools.disabled");i&&t.push(i)}function Pw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=Za(n.timeout,"network.timeout",Sr,Cr);r&&t.push(r);let o=Za(n.maxRetries,"network.maxRetries",Pr,wr);o&&t.push(o)}function ww(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=Np(e.configPath,"lsp.configPath");r&&t.push(r)}function xw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=Za(r.defaultCharLength,"output.pagination.defaultCharLength",xr,Tr);o&&t.push(o)}}function ec(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>1&&n.push(`version: Config version ${r.version} is newer than supported version ${1}`)),Rw(r.github,t),Sw(r.local,t),Cw(r.tools,t),Pw(r.network,t),ww(r.lsp,t),xw(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}var tc=y(()=>{"use strict";qa();Er()});function nc(){return globalThis[Tw]??"mcp"}var Tw,rc=y(()=>{"use strict";Tw="__octocodeRuntimeSurface__"});function Gp(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function oc(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function gi(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function Hp(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||pi.apiUrl}}function zp(e){let t=nc()==="cli",n=Gp(process.env.ENABLE_LOCAL),r=Gp(process.env.ENABLE_CLONE),o=gi(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:t?!0:n??e?.enabled??tn.enabled,enableClone:r??e?.enableClone??(t?!0:tn.enableClone),allowedPaths:o??e?.allowedPaths??tn.allowedPaths,workspaceRoot:i??e?.workspaceRoot??tn.workspaceRoot}}function Bp(e){let t=gi(process.env.TOOLS_TO_RUN),n=gi(process.env.ENABLE_TOOLS),r=gi(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??Dn.enabled,enableAdditional:n??e?.enableAdditional??Dn.enableAdditional,disabled:r??e?.disabled??Dn.disabled}}function Qp(e){let t=oc(process.env.REQUEST_TIMEOUT),n=oc(process.env.MAX_RETRIES),r=t??e?.timeout??Rr.timeout;r=Math.max(Sr,Math.min(Cr,r));let o=n??e?.maxRetries??Rr.maxRetries;return o=Math.max(Pr,Math.min(wr,o)),{timeout:r,maxRetries:o}}function Up(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??fi.configPath}}function $p(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=oc(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||Ft.format,o=n??e?.pagination?.defaultCharLength??Ft.pagination.defaultCharLength,i=Math.max(xr,Math.min(Tr,o));return{format:Ew.has(r)?r:Ft.format,pagination:{defaultCharLength:i}}}var Ew,jp=y(()=>{"use strict";Er();rc();Ew=new Set(["yaml","json"])});function ic(e,t){let n=e!==void 0,r=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??Va.version,github:Hp(e?.github),local:zp(e?.local),tools:Bp(e?.tools),network:Qp(e?.network),lsp:Up(e?.lsp),output:$p(e?.output),source:o,configPath:n?t:void 0}}function sc(){let e=Ya();return e.success&&e.config&&ec(e.config).valid?ic(e.config,e.path):ic(void 0)}function ke(){let e=Date.now();return hi&&e-qp<kw||(hi=sc(),qp=e),hi}var hi,qp,kw,ac=y(()=>{"use strict";Er();mi();tc();jp();hi=null,qp=0,kw=6e4});var Wp=y(()=>{"use strict";ac();ac()});var Kp=y(()=>{"use strict";qa();Er();mi();mi();tc();Wp();rc();Ka()});import{existsSync as Iw,readdirSync as Fw,lstatSync as Mw}from"node:fs";import{join as Dw}from"node:path";function yi(e){if(!Iw(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Fw(r)}catch{continue}for(let i of o){let s=Dw(r,i);try{let a=Mw(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var Yp=y(()=>{"use strict"});var _e=y(()=>{"use strict";hp();Ta();Ip();Kp();Fn();Yp()});var nn,bi=y(()=>{nn="16.6.0"});var cc,kr,Or,Gw,Mt,Gn,ze,Hw,vr,zw,Zz,gt=y(()=>{"use strict";cc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},kr={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"}},Or={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})`}},Gw={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"}},Mt={PATH_IS_DIRECTORY:{code:"FILE_PATH_IS_DIRECTORY",message:e=>`Path is a directory. Use ${e} to list directory contents`},FILE_TOO_LARGE:{code:"FILE_TOO_LARGE",message:(e,t,n)=>`File too large (${e}KB > ${t}KB). Use ${n} to search within the file or use startLine/endLine parameters to get specific sections`},FILE_EMPTY:{code:"FILE_EMPTY",message:"File is empty - no content to display"},BINARY_FILE:{code:"FILE_BINARY",message:"Binary file detected. Cannot display as text - download directly from GitHub"},DECODE_FAILED:{code:"FILE_DECODE_FAILED",message:"Failed to decode file. Encoding may not be supported (expected UTF-8)"},UNSUPPORTED_TYPE:{code:"FILE_UNSUPPORTED_TYPE",message:e=>`Unsupported file type: ${e}`}},Gn={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},ze={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}`}},Hw={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}`}},vr={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},zw={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}`}},Zz={...cc,...kr,...Or,...Gw,...Mt,...Gn,...ze,...Hw,...vr,...zw}});import{maskSensitiveData as Bw}from"@octocodeai/octocode-engine/mask";async function Xp(){try{let e=await Qw({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:Uw.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Jp(){if(Lr!==null)return;if(Ar!==null)return Ar;let e=(async()=>{let t=ke(),n=await Xp();Lr={version:nn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Ar=e;try{await e}catch(t){throw Ar===e&&(Lr=null,Ar=null),t}}function Zp(){if(!Lr){let e=Bw(cc.NOT_INITIALIZED.message);throw new Error(e)}return Lr}async function ef(){return(await Xp()).token}function lc(){return"github"}function uc(){let e=ke().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var Lr,Ar,Qw,Uw,_r=y(()=>{"use strict";_e();bi();gt();Lr=null,Ar=null,Qw=ai,Uw=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"])});import{createRequire as $w}from"node:module";function Y(){if(Ri)return Ri;try{return Ri=qw(),Ri}catch(e){throw new dc(e)}}var jw,tf,Ri,qw,dc,M,ge=y(()=>{"use strict";jw=$w(import.meta.url),tf="@octocodeai/octocode-engine",qw=()=>jw(tf),dc=class extends Error{constructor(n){super(`Failed to load native dependency ${tf}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};M={applyContentViewMinification(e,t){return Y().applyContentViewMinification(e,t)},applyMinification(e,t){return Y().applyMinification(e,t)},minifyContent(e,t){return Y().minifyContent(e,t)},minifyContentSync(e,t){return Y().minifyContentSync(e,t)},minifyContentResult(e,t){return Y().minifyContentResult(e,t)},minifyMarkdownCore(e){return Y().minifyMarkdownCore(e)},extractSignatures(e,t){return Y().extractSignatures(e,t)},extractJsSymbols(e,t){return Y().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return Y().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return Y().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return Y().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return Y().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return Y().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return Y().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return Y().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return Y().getSupportedStructuralExtensions()},inspectBinaryNative(e){return Y().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return Y().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return Y().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return Y().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return Y().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return Y().parseRipgrepJson(e,t)},searchRipgrep(e){return Y().searchRipgrep(e)},queryFileSystem(e){return Y().queryFileSystem(e)},extractMatchingLines(e,t,n){return Y().extractMatchingLines(e,t,n)},filterPatch(e,t){return Y().filterPatch(e,t)},charToByteOffset(e,t){return Y().charToByteOffset(e,t)},byteToCharOffset(e,t){return Y().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return Y().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return Y().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return Y().SIGNATURES_ONLY_HINT}}});function Dt(e){(e.provider?It({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):Qa(1)).session&&e.provider==="github"&&ja(1)}function nf(e){It({packageRegistryFailures:{[e]:1}})}var Si=y(()=>{"use strict";_e()});import{Octokit as Vw}from"octokit";import{throttling as Ww}from"@octokit/plugin-throttling";import{createHash as Kw}from"crypto";function Yw(e){return Kw("sha256").update(e).digest("hex").substring(0,16)}function fc(e){return Date.now()-e.createdAt>Jw}function lf(){for(let[e,t]of lt.entries())fc(t)&&lt.delete(e);if(lt.size>pc){let e=[...lt.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=lt.size-pc;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&lt.delete(r[0])}}}function ex(){Fr||(Fr=setInterval(lf,Zw),typeof Fr=="object"&&"unref"in Fr&&Fr.unref())}function sf(e,t,n){Dt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function af(e){let t=Zp(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${nn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:tx(),log:r,...e&&{auth:e}};return new Xw(o)}async function ue(e){if(ex(),e?.token){let n=Yw(e.token),r=lt.get(n);if(r&&!fc(r))return r.client;lt.size>=pc&&lf();let o=af(e.token);return lt.set(n,{client:o,createdAt:Date.now()}),o}let t=lt.get("DEFAULT");return t&&!fc(t)?t.client:Ir||(Ir=(async()=>{try{let n=await ef(),r=af(n??void 0);return lt.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{Ir=null}})(),Ir)}async function Ye(e,t,n){let r=`${e}/${t}`,o=Mr.get(r);if(o)return o;let i=await ue(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return cf(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}),cf(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 cf(e,t){if(Mr.size>=nx){let n=Mr.keys().next().value;n!==void 0&&Mr.delete(n)}Mr.set(e,t)}var Xw,Jw,pc,Zw,lt,Ir,Fr,rf,of,tx,nx,Mr,Be=y(()=>{"use strict";_r();_r();bi();Si();Xw=Vw.plugin(Ww),Jw=300*1e3,pc=50,Zw=60*1e3;lt=new Map,Ir=null,Fr=null;rf=3,of=60;tx=()=>({onRateLimit:(e,t,n,r)=>(sf("primary",e,t),r<rf&&e<of),onSecondaryRateLimit:(e,t,n,r)=>(sf("secondary",e,t),r<rf&&e<of)});nx=200,Mr=new Map});var j,ye,uf,mc,gc,Ci,df=y(()=>{"use strict";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"},ye={[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."}},uf={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},mc={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},gc={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ci={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as pf}from"octokit";function rn(e){if(!(e instanceof pf)||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 rx.some(o=>r.includes(o))})}function ne(e){return e instanceof pf?ox(e):e instanceof Error?px(e):{error:typeof e=="string"?e:ye[j.UNKNOWN].message,type:"unknown"}}function ox(e){let{status:t,message:n,response:r}=e;if(t===403)return sx(n,r);if(t===429)return ix(n,r);let o=uf[t];return o?dx(o,t):Hn(j.UNKNOWN,{error:n||ye[j.UNKNOWN].message,status:t})}function hc(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function ix(e,t){let n=t?.headers,r=hc(n,"retry-after"),o=hc(n,"x-ratelimit-reset"),i=hc(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ci.RESET_BUFFER_SECONDS,0):void 0);return Dt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Hn(j.RATE_LIMIT_PRIMARY,{error:e||ye[j.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:ye[j.RATE_LIMIT_PRIMARY].suggestion})}function sx(e,t){let n=t?.headers;if(gc.SECONDARY.test(e))return ax(n);let r=n?.["x-ratelimit-remaining"],o=ux(t);return r!==void 0&&String(r)==="0"||o?cx(n):lx(n)}function ax(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ci.SECONDARY_FALLBACK_SECONDS:t;return Dt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Hn(j.RATE_LIMIT_SECONDARY,{error:ye[j.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:ye[j.RATE_LIMIT_SECONDARY].suggestion})}function cx(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)+Ci.RESET_BUFFER_SECONDS,0):void 0,i=r?ye[j.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ye[j.RATE_LIMIT_PRIMARY].messageWithoutTime;return Dt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Hn(j.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:ye[j.RATE_LIMIT_PRIMARY].suggestion})}function lx(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ye[j.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=fx(String(t),String(n))),Hn(j.FORBIDDEN_PERMISSIONS,{error:ye[j.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function ux(e){return e?.data?.errors?.some(n=>n.type===gc.GRAPHQL_TYPE)??!1}function dx(e,t){let n=ye[e];return Hn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function px(e){return mc.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ye[j.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ye[j.NETWORK_CONNECTION_FAILED].suggestion}:mc.TIMEOUT.some(t=>e.message.includes(t))?{error:ye[j.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:ye[j.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Hn(e,t){return{type:"http",...t}}function fx(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[j.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):ye[j.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var rx,St=y(()=>{"use strict";df();Si();rx=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function mx(e){return`user:${e}`}function ff(e){return e.startsWith('"')||yx.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function mf(e){return new yc().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function gf(e){return new bc().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function hf(e){return new Rc().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function yf(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var gx,hx,yx,Dr,yc,bc,Rc,Pi=y(()=>{"use strict";gx=/[@/]/,hx=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,yx=/^[A-Za-z0-9_-]+$/;Dr=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(mx(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=gx.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},yc=class extends Dr{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(ff))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(hx):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}},bc=class extends Dr{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(ff)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},Rc=class extends Dr{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});import bx from"node-cache";import Rx from"crypto";function Px(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function wx(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function xx(e){let t=Px(e);if(!(!t||!wx(t)))try{$a(t,1)}catch{}}function Tx(){let e=Date.now();for(let[t,n]of Nr.entries())e-n.startedAt>Cx&&Nr.delete(t)}function kx(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(Ex.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function Qe(e,t,n){let r=Sc(kx(t)),o=n?`${n}:${r}`:r,i=Rx.createHash("sha256").update(o).digest("hex");return`${Sx}-${e}:${i}`}function Sc(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=>Sc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Sc(i,t)}`}).join(",")}}`)}function Ox(e){return bf[e]||bf.default}function vx(e,t,n){try{return on.set(e,t,n),zn.sets++,zn.totalKeys=on.keys().length,!0}catch{try{let r=on.keys();for(let o of r)on.get(o);return on.set(e,t,n),zn.sets++,zn.totalKeys=on.keys().length,!0}catch{return!1}}}async function Ue(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=on.get(e);if(i!==void 0)return zn.hits++,xx(e),i}catch{}Tx();let r=Nr.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||zn.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=Ox(l)}vx(e,i,a)}return i}finally{Nr.delete(e)}})();return Nr.set(e,{promise:o,startedAt:Date.now()}),o}var Sx,Cx,on,zn,bf,Nr,Ex,Nt=y(()=>{"use strict";_e();Sx="v1",Cx=300*1e3,on=new bx({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),zn={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},bf={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},Nr=new Map;Ex=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as AB,DISCOVERY_IGNORED_FILE_NAMES as LB,DISCOVERY_IGNORED_FOLDER_NAMES as _B,getDiscoveryExtension as Rf,shouldIgnoreDiscoveryDir as Gr,shouldIgnoreDiscoveryFile as Bn}from"@octocodeai/octocode-engine/security";var Hr=y(()=>{"use strict"});function Q(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Cf(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function U(e,t){let n=typeof t=="number"?Cf(t):Q(t);if(n===void 0)return e;try{Object.defineProperty(e,Sf,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ce(e){if(!(typeof e!="object"||e===null))return Cf(e[Sf])}var Sf,ie=y(()=>{"use strict";Sf=Symbol.for("octocode.rawResponseChars")});function wi(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var Cc=y(()=>{"use strict"});import{ContentSanitizer as Ax}from"@octocodeai/octocode-engine/contentSanitizer";async function wf(e,t,n){let r=Qe("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await Ue(r,async()=>await Lx(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Lx(e,t){try{let n=await ue(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(S=>S&&S.trim()).length===0)return{error:ze.QUERY_EMPTY.message,type:"http",status:400};let r=mf(e);if(!r.trim())return{error:ze.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Pf,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 _x(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),p=Math.min(Math.ceil(d/o),10),f=Math.min(i,Math.max(1,p)),m=f<p,g=Math.min(d,p*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:f,totalPages:p,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:m,...m?{nextPage:f+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:wi(a.headers),rawResponseChars:Q(a.data)}}catch(n){if(rn(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Pf,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return ne(n)}}async function _x(e,t){let n=Ix(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!Bn(f.path)),c=0,l=0,u=await Promise.allSettled(a.map(async f=>{s.add(f.path);let m=[],g=await Promise.allSettled((f.text_matches||[]).map(async _=>{let E=_.fragment,O=Ax.sanitizeContent(E||"",f.path);E=O.content,O.hasSecrets&&r.add(`Secrets detected in ${f.path}: ${O.secretsDetected.join(", ")}`),O.warnings.length>0&&O.warnings.forEach(x=>r.add(`${f.path}: ${x}`));try{let x=await M.minifyContent(E||"",f.path);E=x.content,x.failed?o=!0:x.type!=="failed"&&(m.push(x.type),i.push(x.type))}catch{o=!0}return{context:E||"",positions:_.matches?.map(x=>Array.isArray(x.indices)&&x.indices.length>=2?[x.indices[0],x.indices[1]]:[0,0])||[]}})),b=g.filter(_=>_.status==="fulfilled").map(_=>_.value),S=g.filter(_=>_.status==="rejected").length;S>0&&(l+=S);let C=f,k=Array.from(new Set(m));return{path:f.path,matches:b,url:f.html_url,repository:{nameWithOwner:f.repository.full_name,url:f.repository.url,pushedAt:f.repository.pushed_at||void 0},...C.last_modified_at&&{lastModifiedAt:C.last_modified_at},...k.length>0&&{minificationType:k.join(",")}}})),d=u.filter(f=>f.status==="fulfilled").map(f=>f.value);c=u.filter(f=>f.status==="rejected").length;let p={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let f=n.full_name.split("/");return f.length===2&&f[0]&&f[1]?{owner:f[0],repo:f[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(p.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(p.matchLocations=Array.from(r)),p.minified=!o,p.minificationFailed=o,i.length>0&&(p.minificationTypes=Array.from(new Set(i))),p}function Ix(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 Pf,xf=y(()=>{"use strict";ge();Be();St();Pi();Nt();Hr();gt();ie();Cc();fe();Pf=30});function Ef(e){let t={},n=e.license;n?.spdx_id&&n.spdx_id!=="NOASSERTION"&&(t.license=n.spdx_id);let r=e.homepage;return r&&(t.homepage=r),t}async function kf(e,t,n){let r=Qe("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await Ue(r,async()=>await Mx(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Fx(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(f){if(f?.status!==404)return ne(f);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return ne(g)}}let a=i.map(f=>{let g=f.full_name.split("/"),b=g[0]||"",S=g[1]||"";return{owner:b,repo:S,defaultBranch:f.default_branch,stars:f.stargazers_count||0,description:f.description?f.description:"No description",url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at,pushedAt:f.pushed_at,visibility:f.visibility,...f.topics&&f.topics.length>0&&{topics:f.topics},...f.forks_count&&f.forks_count>0&&{forksCount:f.forks_count},...f.open_issues_count&&f.open_issues_count>0&&{openIssuesCount:f.open_issues_count},...f.language&&{language:f.language},...Ef(f)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),p=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:p,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:Q(i)}}async function Mx(e,t){try{let n=await ue(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 Fx({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=gf(e);if(!i.trim())return{error:ze.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||Tf,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(C=>{let _=C.full_name.split("/"),E=_[0]||"",O=_[1]||"";return{owner:E,repo:O,defaultBranch:C.default_branch,stars:C.stargazers_count||0,description:C.description?C.description:"No description",url:C.html_url,createdAt:C.created_at,updatedAt:C.updated_at,pushedAt:C.pushed_at,visibility:C.visibility,...C.topics&&C.topics.length>0&&{topics:C.topics},...C.forks_count&&C.forks_count>0&&{forksCount:C.forks_count},...C.open_issues_count&&C.open_issues_count>0&&{openIssuesCount:C.open_issues_count},...C.language&&{language:C.language},...Ef(C)}}),p=u.data.total_count,f=Math.min(p,1e3),m=Math.min(Math.ceil(f/s),10),g=Math.min(a,Math.max(1,m)),b=g<m,S=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:S,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:g+1}:{}}},status:200,headers:wi(u.headers),rawResponseChars:Q(u.data)}}catch(n){if(rn(n)){let r=Math.min(e.limit||Tf,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return ne(n)}}var Tf,Of=y(()=>{"use strict";Be();St();Pi();Nt();gt();ie();Cc();fe();Tf=30});function Qn(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var xi=y(()=>{"use strict"});function be(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 Dx(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 Ct(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:Dx(e)}}function Ti(e){return Nx(e)?Ct({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 Nx(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||Gx(n)}function Gx(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var ht=y(()=>{"use strict"});function vf(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Hx(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,...vf(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function zx(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,...vf(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Af(e,t,n=be){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 wf(s,t);return Qn(a)?Ct(a):a.data?{data:Hx(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Lf(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 kf(n,t);return"error"in r?Ti(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:zx(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??Q(r.data)}}var _f=y(()=>{"use strict";xf();Of();xi();ie();ht();ht()});import{completeMetadata as Pc}from"@octocodeai/octocode-core";var A,If=y(()=>{"use strict";A=new Proxy({},{get(e,t){return Pc.toolNames[t]},ownKeys(){return Object.keys(Pc.toolNames)},getOwnPropertyDescriptor(e,t){let n=Pc.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as Qx}from"@octocodeai/octocode-core";var wc,Ff=y(()=>{"use strict";wc=new Proxy({},{get(e,t){return Qx.tools[t]?.description??""}})});import{completeMetadata as Ux}from"@octocodeai/octocode-core";function xc(e){return Object.prototype.hasOwnProperty.call(Ux.tools,e)}var Mf=y(()=>{"use strict"});import{completeMetadata as $x}from"@octocodeai/octocode-core";function Tc(){return $x.baseSchema}var jx,Df=y(()=>{"use strict";jx=new Proxy({},{get(e,t){return Tc()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Tc())]))},getOwnPropertyDescriptor(e,t){let n=Tc();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var pe=y(()=>{"use strict";If();Ff();Mf();Df()});import{RequestError as Nf}from"octokit";async function qx(e,t,n,r,o,i,s,a){let c=await Ye(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=ne(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,p=await Bf(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...zf(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function Vx(e,t,n,r,o,i){let s=ne(t),a=await Bf(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...zf(o,a)]),s}async function Gf(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:Mt.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:Mt.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:Mt.DECODE_FAILED.message,type:"unknown",status:422}}}async function Hf(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"?Gf(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return ne(i)}}async function Wx(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 Ye(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(p=>p.name===a&&p.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await Hf(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return ne(s)}}async function Ei(e,t){try{let n=await ue(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof Nf&&d.status===404)if(s){let p=await qx(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await Vx(n,d,r,o,i,s);else{if(d instanceof Nf&&d.status===413)return await Wx(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:Mt.PATH_IS_DIRECTORY.message(A.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in u&&u.type==="file"){let d=typeof u.content=="string"?u.content:"",p=u.size??0,f;if(d.length>0)f=await Gf(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await Hf(n,r,o,u.sha,i);else return{error:Mt.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await Ye(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:Q(u)}}return{error:Mt.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return ne(n)}}function zf(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 Bf(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(f=>f.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(f=>f.name===s?!1:!!f.name.startsWith(d+".")).forEach(f=>l.push(f.path)),l.length===0&&d.length>=3&&c.filter(m=>{let g=m.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(m=>l.push(m.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var Ec=y(()=>{"use strict";Be();St();pe();gt();ie()});function Ze(){try{return ke().output.pagination.defaultCharLength}catch{return Ft.pagination.defaultCharLength}}var zr=y(()=>{"use strict";_e();_e()});function Br(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Pt(e){return Br(e).length}var Qr=y(()=>{"use strict"});function kc(e,t){return M.byteToCharOffset(e,t)}function Qf(e,t){return M.charToByteOffset(e,t)}function Uf(e){return M.charToByteOffset(e,e.length)}function Oc(e,t,n,r){return M.sliceContent(e,t,n,r)}var $f=y(()=>{"use strict";ge()});function Un(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Uf(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,p,f,m,g;if(o==="bytes"){let b=Math.min(t,s),S=Math.min(b+n,s);d=kc(e,b),p=kc(e,S),p<i&&Qf(e,p)<S&&(p+=1);let C=Oc(e,d,p-d);c=C.text,d=C.charOffset,p=C.charOffset+C.charLength,l=C.byteOffset,u=C.byteOffset+C.byteLength,f=u<s;let k=r.actualOffset??b;m=Math.floor(k/a)+1,g=Math.max(m,Math.ceil(s/a))}else{let b=Oc(e,t,n);c=b.text,d=b.charOffset,p=b.charOffset+b.charLength,l=b.byteOffset,u=b.byteOffset+b.byteLength,f=p<i;let S=r.actualOffset??d;m=Math.floor(S/a)+1,g=Math.max(m,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:f?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:f?p:void 0,hasMore:f,estimatedTokens:Math.ceil(c.length/4),currentPage:m,totalPages:g}}function jf(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 ki=y(()=>{"use strict";$f()});function Xx(e){return e&&e.trim().length>0?e:Yx}function qf(e,t){return M.getSemanticBoundaryOffsets(e,Xx(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function Jx(e,t){let n=e.indexOf(`
10
- `,t);return n===-1?void 0:n+1}function Oi(e){let t=e.trimEnd().split(`
11
- `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function vi(e,t,n){let r=Jx(e,Math.max(0,t));if(r!==void 0)return qf(e,n).find(o=>o>=r&&o>t)}function Ai(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=qf(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=Kx?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var Kx,Yx,vc=y(()=>{"use strict";ge();Kx=8e3,Yx="__octocode_generic__.unknown"});function Li(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
12
- `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=M.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var Ac=y(()=>{"use strict";ge()});function eT(e){return Zx.test(e.split(/[?#]/,1)[0]??e)}function Vf(e,t){return eT(t)?nT(tT(e)):null}function _i(e,t){let n=Vf(e,t);if(n===null||n.length===0)return null;let r=[];return Kf(n,r),r.join(`
13
- `)}function Wf(e,t){let n=Vf(e,t);return n===null?null:n.map(Yf)}function tT(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function nT(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 Kf(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}`),Kf(n.children,t)}}function Yf(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(Yf)}}var Zx,Ii=y(()=>{"use strict";Zx=/\.(?:md|markdown|mdx)$/i});import{ContentSanitizer as Xf}from"@octocodeai/octocode-engine/contentSanitizer";function oT(){let e=Ze();return Math.min(e,8e3)}function Ur(e,t){return{sourceChars:e,sourceBytes:t}}function Jf(e,t,n){let r=e.content??"",o=n??oT();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=Ai(r,t,o,i),c=Un(r,t,s),l;if(c.hasMore&&a==="char-limit"&&Oi(c.paginatedContent)){let u=c.charOffset+c.charLength;l=vi(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function Zf(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function em(e,t,n,r,o,i,s,a,c=5,l,u,d,p="standard"){let f=e.length,m=Buffer.byteLength(e,"utf-8"),g=p==="standard"||p==="symbols",b=g?"standard":"none",S;if(p==="symbols"){let Z=M.extractSignatures(e,o);if(Z===null){let z=_i(e,o);if(z!==null)return{owner:t,repo:n,path:o,content:z,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Pt(e),...Ur(f,m),isPartial:!1,signaturesExtracted:!0,hints:[M.SIGNATURES_ONLY_HINT]};S=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(Z!==null){let z=Xf.sanitizeContent(Z,o),Ae=M.applyContentViewMinification(z.content,o),Pe=[M.SIGNATURES_ONLY_HINT];return l&&Pe.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),z.hasSecrets&&Pe.push(`Secrets detected and redacted: ${z.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Ae,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Pt(e),...Ur(f,m),isPartial:!1,signaturesExtracted:!0,hints:Pe}}}let C=new Set,k=e,_=k.split(`
14
- `),E=Pt(k),O=e,x,H,I=!1,v;if(i)O=e;else if(l){let Z=d===!0,z;try{z=Li(_,l,c,u??!1,Z)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...Ur(f,m),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(z.matchCount===0){let K=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${Z?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${Z?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...Ur(f,m),matchNotFound:!0,searchedFor:l,hints:K}}O=z.lines.join(`
15
- `);let Ae=z.matchRanges[0],Pe=z.matchRanges[z.matchRanges.length-1];s=Ae.start,a=Pe.end,x=Ae.start,H=Pe.end,I=!0,z.matchRanges.length>1&&(v=z.matchRanges);let mt=z.matchingLines.slice(0,5).join(", "),Vt=z.matchingLines.length>5?` and ${z.matchingLines.length-5} more`:"";C.add(z.matchCount>1?`Found ${z.matchCount} occurrences of "${l}" on lines ${mt}${Vt} \u2014 all shown as ${z.matchRanges.length} slice${z.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${z.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let Z=s||1,z=a||E;if(Z<1||Z>E)O=e;else if(z<Z)O=e;else{let Ae=Math.max(1,Z),Pe=Math.min(E,z),mt=_.slice(Ae-1,Pe);x=Ae,H=Pe,I=!0,O=mt.join(`
16
- `),z>E&&C.add(`Requested endLine ${z} adjusted to ${E} (file end)`)}}let D=Xf.sanitizeContent(O,o);if(O=g?M.applyContentViewMinification(D.content,o):D.content,D.hasSecrets&&C.add(`Secrets detected and redacted: ${D.secretsDetected.join(", ")}`),D.warnings.length>0&&D.warnings.forEach(Z=>C.add(Z)),E>2e3&&p!=="symbols"&&!l&&!s&&!a&&!i){let Z=Math.max(1,E-200);C.add(`Large file (${E} lines) \u2014 minify:"symbols" for an export index, or startLine=${Z} for the tail.`)}let B=Array.from(C);return{owner:t,repo:n,path:o,content:O,...b!=="standard"&&{contentView:b},branch:r,totalLines:E,...Ur(f,m),...I&&{startLine:x,endLine:H,isPartial:I},...v&&{matchRanges:v},...B.length>0&&{matchLocations:B},...(B.length>0||S)&&{warnings:[...S?[S]:[],...B]}}}var tm=y(()=>{"use strict";zr();fe();ge();Qr();ki();vc();Ac();Ii()});async function nm(e,t,n){let r=Qe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await Ue(r,async()=>await Ei(e,t),{shouldCache:f=>"data"in f&&!f.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await em(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,l=e.charOffset??0,u=e.charLength,d=a?c:Jf(c,l,u),p=(e.charOffset??0)>0;if(!e.noTimestamp&&!p)try{let f=await ue(t),m=await Ue(Qe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>Zf(f,e.owner,e.repo,e.path,e.branch),{shouldCache:g=>g!==null,forceRefresh:e.forceRefresh===!0});m&&(d.lastModified=m.lastModified,d.lastModifiedBy=m.lastModifiedBy)}catch{}return{data:d,status:200,rawResponseChars:o.rawResponseChars}}var rm=y(()=>{"use strict";Be();Nt();Ec();tm()});function iT(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:sT(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function sT(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function om(e,t,n=be){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await nm(i,t);if(Qn(s))return Ct(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:iT(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s.data),...a?.length?{hints:a}:{}}}var im=y(()=>{"use strict";rm();xi();ie();ht();ht()});function $r(e,t=lT){let n=e?Br(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function sm(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return M.filterPatch(e,r)}function am(e){return e?M.filterPatch(e,{trimContext:!0,contextLines:cT}):""}var cT,lT,Fi=y(()=>{"use strict";ge();Qr();cT=2,lT=20});import{ContentSanitizer as cm}from"@octocodeai/octocode-engine/contentSanitizer";function Lc(e){let t=cm.sanitizeContent(e.title??""),n=e.body?cm.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function um(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function jr(e,t={}){let n=t.charOffset??0,r=t.charLength??uT,o=t.charLength??dT,i=typeof e.body=="string"?M.minifyMarkdownCore(e.body):e.body,s=um(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((m,g)=>{let b=m.commentType==="review_inline"?0:1,S=g.commentType==="review_inline"?0:1;return b-S}),c=a.filter(m=>m.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,lm),d=u.map(m=>{let g=um(m.body,n,o,!t.includeFullCommentDetails);return{...m,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),p=!t.includeFullCommentDetails&&(a.length>u.length||d.some(m=>"body_pagination"in m)),f=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...p?[`PR comments are paginated/summarized to ${lm} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(m=>({id:0,name:m,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((m,g)=>m+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((m,g)=>m+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(m=>({filename:m.filename,status:m.status,additions:m.additions,deletions:m.deletions,patch:m.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...p?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||f.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...f]}}}function qr(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function Mi(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?sm(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?am(a.patch):a.patch}))}var uT,dT,lm,Di=y(()=>{"use strict";Fi();ge();zr();uT=Ze(),dT=Math.round(Ze()/4),lm=3});import{ContentSanitizer as _c}from"@octocodeai/octocode-engine/contentSanitizer";function Ni(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function dm(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function pm(e){let t=dm(e);return t?t.discussion!==!1:!1}function fm(e){let t=dm(e);return t?t.reviewInline!==!1:!1}function mm(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function gm(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function hm(e){return!!e.content?.comments?.includeBots}function ym(e){let t=e.toLowerCase();return t.endsWith("[bot]")||pT.has(t.replace(/\[bot\]$/,""))}function Ic(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
8
+ var nP=Object.defineProperty;var y=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var rP=(e,t)=>{for(var n in t)nP(e,n,{get:t[n],enumerable:!0})};import{completeMetadata as oP}from"@octocodeai/octocode-core";function Sr(e=process.env){let t=e.ENABLE_OQL;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var q,De,an,aN,Mo=y(()=>{"use strict";q=oP.toolNames,De=q.LSP_GET_SEMANTIC_CONTENT,an="oqlSearch";aN=new Set([q.LOCAL_RIPGREP,q.LOCAL_FETCH_CONTENT,q.LOCAL_FIND_FILES,q.LOCAL_VIEW_STRUCTURE,q.LOCAL_BINARY_INSPECT,De])});function cn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function fa(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var Bu,Pr=y(()=>{"use strict";Mo();Bu=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});var Se=y(()=>{"use strict"});import{z as Do}from"zod";function H(e,t){return Do.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Do.number().int().min(e).max(t))}function se(e,t={}){let{maxQueries:n=5}=t;return Do.object({queries:Do.array(e).min(1).max(n).describe("Parallel queries."),...sP}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var ue,An,Ln,sP,Be=y(()=>{"use strict";Se();ue=H(1,1e3).optional().default(1),An=H(0,100).optional(),Ln=H(1,1e9).optional(),sP={responseCharOffset:H(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:H(1,5e4).optional().describe("Full-response char window.")}});import{z as $u}from"zod";function aP(e,t){return e?.description&&!t.description?t.describe(e.description):t}function ju(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=aP(e.shape[r],o);return n}function cP(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Uu(e,t){if(!t?.length)return e;let n=new Set(t);return $u.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function fe(e,t={},n={}){let r=Uu(e,n.omit),o=cP(r,ju(r,t));return n.strict?o.strict():o}function ye(e,t={},n={}){let r=Uu(e,n.omit),o=$u.object({...r.shape,...ju(r,t)});return n.strict?o.strict():o}var Je=y(()=>{"use strict"});import{z as oe}from"zod";var xe,No,Cr,qu,mt=y(()=>{"use strict";xe=oe.object({currentPage:oe.number(),totalPages:oe.number(),hasMore:oe.boolean(),nextPage:oe.number().optional(),pageSize:oe.number().optional(),totalItems:oe.number().optional()}),No=oe.object({charOffset:oe.number(),charLength:oe.number(),totalChars:oe.number(),hasMore:oe.boolean(),nextCharOffset:oe.number().optional(),currentPage:oe.number().optional(),totalPages:oe.number().optional(),chunkMode:oe.enum(["semantic","char-limit"]).optional()}),Cr=oe.object({tool:oe.string(),query:oe.record(oe.string(),oe.unknown()),why:oe.string().optional(),confidence:oe.enum(["exact","heuristic"]).optional()}),qu=oe.object({level:oe.enum(["info","warning","error"]),message:oe.string(),field:oe.string().optional(),code:oe.string().optional()})});import{z as J}from"zod";function lP(e){return J.object({id:J.string(),status:J.enum(["empty","error"]).optional(),data:e,diagnostics:J.array(qu).optional(),next:J.record(J.string(),Cr).optional()})}var Wu,$e,PN,Ct,Ze=y(()=>{"use strict";mt();Wu=J.object({currentPage:J.number(),totalPages:J.number(),hasMore:J.boolean(),charOffset:J.number(),charLength:J.number(),totalChars:J.number(),nextCharOffset:J.number().optional()}).optional(),$e={base:J.string().optional(),shared:J.record(J.string(),J.union([J.string(),J.number(),J.boolean()])).optional(),responsePagination:Wu};PN=lP(J.record(J.string(),J.unknown()).optional()),Ct={base:J.string().optional(),shared:J.record(J.string(),J.union([J.string(),J.number(),J.boolean()])).optional(),responsePagination:Wu}});import{CloneRepoQuerySchema as uP}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as dP}from"@octocodeai/octocode-core/schemas/outputs";var wr,Go,ON,ga=y(()=>{"use strict";Be();Je();Ze();wr=fe(uP),Go=se(wr),ON=dP.extend($e)});import{z as T}from"zod";import{FileContentQuerySchema as Vu}from"@octocodeai/octocode-core/schemas";var pP,fP,mP,gP,hP,Ku,yP,_n,Ho,DN,zo=y(()=>{"use strict";Se();Be();Je();Ze();pP=T.enum(["none","standard","symbols"]).optional().default("standard"),fP=T.object({currentPage:T.number(),totalPages:T.number(),hasMore:T.boolean(),nextPage:T.number().optional(),charOffset:T.number().optional(),charLength:T.number().optional(),totalChars:T.number().optional(),nextCharOffset:T.number().optional()}),mP=T.object({continueChars:T.object({tool:T.literal("ghGetFileContent"),query:T.record(T.string(),T.unknown())}).optional()}),gP=T.object({path:T.string(),content:T.string(),localPath:T.string().optional(),repoRoot:T.string().optional(),contentView:T.enum(["none","standard","symbols"]).optional(),isSkeleton:T.boolean().optional(),totalLines:T.number().optional(),sourceChars:T.number().optional(),sourceBytes:T.number().optional(),resolvedBranch:T.string().optional(),pagination:fP.optional(),next:mP.optional(),isPartial:T.boolean().optional(),startLine:T.number().optional(),endLine:T.number().optional(),matchRanges:T.array(T.object({start:T.number(),end:T.number()})).optional(),lastModified:T.string().optional(),lastModifiedBy:T.string().optional(),warnings:T.array(T.string()).optional(),matchNotFound:T.boolean().optional(),searchedFor:T.string().optional(),cached:T.boolean().optional()}),hP=T.object({path:T.string(),localPath:T.string(),repoRoot:T.string().optional(),fileCount:T.number(),totalSize:T.number(),complete:T.boolean().optional(),directoryEntryCount:T.number().optional(),eligibleFileCount:T.number().optional(),savedFileCount:T.number().optional(),skipped:T.object({nonFile:T.number(),missingDownloadUrl:T.number(),oversized:T.number(),binary:T.number(),fileLimit:T.number(),fetchFailed:T.number(),totalSizeLimit:T.number(),pathTraversal:T.number()}).optional(),limits:T.object({maxDirectoryFiles:T.number(),maxTotalSize:T.number(),maxFileSize:T.number()}).optional(),warnings:T.array(T.string()).optional(),files:T.array(T.object({path:T.string(),size:T.number(),type:T.string()})).optional(),cached:T.boolean().optional(),resolvedBranch:T.string().optional()}),Ku={startLine:Ln,endLine:Ln,contextLines:An,charOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional(),minify:pP},yP=ye(Vu,Ku),_n=fe(Vu,Ku),Ho=se(yP),DN=T.object({base:T.string().optional(),shared:T.record(T.string(),T.union([T.string(),T.number(),T.boolean()])).optional(),responsePagination:$e.responsePagination,results:T.array(T.object({id:T.string(),data:T.object({owner:T.string(),repo:T.string(),files:T.array(gP).optional(),directories:T.array(hP).optional()}).optional()})),errors:T.array(T.object({id:T.string(),owner:T.string().optional(),repo:T.string().optional(),path:T.string().optional(),error:T.string()})).optional()})});import{z as B}from"zod";import{GitHubCodeSearchQuerySchema as Yu}from"@octocodeai/octocode-core/schemas";var Xu,Qo,Bo,bP,UN,ha=y(()=>{"use strict";Se();Be();Je();Ze();mt();Xu={limit:H(1,100).optional(),page:ue.default(1)},Qo=fe(Yu,Xu),Bo=se(ye(Yu,Xu)),bP=xe.extend({totalMatchesKind:B.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:B.boolean().optional(),uniqueFileCount:B.number().optional()}),UN=B.object({base:B.string().optional(),shared:B.record(B.string(),B.union([B.string(),B.number(),B.boolean()])).optional(),responsePagination:$e.responsePagination,results:B.array(B.object({id:B.string(),data:B.object({files:B.array(B.object({owner:B.string(),repo:B.string(),path:B.string(),queryId:B.string().optional(),matches:B.array(B.object({value:B.string().optional(),pathOnly:B.boolean().optional(),matchIndices:B.array(B.object({start:B.number(),end:B.number(),lineOffset:B.number()})).optional(),url:B.string().optional()}))})),pagination:bP.optional()})})),emptyQueries:B.array(B.object({id:B.string(),nonExistentScope:B.literal(!0).optional(),incompleteResults:B.literal(!0).optional()})).optional(),warnings:B.array(B.string()).optional(),errors:B.array(B.object({id:B.string(),error:B.string()})).optional()})});import{z as ln}from"zod";import{GitHubPullRequestSearchQuerySchema as Ju}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as SP}from"@octocodeai/octocode-core/schemas/outputs";var Zu,PP,Fn,$o,eG,jo=y(()=>{"use strict";Se();Be();Je();Ze();Zu={perPage:H(1,100).optional().default(30),prNumber:H(1,1e9).optional(),limit:H(1,100).optional().default(30),page:ue.default(1),filePage:ue.optional(),commentPage:ue.optional(),commitPage:ue.optional(),itemsPerPage:H(1,100).optional().default(20),charOffset:H(0,1e8).optional(),commentBodyOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional()},PP=ye(Ju,Zu),Fn=fe(Ju,Zu),$o=se(PP),eG=SP.extend({results:ln.array(ln.object({id:ln.string().optional(),status:ln.string().optional(),data:ln.object({pull_requests:ln.array(ln.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...$e})});import{z as ne}from"zod";import{GitHubReposSearchSingleQuerySchema as ed}from"@octocodeai/octocode-core/schemas";var td,Uo,qo,CP,wP,xP,lG,ya=y(()=>{"use strict";Se();Be();Je();Ze();mt();td={limit:H(1,100).optional(),page:ue.default(1)},Uo=fe(ed,td),qo=se(ye(ed,td)),CP=ne.object({owner:ne.string(),repo:ne.string(),stars:ne.number().optional(),forks:ne.number().optional(),openIssuesCount:ne.number().optional(),language:ne.string().optional(),license:ne.string().optional(),description:ne.string().optional(),homepage:ne.string().optional(),pushedAt:ne.string().optional(),createdAt:ne.string().optional(),defaultBranch:ne.string().optional(),topics:ne.array(ne.string()).optional(),visibility:ne.string().optional(),url:ne.string().optional(),updatedAt:ne.string().optional()}),wP=xe.extend({totalMatchesKind:ne.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:ne.boolean().optional()}).optional(),xP=ne.object({repositories:ne.array(ne.union([ne.string(),CP])).optional(),pagination:wP}).passthrough(),lG=ne.object({results:ne.array(ne.object({id:ne.string().optional(),status:ne.string().optional(),data:xP.optional()}).passthrough()).optional()}).extend($e)});import{GitHubViewRepoStructureQuerySchema as nd}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as kP}from"@octocodeai/octocode-core/schemas/outputs";var rd,Wo,Vo,bG,ba=y(()=>{"use strict";Se();Se();Be();Je();Ze();rd={maxDepth:H(0,20).optional(),page:ue.default(1),itemsPerPage:H(1,200).optional()},Wo=fe(nd,rd),Vo=se(ye(nd,rd)),bG=kP.extend($e)});import{z as te}from"zod";import{NpmPackageQuerySchema as od}from"@octocodeai/octocode-core/schemas";var id,Ko,Yo,kG,Ra=y(()=>{"use strict";Be();Je();Ze();mt();id={page:ue,mode:te.enum(["lean","full"]).optional()},Ko=fe(od,id),Yo=se(ye(od,id,{strict:!0}),{maxQueries:5}),kG=te.object({results:te.array(te.looseObject({id:te.string(),data:te.looseObject({packages:te.array(te.object({name:te.string(),version:te.string().optional(),description:te.string().optional(),license:te.string().optional(),downloads:te.number().optional(),repository:te.string().optional(),repositoryDirectory:te.string().optional(),repositoryId:te.string().optional(),next:te.record(te.string(),te.unknown()).optional()}).passthrough()).optional(),repositories:te.record(te.string(),te.object({repository:te.string(),owner:te.string(),repo:te.string(),repositoryDirectory:te.string().optional(),next:te.record(te.string(),te.unknown())}).passthrough()).optional(),pagination:xe.optional()}).optional(),status:te.string().optional()})).optional()}).extend($e)});import{z as ie}from"zod";import{FetchContentQuerySchema as sd}from"@octocodeai/octocode-core/schemas";var EP,ad,OP,Mn,Xo,vP,AP,MG,Jo=y(()=>{"use strict";Se();Be();Je();Ze();mt();EP=ie.enum(["none","standard","symbols"]).optional().default("standard"),ad={startLine:Ln,endLine:Ln,contextLines:An.default(5),charOffset:H(0,1e8).optional(),charLength:H(1,5e4).optional(),minify:EP},OP=ye(sd,ad),Mn=fe(sd,ad),Xo=se(OP,{maxQueries:5}),vP=ie.object({start:ie.number(),end:ie.number()}),AP=ie.object({path:ie.string().optional(),content:ie.string().optional(),contentView:ie.enum(["none","standard","symbols"]).optional(),isSkeleton:ie.boolean().optional(),totalLines:ie.number().optional(),sourceChars:ie.number().optional(),startLine:ie.number().optional(),endLine:ie.number().optional(),isPartial:ie.boolean().optional(),matchRanges:ie.array(vP).optional(),pagination:ie.union([No,xe]).optional(),modified:ie.string().optional(),lastModified:ie.string().optional(),lastModifiedBy:ie.string().optional(),warnings:ie.array(ie.string()).optional(),matchNotFound:ie.boolean().optional(),searchedFor:ie.string().optional()}),MG=ie.object({results:ie.array(ie.object({id:ie.string(),status:ie.enum(["empty","error"]).optional(),data:AP}))}).extend(Ct)});import{z as be}from"zod";import{FindFilesQuerySchema as LP}from"@octocodeai/octocode-core/schemas";function _P(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 cd,ld,IP,Dn,Zo,FP,MP,jG,ei=y(()=>{"use strict";Se();Be();Je();Ze();mt();cd={maxDepth:H(0,100).optional(),minDepth:H(0,100).optional(),limit:H(1,1e4).optional(),page:ue.default(1),itemsPerPage:H(1,50).optional()},ld=be.object(Object.fromEntries(Object.entries(LP.shape).filter(([e])=>e!=="regexType")));IP=ye(ld,cd),Dn=fe(ld,cd).superRefine(_P),Zo=se(IP,{maxQueries:5}),FP=be.object({name:be.string().optional(),path:be.string().optional(),type:be.enum(["file","dir","directory","link","symlink"]).optional(),size:be.union([be.number(),be.string()]).optional(),modified:be.string().optional(),accessed:be.string().optional(),created:be.string().optional(),permissions:be.string().optional()}),MP=be.object({files:be.array(FP).optional(),summary:be.string().optional(),pagination:xe.optional(),warnings:be.array(be.string()).optional()}),jG=be.object({results:be.array(be.object({id:be.string(),status:be.enum(["empty","error"]).optional(),data:MP}))}).extend(Ct)});import{z as V}from"zod";import{RipgrepQuerySchema as ud}from"@octocodeai/octocode-core/schemas";var DP,NP,dd,GP,HP,zP,Ut,ti,QP,BP,$P,ZG,kr=y(()=>{"use strict";Se();Be();Je();Ze();mt();DP=["paginated","discovery","detailed","structural"],NP=["semanticRanking"],dd={mode:V.enum(DP).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters.'),pattern:V.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:V.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:An,matchContentLength:H(1,1e5).optional().default(500),maxMatchesPerFile:H(1,1e5).optional(),maxFiles:H(1,1e5).optional(),matchPage:ue.optional(),itemsPerPage:H(1,1e3).optional(),page:ue.default(1),unique:V.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:V.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},GP={...dd,semanticRanking:V.never().optional()},HP=ye(ud,GP),zP=fe(ud,dd,{strict:!0,omit:NP}),Ut=zP.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),ti=se(HP,{maxQueries:5}),QP=V.object({line:V.number(),endLine:V.number().optional(),value:V.string().optional(),column:V.number().optional(),count:V.number().optional(),metavars:V.record(V.string(),V.array(V.string())).optional()}),BP=V.object({path:V.string(),matches:V.array(QP).optional(),totalOccurrences:V.number().optional(),totalMatchedLines:V.number().optional(),totalMatchRows:V.number().optional(),returnedMatchRows:V.number().optional(),matchPagination:xe.optional(),next:V.record(V.string(),Cr).optional()}),$P=V.object({files:V.array(BP).optional(),summary:V.string().optional(),searchEngine:V.string().optional(),pagination:xe.optional(),next:V.record(V.string(),Cr).optional(),warnings:V.array(V.string()).optional()}),ZG=V.object({results:V.array(V.object({id:V.string(),status:V.enum(["empty","error"]).optional(),data:$P}))}).extend(Ct)});import{z as Z}from"zod";import{ViewStructureQuerySchema as pd}from"@octocodeai/octocode-core/schemas";var fd,jP,Nn,ni,UP,qP,cH,ri=y(()=>{"use strict";Se();Be();Je();Ze();mt();fd={maxDepth:H(0,20).optional(),limit:H(1,1e4).optional(),page:ue.default(1),itemsPerPage:H(1,50).optional()},jP=ye(pd,fd),Nn=fe(pd,fd),ni=se(jP,{maxQueries:5}),UP=Z.object({name:Z.string().optional(),type:Z.enum(["file","dir","directory","link","symlink"]),path:Z.string().optional(),depth:Z.number().optional(),size:Z.union([Z.number(),Z.string()]).optional(),modified:Z.string().optional(),permissions:Z.string().optional()}),qP=Z.object({path:Z.string().optional(),entries:Z.array(UP).optional(),files:Z.array(Z.string()).optional(),folders:Z.array(Z.string()).optional(),links:Z.array(Z.string()).optional(),summary:Z.union([Z.string(),Z.record(Z.string(),Z.unknown())]).optional(),pagination:xe.optional(),warnings:Z.array(Z.string()).optional()}),cH=Z.object({results:Z.array(Z.object({id:Z.string(),status:Z.enum(["empty","error"]).optional(),data:qP}))}).extend(Ct)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as hd}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as WP}from"@octocodeai/octocode-core/schemas/outputs";var VP,KP,YP,yd,XP,si,ai,md,JP,ZP,oi,ii,eC,tC,bd,Gn,nC,rC,oC,Rd,iC,sC,aC,cC,lC,uC,dC,gd,bH,Ca=y(()=>{"use strict";Se();Be();Je();Pr();mt();VP=H(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),KP=H(0,1e5).optional(),YP=["structured","compact"],yd={type:R.enum(Bu).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:R.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:VP.optional(),orderHint:KP,depth:H(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:ue,itemsPerPage:H(1,100).optional(),contextLines:H(0,100).optional(),format:R.enum(YP).optional().default("structured")},XP=ye(hd,yd),si=fe(hd,yd),ai=se(XP,{maxQueries:5}),md=R.object({line:R.number(),character:R.number()}),JP=R.object({start:md,end:md}),ZP=R.object({startLine:R.number(),endLine:R.number()}),oi=R.object({uri:R.string(),content:R.string().optional(),displayRange:ZP.optional(),isDefinition:R.boolean().optional()}),ii=R.string(),eC=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),tC=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),bd=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Gn=R.object({category:bd,reason:R.string()}),nC=xe,rC=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),oC=R.string(),Rd=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),iC=R.string(),sC=R.object({direction:R.enum(["incoming","outgoing"]),item:Rd,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),aC=R.string(),cC=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),lC=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),uC=R.string(),dC=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([oi,ii]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([oi,ii]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([oi,ii]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([oi,ii])).optional(),byFile:R.array(R.union([lC,uC])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:Gn.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([Rd,iC]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([sC,aC])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:cC,empty:Gn.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:JP.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([rC,oC])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:Gn.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:Gn.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:Gn.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:Gn.optional()}),R.object({kind:R.literal("empty"),category:bd,reason:R.string()})]),gd=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:eC.optional(),lsp:tC.optional(),payload:dC,pagination:nC.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),bH=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:gd}),R.object({id:R.string().min(1),status:R.literal("error"),data:WP}),R.object({id:R.string().min(1),data:gd})]))})});import{z as I}from"zod";import{LocalBinaryInspectQuerySchema as pC}from"@octocodeai/octocode-core/schemas";var fC,Sd,Hn,ci,mC,gC,hC,yC,bC,RC,SC,TH,li=y(()=>{"use strict";Be();Ze();mt();fC={entryPageNumber:ue.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:H(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:H(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:ue.default(1).describe("1-based page for paginated entry/content listings."),detailed:I.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Sd=I.object({...pC.shape,...fC}),Hn=Sd.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),ci=se(Sd,{maxQueries:5}),mC=I.object({path:I.string(),mode:I.literal("inspect"),format:I.string().optional(),size:I.number().optional(),isText:I.boolean().optional(),encoding:I.string().optional(),symbols:I.array(I.string()).optional(),imports:I.array(I.string()).optional(),exports:I.array(I.string()).optional(),sections:I.array(I.string()).optional(),warnings:I.array(I.string()).optional()}),gC=I.object({name:I.string(),size:I.number().optional(),compressedSize:I.number().optional(),isDir:I.boolean().optional(),modified:I.string().optional()}),hC=I.object({path:I.string(),mode:I.literal("list"),entries:I.array(gC).optional(),pagination:xe.optional(),warnings:I.array(I.string()).optional()}),yC=I.object({path:I.string(),mode:I.enum(["extract","decompress"]),archiveFile:I.string().optional(),content:I.string().optional(),isPartial:I.boolean().optional(),pagination:No.optional(),warnings:I.array(I.string()).optional()}),bC=I.object({path:I.string(),mode:I.literal("strings"),strings:I.array(I.object({value:I.string(),offset:I.number().optional()})).optional(),content:I.string().optional(),totalStrings:I.number().optional(),scanOffset:I.number().optional(),nextScanOffset:I.number().optional(),hasMore:I.boolean().optional(),warnings:I.array(I.string()).optional()}),RC=I.object({path:I.string(),mode:I.literal("unpack"),localPath:I.string().optional(),fileCount:I.number().optional(),totalSize:I.number().optional(),warnings:I.array(I.string()).optional()}),SC=I.union([mC,hC,yC,bC,RC]),TH=I.object({results:I.array(I.object({id:I.string(),status:I.enum(["empty","error","success"]).optional(),data:SC}))}).extend(Ct)});function wd(e){return Array.isArray(e.queries)}function xd(e){return Array.isArray(e.queries)}function Td(e){return Array.isArray(e.children)}var un,ui,Pd,Cd,zn=y(()=>{"use strict";un=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],ui=["fixes","dataflow"],Pd=["packages","repositories"],Cd={code:["relevance","matchCount","path","modified","accessed","created"],files:["size","name","path","modified"]}});import{z as h}from"zod";var xa,wa,PC,kd,Ed,CC,wC,Qn,Od,xC,TC,dn,vd,Ad,Ld,_d,di,kC,AH,Id,Fd,Md,Dd,pi,Nd,Gd,Bn,Er=y(()=>{"use strict";zn();xa=h.lazy(()=>h.union([h.strictObject({kind:h.literal("local"),path:h.string().min(1)}),h.strictObject({kind:h.literal("github"),repo:h.string().min(1).optional(),owner:h.string().min(1).optional(),ref:h.string().min(1).optional()}),h.strictObject({kind:h.literal("materialized"),localPath:h.string().min(1),source:xa.optional()}),h.strictObject({kind:h.literal("npm")})])),wa=h.union([h.string(),h.array(h.string()).max(100)]),PC=h.strictObject({path:wa.optional(),language:wa.optional(),include:h.array(h.string()).max(100).optional(),exclude:h.array(h.string()).max(100).optional(),excludeDir:h.array(h.string()).max(100).optional(),hidden:h.boolean().optional(),noIgnore:h.boolean().optional(),minDepth:h.number().int().min(0).max(64).optional(),maxDepth:h.number().int().min(0).max(64).optional()}).optional(),kd=h.enum(["smart","sensitive","insensitive"]),Ed=h.string().max(1e4),CC=h.strictObject({id:h.string().optional(),kind:h.literal("text"),value:Ed,case:kd.optional(),wholeWord:h.boolean().optional()}),wC=h.strictObject({id:h.string().optional(),kind:h.literal("regex"),value:Ed,dialect:h.enum(["rust","pcre2","provider"]).optional(),case:kd.optional(),wholeWord:h.boolean().optional(),multiline:h.boolean().optional(),dotAll:h.boolean().optional()}),Qn=h.lazy(()=>h.strictObject({pattern:h.string().optional(),kind:h.string().optional(),inside:Qn.optional(),has:Qn.optional(),not:Qn.optional(),all:h.array(Qn).optional(),any:h.array(Qn).optional(),stopBy:h.literal("end").optional()})),Od=h.union([Qn,h.string().min(1)]),xC=h.strictObject({id:h.string().optional(),kind:h.literal("structural"),lang:h.string().min(1),pattern:h.string().optional(),rule:Od.optional()}),TC=h.strictObject({id:h.string().optional(),kind:h.literal("field"),field:h.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:h.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:h.unknown().optional()}),dn=h.lazy(()=>h.discriminatedUnion("kind",[h.strictObject({kind:h.literal("all"),id:h.string().optional(),of:h.array(dn).min(1)}),h.strictObject({kind:h.literal("any"),id:h.string().optional(),of:h.array(dn).min(1)}),h.strictObject({kind:h.literal("not"),id:h.string().optional(),predicate:dn}),CC,wC,xC,TC])),vd=h.strictObject({mode:h.enum(["never","auto","required"]),strategy:h.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:h.boolean().optional(),forceRefresh:h.boolean().optional()}),Ad=h.strictObject({content:h.strictObject({range:h.strictObject({startLine:h.number().int().min(1).optional(),endLine:h.number().int().min(1).optional(),contextLines:h.number().int().min(0).max(100).optional()}).optional(),match:h.strictObject({text:h.string(),regex:h.boolean().optional(),caseSensitive:h.boolean().optional()}).optional(),contentView:h.enum(["exact","compact","symbols"]).optional(),charOffset:h.number().int().min(0).max(1e8).optional(),charLength:h.number().int().min(1).max(5e4).optional(),fullContent:h.boolean().optional()}).optional(),tree:h.strictObject({maxDepth:h.number().int().min(0).max(64).optional(),pattern:h.string().optional(),includeSizes:h.boolean().optional(),extensions:h.array(h.string()).optional(),filesOnly:h.boolean().optional(),directoriesOnly:h.boolean().optional(),sortBy:h.enum(["name","size","time","extension"]).optional(),reverse:h.boolean().optional()}).optional()}),Ld=h.strictObject({search:h.strictObject({countLinesPerFile:h.boolean().optional(),countMatchesPerFile:h.boolean().optional(),onlyMatching:h.boolean().optional(),unique:h.boolean().optional(),countUnique:h.boolean().optional(),contextLines:h.number().int().min(0).max(100).optional(),invertMatch:h.boolean().optional(),matchWindow:h.number().int().min(0).optional(),matchContentLength:h.number().int().min(1).optional(),maxMatchesPerFile:h.number().int().min(1).optional(),matchPage:h.number().int().min(1).optional(),sort:h.enum(["relevance","matchCount","path","modified","accessed","created","size","name"]).optional(),sortReverse:h.boolean().optional(),rankingProfile:h.string().optional(),debugRanking:h.boolean().optional()}).optional(),budget:h.strictObject({maxFiles:h.number().int().min(1).optional(),maxCandidates:h.number().int().min(1).optional(),maxBytes:h.number().int().min(1).optional(),maxMaterializedBytes:h.number().int().min(1).optional(),maxPlanNodes:h.number().int().min(1).optional(),maxBooleanExpansion:h.number().int().min(1).optional(),timeoutMs:h.number().int().min(1).optional()}).optional()}),_d=h.enum(["discovery","paginated","detailed"]),di=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),target:h.enum(un),from:xa.optional(),scope:PC,where:dn.optional(),materialize:vd.optional(),fetch:Ad.optional(),select:h.array(h.string()).optional(),view:_d.optional(),controls:Ld.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional()}),kC=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),queries:h.array(di).min(1).max(5),combine:h.enum(["independent","merge"]).optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),explain:h.boolean().optional()}),AH=h.union([di,kC]),Id=[...un,...ui],Fd={schema:h.literal("oql").optional(),id:h.string().optional(),mainResearchGoal:h.string().optional(),researchGoal:h.string().optional(),reasoning:h.string().optional()},Md={...Fd,target:h.enum(Id).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:xa.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:dn.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:h.union([vd,h.enum(["never","auto","required"])]).optional(),fetch:Ad.optional(),select:h.array(h.string()).optional(),view:_d.optional(),controls:Ld.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional(),repo:h.string().optional(),owner:h.string().optional(),ref:h.string().optional(),path:wa.optional(),text:h.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:h.string().optional(),pattern:h.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:Od.optional(),lang:h.string().optional(),and:h.array(h.unknown()).optional(),or:h.array(h.unknown()).optional(),xor:h.array(h.unknown()).optional(),noneOf:h.array(h.unknown()).optional(),oneOf:h.array(h.unknown()).optional(),invert:h.unknown().optional(),filesOnly:h.boolean().optional(),filesWithoutMatch:h.boolean().optional(),verbose:h.boolean().optional()},Dd={...Md,target:h.enum(Id).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},pi=h.object(Dd).catchall(h.unknown()),Nd=h.object(Md).catchall(h.unknown()),Gd=h.object({...Fd,queries:h.array(h.unknown()).min(1)}).catchall(h.unknown()),Bn=h.object({...Dd,queries:h.array(h.unknown()).min(1).max(5).optional(),combine:h.enum(["independent","merge"]).optional()}).catchall(h.unknown())});import{z as Ta}from"zod";function vr(e){return jd.find(t=>t.name===e)}function Or(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===q.PACKAGE_SEARCH?"Package":"Other"}function vC(e){return[...e].sort((t,n)=>{let r=ka.indexOf(Or(t)),o=ka.indexOf(Or(n));if(r!==o)return r-o;let i=Hd.get(t)??Number.MAX_SAFE_INTEGER,s=Hd.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function AC(e){let t=vr(e);if(!t)return"{}";try{return JSON.stringify(Ta.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(Ta.toJSONSchema(t.schema,{io:"input"}),null,2)}}function LC(e){return JSON.stringify(e??{},null,2)}function _C(e){let t=Or(e),n=[...OC];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function IC(){return $d.map(e=>({...e}))}function FC(){return JSON.stringify(Object.fromEntries($d.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function MC(e,t){return t?.tools?.[e]?.description??e}function _a(e){let t=vr(e);if(!t)return[];let n=Ta.toJSONSchema(t.schema,{io:"input"});if(!$n(n))return[];let r=qt(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!La.has(i)&&!Aa(r[i])):[]);return va(r,o)}function zd(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function DC(e){let t=HC(e);if(t.length>0)return t.map(r=>({...r,command:zd(e,r.query)}));let n=GC(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:zd(e,n)}]}function NC(e){return DC(e)[0]?.query??{}}function GC(e){if(!vr(e))return{};let t=_a(e),n=t.filter(i=>!i.name.includes(".")),r=WC(n),o={};for(let i of r)o[i.name]=XC(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===De&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function HC(e){return e===an?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===q.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"2024-01-01T00:00:00Z",perPage:5}}]:e===q.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===q.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===q.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===q.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===q.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:e===q.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"src/index.ts",startLine:1,endLine:40,minify:"none"}},{label:"matched slice",query:{path:"src/index.ts",matchString:"registerTool",contextLines:8,minify:"standard"}}]:e===q.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:".",names:["*.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/**",entryType:"f",itemsPerPage:20}}]:e===q.LOCAL_BINARY_INSPECT?[{label:"archive listing",query:{path:"archive.zip",mode:"list",entriesPerPage:50}},{label:"binary strings",query:{path:"dist/app.node",mode:"strings",minLength:8,charLength:2e3}}]:e===De?[{label:"semantic definition",query:{uri:"/path/to/file.ts",type:"definition",symbolName:"myFunction",lineHint:42}},{label:"symbol outline",query:{uri:"/path/to/file.ts",type:"documentSymbols"}}]:[]}function zC(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new ht("Tool input must be valid JSON.")}return Ud(e,r,n)}function Ud(e,t,n={}){let r=BC(e,t,n),o=vr(e);if(!o)throw new ht(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new ht("Tool input does not match the expected schema.",QC(i.error));return i.data}function QC(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function BC(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(qt(t)&&Array.isArray(t.queries))r=t.queries;else if(qt(t))r=[t];else throw new ht('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new ht("At least one query is required.");let o=qt(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>$C(e,a,UC(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function $C(e,t,n,r){let o={...n},i=Or(e),s=r.sourceLabel??"direct tool execution",a=jC(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 jC(e,t){return`Execute ${e} via ${t}`}function UC(e,t,n,r={}){if(!qt(t))throw new ht("Tool input must be a JSON object or an array of objects.");let o=new Set([..._a(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...La]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}if(s.length>0&&o.size>0&&(r.onUnknownFields?.(s,n),r.rejectUnknownFields===!0))throw new ht(`Unknown field(s): ${s.join(", ")}`,[`Remove unknown field(s) from query ${n+1}: ${s.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`]);return i}function qC(e){let t=[],n=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return n!==void 0&&r!==void 0?t.push(`${n}-${r}`):n!==void 0?t.push(`>=${n}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function Ea(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=$n(e.items)?e.items:void 0;return`array<${n?Ea(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter($n).map(Ea).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 WC(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&&VC(i)).sort(KC),o=Math.max(Qd,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=>!qd.has(i.name)).filter(i=>i.type!=="boolean").slice(0,Qd)}function VC(e){return qd.has(e.name)||e.type==="boolean"?!1:YC(e)?Oa.has(e.name):!0}function KC(e,t){let n=Oa.get(e.name)??Number.MAX_SAFE_INTEGER,r=Oa.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function YC(e){return e.constraints?.includes("default ")===!0}function va(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&La.has(o))continue;let s=$n(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Ea(s),constraints:qC(s),description:typeof s.description=="string"?s.description:void 0}),qt(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!Aa(s.properties?.[u]):!1):[]);r.push(...va(s.properties,l,a))}let c=s.type==="array"&&$n(s.items)?s.items:void 0;if(c&&qt(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!Aa(c.properties?.[u]):!1):[]);r.push(...va(c.properties,l,a))}}return r}function XC(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[Bd(e,n)]}return Bd(e,t)}function Bd(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 qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $n(e){return qt(e)}function Aa(e){return $n(e)&&"default"in e}var ka,Hd,ht,EC,La,OC,$d,jd,Qd,Oa,qd,Ia=y(()=>{"use strict";Mo();Pr();ga();zo();ha();jo();ya();ba();Ra();Jo();ei();kr();ri();Ca();li();Er();ka=["GitHub","Local Code","Package","Other"],Hd=new Map([q.GITHUB_SEARCH_CODE,q.GITHUB_SEARCH_REPOSITORIES,q.GITHUB_SEARCH_PULL_REQUESTS,q.GITHUB_FETCH_CONTENT,q.GITHUB_VIEW_REPO_STRUCTURE,q.GITHUB_CLONE_REPO,q.LOCAL_RIPGREP,q.LOCAL_FIND_FILES,q.LOCAL_FETCH_CONTENT,q.LOCAL_VIEW_STRUCTURE,De,q.PACKAGE_SEARCH,...Sr()?[an]:[]].map((e,t)=>[e,t])),ht=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},EC=["id","mainResearchGoal","researchGoal","reasoning"],La=new Set([...EC]),OC=["id","researchGoal","reasoning"],$d=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],jd=[{name:q.GITHUB_SEARCH_CODE,schema:Qo,inputSchema:Bo},{name:q.GITHUB_FETCH_CONTENT,schema:_n,inputSchema:Ho},{name:q.GITHUB_VIEW_REPO_STRUCTURE,schema:Wo,inputSchema:Vo},{name:q.GITHUB_SEARCH_REPOSITORIES,schema:Uo,inputSchema:qo},{name:q.GITHUB_SEARCH_PULL_REQUESTS,schema:Fn,inputSchema:$o},{name:q.PACKAGE_SEARCH,schema:Ko,inputSchema:Yo},{name:q.GITHUB_CLONE_REPO,schema:wr,inputSchema:Go},{name:q.LOCAL_RIPGREP,schema:Ut,inputSchema:ti},{name:q.LOCAL_VIEW_STRUCTURE,schema:Nn,inputSchema:ni},{name:q.LOCAL_FIND_FILES,schema:Dn,inputSchema:Zo},{name:q.LOCAL_FETCH_CONTENT,schema:Mn,inputSchema:Xo},{name:De,schema:si,inputSchema:ai},{name:q.LOCAL_BINARY_INSPECT,schema:Hn,inputSchema:ci},...Sr()?[{name:an,schema:pi,inputSchema:Bn}]:[]];Qd=4,Oa=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]]),qd=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});function Wt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function jn(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 fi(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var mi=y(()=>{"use strict"});function ZC(e){let t=Wt(e),n=Ar.get(t);return!n||Date.now()-n.cachedAt>=JC?!1:n.credentials?!jn(n.credentials):!0}function Fa(e){e?Ar.delete(Wt(e)):Ar.clear()}function Wd(e){let t=Wt(e);if(ZC(t))return Ar.get(t).credentials}function Vd(e,t){let n=Wt(e);Ar.set(n,{credentials:t,cachedAt:Date.now()})}var Ar,JC,Kd=y(()=>{"use strict";mi();Ar=new Map,JC=300*1e3});import ez from"node:fs";import nz from"node:path";import Yd from"node:os";import Un from"node:path";import{existsSync as dw,readFileSync as pw}from"node:fs";import fw from"node:path";function za(e=process.env){let t=e.OCTOCODE_HOME;if(t&&t.trim())return Un.resolve(t.trim());let n=Yd.homedir(),r=Yd.platform();if(r==="win32"){let i=e.APPDATA??Un.join(n,"AppData","Roaming");return Un.join(i,".octocode")}if(r==="darwin")return Un.join(n,".octocode");let o=e.XDG_CONFIG_HOME??Un.join(n,".config");return Un.join(o,".octocode")}function Qa(){return globalThis[tw]??"mcp"}function nw(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function Ga(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Jd(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function lp(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function rw(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function Ma(e,t){return e===void 0||e===null?null:lp(e,t)}function up(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function ow(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=nw(e.apiUrl,"github.apiUrl");r&&t.push(r)}function iw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Jd(n.enabled,"local.enabled");r&&t.push(r);let o=Jd(n.enableClone,"local.enableClone");o&&t.push(o);let i=lp(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=rw(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=up(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function sw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=Ma(n.enabled,"tools.enabled");r&&t.push(r);let o=Ma(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=Ma(n.disabled,"tools.disabled");i&&t.push(i)}function aw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=Ga(n.timeout,"network.timeout",rp,op);r&&t.push(r);let o=Ga(n.maxRetries,"network.maxRetries",ip,sp);o&&t.push(o)}function cw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=up(e.configPath,"lsp.configPath");r&&t.push(r)}function lw(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=Ga(r.defaultCharLength,"output.pagination.defaultCharLength",ap,cp);o&&t.push(o)}}function uw(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>Xd&&n.push(`version: Config version ${r.version} is newer than supported version ${Xd}`)),ow(r.github,t),iw(r.local,t),sw(r.tools,t),aw(r.network,t),cw(r.lsp,t),lw(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}function mw(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
9
+ `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t.replace(/,(\s*[}\]])/g,"$1")}function gw(e){return JSON.parse(mw(e))}function hw(e=za()){return fw.join(e,".octocoderc")}function yw(e){let t=hw(e);if(!dw(t))return{success:!1,error:"Config file does not exist",path:t};try{let n=pw(t,"utf-8");if(!n.trim())return{success:!0,config:{},path:t};let r=gw(n);return typeof r!="object"||r===null||Array.isArray(r)?{success:!1,error:"Config file has invalid structure: must be a JSON object",path:t}:{success:!0,config:r,path:t}}catch(n){return{success:!1,error:`Failed to parse config file: ${n instanceof Error?n.message:String(n)}`,path:t}}}function Zd(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Ha(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function yi(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function bw(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||tp.apiUrl}}function Rw(e){let t=Qa()==="cli",n=Zd(process.env.ENABLE_LOCAL),r=Zd(process.env.ENABLE_CLONE),o=yi(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??Lr.enabled,enableClone:r??e?.enableClone??(t?!0:Lr.enableClone),allowedPaths:o??e?.allowedPaths??Lr.allowedPaths,workspaceRoot:i??e?.workspaceRoot??Lr.workspaceRoot}}function Sw(e){let t=yi(process.env.TOOLS_TO_RUN),n=yi(process.env.ENABLE_TOOLS),r=yi(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??hi.enabled,enableAdditional:n??e?.enableAdditional??hi.enableAdditional,disabled:r??e?.disabled??hi.disabled}}function Pw(e){let t=Ha(process.env.REQUEST_TIMEOUT),n=Ha(process.env.MAX_RETRIES),r=t??e?.timeout??Na.timeout;r=Math.max(rp,Math.min(op,r));let o=n??e?.maxRetries??Na.maxRetries;return o=Math.max(ip,Math.min(sp,o)),{timeout:r,maxRetries:o}}function Cw(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??np.configPath}}function xw(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=Ha(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||qn.format,o=n??e?.pagination?.defaultCharLength??qn.pagination.defaultCharLength,i=Math.max(ap,Math.min(cp,o));return{format:ww.has(r)?r:qn.format,pagination:{defaultCharLength:i}}}function Da(e,t){let n=e!==void 0,r=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??ew.version,github:bw(e?.github),local:Rw(e?.local),tools:Sw(e?.tools),network:Pw(e?.network),lsp:Cw(e?.lsp),output:xw(e?.output),source:o,configPath:n?t:void 0}}function Tw(){let e=yw();return e.success&&e.config&&uw(e.config).valid?Da(e.config,e.path):Da(void 0)}function yt(){let e=Date.now();return gi&&e-ep<kw||(gi=Tw(),ep=e),gi}function dp(e=process.env){for(let t of Ew){let n=e[t];if(n?.trim())return{token:n.trim(),source:`env:${t}`}}return null}var Xd,tp,Lr,hi,Na,np,qn,ew,rp,op,ip,sp,ap,cp,tw,ww,gi,ep,kw,Ew,wt=y(()=>{"use strict";Xd=1,tp={apiUrl:"https://api.github.com"},Lr={enabled:!0,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},hi={enabled:null,enableAdditional:null,disabled:null},Na={timeout:3e4,maxRetries:3},np={configPath:void 0},qn={format:"yaml",pagination:{defaultCharLength:2e4}},ew={version:1,github:tp,local:Lr,tools:hi,network:Na,lsp:np,output:qn},rp=5e3,op=3e5,ip=0,sp=10,ap=1e3,cp=5e4,tw="__octocodeRuntimeSurface__";ww=new Set(["yaml","json"]);gi=null,ep=0,kw=6e4;Ew=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN"]});import{existsSync as Ow,mkdirSync as vw}from"node:fs";import{join as et}from"node:path";function Lw(){return za(process.env)}function _r(){return Ne}function pp(){Ow(ot.home)||vw(ot.home,{recursive:!0,mode:Aw})}var Aw,Ne,ot,Ir=y(()=>{"use strict";wt();Aw=448;Ne=Lw(),ot={home:Ne,config:et(Ne,".octocoderc"),credentials:et(Ne,"credentials.json"),key:et(Ne,".key"),session:et(Ne,"session.json"),stats:et(Ne,"stats.json"),tmp:et(Ne,"tmp"),clone:et(Ne,"tmp","clone"),tree:et(Ne,"tmp","tree"),binary:et(Ne,"tmp","binary"),repos:et(Ne,"tmp","clone"),unzip:et(Ne,"tmp","unzip"),cliConfig:et(Ne,"config.json"),lspConfig:et(Ne,"lsp-servers.json")}});import{z as Ae}from"zod";var _w,Iw,fp,mp=y(()=>{"use strict";_w=Ae.object({token:Ae.string(),tokenType:Ae.literal("oauth"),scopes:Ae.array(Ae.string()).optional(),refreshToken:Ae.string().optional(),expiresAt:Ae.string().optional(),refreshTokenExpiresAt:Ae.string().optional()}),Iw=Ae.object({hostname:Ae.string(),username:Ae.string(),token:_w,gitProtocol:Ae.enum(["ssh","https"]),createdAt:Ae.string(),updatedAt:Ae.string()}),fp=Ae.object({version:Ae.number(),credentials:Ae.record(Ae.string(),Iw)})});import{existsSync as gp,readFileSync as hp,writeFileSync as yp,unlinkSync as gz,statSync as Fw,chmodSync as Mw}from"node:fs";import{createCipheriv as Dw,createDecipheriv as Nw,randomBytes as bp}from"node:crypto";function fn(){pp()}function Pp(){if(fn(),gp(pn))return Fw(pn).mode&511&63&&Mw(pn,384),Buffer.from(hp(pn,"utf8"),"hex");let e=bp(32);return yp(pn,e.toString("hex"),{mode:384}),e}function Ba(e){let t=Pp(),n=bp(Gw),r=Dw(Sp,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 $a(e){let t=Pp(),[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=Nw(Sp,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function bi(){if(fn(),!gp(Fr))return{version:1,credentials:{}};try{let e=hp(Fr,"utf8"),t=$a(e),n=JSON.parse(t),r=fp.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Cp(e){fn();let t=Ba(JSON.stringify(e,null,2));yp(Fr,t,{mode:384})}var Rp,Fr,pn,Sp,Gw,wp=y(()=>{"use strict";Ir();mp();Rp=ot.home,Fr=ot.credentials,pn=ot.key,Sp="aes-256-gcm",Gw=16});var Mr,Wn,ja=y(()=>{"use strict";Mr="178c6fc778ccc68e1d6a",Wn="github.com"});import{refreshToken as Hw}from"@octokit/oauth-methods";import{request as zw}from"@octokit/request";function Qw(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 Bw(e){return e==="github.com"||e===Wn?"https://api.github.com":`https://${e}/api/v3`}async function xp(e,t=Wn,n=Mr){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(fi(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Hw({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:zw.defaults({baseUrl:Bw(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?Qw(o.message):"Token refresh failed"}}}async function Tp(e,t=Wn,n=Mr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!jn(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await xp(e,t,n);if(o.success){let i=await e.getCredentials(t);if(i?.token.token)return{token:i.token.token,source:"refreshed",username:i.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var kp=y(()=>{"use strict";mi();ja()});import{execFile as $w}from"child_process";function Ua(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=jw.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;$w("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var jw,qa=y(()=>{"use strict";jw=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function Ep(e){Wa=e}function Uw(){if(!Wa)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Wa}async function Ri(e){let t=e?.hostname??Wn,n=e?.clientId??Mr,r=e?.getGhCliToken??Ua,o=dp();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await Uw().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}var Wa,Op=y(()=>{"use strict";wt();qa();ja();Wa=null});async function vp(e){let t=Wt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=bi();return r.credentials[t]=n,Cp(r),Fa(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function Va(e="github.com",t){let n=Wt(e);if(!t?.bypassCache){let i=Wd(n);if(i!==void 0)return i}let o=bi().credentials[n]||null;return Vd(n,o),o}async function Ap(e,t){let n=await Va(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await vp(n),!0):!1}async function Lp(e,t){return Tp({getCredentials:Va,updateToken:Ap},e,t)}var Ka=y(()=>{"use strict";Kd();wp();kp();Op();mi();Ep({getTokenWithRefresh:Lp})});var _p=y(()=>{"use strict";Ka();qa()});import Si from"node:os";import nQ from"node:path";var Kw,Yw,Xw,Jw,Ip=y(()=>{"use strict";Kw=Si.platform()==="win32",Yw=Si.platform()==="darwin",Xw=Si.platform()==="linux",Jw=Si.homedir()});var Fp=y(()=>{"use strict";Ip()});import{z as K}from"zod";var Zw,ex,Pi,tx,Ci,Mp,Dp,Np=y(()=>{"use strict";Zw=K.object({rawChars:K.number(),responseChars:K.number(),savedChars:K.number(),calls:K.number()}),ex=K.object({hits:K.record(K.string(),K.number()).default({}),rateLimits:K.number().default(0)}),Pi=K.record(K.string(),K.number()).default({}),tx=K.object({toolCalls:K.number(),errors:K.number(),rateLimits:K.number(),rateLimitsByProvider:Pi,rawChars:K.number(),responseChars:K.number(),savedChars:K.number(),charSavingsCalls:K.number(),githubCacheHits:K.number(),githubCacheRateLimits:K.number(),packageRegistryFailures:K.number().default(0),packageRegistryFailuresByRegistry:Pi}),Ci=K.object({toolCalls:K.number(),errors:K.number(),rateLimits:K.number(),rateLimitsByProvider:Pi,charsSavedByTool:K.record(K.string(),Zw).default({}),githubCacheHits:ex.default({hits:{},rateLimits:0}),packageRegistryFailures:Pi,totalUsage:tx.optional()}),Mp=K.object({version:K.literal(1),sessionId:K.string(),createdAt:K.string(),lastActiveAt:K.string(),stats:Ci.optional()}),Dp=K.object({version:K.literal(1),stats:Ci})});function Gp(e){return Object.values(e).reduce((t,n)=>t+n,0)}function nx(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:Gp(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:Gp(o),packageRegistryFailuresByRegistry:o}}function At(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:nx(t)}}function Ya(){return At({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Xa=y(()=>{"use strict"});import{existsSync as zp,readFileSync as Qp,writeFileSync as rx,unlinkSync as mQ,renameSync as ox}from"node:fs";function Hp(e,t){let n=`${e}.tmp`;rx(n,JSON.stringify(t,null,2),{mode:384}),ox(n,e)}function ix(e){let{stats:t,...n}=e;return n}function sx(e){let t=JSON.parse(e),n=Dp.safeParse(t);if(n.success)return At(n.data.stats);let r=Ci.safeParse(t);return r.success?At(r.data):null}function ax(e){let t=e?At(e):Ya();if(!zp(Nr))return t;try{let n=Qp(Nr,"utf8"),r=sx(n);return r||t}catch{return t}}function Ja(e){fn(),Hp(Nr,{version:e.version,stats:At(e.stats)}),Hp(Dr,ix(e))}function Bp(){if(!zp(Dr))return null;try{let e=Qp(Dr,"utf8"),t=JSON.parse(e),n=Mp.safeParse(t);return n.success?{...n.data,stats:ax(n.data.stats)}:null}catch{return null}}var Dr,Nr,wi=y(()=>{"use strict";Ka();Ir();Np();Xa();Dr=ot.session,Nr=ot.stats});function lx(){$p||($p=!0,jp=()=>{xi()},Up=()=>{xi()},qp=()=>{xi()},process.on("exit",jp),process.on("SIGINT",Up),process.on("SIGTERM",qp))}function ux(){Za||(Za=setInterval(()=>{Gr&&Vt&&(Ja(Vt),Gr=!1)},cx),Za.unref())}function Wp(){if(Vt)return Vt;let e=Bp();return e&&(Vt=e),e}function Vp(e){Vt=e,Gr=!0,lx(),ux()}function xi(){if(!ec&&Gr&&Vt){ec=!0;try{Ja(Vt),Gr=!1}catch{}finally{ec=!1}}}var cx,Vt,Gr,Za,$p,jp,Up,qp,ec,Kp=y(()=>{"use strict";wi();cx=6e4,Vt=null,Gr=!1,Za=null,$p=!1,jp=null,Up=null,qp=null,ec=!1});import{randomUUID as vQ}from"node:crypto";function dx(e){return At(e)}function px(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 Yp(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 fx(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 Kt(e){let t=Wp();if(!t)return{success:!1,session:null};let n=dx(t.stats),r=At({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Yp(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:px(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:fx(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Yp(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Vp(o),{success:!0,session:o}}function tc(e=1){return Kt({rateLimits:e})}function nc(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Kt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function rc(e,t=1){return Kt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function oc(e=1){return Kt({githubCacheHits:{hits:{},rateLimits:e}})}var Hr=y(()=>{"use strict";wi();Xa();Kp();wi()});var Xp=y(()=>{"use strict";Hr();Hr();Hr();Hr()});import{z as Pe}from"zod";var mx,Jp=y(()=>{"use strict";mx=Pe.looseObject({$schema:Pe.string().optional(),version:Pe.number().int().optional(),github:Pe.record(Pe.string(),Pe.unknown()).optional(),local:Pe.record(Pe.string(),Pe.unknown()).optional(),tools:Pe.record(Pe.string(),Pe.unknown()).optional(),network:Pe.record(Pe.string(),Pe.unknown()).optional(),lsp:Pe.record(Pe.string(),Pe.unknown()).optional(),output:Pe.record(Pe.string(),Pe.unknown()).optional()})});var Zp=y(()=>{"use strict";Jp();wt()});import{existsSync as hx,readdirSync as yx,lstatSync as bx}from"node:fs";import{join as Rx}from"node:path";function Ti(e){if(!hx(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=yx(r)}catch{continue}for(let i of o){let s=Rx(r,i);try{let a=bx(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var ef=y(()=>{"use strict"});var Lt=y(()=>{"use strict";_p();Fp();Xp();Zp();Ir();ef()});var mn,ki=y(()=>{mn="16.6.3"});var ic,zr,Qr,Px,Yt,Vn,je,Cx,Br,wx,hB,xt=y(()=>{"use strict";ic={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},zr={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"}},Qr={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})`}},Px={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}`}},Vn={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"}},je={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}`}},Cx={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}`}},Br={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},wx={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}`}},hB={...ic,...zr,...Qr,...Px,...Yt,...Vn,...je,...Cx,...Br,...wx}});import{maskSensitiveData as xx}from"@octocodeai/octocode-engine/mask";async function tf(){try{let e=await Tx({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:kx.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function nf(){if(jr!==null)return;if($r!==null)return $r;let e=(async()=>{let t=yt(),n=await tf();jr={version:mn,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}})();$r=e;try{await e}catch(t){throw $r===e&&(jr=null,$r=null),t}}function rf(){if(!jr){let e=xx(ic.NOT_INITIALIZED.message);throw new Error(e)}return jr}async function of(){return(await tf()).token}function sc(){return"github"}function ac(){let e=yt().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var jr,$r,Tx,kx,Ur=y(()=>{"use strict";Lt();wt();ki();xt();jr=null,$r=null,Tx=Ri,kx=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});import{createRequire as Ex}from"node:module";function ee(){if(Ei)return Ei;try{return Ei=vx(),Ei}catch(e){throw new cc(e)}}var Ox,sf,Ei,vx,cc,D,Ce=y(()=>{"use strict";Ox=Ex(import.meta.url),sf="@octocodeai/octocode-engine",vx=()=>Ox(sf),cc=class extends Error{constructor(n){super(`Failed to load native dependency ${sf}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};D={applyContentViewMinification(e,t){return ee().applyContentViewMinification(e,t)},applyMinification(e,t){return ee().applyMinification(e,t)},minifyContent(e,t){return ee().minifyContent(e,t)},minifyContentSync(e,t){return ee().minifyContentSync(e,t)},minifyContentResult(e,t){return ee().minifyContentResult(e,t)},minifyMarkdownCore(e){return ee().minifyMarkdownCore(e)},extractSignatures(e,t){return ee().extractSignatures(e,t)},extractJsSymbols(e,t){return ee().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return ee().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return ee().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return ee().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return ee().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return ee().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return ee().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return ee().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return ee().getSupportedStructuralExtensions()},inspectBinaryNative(e){return ee().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return ee().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return ee().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return ee().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return ee().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return ee().parseRipgrepJson(e,t)},searchRipgrep(e){return ee().searchRipgrep(e)},queryFileSystem(e){return ee().queryFileSystem(e)},extractMatchingLines(e,t,n){return ee().extractMatchingLines(e,t,n)},filterPatch(e,t){return ee().filterPatch(e,t)},charToByteOffset(e,t){return ee().charToByteOffset(e,t)},byteToCharOffset(e,t){return ee().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return ee().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return ee().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return ee().SIGNATURES_ONLY_HINT}}});function Xt(e){(e.provider?Kt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):tc(1)).session&&e.provider==="github"&&oc(1)}function af(e){Kt({packageRegistryFailures:{[e]:1}})}var Oi=y(()=>{"use strict";Lt()});import{Octokit as Ax}from"octokit";import{throttling as Lx}from"@octokit/plugin-throttling";import{createHash as _x}from"crypto";function Ix(e){return _x("sha256").update(e).digest("hex").substring(0,16)}function pf(e){return Date.now()-e.createdAt>Mx}function ff(){for(let[e,t]of _t.entries())pf(t)&&_t.delete(e);if(_t.size>lc){let e=_t.size-lc,t=0;for(let[n]of _t){if(t>=e)break;_t.delete(n),t++}}}function Nx(){qr||(qr=setInterval(ff,Dx),typeof qr=="object"&&"unref"in qr&&qr.unref())}function uf(e,t,n){Xt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function Hx(e){let t=rf(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${mn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:Gx(),log:r,...e&&{auth:e}};return new Fx(o)}async function he(e){Nx();let t=e?.token??await of(),n=t?Ix(t):"ANONYMOUS",r=_t.get(n);if(r&&!pf(r))return r.client;_t.size>=lc&&ff();let o=Hx(t??void 0);return _t.set(n,{client:o,createdAt:Date.now()}),o}async function tt(e,t,n){let r=`${e}/${t}`,o=Wr.get(r);if(o)return o;let i=await he(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return df(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}),df(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 df(e,t){if(Wr.size>=zx){let n=Wr.keys().next().value;n!==void 0&&Wr.delete(n)}Wr.set(e,t)}var Fx,Mx,lc,Dx,_t,qr,cf,lf,Gx,zx,Wr,Ue=y(()=>{"use strict";Ur();Ur();ki();Oi();Fx=Ax.plugin(Lx),Mx=300*1e3,lc=50,Dx=60*1e3;_t=new Map,qr=null;cf=3,lf=60;Gx=()=>({onRateLimit:(e,t,n,r)=>(uf("primary",e,t),r<cf&&e<lf),onSecondaryRateLimit:(e,t,n,r)=>(uf("secondary",e,t),r<cf&&e<lf)});zx=200,Wr=new Map});var W,Te,mf,uc,dc,vi,gf=y(()=>{"use strict";W={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},Te={[W.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[W.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[W.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[W.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[W.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[W.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[W.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[W.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[W.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[W.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},mf={401:W.AUTH_REQUIRED,403:W.FORBIDDEN_PERMISSIONS,404:W.NOT_FOUND,422:W.INVALID_REQUEST,502:W.SERVER_UNAVAILABLE,503:W.SERVER_UNAVAILABLE,504:W.SERVER_UNAVAILABLE},uc={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},dc={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},vi={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as hf}from"octokit";function gn(e){if(!(e instanceof hf)||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 Qx.some(o=>r.includes(o))})}function ae(e){return e instanceof hf?Bx(e):e instanceof Error?Yx(e):{error:typeof e=="string"?e:Te[W.UNKNOWN].message,type:"unknown"}}function Bx(e){let{status:t,message:n,response:r}=e;if(t===403)return jx(n,r);if(t===429)return $x(n,r);let o=mf[t];return o?Kx(o,t):Kn(W.UNKNOWN,{error:n||Te[W.UNKNOWN].message,status:t})}function pc(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function $x(e,t){let n=t?.headers,r=pc(n,"retry-after"),o=pc(n,"x-ratelimit-reset"),i=pc(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+vi.RESET_BUFFER_SECONDS,0):void 0);return Xt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Kn(W.RATE_LIMIT_PRIMARY,{error:e||Te[W.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Te[W.RATE_LIMIT_PRIMARY].suggestion})}function jx(e,t){let n=t?.headers;if(dc.SECONDARY.test(e))return Ux(n);let r=n?.["x-ratelimit-remaining"],o=Vx(t);return r!==void 0&&String(r)==="0"||o?qx(n):Wx(n)}function Ux(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?vi.SECONDARY_FALLBACK_SECONDS:t;return Xt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Kn(W.RATE_LIMIT_SECONDARY,{error:Te[W.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Te[W.RATE_LIMIT_SECONDARY].suggestion})}function qx(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)+vi.RESET_BUFFER_SECONDS,0):void 0,i=r?Te[W.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Te[W.RATE_LIMIT_PRIMARY].messageWithoutTime;return Xt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Kn(W.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Te[W.RATE_LIMIT_PRIMARY].suggestion})}function Wx(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Te[W.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=Xx(String(t),String(n))),Kn(W.FORBIDDEN_PERMISSIONS,{error:Te[W.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Vx(e){return e?.data?.errors?.some(n=>n.type===dc.GRAPHQL_TYPE)??!1}function Kx(e,t){let n=Te[e];return Kn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function Yx(e){return uc.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Te[W.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Te[W.NETWORK_CONNECTION_FAILED].suggestion}:uc.TIMEOUT.some(t=>e.message.includes(t))?{error:Te[W.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Te[W.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function Kn(e,t){return{type:"http",...t}}function Xx(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?Te[W.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Te[W.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var Qx,It=y(()=>{"use strict";gf();Oi();Qx=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function Jx(e){return`user:${e}`}function yf(e){return e.startsWith('"')||tT.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function bf(e){return new fc().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function Rf(e){return new mc().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function Sf(e){return new gc().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Pf(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var Zx,eT,tT,Vr,fc,mc,gc,Ai=y(()=>{"use strict";Zx=/[@/]/,eT=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,tT=/^[A-Za-z0-9_-]+$/;Vr=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(Jx(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=Zx.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},fc=class extends Vr{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(yf))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(eT):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}},mc=class extends Vr{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(yf)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},gc=class extends Vr{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});import nT from"node-cache";import rT from"crypto";function sT(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function aT(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function cT(e){let t=sT(e);if(!(!t||!aT(t)))try{rc(t,1)}catch{}}function lT(){let e=Date.now();for(let[t,n]of Kr.entries())e-n.startedAt>iT&&Kr.delete(t)}function dT(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(uT.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function qe(e,t,n){let r=hc(dT(t)),o=n?`${n}:${r}`:r,i=rT.createHash("sha256").update(o).digest("hex");return`${oT}-${e}:${i}`}function hc(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=>hc(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${hc(i,t)}`}).join(",")}}`)}function pT(e){return Cf[e]||Cf.default}function fT(e,t,n){try{return hn.set(e,t,n),Yn.sets++,Yn.totalKeys=hn.keys().length,!0}catch{try{let r=hn.keys();for(let o of r)hn.get(o);return hn.set(e,t,n),Yn.sets++,Yn.totalKeys=hn.keys().length,!0}catch{return!1}}}async function We(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=hn.get(e);if(i!==void 0)return Yn.hits++,cT(e),i}catch{}lT();let r=Kr.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Yn.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=pT(l)}fT(e,i,a)}return i}finally{Kr.delete(e)}})();return Kr.set(e,{promise:o,startedAt:Date.now()}),o}var oT,iT,hn,Yn,Cf,Kr,uT,Jt=y(()=>{"use strict";Lt();oT="v1",iT=300*1e3,hn=new nT({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Yn={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Cf={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},Kr=new Map;uT=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as VB,DISCOVERY_IGNORED_FILE_NAMES as KB,DISCOVERY_IGNORED_FOLDER_NAMES as YB,getDiscoveryExtension as wf,shouldIgnoreDiscoveryDir as Yr,shouldIgnoreDiscoveryFile as Xn}from"@octocodeai/octocode-engine/security";var Xr=y(()=>{"use strict"});function $(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Tf(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function U(e,t){let n=typeof t=="number"?Tf(t):$(t);if(n===void 0)return e;try{Object.defineProperty(e,xf,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function me(e){if(!(typeof e!="object"||e===null))return Tf(e[xf])}var xf,de=y(()=>{"use strict";xf=Symbol.for("octocode.rawResponseChars")});function Li(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var yc=y(()=>{"use strict"});import{ContentSanitizer as mT}from"@octocodeai/octocode-engine/contentSanitizer";async function Ef(e,t,n){let r=qe("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await We(r,async()=>await gT(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function gT(e,t){try{let n=await he(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(x=>x&&x.trim()).length===0)return{error:je.QUERY_EMPTY.message,type:"http",status:400};let r=bf(e);if(!r.trim())return{error:je.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:kf,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 hT(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),p=Math.min(Math.ceil(d/o),10),f=Math.min(i,Math.max(1,p)),m=f<p,g=Math.min(d,p*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:f,totalPages:p,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:m,...m?{nextPage:f+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Li(a.headers),rawResponseChars:$(a.data)}}catch(n){if(gn(n)){let o=Math.min(typeof e.limit=="number"?e.limit:kf,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return ae(n)}}async function hT(e,t){let n=yT(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!Xn(f.path)),c=0,l=0,u=await Promise.allSettled(a.map(async f=>{s.add(f.path);let m=[],g=await Promise.allSettled((f.text_matches||[]).map(async A=>{let _=A.fragment,E=mT.sanitizeContent(_||"",f.path);_=E.content,E.hasSecrets&&r.add(`Secrets detected in ${f.path}: ${E.secretsDetected.join(", ")}`),E.warnings.length>0&&E.warnings.forEach(w=>r.add(`${f.path}: ${w}`));try{let w=await D.minifyContent(_||"",f.path);_=w.content,w.failed?o=!0:w.type!=="failed"&&(m.push(w.type),i.push(w.type))}catch{o=!0}return{context:_||"",positions:A.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),b=g.filter(A=>A.status==="fulfilled").map(A=>A.value),x=g.filter(A=>A.status==="rejected").length;x>0&&(l+=x);let S=f,k=Array.from(new Set(m));return{path:f.path,matches:b,url:f.html_url,repository:{nameWithOwner:f.repository.full_name,url:f.repository.url,pushedAt:f.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...k.length>0&&{minificationType:k.join(",")}}})),d=u.filter(f=>f.status==="fulfilled").map(f=>f.value);c=u.filter(f=>f.status==="rejected").length;let p={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let f=n.full_name.split("/");return f.length===2&&f[0]&&f[1]?{owner:f[0],repo:f[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(p.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(p.matchLocations=Array.from(r)),p.minified=!o,p.minificationFailed=o,i.length>0&&(p.minificationTypes=Array.from(new Set(i))),p}function yT(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 kf,Of=y(()=>{"use strict";Ce();Ue();It();Ai();Jt();Xr();xt();de();yc();Se();kf=30});function Af(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 Lf(e,t,n){let r=qe("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await We(r,async()=>await RT(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function bT(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(f){if(f?.status!==404)return ae(f);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return ae(g)}}let a=i.map(f=>{let g=f.full_name.split("/"),b=g[0]||"",x=g[1]||"";return{owner:b,repo:x,defaultBranch:f.default_branch,stars:f.stargazers_count||0,description:f.description?f.description:"No description",url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at,pushedAt:f.pushed_at,visibility:f.visibility,...f.topics&&f.topics.length>0&&{topics:f.topics},...f.forks_count&&f.forks_count>0&&{forksCount:f.forks_count},...f.open_issues_count&&f.open_issues_count>0&&{openIssuesCount:f.open_issues_count},...f.language&&{language:f.language},...Af(f)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),p=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:p,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:$(i)}}async function RT(e,t){try{let n=await he(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 bT({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=Rf(e);if(!i.trim())return{error:je.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||vf,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let A=S.full_name.split("/"),_=A[0]||"",E=A[1]||"";return{owner:_,repo:E,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...Af(S)}}),p=u.data.total_count,f=Math.min(p,1e3),m=Math.min(Math.ceil(f/s),10),g=Math.min(a,Math.max(1,m)),b=g<m,x=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:x,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:g+1}:{}}},status:200,headers:Li(u.headers),rawResponseChars:$(u.data)}}catch(n){if(gn(n)){let r=Math.min(e.limit||vf,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return ae(n)}}var vf,_f=y(()=>{"use strict";Ue();It();Ai();Jt();xt();de();yc();Se();vf=30});function Jn(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var _i=y(()=>{"use strict"});function ke(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function ST(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 Ft(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:ST(e)}}function Ii(e){return PT(e)?Ft({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function PT(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||CT(n)}function CT(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var Tt=y(()=>{"use strict"});function If(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function wT(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,...If(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function xT(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,...If(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Ff(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await Ef(s,t);return Jn(a)?Ft(a):a.data?{data:wT(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??$(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function Mf(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 Lf(n,t);return"error"in r?Ii(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:xT(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??$(r.data)}}var Df=y(()=>{"use strict";Of();_f();_i();de();Tt();Tt()});import{completeMetadata as bc}from"@octocodeai/octocode-core";var v,Nf=y(()=>{"use strict";v=new Proxy({},{get(e,t){return bc.toolNames[t]},ownKeys(){return Object.keys(bc.toolNames)},getOwnPropertyDescriptor(e,t){let n=bc.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as kT}from"@octocodeai/octocode-core";var Rc,Gf=y(()=>{"use strict";Rc=new Proxy({},{get(e,t){return kT.tools[t]?.description??""}})});import{completeMetadata as ET}from"@octocodeai/octocode-core";function Sc(e){return Object.prototype.hasOwnProperty.call(ET.tools,e)}var Hf=y(()=>{"use strict"});import{completeMetadata as OT}from"@octocodeai/octocode-core";function Pc(){return OT.baseSchema}var vT,zf=y(()=>{"use strict";vT=new Proxy({},{get(e,t){return Pc()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Pc())]))},getOwnPropertyDescriptor(e,t){let n=Pc();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var Re=y(()=>{"use strict";Nf();Gf();Hf();zf()});import{RequestError as Qf}from"octokit";async function AT(e,t,n,r,o,i,s,a){let c=await tt(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=ae(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,p=await Uf(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...jf(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function LT(e,t,n,r,o,i){let s=ae(t),a=await Uf(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...jf(o,a)]),s}async function Bf(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 $f(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"?Bf(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return ae(i)}}async function _T(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 tt(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(p=>p.name===a&&p.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await $f(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return ae(s)}}async function Fi(e,t){try{let n=await he(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof Qf&&d.status===404)if(s){let p=await AT(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await LT(n,d,r,o,i,s);else{if(d instanceof Qf&&d.status===413)return await _T(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:Yt.PATH_IS_DIRECTORY.message(v.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in u&&u.type==="file"){let d=typeof u.content=="string"?u.content:"",p=u.size??0,f;if(d.length>0)f=await Bf(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await $f(n,r,o,u.sha,i);else return{error:Yt.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await tt(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:$(u)}}return{error:Yt.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return ae(n)}}function jf(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 Uf(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(f=>f.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(f=>f.name===s?!1:!!f.name.startsWith(d+".")).forEach(f=>l.push(f.path)),l.length===0&&d.length>=3&&c.filter(m=>{let g=m.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(m=>l.push(m.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var Cc=y(()=>{"use strict";Ue();It();Re();xt();de()});function it(){try{return yt().output.pagination.defaultCharLength}catch{return qn.pagination.defaultCharLength}}var Jr=y(()=>{"use strict";wt()});function Zr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Mt(e){return Zr(e).length}var eo=y(()=>{"use strict"});function wc(e,t){return D.byteToCharOffset(e,t)}function qf(e,t){return D.charToByteOffset(e,t)}function Wf(e){return D.charToByteOffset(e,e.length)}function xc(e,t,n,r){return D.sliceContent(e,t,n,r)}var Vf=y(()=>{"use strict";Ce()});function Zn(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Wf(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,p,f,m,g;if(o==="bytes"){let b=Math.min(t,s),x=Math.min(b+n,s);d=wc(e,b),p=wc(e,x),p<i&&qf(e,p)<x&&(p+=1);let S=xc(e,d,p-d);c=S.text,d=S.charOffset,p=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,f=u<s;let k=r.actualOffset??b;m=Math.floor(k/a)+1,g=Math.max(m,Math.ceil(s/a))}else{let b=xc(e,t,n);c=b.text,d=b.charOffset,p=b.charOffset+b.charLength,l=b.byteOffset,u=b.byteOffset+b.byteLength,f=p<i;let x=r.actualOffset??d;m=Math.floor(x/a)+1,g=Math.max(m,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:f?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:f?p:void 0,hasMore:f,estimatedTokens:Math.ceil(c.length/4),currentPage:m,totalPages:g}}function Tc(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 Mi=y(()=>{"use strict";Vf()});function MT(e){return e&&e.trim().length>0?e:FT}function Kf(e,t){return D.getSemanticBoundaryOffsets(e,MT(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function DT(e,t){let n=e.indexOf(`
11
+ `,t);return n===-1?void 0:n+1}function Di(e){let t=e.trimEnd().split(`
12
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function Ni(e,t,n){let r=DT(e,Math.max(0,t));if(r!==void 0)return Kf(e,n).find(o=>o>=r&&o>t)}function Gi(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=Kf(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=IT?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var IT,FT,kc=y(()=>{"use strict";Ce();IT=8e3,FT="__octocode_generic__.unknown"});function Hi(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
13
+ `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=D.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var Ec=y(()=>{"use strict";Ce()});function GT(e){return NT.test(e.split(/[?#]/,1)[0]??e)}function Yf(e,t){return GT(t)?zT(HT(e)):null}function zi(e,t){let n=Yf(e,t);if(n===null||n.length===0)return null;let r=[];return Jf(n,r),r.join(`
14
+ `)}function Xf(e,t){let n=Yf(e,t);return n===null?null:n.map(Zf)}function HT(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function zT(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 Jf(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}`),Jf(n.children,t)}}function Zf(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(Zf)}}var NT,Qi=y(()=>{"use strict";NT=/\.(?:md|markdown|mdx)$/i});import{ContentSanitizer as em}from"@octocodeai/octocode-engine/contentSanitizer";function BT(){let e=it();return Math.min(e,8e3)}function to(e,t){return{sourceChars:e,sourceBytes:t}}function tm(e,t,n){let r=e.content??"",o=n??BT();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=Gi(r,t,o,i),c=Zn(r,t,s),l;if(c.hasMore&&a==="char-limit"&&Di(c.paginatedContent)){let u=c.charOffset+c.charLength;l=Ni(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function nm(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function rm(e,t,n,r,o,i,s,a,c=5,l,u,d,p="standard"){let f=e.length,m=Buffer.byteLength(e,"utf-8"),g=p==="standard"||p==="symbols",b=g?"standard":"none",x;if(p==="symbols"){let Y=D.extractSignatures(e,o);if(Y===null){let j=zi(e,o);if(j!==null)return{owner:t,repo:n,path:o,content:j,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Mt(e),...to(f,m),isPartial:!1,signaturesExtracted:!0,hints:[D.SIGNATURES_ONLY_HINT]};x=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(Y!==null){let j=em.sanitizeContent(Y,o),Oe=D.applyContentViewMinification(j.content,o),ve=[D.SIGNATURES_ONLY_HINT];return l&&ve.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),j.hasSecrets&&ve.push(`Secrets detected and redacted: ${j.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Oe,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Mt(e),...to(f,m),isPartial:!1,signaturesExtracted:!0,hints:ve}}}let S=new Set,k=e,A=k.split(`
15
+ `),_=Mt(k),E=e,w,N,F=!1,O;if(i)E=e;else if(l){let Y=d===!0,j;try{j=Hi(A,l,c,u??!1,Y)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:_,...to(f,m),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(j.matchCount===0){let re=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${Y?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${Y?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:_,...to(f,m),matchNotFound:!0,searchedFor:l,hints:re}}E=j.lines.join(`
16
+ `);let Oe=j.matchRanges[0],ve=j.matchRanges[j.matchRanges.length-1];s=Oe.start,a=ve.end,w=Oe.start,N=ve.end,F=!0,j.matchRanges.length>1&&(O=j.matchRanges);let Bt=j.matchingLines.slice(0,5).join(", "),$t=j.matchingLines.length>5?` and ${j.matchingLines.length-5} more`:"";S.add(j.matchCount>1?`Found ${j.matchCount} occurrences of "${l}" on lines ${Bt}${$t} \u2014 all shown as ${j.matchRanges.length} slice${j.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${j.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let Y=s||1,j=a||_;if(Y<1||Y>_)E=e;else if(j<Y)E=e;else{let Oe=Math.max(1,Y),ve=Math.min(_,j),Bt=A.slice(Oe-1,ve);w=Oe,N=ve,F=!0,E=Bt.join(`
17
+ `),j>_&&S.add(`Requested endLine ${j} adjusted to ${_} (file end)`)}}let Q=em.sanitizeContent(E,o);if(E=g?D.applyContentViewMinification(Q.content,o):Q.content,Q.hasSecrets&&S.add(`Secrets detected and redacted: ${Q.secretsDetected.join(", ")}`),Q.warnings.length>0&&Q.warnings.forEach(Y=>S.add(Y)),_>2e3&&p!=="symbols"&&!l&&!s&&!a&&!i){let Y=Math.max(1,_-200);S.add(`Large file (${_} lines) \u2014 minify:"symbols" for an export index, or startLine=${Y} for the tail.`)}let G=Array.from(S);return{owner:t,repo:n,path:o,content:E,...b!=="standard"&&{contentView:b},branch:r,totalLines:_,...to(f,m),...F&&{startLine:w,endLine:N,isPartial:F},...O&&{matchRanges:O},...G.length>0&&{matchLocations:G},...(G.length>0||x)&&{warnings:[...x?[x]:[],...G]}}}var om=y(()=>{"use strict";Jr();Se();Ce();eo();Mi();kc();Ec();Qi()});async function im(e,t,n){let r=qe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await We(r,async()=>await Fi(e,t),{shouldCache:m=>"data"in m&&!m.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await rm(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,l=e.charOffset??0,u=e.charLength,d=e.fullContent===!0&&l===0&&u===void 0,p=a||d?c:tm(c,l,u),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let m=await he(t),g=await We(qe("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>nm(m,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});g&&(p.lastModified=g.lastModified,p.lastModifiedBy=g.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:o.rawResponseChars}}var sm=y(()=>{"use strict";Ue();Jt();Cc();om()});function $T(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:jT(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function jT(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function am(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await im(i,t);if(Jn(s))return Ft(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:$T(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??$(s.data),...a?.length?{hints:a}:{}}}var cm=y(()=>{"use strict";sm();_i();de();Tt();Tt()});function no(e,t=WT){let n=e?Zr(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function lm(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return D.filterPatch(e,r)}function um(e){return e?D.filterPatch(e,{trimContext:!0,contextLines:qT}):""}var qT,WT,Bi=y(()=>{"use strict";Ce();eo();qT=2,WT=20});import{ContentSanitizer as dm}from"@octocodeai/octocode-engine/contentSanitizer";function Oc(e){let t=dm.sanitizeContent(e.title??""),n=e.body?dm.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function fm(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function ro(e,t={}){let n=t.charOffset??0,r=t.charLength??VT,o=t.charLength??KT,i=typeof e.body=="string"?D.minifyMarkdownCore(e.body):e.body,s=fm(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((m,g)=>{let b=m.commentType==="review_inline"?0:1,x=g.commentType==="review_inline"?0:1;return b-x}),c=a.filter(m=>m.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,pm),d=u.map(m=>{let g=fm(m.body,n,o,!t.includeFullCommentDetails);return{...m,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),p=!t.includeFullCommentDetails&&(a.length>u.length||d.some(m=>"body_pagination"in m)),f=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...p?[`PR comments are paginated/summarized to ${pm} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(m=>({id:0,name:m,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((m,g)=>m+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((m,g)=>m+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(m=>({filename:m.filename,status:m.status,additions:m.additions,deletions:m.deletions,patch:m.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...p?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||f.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...f]}}}function oo(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function $i(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?lm(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?um(a.patch):a.patch}))}var VT,KT,pm,ji=y(()=>{"use strict";Bi();Ce();Jr();VT=it(),KT=Math.round(it()/4),pm=3});import{ContentSanitizer as vc}from"@octocodeai/octocode-engine/contentSanitizer";function Ui(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function mm(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function gm(e){let t=mm(e);return t?t.discussion!==!1:!1}function hm(e){let t=mm(e);return t?t.reviewInline!==!1:!1}function ym(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function bm(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Rm(e){return!!e.content?.comments?.includeBots}function Sm(e){let t=e.toLowerCase();return t.endsWith("[bot]")||YT.has(t.replace(/\[bot\]$/,""))}function Ac(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
17
18
 
18
- `).trim()}async function bm(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=Q(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!ym(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=M.minifyMarkdownCore(Ic(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:_c.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"discussion"}}),p=[];return u>0&&p.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:U([],0)}}}async function Rm(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Fc(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return U(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:_c.sanitizeContent(M.minifyMarkdownCore(Ic(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return U([],0)}}async function Sm(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=Q(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!ym(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=M.minifyMarkdownCore(Ic(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:_c.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"review_inline",path:f.path,line:f.line??f.original_line??void 0,...f.in_reply_to_id!=null?{in_reply_to_id:f.in_reply_to_id}:{}}}),p=[];return u>0&&p.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:U([],0)}}}async function Cm(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Lc(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=qr(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=Q(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Ni(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Ni(t))){let p=await Pm(l,u,e.number);p&&(s+=ce(p)??0,p.files=Mi(p.files,t),o.file_changes=p)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=pm(t),c=fm(t);if(a||c){let{owner:l,repo:u}=qr(t);if(l&&u){let d=hm(t),p=()=>Promise.resolve({comments:U([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([a?bm(n,l,u,e.number,d):p(),c?Sm(n,l,u,e.number,d):p()]);o.comments=[...f,...g],s+=(ce(f)??0)+(ce(g)??0);let S=[m,b].filter(C=>typeof C=="string");S.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...S])}}if(gm(t))try{let{owner:l,repo:u}=qr(t);if(l&&u){let d=await Rm(n,l,u,e.number);s+=ce(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(mm(t))try{let{owner:l,repo:u}=qr(t);if(l&&u){let d=await wm(l,u,e.number,t);d&&(s+=ce(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return U(o,s)}async function Fc(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=Q(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Pm(e,t,n,r){let o=await ue(r),{items:i,rawResponseChars:s}=await Fc(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U({total_count:i.length,files:i},s)}async function fT(e,t,n,r){let o=await ue(r),{items:i,rawResponseChars:s}=await Fc(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U(i,s)}async function mT(e,t,n,r){try{let i=await(await ue(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return U(i.data.files||[],i.data)}catch{return null}}async function wm(e,t,n,r,o){let i=await fT(e,t,n,o);if(!i)return null;let s=ce(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await Promise.all(a.map(async l=>{let u=await mT(e,t,l.sha,o),d=[];return u&&(s+=ce(u)??0,d=Mi(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return U(c,s)}async function Gi(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Lc(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Ni(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ni(t))try{let d=await Pm(a,c,e.number,r);d&&(s+=ce(d)??0,d.files=Mi(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=pm(t),u=fm(t);if(l||u){let d=hm(t),p=()=>Promise.resolve({comments:U([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([l?bm(n,a,c,e.number,d):p(),u?Sm(n,a,c,e.number,d):p()]);o.comments=[...f,...g],s+=(ce(f)??0)+(ce(g)??0);let S=[m,b].filter(C=>typeof C=="string");S.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...S])}if(gm(t))try{let d=await Rm(n,a,c,e.number);s+=ce(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(mm(t))try{let d=await wm(a,c,e.number,t,r);d&&(s+=ce(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return U(o,s)}var pT,Mc=y(()=>{"use strict";ge();Be();Di();ie();pT=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function gT(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function xm(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:ze.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:ze.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ue(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Gi(a,e,i,t);return{pull_requests:[jr(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:Q(s.data)+(ce(c)??0)}}catch(i){let s=ne(i);return gT(s,ze.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var Tm=y(()=>{"use strict";gt();Be();St();Nt();Di();Mc();ie()});function Em(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function km(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function hT(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}async function Om(e,t,n){let r=Qe("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await Ue(r,async()=>await yT(e,t,n),{shouldCache:i=>!i.error})}async function yT(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await xm(e,t);let r=await ue(t);if(!yf(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await bT(r,e);let i=await hT(r,e),s=hf(i);if(!s)return{pull_requests:[],total_count:0,error:ze.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),p=d.data.items?.filter(O=>!!O.pull_request)||[],f=await Promise.all(p.map(async O=>await Cm(O,i,r))),m=f.reduce((O,x)=>O+(ce(x)??0),0),g=f.map(O=>jr(O,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,S=Math.min(b,1e3),C=Math.min(Math.ceil(S/c),10),k=Math.min(l,Math.max(1,C)),_=k<C,E=Math.min(S,C*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:k,totalPages:C,perPage:c,totalMatches:S,reportedTotalMatches:b,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:b>S,hasMore:_,..._?{nextPage:k+1}:{}},rawResponseChars:Q(d.data)+m}}catch(r){if(rn(r))return km(e);let o=ne(r);return Em(o,ze.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function bT(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async p=>await Gi(p,t,e))),c=a.reduce((p,f)=>p+(ce(f)??0),0),l=a.map(p=>jr(p,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:Q(s.data)+c}}catch(n){if(rn(n))return km(t);let r=ne(n);return Em(r,ze.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var vm=y(()=>{"use strict";fe();gt();Be();St();Pi();Nt();ie();Di();Mc();Tm()});function RT(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function ST(e,t,n=be){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...RT(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Am(e,t,n=be){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Om(s,t);return a.error?Ct({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:ST(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a)}}var Lm=y(()=>{"use strict";vm();ie();ht();ht()});var sn,Hi=y(()=>{"use strict";sn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function zi(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Dc=y(()=>{"use strict"});function _m(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:I,...v}=e;return v}let r=t.itemsPerPage??sn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,p=I=>{let v=I;d&&I.startsWith(d)&&(v=I.slice(d.length),v.startsWith("/")&&(v=v.slice(1)));let D=v.lastIndexOf("/");return D===-1?".":v.slice(0,D)},f=I=>{let v=I.lastIndexOf("/");return v===-1?I:I.slice(v+1)};for(let I of l){let v=p(I.path);u[v]||(u[v]={files:[],folders:[]});let D=f(I.path);I.type==="file"?u[v].files.push(D):u[v].folders.push(D)}for(let I of Object.keys(u)){let v=u[I];v&&(v.files.sort(),v.folders.sort())}let m=Object.create(null),g=Object.keys(u).sort((I,v)=>I==="."?-1:v==="."?1:I.localeCompare(v));for(let I of g){let v=u[I];v&&(m[I]=v)}let b=l.filter(I=>I.type==="file").length,S=l.filter(I=>I.type==="dir").length,C=n.filter(I=>I.type==="file").length,k=n.filter(I=>I.type==="dir").length,_=o<s,E={currentPage:o,totalPages:s,hasMore:_,..._?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},O=zi(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:S,allFiles:C,allFolders:k}),x,H=e._cachedFileSizeMap;if(H){let I=new Set(l.filter(B=>B.type==="file").map(B=>B.path)),v=e.path==="/"?"":e.path,D=Object.create(null);for(let[B,Z]of Object.entries(H))for(let[z,Ae]of Object.entries(Z)){let Pe=B==="."?v?`${v}/${z}`:z:v?`${v}/${B}/${z}`:`${B}/${z}`;I.has(Pe)&&(D[B]||(D[B]=Object.create(null)),D[B][z]=Ae)}Object.keys(D).length>0&&(x=D)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:C,totalFolders:k,truncated:_,filtered:!0,originalCount:i},structure:m,...x!==void 0&&{fileSizeMap:x},...H!==void 0&&{_cachedFileSizeMap:H},pagination:E,hints:O,rawResponseChars:e.rawResponseChars}}var Im=y(()=>{"use strict";Hi();Dc()});import{RequestError as PT}from"octokit";function Fm(e){return e instanceof PT&&wT.has(e.status)}function Nc(e,t){try{Object.defineProperty(e,Mm,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Gc(e){if(typeof e!="object"||e===null)return 0;let t=e[Mm];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Hc(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Nc(U([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(m){if(Fm(m))throw m;return Nc(U([],0),1)}let l=Q(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(m=>m.type==="file"||m.type==="dir").map(m=>({name:m.name,path:m.path,type:m.type,size:"size"in m?m.size:void 0,download_url:"download_url"in m?m.download_url:void 0,url:m.url,html_url:m.html_url,git_url:m.git_url,sha:m.sha})),p=[...d],f=0;if(i<s){let m=d.filter(b=>b.type==="dir"),g=3;for(let b=0;b<m.length;b+=g){let S=m.slice(b,b+g),C=await Promise.allSettled(S.map(k=>Hc(e,t,n,r,k.path,i+1,s,a)));for(let k of C)if(k.status==="fulfilled"){let _=k.value;l+=ce(_)??0,f+=Gc(_),p.push(..._)}else{if(Fm(k.reason))throw k.reason;f+=1}}}return Nc(U(p,l),f)}var Mm,wT,Dm=y(()=>{"use strict";ie();Mm=Symbol.for("octocode.recursiveFetchFailures"),wT=new Set([401,403,429])});import{RequestError as xT}from"octokit";async function TT(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await Ye(t,n,i),s=a)}catch(c){let l=ne(c);return{error:Gn.NOT_FOUND.message(t,n,l.error),status:l.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s,...a!==void 0?{repoDefaultBranch:a}:{}}}catch(c){if(!(c instanceof xT&&c.status===404)){let u=ne(c);return{error:Gn.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let l=ne(c);return{error:Gn.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function ET(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function kT(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function Nm(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function Gm(e,t,n){let r=Qe("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await Ue(r,async()=>await OT({...e,itemsPerPage:e.itemsPerPage??sn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?_m(o,e):o}async function OT(e,t){try{let n=await ue(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await TT(n,r,o,c,i,t);if("error"in l)return l;let{data:u,workingBranch:d,repoDefaultBranch:p}=l,f=Q(u),m=Array.isArray(u)?u:[u],g=ET(m),b=0;if(a>1){let K=await Hc(n,r,o,d,c,1,a);b=Gc(K),f+=ce(K)??0,g=[...g,...K].filter((wo,xo,BS)=>BS.findIndex(QS=>QS.path===wo.path)===xo)}let S=g.filter(K=>K.type==="dir"?!Gr(K.name):!Bn(K.path));S.sort((K,rr)=>{if(K.type!==rr.type)return K.type==="dir"?-1:1;let wo=K.path.split("/").length,xo=rr.path.split("/").length;return wo!==xo?wo-xo:K.path.localeCompare(rr.path)});let C=e.itemsPerPage??sn.ENTRIES_PER_PAGE,k=e.page??1,_=S.length,E=Math.max(1,Math.ceil(_/C)),O=(k-1)*C,x=Math.min(O+C,_),H=S.slice(O,x),I=kT(H,c),v=e.includeSizes===!0?Nm(S,c):void 0,D=v!==void 0?Nm(H,c):void 0,B=H.filter(K=>K.type==="file").length,Z=H.filter(K=>K.type==="dir").length,z=S.filter(K=>K.type==="file").length,Ae=S.filter(K=>K.type==="dir").length,Pe=k<E,mt={currentPage:k,totalPages:E,hasMore:Pe,...Pe?{nextPage:k+1}:{},entriesPerPage:C,totalEntries:_},Vt=zi(mt,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:B,pageFolders:Z,allFiles:z,allFolders:Ae});return b>0&&Vt.unshift(`Partial tree: ${b} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...p!==void 0&&{defaultBranch:p},path:c||"/",apiSource:!0,summary:{totalFiles:z,totalFolders:Ae,truncated:Pe,filtered:!0,originalCount:S.length},structure:I,...D!==void 0&&{fileSizeMap:D},...v!==void 0&&{_cachedFileSizeMap:v},pagination:mt,hints:Vt,rawResponseChars:f,_cachedItems:S.map(K=>({path:K.path,type:K.type}))}}catch(n){let r=ne(n);return{error:Gn.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var Hm=y(()=>{"use strict";Hi();Be();St();Nt();Dc();Hr();gt();ie();Im();Dm()});function vT(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function zm(e,t,n=be){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Gm(i,t);return"error"in s?Ti(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:vT(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s)}}var Bm=y(()=>{"use strict";Hm();ie();ht();ht()});var Qm,Um=y(()=>{"use strict";Qm={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var Bi,$m=y(()=>{"use strict";_f();im();Lm();Bm();St();Be();Um();ht();Bi=class{type="github";capabilities=Qm.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Af(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await om(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Lf(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Am(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await zm(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=be(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ye(n,r,this.authInfo)}handleError(t){let n=ne(t);return Ct(n)}}});import{createHash as LT}from"crypto";function jm(e){return Date.now()-e.createdAt<_T}function IT(){for(let[e,t]of yt.entries())jm(t)||yt.delete(e);if(yt.size>zc){let e=[...yt.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=yt.size-zc;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&yt.delete(r[0])}}}function FT(e){return e?LT("sha256").update(e).digest("hex").slice(0,16):"default"}function MT(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function DT(e,t){let n=MT(t?.baseUrl||"default"),r=FT(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Bc(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=DT(e,t),r=yt.get(n);if(r&&jm(r))return r.lastAccessedAt=Date.now(),r.provider;r&&yt.delete(n),yt.size>=zc&&IT();let o=new Bi({...t,type:e}),i=Date.now();return yt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function qm(){try{return Bc("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
19
- `),[{provider:"github",ok:!1,error:t}]}}var _T,zc,yt,Qc=y(()=>{"use strict";$m();_T=3600*1e3,zc=20,yt=new Map});async function Vm(e,t={}){if(!Array.isArray(e))throw new Error(kr.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(kr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(kr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(vr.NOT_A_FUNCTION.message(l))));if(r<i.length)return NT(i,r,n,o);let s=i.map((c,l)=>Wm(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function Wm(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(vr.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function NT(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(vr.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await Wm(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Km=y(()=>{"use strict";gt()});var Ym=y(()=>{"use strict"});import{ContentSanitizer as Xm}from"@octocodeai/octocode-engine/contentSanitizer";function GT(){try{return ke().output.format}catch{return"yaml"}}function Gt(e){if(e==null)return e;if(typeof e=="string")return Xm.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>Gt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Gt(r);return t}return e}function HT(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
19
+ `).trim()}async function Pm(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=$(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!Sm(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=D.minifyMarkdownCore(Ac(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:vc.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"discussion"}}),p=[];return u>0&&p.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:U([],0)}}}async function Cm(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Lc(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return U(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:vc.sanitizeContent(D.minifyMarkdownCore(Ac(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return U([],0)}}async function wm(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=$(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!Sm(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=D.minifyMarkdownCore(Ac(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:vc.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"review_inline",path:f.path,line:f.line??f.original_line??void 0,...f.in_reply_to_id!=null?{in_reply_to_id:f.in_reply_to_id}:{}}}),p=[];return u>0&&p.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:U([],0)}}}async function xm(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Oc(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=oo(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=$(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Ui(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Ui(t))){let p=await Tm(l,u,e.number);p&&(s+=me(p)??0,p.files=$i(p.files,t),o.file_changes=p)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=gm(t),c=hm(t);if(a||c){let{owner:l,repo:u}=oo(t);if(l&&u){let d=Rm(t),p=()=>Promise.resolve({comments:U([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([a?Pm(n,l,u,e.number,d):p(),c?wm(n,l,u,e.number,d):p()]);o.comments=[...f,...g],s+=(me(f)??0)+(me(g)??0);let x=[m,b].filter(S=>typeof S=="string");x.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...x])}}if(bm(t))try{let{owner:l,repo:u}=oo(t);if(l&&u){let d=await Cm(n,l,u,e.number);s+=me(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(ym(t))try{let{owner:l,repo:u}=oo(t);if(l&&u){let d=await km(l,u,e.number,t);d&&(s+=me(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return U(o,s)}async function Lc(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=$(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function Tm(e,t,n,r){let o=await he(r),{items:i,rawResponseChars:s}=await Lc(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U({total_count:i.length,files:i},s)}async function XT(e,t,n,r){let o=await he(r),{items:i,rawResponseChars:s}=await Lc(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U(i,s)}async function JT(e,t,n,r){try{let i=await(await he(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return U(i.data.files||[],i.data)}catch{return null}}async function km(e,t,n,r,o){let i=await XT(e,t,n,o);if(!i)return null;let s=me(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await Promise.all(a.map(async l=>{let u=await JT(e,t,l.sha,o),d=[];return u&&(s+=me(u)??0,d=$i(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return U(c,s)}async function qi(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Oc(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Ui(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ui(t))try{let d=await Tm(a,c,e.number,r);d&&(s+=me(d)??0,d.files=$i(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=gm(t),u=hm(t);if(l||u){let d=Rm(t),p=()=>Promise.resolve({comments:U([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([l?Pm(n,a,c,e.number,d):p(),u?wm(n,a,c,e.number,d):p()]);o.comments=[...f,...g],s+=(me(f)??0)+(me(g)??0);let x=[m,b].filter(S=>typeof S=="string");x.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...x])}if(bm(t))try{let d=await Cm(n,a,c,e.number);s+=me(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(ym(t))try{let d=await km(a,c,e.number,t,r);d&&(s+=me(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return U(o,s)}var YT,_c=y(()=>{"use strict";Ce();Ue();ji();de();YT=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function ZT(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function Em(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:je.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:je.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await he(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await qi(a,e,i,t);return{pull_requests:[ro(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:$(s.data)+(me(c)??0)}}catch(i){let s=ae(i);return ZT(s,je.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var Om=y(()=>{"use strict";xt();Ue();It();Jt();ji();_c();de()});function vm(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Am(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function ek(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}function tk(e,t){return qe("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e["team-mentions"],project:e.project,archived:e.archived,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},t)}async function Lm(e,t,n){let r=tk(e,n);return await We(r,async()=>await nk(e,t,n),{shouldCache:i=>!i.error})}async function nk(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Em(e,t);let r=await he(t);if(!Pf(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await rk(r,e);let i=await ek(r,e),s=Sf(i);if(!s)return{pull_requests:[],total_count:0,error:je.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),p=d.data.items?.filter(E=>!!E.pull_request)||[],f=await Promise.all(p.map(async E=>await xm(E,i,r))),m=f.reduce((E,w)=>E+(me(w)??0),0),g=f.map(E=>ro(E,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,x=Math.min(b,1e3),S=Math.min(Math.ceil(x/c),10),k=Math.min(l,Math.max(1,S)),A=k<S,_=Math.min(x,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:k,totalPages:S,perPage:c,totalMatches:x,reportedTotalMatches:b,reachableTotalMatches:_,totalMatchesKind:"reported",totalMatchesCapped:b>x,hasMore:A,...A?{nextPage:k+1}:{}},rawResponseChars:$(d.data)+m}}catch(r){if(gn(r))return Am(e);let o=ae(r);return vm(o,je.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function rk(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async p=>await qi(p,t,e))),c=a.reduce((p,f)=>p+(me(f)??0),0),l=a.map(p=>ro(p,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:$(s.data)+c}}catch(n){if(gn(n))return Am(t);let r=ae(n);return vm(r,je.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var _m=y(()=>{"use strict";Se();xt();Ue();It();Ai();Jt();de();ji();_c();Om()});function ok(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function ik(e,t,n=ke){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...ok(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Im(e,t,n=ke){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Lm(s,t);return a.error?Ft({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:ik(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??$(a)}}var Fm=y(()=>{"use strict";_m();de();Tt();Tt()});var yn,Wi=y(()=>{"use strict";yn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function Vi(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Ic=y(()=>{"use strict"});function Mm(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:F,...O}=e;return O}let r=t.itemsPerPage??yn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,p=F=>{let O=F;d&&F.startsWith(d)&&(O=F.slice(d.length),O.startsWith("/")&&(O=O.slice(1)));let Q=O.lastIndexOf("/");return Q===-1?".":O.slice(0,Q)},f=F=>{let O=F.lastIndexOf("/");return O===-1?F:F.slice(O+1)};for(let F of l){let O=p(F.path);u[O]||(u[O]={files:[],folders:[]});let Q=f(F.path);F.type==="file"?u[O].files.push(Q):u[O].folders.push(Q)}for(let F of Object.keys(u)){let O=u[F];O&&(O.files.sort(),O.folders.sort())}let m=Object.create(null),g=Object.keys(u).sort((F,O)=>F==="."?-1:O==="."?1:F.localeCompare(O));for(let F of g){let O=u[F];O&&(m[F]=O)}let b=l.filter(F=>F.type==="file").length,x=l.filter(F=>F.type==="dir").length,S=n.filter(F=>F.type==="file").length,k=n.filter(F=>F.type==="dir").length,A=o<s,_={currentPage:o,totalPages:s,hasMore:A,...A?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},E=Vi(_,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:x,allFiles:S,allFolders:k}),w,N=e._cachedFileSizeMap;if(N){let F=new Set(l.filter(G=>G.type==="file").map(G=>G.path)),O=e.path==="/"?"":e.path,Q=Object.create(null);for(let[G,Y]of Object.entries(N))for(let[j,Oe]of Object.entries(Y)){let ve=G==="."?O?`${O}/${j}`:j:O?`${O}/${G}/${j}`:`${G}/${j}`;F.has(ve)&&(Q[G]||(Q[G]=Object.create(null)),Q[G][j]=Oe)}Object.keys(Q).length>0&&(w=Q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:k,truncated:A,filtered:!0,originalCount:i},structure:m,...w!==void 0&&{fileSizeMap:w},...N!==void 0&&{_cachedFileSizeMap:N},pagination:_,hints:E,rawResponseChars:e.rawResponseChars}}var Dm=y(()=>{"use strict";Wi();Ic()});import{RequestError as ak}from"octokit";function Nm(e){return e instanceof ak&&ck.has(e.status)}function Fc(e,t){try{Object.defineProperty(e,Gm,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Mc(e){if(typeof e!="object"||e===null)return 0;let t=e[Gm];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function Dc(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return Fc(U([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(m){if(Nm(m))throw m;return Fc(U([],0),1)}let l=$(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(m=>m.type==="file"||m.type==="dir").map(m=>({name:m.name,path:m.path,type:m.type,size:"size"in m?m.size:void 0,download_url:"download_url"in m?m.download_url:void 0,url:m.url,html_url:m.html_url,git_url:m.git_url,sha:m.sha})),p=[...d],f=0;if(i<s){let m=d.filter(b=>b.type==="dir"),g=3;for(let b=0;b<m.length;b+=g){let x=m.slice(b,b+g),S=await Promise.allSettled(x.map(k=>Dc(e,t,n,r,k.path,i+1,s,a)));for(let k of S)if(k.status==="fulfilled"){let A=k.value;l+=me(A)??0,f+=Mc(A),p.push(...A)}else{if(Nm(k.reason))throw k.reason;f+=1}}}return Fc(U(p,l),f)}var Gm,ck,Hm=y(()=>{"use strict";de();Gm=Symbol.for("octocode.recursiveFetchFailures"),ck=new Set([401,403,429])});import{RequestError as lk}from"octokit";async function uk(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await tt(t,n,i),s=a)}catch(c){let l=ae(c);return{error:Vn.NOT_FOUND.message(t,n,l.error),status:l.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s,...a!==void 0?{repoDefaultBranch:a}:{}}}catch(c){if(!(c instanceof lk&&c.status===404)){let u=ae(c);return{error:Vn.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let l=ae(c);return{error:Vn.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function dk(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function pk(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function zm(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function Qm(e,t,n){let r=qe("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await We(r,async()=>await fk({...e,itemsPerPage:e.itemsPerPage??yn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Mm(o,e):o}async function fk(e,t){try{let n=await he(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await uk(n,r,o,c,i,t);if("error"in l)return l;let{data:u,workingBranch:d,repoDefaultBranch:p}=l,f=$(u),m=Array.isArray(u)?u:[u],g=dk(m),b=0;if(a>1){let re=await Dc(n,r,o,d,c,1,a);b=Mc(re),f+=me(re)??0,g=[...g,...re].filter((Rr,Fo,eP)=>eP.findIndex(tP=>tP.path===Rr.path)===Fo)}let x=g.filter(re=>re.type==="dir"?!Yr(re.name):!Xn(re.path));x.sort((re,Pt)=>{if(re.type!==Pt.type)return re.type==="dir"?-1:1;let Rr=re.path.split("/").length,Fo=Pt.path.split("/").length;return Rr!==Fo?Rr-Fo:re.path.localeCompare(Pt.path)});let S=e.itemsPerPage??yn.ENTRIES_PER_PAGE,k=e.page??1,A=x.length,_=Math.max(1,Math.ceil(A/S)),E=(k-1)*S,w=Math.min(E+S,A),N=x.slice(E,w),F=pk(N,c),O=e.includeSizes===!0?zm(x,c):void 0,Q=O!==void 0?zm(N,c):void 0,G=N.filter(re=>re.type==="file").length,Y=N.filter(re=>re.type==="dir").length,j=x.filter(re=>re.type==="file").length,Oe=x.filter(re=>re.type==="dir").length,ve=k<_,Bt={currentPage:k,totalPages:_,hasMore:ve,...ve?{nextPage:k+1}:{},entriesPerPage:S,totalEntries:A},$t=Vi(Bt,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:G,pageFolders:Y,allFiles:j,allFolders:Oe});return b>0&&$t.unshift(`Partial tree: ${b} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...p!==void 0&&{defaultBranch:p},path:c||"/",apiSource:!0,summary:{totalFiles:j,totalFolders:Oe,truncated:ve,filtered:!0,originalCount:x.length},structure:F,...Q!==void 0&&{fileSizeMap:Q},...O!==void 0&&{_cachedFileSizeMap:O},pagination:Bt,hints:$t,rawResponseChars:f,_cachedItems:x.map(re=>({path:re.path,type:re.type}))}}catch(n){let r=ae(n);return{error:Vn.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var Bm=y(()=>{"use strict";Wi();Ue();It();Jt();Ic();Xr();xt();de();Dm();Hm()});function mk(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function $m(e,t,n=ke){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Qm(i,t);return"error"in s?Ii(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:mk(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??$(s)}}var jm=y(()=>{"use strict";Bm();de();Tt();Tt()});var Um,qm=y(()=>{"use strict";Um={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var Ki,Wm=y(()=>{"use strict";Df();cm();Fm();jm();It();Ue();qm();Tt();Ki=class{type="github";capabilities=Um.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Ff(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await am(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await Mf(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Im(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await $m(t,this.authInfo,ke)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=ke(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return tt(n,r,this.authInfo)}handleError(t){let n=ae(t);return Ft(n)}}});import{createHash as hk}from"crypto";function Vm(e){return Date.now()-e.createdAt<yk}function bk(){for(let[e,t]of kt.entries())Vm(t)||kt.delete(e);if(kt.size>Nc){let e=[...kt.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=kt.size-Nc;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&kt.delete(r[0])}}}function Rk(e){return e?hk("sha256").update(e).digest("hex").slice(0,16):"default"}function Sk(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function Pk(e,t){let n=Sk(t?.baseUrl||"default"),r=Rk(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Gc(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=Pk(e,t),r=kt.get(n);if(r&&Vm(r))return r.lastAccessedAt=Date.now(),r.provider;r&&kt.delete(n),kt.size>=Nc&&bk();let o=new Ki({...t,type:e}),i=Date.now();return kt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function Km(){try{return Gc("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
20
+ `),[{provider:"github",ok:!1,error:t}]}}var yk,Nc,kt,Hc=y(()=>{"use strict";Wm();yk=3600*1e3,Nc=20,kt=new Map});async function Ym(e,t={}){if(!Array.isArray(e))throw new Error(zr.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(zr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(zr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Br.NOT_A_FUNCTION.message(l))));if(r<i.length)return Ck(i,r,n,o);let s=i.map((c,l)=>Xm(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function Xm(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Br.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function Ck(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Br.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await Xm(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var Jm=y(()=>{"use strict";xt()});import{ContentSanitizer as wk}from"@octocodeai/octocode-engine/contentSanitizer";function xk(){try{return yt().output.format}catch{return"yaml"}}function bt(e){if(e==null)return e;if(typeof e=="string")return wk.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>bt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=bt(r);return t}return e}function Tk(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
20
21
 
21
- `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Ui(e,t){let n=Uc(e)??{},r=GT(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;return r==="json"?i=JSON.stringify(Qi(n,t||o),null,2):i=M.jsonToYamlString(n,{keysPriority:t||o}),Xm.sanitizeContent(i).content}function Qi(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Qi(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Qi(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Qi(n[o],t));return r}function BT(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>zT.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Uc(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>Uc(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(BT(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Uc(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var zT,Vr=y(()=>{"use strict";_e();ge();Ym();zT=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"])});function QT(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function $c(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)$c(o,t,n+1);return}let r=e;for(let o of jc){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))Jm.has(o)||i&&typeof i=="object"&&$c(i,t,n+1)}function Zm(e){let t=[];for(let i of e)$c(i?.data,t,0);if(t.length===0)return;let n=QT(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return UT(e,r),n}function UT(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(Jm.has(s))continue;let a=i[s];typeof a=="string"?!jc.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function $T(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function jT(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function eg(e){let t=$T(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(qT.has(i))continue;let s=n[i];jT(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var jc,Jm,qT,tg=y(()=>{"use strict";jc=["path","uri"],Jm=new Set(["next","location"]);qT=new Set([...jc,"owner","repo","name","id"])});function YT(e,t,n){if(e<=1)return ng;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(WT/o),s=Math.max(KT,Math.min(i,ng));return n?Math.max(s,n):s}async function re(e,t,n,r){let o=n.concurrency??VT,{results:i,errors:s}=await eE(e,t,o,n.minQueryTimeoutMs);return XT(n,i,s,e,r)}function XT(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let b=g.result.status;c[g.queryIndex]={id:sg(g.originalQuery,g.queryIndex),...b!==void 0?{status:b}:{},data:tE(g.result)}}),n.forEach(g=>{let b=r[g.queryIndex];b&&(c[g.queryIndex]={id:sg(b,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),b=rg(g.text,o),S=og(g.structuredContent,b.pagination);return ig(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:S,isError:g.isError??(l.length>0&&l.every(k=>k.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let g=Zm(u.results);g&&(u.base=g);let b=eg(u.results);b&&(u.shared=b)}let d=Ui(u,a),p=rg(d,o),f=og(Gt(u),p.pagination);return ig(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(g=>g.status==="error")}}function qc(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
22
- `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function JT(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=qc(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function ZT(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=qc(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function rg(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=qc(e,s,i),c=a<o,l=JT(e,s,i),u=ZT(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
22
+ `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Rn(e,t){let n=bn(e)??{},r=bt(n),o=xk(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Yi(r,t||i),null,2):D.jsonToYamlString(r,{keysPriority:t||i})}function Yi(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Yi(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Yi(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Yi(n[o],t));return r}function Ok(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>kk.has(r))||Ek.some(r=>typeof t[r]=="number"&&t[r]>0)||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function bn(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>bn(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(Ok(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=bn(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var kk,Ek,er=y(()=>{"use strict";wt();Ce();kk=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]),Ek=["totalMatches","totalItems","totalFiles","totalEntries","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches"]});function vk(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function zc(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)zc(o,t,n+1);return}let r=e;for(let o of Qc){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))Zm.has(o)||i&&typeof i=="object"&&zc(i,t,n+1)}function Xi(e){let t=[];for(let i of e)zc(i?.data,t,0);if(t.length===0)return;let n=vk(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return Ak(e,r),n}function Ak(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(Zm.has(s))continue;let a=i[s];typeof a=="string"?!Qc.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function Lk(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function _k(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function Ji(e){let t=Lk(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(Ik.has(i))continue;let s=n[i];_k(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var Qc,Zm,Ik,Bc=y(()=>{"use strict";Qc=["path","uri"],Zm=new Set(["next","location"]);Ik=new Set([...Qc,"owner","repo","name","id"])});function Nk(e,t,n){if(e<=1)return eg;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(Mk/o),s=Math.max(Dk,Math.min(i,eg));return n?Math.max(s,n):s}async function ce(e,t,n,r){let o=n.concurrency??Fk,{results:i,errors:s}=await Qk(e,t,o,n.minQueryTimeoutMs);return Gk(n,i,s,e,r)}function Gk(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let b=g.result.status;c[g.queryIndex]={id:Zi(g.originalQuery,g.queryIndex),...b!==void 0?{status:b}:{},data:Bk(g.result)}}),n.forEach(g=>{let b=r[g.queryIndex];b&&(c[g.queryIndex]={id:Zi(b,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),b=tg(g.text,o),x=ng(g.structuredContent,b.pagination);return rg(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:x,isError:g.isError??(l.length>0&&l.every(k=>k.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let g=Xi(u.results);g&&(u.base=g);let b=Ji(u.results);b&&(u.shared=b)}let d=Rn(u,a),p=tg(d,o),f=ng(bt(bn(u)??{}),p.pagination);return rg(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(g=>g.status==="error")}}function $c(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
23
+ `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function Hk(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=$c(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function zk(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=$c(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function tg(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=$c(e,s,i),c=a<o,l=Hk(e,s,i),u=zk(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
23
24
  `:`# Response page ${l}/${u}.
24
- `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function og(e,t){return t?{...e,responsePagination:t}:e}function ig(e,t,n,r){let o=t.reduce((i,s)=>i+(ce(s.result)??Q(s.result)),0)+n.reduce((i,s)=>i+Q(s),0);try{Ua(e,o,r)}catch{}}async function eE(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await Vm(s,{timeout:YT(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data&&o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}),{results:o,errors:i}}function tE(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function sg(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var VT,ng,WT,KT,$e=y(()=>{"use strict";_e();Km();Vr();ie();tg();VT=3,ng=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,WT=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,KT=5e3});var q,ag,Wr=y(()=>{"use strict";q={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed"},ag={[q.PATH_VALIDATION_FAILED]:{code:q.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[q.FILE_ACCESS_FAILED]:{code:q.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[q.FILE_READ_FAILED]:{code:q.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[q.FILE_TOO_LARGE]:{code:q.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[q.BINARY_FILE_UNSUPPORTED]:{code:q.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[q.NO_MATCHES]:{code:q.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[q.OUTPUT_TOO_LARGE]:{code:q.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[q.COMMAND_NOT_AVAILABLE]:{code:q.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[q.COMMAND_EXECUTION_FAILED]:{code:q.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[q.COMMAND_TIMEOUT]:{code:q.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[q.TOOL_EXECUTION_FAILED]:{code:q.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"}}});function Vc(e){return e instanceof Ie}function cg(e,t=q.TOOL_EXECUTION_FAILED,n){if(Vc(e))return e;if(e instanceof Error)return new Ie(t,e.message,n,e);let r=String(e);return new Ie(t,r,n)}var Ie,Wc=y(()=>{"use strict";Wr();Ie=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=ag[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
25
- Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}}});function nE(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function F(e,t,n={}){let{extra:r}=n,o={status:"error"};if(nE(e))o.error=e;else if(Vc(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=cg(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:U(o,n.rawResponse)}function Fe(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:F(i,t,{toolName:n.toolName})}}var Kc=y(()=>{"use strict";Wc();ie()});function Oe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:U(s,o.rawResponse)}function $i(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return F(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function ve(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return F(i,t)}var Me=y(()=>{"use strict";Kc();ie()});async function je({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return ve(o,t,r,e)}}var Ht=y(()=>{"use strict";Me()});import{redactPath as Kr}from"@octocodeai/octocode-engine/pathUtils";var lg=y(()=>{"use strict"});var et,ji=y(()=>{"use strict";Wc();Wr();lg();et={pathValidationFailed:(e,t,n)=>new Ie(q.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Kr(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Kr(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 Ie(q.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Ie(q.FILE_READ_FAILED,`Failed to read file: ${Kr(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Ie(q.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Ie(q.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Kr(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Ie(q.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Ie(q.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new Ie(q.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Ie(q.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});import ug from"path";import{pathValidator as rE}from"@octocodeai/octocode-engine/pathValidator";function qe(e,t){if(!e.path?.trim()){let s=et.pathValidationFailed("","path is required");return{isValid:!1,errorResult:F(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||ke().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=ug.isAbsolute(r)?r:ug.resolve(n,r),i=rE.validate(o);if(!i.isValid){let s=et.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:F(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}var wt=y(()=>{"use strict";ji();Kc();_e()});import{spawn as oE}from"child_process";function aE(e={},t=Yc){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function an(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Yc,maxOutputSize:a=iE}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),p={cwd:o,env:aE(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=oE(e,t,p)}catch(C){c({stdout:"",stderr:"",exitCode:null,success:!1,error:C instanceof Error?C:new Error(`Failed to spawn command '${e}'`)});return}let m,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{f.kill("SIGTERM")}catch{}m=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},sE),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),b=()=>{clearTimeout(g),m!==void 0&&(clearTimeout(m),m=void 0)},S=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{f.kill("SIGKILL")}catch{}b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};f.stdout?.on("data",C=>{if(l.killed)return;let k=C.toString();l.totalOutputSize+=Buffer.byteLength(k),!S()&&l.stdoutChunks.push(k)}),f.stderr?.on("data",C=>{if(l.killed)return;let k=C.toString();l.totalOutputSize+=Buffer.byteLength(k),!S()&&l.stderrChunks.push(k)}),f.on("close",C=>{l.killed||(b(),c({stdout:u(),stderr:d(),exitCode:C,success:C===0}))}),f.on("error",C=>{l.killed||(l.killed=!0,b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:C}))})})}function Vi(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var Yc,qi,dg,iE,sE,yj,Wi=y(()=>{"use strict";Yc=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],qi=[...Yc,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],dg=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],iE=10*1024*1024,sE=5e3;yj=1*1024*1024});import{validateCommand as cE}from"@octocodeai/octocode-engine/commandValidator";async function $n(e,t=[],n={}){let r=cE(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Vi(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024,tolerateOutputLimit:l=!1}=n,u=await an(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(u.outputLimitExceeded&&l)return{success:!0,code:u.exitCode,stdout:u.stdout,stderr:u.stderr,truncated:!0};if(u.error)throw u.error;return{success:u.success,code:u.exitCode,stdout:u.stdout,stderr:u.stderr}}var Xc=y(()=>{"use strict";Wi()});function ut(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function lE(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},u={command:"7z",args:i},d={command:"7zz",args:i},p={command:"aa",args:s};return ut(pg,e)?[p]:ut(el,e)?[u,d,l,c,a]:ut(Zc,e)?[l,u,d,c,a]:ut(Jc,e)?[a,c,l,u,d]:[c,a,l,u,d]}function uE(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return ut(el,e)?[s,a,o,r,n]:ut(Zc,e)?[o,s,a,r,n]:ut(Jc,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function tl(e){let t=[];for(let n of e){let r=await $n(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function dE(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
25
+ `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function ng(e,t){return t?{...e,responsePagination:t}:e}function rg(e,t,n,r){let o=t.reduce((i,s)=>i+(me(s.result)??$(s.result)),0)+n.reduce((i,s)=>i+$(s),0);try{nc(e,o,r)}catch{}}async function Qk(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await Ym(s,{timeout:Nk(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data?o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery}):c.success&&i.push({queryIndex:c.index,error:"Query produced no result"})}),{results:o,errors:i}}function Bk(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function Zi(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var Fk,eg,Mk,Dk,Ge=y(()=>{"use strict";Lt();Jm();er();de();Bc();Fk=3,eg=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,Mk=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,Dk=5e3});var z,og,tr=y(()=>{"use strict";z={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"},og={[z.PATH_VALIDATION_FAILED]:{code:z.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[z.FILE_ACCESS_FAILED]:{code:z.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[z.FILE_READ_FAILED]:{code:z.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[z.FILE_TOO_LARGE]:{code:z.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[z.BINARY_FILE_UNSUPPORTED]:{code:z.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[z.NO_MATCHES]:{code:z.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[z.OUTPUT_TOO_LARGE]:{code:z.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[z.COMMAND_NOT_AVAILABLE]:{code:z.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[z.COMMAND_EXECUTION_FAILED]:{code:z.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[z.COMMAND_TIMEOUT]:{code:z.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[z.TOOL_EXECUTION_FAILED]:{code:z.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[z.LSP_SERVER_UNAVAILABLE]:{code:z.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function jc(e){return e instanceof Ie}function ig(e,t=z.TOOL_EXECUTION_FAILED,n){if(jc(e))return e;if(e instanceof Error)return new Ie(t,e.message,n,e);let r=String(e);return new Ie(t,r,n)}var Ie,es=y(()=>{"use strict";tr();Ie=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=og[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}
26
+ 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 $k(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function M(e,t,n={}){let{extra:r}=n,o={status:"error"};if($k(e))o.error=e;else if(jc(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=ig(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(n.toolName&&(o.toolName=n.toolName),r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:U(o,n.rawResponse)}function He(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:M(i,t,{toolName:n.toolName})}}var Uc=y(()=>{"use strict";es();de()});function Fe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:U(s,o.rawResponse)}function ts(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return M(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Me(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return M(i,t,{toolName:r})}var ze=y(()=>{"use strict";Uc();de()});async function Ve({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Me(o,t,r,e)}}var Zt=y(()=>{"use strict";ze()});import{redactPath as io}from"@octocodeai/octocode-engine/pathUtils";var sg=y(()=>{"use strict"});var st,ns=y(()=>{"use strict";es();tr();sg();st={pathValidationFailed:(e,t,n)=>new Ie(z.PATH_VALIDATION_FAILED,t||`Path validation failed: ${io(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=io(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 Ie(z.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Ie(z.FILE_READ_FAILED,`Failed to read file: ${io(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Ie(z.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Ie(z.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${io(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Ie(z.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Ie(z.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 Ie(z.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Ie(z.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});import ag from"path";import{pathValidator as jk}from"@octocodeai/octocode-engine/pathValidator";function Ke(e,t){if(!e.path?.trim()){let s=st.pathValidationFailed("","path is required");return{isValid:!1,errorResult:M(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||yt().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=ag.isAbsolute(r)?r:ag.resolve(n,r),i=jk.validate(o);if(!i.isValid){let s=st.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:M(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}var Dt=y(()=>{"use strict";ns();Uc();wt()});import{spawn as Uk}from"child_process";function Vk(e={},t=qc){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function Nt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=qc,maxOutputSize:a=qk}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),p={cwd:o,env:Vk(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=Uk(e,t,p)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let m,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{f.kill("SIGTERM")}catch{}m=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},Wk),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),b=()=>{clearTimeout(g),m!==void 0&&(clearTimeout(m),m=void 0)},x=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{f.kill("SIGKILL")}catch{}b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};f.stdout?.on("data",S=>{if(l.killed)return;let k=S.toString();l.totalOutputSize+=Buffer.byteLength(k),!x()&&l.stdoutChunks.push(k)}),f.stderr?.on("data",S=>{if(l.killed)return;let k=S.toString();l.totalOutputSize+=Buffer.byteLength(k),!x()&&l.stderrChunks.push(k)}),f.on("close",S=>{l.killed||(b(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),f.on("error",S=>{l.killed||(l.killed=!0,b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function os(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var qc,rs,cg,qk,Wk,L1,so=y(()=>{"use strict";qc=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],rs=[...qc,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],cg=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],qk=10*1024*1024,Wk=5e3;L1=1*1024*1024});import{validateCommand as Kk}from"@octocodeai/octocode-engine/commandValidator";async function nr(e,t=[],n={}){let r=Kk(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=os(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024,tolerateOutputLimit:l=!1}=n,u=await Nt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(u.outputLimitExceeded&&l)return{success:!0,code:u.exitCode,stdout:u.stdout,stderr:u.stderr,truncated:!0};if(u.error)throw u.error;return{success:u.success,code:u.exitCode,stdout:u.stdout,stderr:u.stderr}}var Wc=y(()=>{"use strict";so()});function Rt(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function Yk(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},u={command:"7z",args:i},d={command:"7zz",args:i},p={command:"aa",args:s};return Rt(lg,e)?[p]:Rt(Yc,e)?[u,d,l,c,a]:Rt(Kc,e)?[l,u,d,c,a]:Rt(Vc,e)?[a,c,l,u,d]:[c,a,l,u,d]}function Xk(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return Rt(Yc,e)?[s,a,o,r,n]:Rt(Kc,e)?[o,s,a,r,n]:Rt(Vc,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Xc(e){let t=[];for(let n of e){let r=await nr(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function Jk(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
26
27
  `).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
27
- `)}async function fg(e,t){let n=await tl(lE(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?dE(n.stdout,n.commandUsed):n.stdout).split(`
28
- `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function mg(e,t){return tl(uE(e,t))}function pE(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return ut(pg,e)?[c]:ut(el,e)?[s,a,o,n,r]:ut(Zc,e)?[o,s,a,n,r]:ut(Jc,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function gg(e,t){return tl(pE(e,t))}var Jc,Zc,el,pg,hg=y(()=>{"use strict";Xc();Jc=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Zc=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],el=[".dmg",".rar",".cpgz"],pg=[".aar",".yaa"]});function hE(e){let t=e.toLowerCase();for(let{ext:n,format:r}of mE)if(t.endsWith(n))return r}async function yE(e){let t=await $n("file",["--mime-type","-b",e]);if(t.success)return gE[t.stdout.trim().toLowerCase()]}async function bE(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await $n(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await $n(r.command,r.args)).stderr,commandUsed:r.command}}async function yg(e,t){let n;if(t!=="auto"?n=t:n=hE(e)??await yE(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=fE[n],o=await bE(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}var fE,mE,gE,bg=y(()=>{"use strict";Xc();fE={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},mE=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],gE={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"}});function Rg(e){try{return{success:!0,info:M.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function Sg(e,t,n,r=0){try{let o=M.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var Cg=y(()=>{"use strict";ge()});import{promises as jn}from"fs";import{join as nl,basename as Ki,dirname as RE,resolve as Pg,sep as SE}from"node:path";import{securityRegistry as CE}from"@octocodeai/octocode-engine/registry";function xg(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function xE(e){return nl(Le.unzip,`${Ki(e)}-${xg()}`)}function TE(e,t){return nl(Le.binary,`${Ki(e)}-${t}-${xg()}`)}function EE(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function rl(e,t,n,r){let o=Pg(TE(e,t)),i=Pg(nl(o,EE(n)));if(!i.startsWith(o+SE)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await jn.mkdir(RE(i),{recursive:!0}),await jn.writeFile(i,r,"utf-8"),i}function OE(){if(!wg){try{CE.addAllowedCommands(kE)}catch{}wg=!0}}function ol(e,t,n){let r=M.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
29
- `):null}function il(e,t,n,r){let s=Un(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function LE(e,t){let n=Rg(e);if(!n.success||!n.info)return F(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function _E(e,t){let n=t.verbose??!1,r=await fg(e,n);if(!r.success)return F(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??vE,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,u=a?Math.ceil(s.length/a):1,d=a?c<u:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:u,hasMore:d,entriesPerPage:a,totalEntries:s.length}}}}async function IE(e,t){let n=t.archiveFile,r=await mg(e,n);if(!r.success)return F(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return F("Entry is empty",t);let i=await rl(e,"extract",n,o);if(t.matchString){let c=ol(o,t.matchString,t.matchStringContextLines??3);if(!c)return F(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=Ze(),a=il(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,contentLength:o.length,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function FE(e,t){let n=await yg(e,t.format??"auto");if(!n.success)return F(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return F("Decompressed file is empty",t);let o=await rl(e,"decompress",`${Ki(e)}.decompressed.txt`,r);if(t.matchString){let a=ol(r,t.matchString,t.matchStringContextLines??3);if(!a)return F(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=Ze(),s=il(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,contentLength:r.length,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function ME(e,t){let n=t.minLength??AE,r=t.includeOffsets??!1,o=t.scanOffset??0,i=Sg(e,n,r,o);if(!i.success)return F(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
30
- `),a=s?await rl(e,"strings",`${Ki(e)}.strings.txt`,s):void 0;if(t.matchString){let d=ol(s,t.matchString,t.matchStringContextLines??3);if(!d)return F(`No lines match "${t.matchString}" in extracted strings`,t);s=d}let l=!!a&&t.charOffset===void 0&&t.charLength===void 0&&!t.matchString?Math.min(wE,Ze()):Ze(),u=il(s,t.charOffset,t.charLength,l);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},contentLength:s.length,totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function DE(e,t){try{await jn.stat(e)}catch{return F(`File not found: ${e}`,t)}let n=xE(e);await jn.mkdir(n,{recursive:!0});let r=await gg(e,n);if(!r.success)return F(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await jn.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function Tg(e){OE();let t=qe(e,PE);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await jn.stat(n)).isFile())return F(`Path is not a regular file: ${n}`,e)}catch{return F(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return LE(n,e);case"list":return _E(n,e);case"extract":return IE(n,e);case"decompress":return FE(n,e);case"strings":return ME(n,e);case"unpack":return DE(n,e);default:return F(`Unknown mode: ${String(e.mode)}`,e)}}var PE,wE,kE,wg,vE,AE,Eg=y(()=>{"use strict";pe();Fn();wt();ge();ki();zr();hg();bg();Cg();PE=A.LOCAL_BINARY_INSPECT,wE=4e3;kE=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],wg=!1;vE=1e3,AE=8});async function kg(e){let{queries:t}=e;return re(t||[],async n=>je({toolName:A.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Fe(On,n);if(r.ok===!1)return r.error;let o=await Tg(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return U(o,s),o}}),{toolName:A.LOCAL_BINARY_INSPECT},e)}var Og=y(()=>{"use strict";Jo();pe();$e();Me();ie();Ht();Eg()});function sl(e){return e.data!==void 0&&!e.error}var vg=y(()=>{"use strict"});import{maskSensitiveData as Ag}from"@octocodeai/octocode-engine/mask";function NE(){return uc().provider??lc()}function GE(e){let t=uc(),n=t.provider??lc(),{baseUrl:r,token:o}=t;try{let i=Bc(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=Ag(s);throw new al(n,`Failed to initialize ${n} provider: ${a}`)}}function tt(e){let t;return()=>t??=GE(e)}function Yi(e,t){return e.capabilities[t]}async function zt(e,t){let n=await t();return sl(n)?{ok:!0,response:n}:{ok:!1,result:$i(n,e)}}async function Lg(e,t){let n=t??NE(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:Ag(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)sl(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var al,cn=y(()=>{"use strict";Qc();vg();_r();Me();al=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});import{existsSync as Jr,readFileSync as HE,writeFileSync as zE,mkdirSync as BE,rmSync as Xr,readdirSync as QE,statSync as UE}from"node:fs";import{join as nt}from"node:path";import{createHash as $E}from"node:crypto";function Fg(e){return nt(e,"tmp","clone")}function Mg(e){return nt(e,"tmp","tree")}function WE(e){return e?`__sp_${$E("sha256").update(e).digest("hex").substring(0,6)}`:""}function Dg(e,t,n,r,o){let i=`${r}${WE(o)}`;return nt(Fg(e),t,n,i)}function cl(e,t,n,r){return nt(Mg(e),t,n,r)}function KE(e){return typeof e=="object"&&e!==null}function YE(e){if(!KE(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 ll(e){let t=nt(e,Ig);if(!Jr(t))return null;try{return YE(JSON.parse(HE(t,"utf-8")))}catch{return null}}function Zr(e,t){try{zE(nt(e,Ig),JSON.stringify(t,null,2),"utf-8")}catch{}}function Ng(e){return Date.now()<new Date(e.expiresAt).getTime()}function eo(e){let t=ll(e);return t?Ng(t)?Jr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function XE(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return jE}function JE(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return qE}function ZE(){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 VE}function to(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+XE()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function un(e){let t=nt(e,"..");try{Jr(t)||BE(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 Xi(e){try{Jr(e)&&Xr(e,{recursive:!0,force:!0})}catch{}}function Yr(e){try{return UE(e).isDirectory()}catch{return!1}}function ln(e){try{return QE(e)}catch{return[]}}function*Gg(e){for(let t of ln(e)){let n=nt(e,t);if(Yr(n))for(let r of ln(n)){let o=nt(n,r);if(Yr(o))for(let i of ln(o)){let s=nt(o,i);Yr(s)&&(yield s)}}}}function _g(e){for(let t of[...ln(e)]){let n=nt(e,t);if(Yr(n)){for(let r of[...ln(n)]){let o=nt(n,r);if(Yr(o)&&ln(o).length===0)try{Xr(o,{recursive:!0,force:!0})}catch{}}if(ln(n).length===0)try{Xr(n,{recursive:!0,force:!0})}catch{}}}}function ek(e){let t=0;for(let n of Gg(e))try{let r=ll(n);(!r||!Ng(r))&&(Xr(n,{recursive:!0,force:!0}),t++)}catch{}return t}function tk(e){let t=[];for(let n of Gg(e)){let r=ll(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??yi(n)})}return t}function nk(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{Xr(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Hg(e){if(!Jr(e))return 0;let t=0;try{t+=ek(e)}catch{return t}_g(e);let n=nk(tk(e),JE(),ZE());return t+=n,n>0&&_g(e),t}function zg(e){return Hg(Fg(e))}function ul(e){return Hg(Mg(e))}var jE,s1,qE,VE,Ig,dl=y(()=>{"use strict";_e();jE=1440*60*1e3,s1=600*1e3,qE=2*1024*1024*1024,VE=50,Ig=".octocode-clone-meta.json"});import{existsSync as rk,mkdirSync as pl,renameSync as ok,rmSync as ik}from"fs";import{join as no}from"path";import{createHash as sk}from"crypto";async function $g(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await Rk();let a=e.branch??await Ye(r,o,t),c=Nn(),l=Dg(c,r,o,a,i);return dk(c,l,async()=>{let u=eo(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};zg(c),un(l);let d=bk(t,n),p=fk(c,l);Xi(p);try{if(i){if(await yk(r,o,a,p,i,d),!rk(no(p,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await hk(r,o,a,p,d);let f=to(r,o,a,"clone",i);return Zr(p,f),mk(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw Xi(p),f}})}async function dk(e,t,n){un(t);let r=pk(e,t);pl(no(e,"tmp",Qg),{recursive:!0,mode:448});let o=Date.now();for(;;)try{pl(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>ck)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await gk(lk)}try{return await n()}finally{ik(r,{recursive:!0,force:!0})}}function jg(e){return sk("sha256").update(e).digest("hex").slice(0,16)}function pk(e,t){return no(e,"tmp",Qg,jg(t))}function fk(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=no(e,"tmp",uk);return pl(r,{recursive:!0,mode:448}),no(r,`${jg(t)}-${n}`)}function mk(e,t){Xi(t),un(t),ok(e,t)}function gk(e){return new Promise(t=>setTimeout(t,e))}async function hk(e,t,n,r,o){let i=Vg(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",qg(e,t),r),await fl(i,Bg,`full clone of ${e}/${t}`,o)}async function yk(e,t,n,r,o,i){let s=Vg(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",qg(e,t),r),await fl(s,Bg,`sparse clone of ${e}/${t}`,i),await fl(["-C",r,"sparse-checkout","set","--skip-checks","--",o],ak,`sparse-checkout set ${o}`,void 0)}function qg(e,t){return`https://github.com/${e}/${t}.git`}function Vg(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function bk(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function Rk(){try{if(!(await an("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Ug,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function Sk(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function fl(e,t,n,r){let o=await an("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Ug,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=Sk(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var Bg,ak,ck,lk,Qg,uk,Ug,Wg=y(()=>{"use strict";_e();Be();Wi();dl();Bg=120*1e3,ak=30*1e3,ck=300*1e3,lk=100,Qg="clone-locks",uk="clone-tmp",Ug=[...qi,"GIT_TERMINAL_PROMPT"]});async function Kg(e){let{queries:t,authInfo:n}=e,r=tt(n);return re(t,async(o,i)=>je({toolName:A.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Yi(s,"cloneRepo"))return ve(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",A.GITHUB_CLONE_REPO);let a;try{a=await $g(o,n,s.token)}catch(p){let f=p instanceof Error?p.message:String(p);return F(`Clone failed for ${o.owner}/${o.repo}: ${f}`,o)}let c=yi(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={localSearch:{tool:"localSearchCode",query:{path:a.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return Oe(o,d,!0,A.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:A.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}var Yg=y(()=>{"use strict";_e();pe();$e();Me();Ht();cn();Wg()});import{writeFileSync as eh,mkdirSync as ml,existsSync as ro,rmSync as Ck,readdirSync as Pk,statSync as th}from"node:fs";import{join as Ji,dirname as nh,resolve as gl,sep as hl}from"node:path";function Jg(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function Ek(e){return Object.values(e).every(t=>t===0)}function Zg(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 ih(e,t,n,r,o,i=!1){let s=Nn(),a=cl(s,e,t,r),c=gl(Ji(a,n));if(!c.startsWith(a+hl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=eo(a);if(l.hit&&!i&&ro(c)){let v=Ak(c,a),D=Jg();return{localPath:c,repoRoot:a,files:v.files,fileCount:v.fileCount,totalSize:v.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:v.fileCount,eligibleFileCount:v.fileCount,savedFileCount:v.fileCount,skipped:D,limits:Xg,warnings:Zg(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await ue(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:p}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(p))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=p,m=Jg(),g=[];for(let v of f){if(v.type!=="file"){m.nonFile+=1;continue}if(!v.download_url){m.missingDownloadUrl+=1;continue}if(v.size>oh){m.oversized+=1;continue}let D=Rf(v.name,{lowercase:!0,leadingDot:!0});if(Tk.has(D)){m.binary+=1;continue}g.push(v)}m.fileLimit=Math.max(0,g.length-yl);let b=g.slice(0,yl),S=o?.token,C=await kk(b,wk,S);m.fetchFailed=b.length-C.length;let k=0,_=[];for(let v=0;v<C.length;v+=1){let{entry:D,content:B}=C[v];if(k+B.length>rh){m.totalSizeLimit=C.length-v;break}k+=B.length,_.push({entry:D,content:B})}ul(s),un(a),ro(c)&&Ck(c,{recursive:!0,force:!0}),ml(c,{recursive:!0,mode:448});let E=[];for(let{entry:v,content:D}of _){let B=gl(Ji(a,v.path));if(!B.startsWith(a+hl)){m.pathTraversal+=1;continue}let Z=nh(B);ro(Z)||ml(Z,{recursive:!0,mode:448}),eh(B,D,"utf-8"),E.push({path:v.path,size:D.length,type:"file"})}let O=to(e,t,r,"treeFetch",void 0,void 0,d);Zr(a,O);let x=Ek(m),H=x,I=m.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:k,complete:x,verified:H,...d?{commitSha:d}:{},...I?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:m,limits:Xg,warnings:Zg(x,H),cached:!1,expiresAt:O.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function sh(e,t,n,r,o,i=!1){let s=Nn(),a=cl(s,e,t,r),c=gl(Ji(a,n));if(!c.startsWith(a+hl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=eo(a);if(!i&&l.hit&&ro(c))return{localPath:c,repoRoot:a,path:n,size:Lk(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await Ei({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let m="error"in u?u.error:void 0;throw new Error(m||`Failed to fetch ${e}/${t}/${n}`)}ul(s),un(a);let d=nh(c);ro(d)||ml(d,{recursive:!0,mode:448}),eh(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=to(e,t,p,"treeFetch");return Zr(a,f),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:p}}async function kk(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 vk(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function vk(e,t){try{let o=new URL(e);if(!Ok.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(),xk);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 Ak(e,t){let n=[],r=0;function o(i){let s;try{s=Pk(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Ji(i,a);try{let l=th(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function Lk(e){try{return th(e).size}catch{return 0}}var yl,rh,oh,wk,xk,Tk,Xg,Ok,ah=y(()=>{"use strict";_e();Be();Ec();dl();Hr();yl=50,rh=5*1024*1024,oh=300*1024,wk=5,xk=1e4,Tk=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"]),Xg={maxDirectoryFiles:yl,maxTotalSize:rh,maxFileSize:oh};Ok=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function Ik(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function ch(e,t){return e&&t?`${e}/${t}`:void 0}function lh(e){return{keywords:e.keywords??[],projectId:ch(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function uh(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Fk(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function dh(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=Fk(a),u=`${c}/${l}`,d=s,p=o.get(u);if(p||(p={id:u,owner:c,repo:l,matches:[]},o.set(u,p)),n||!s.matches?.length){p.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let f=!0,m=!1;for(let g of s.matches){if(!g.context)continue;let b={path:s.path,value:Ik(g.context)};g.positions?.length>0&&(b.matchIndices=g.positions.map(([S,C])=>({start:S,end:C,lineOffset:(g.context??"").substring(0,S).split(`
31
- `).length-1}))),r&&f&&d.url&&(b.url=d.url,f=!1),p.matches.push(b),m=!0}m||p.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...uh(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function ph(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function fh(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function Mk(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function mh(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Mk),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ch(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Dk(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function Nk(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function Gk(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:Nk(e)}}function gh(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=Dk(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=Gk(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...uh(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function hh(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function yh(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function bh(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??sn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Rh(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[p])=>d==="."?-1:p==="."?1:d.localeCompare(p)).map(([d,p])=>({dir:d,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[d,p]of Object.entries(c))if(n[d]){let f=new Set(n[d].files);for(let[m,g]of Object.entries(p))f.has(m)&&(l[m]=g)}}let u={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(u.resolvedBranch=i),s&&(u.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(u.pagination=e.pagination),u}var qn=y(()=>{"use strict";fe();Hi()});function Hk(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function Zi(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=Hk(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function es(e,t,n){let r=Ui(e,[...t]);return{structuredContent:Gt(e),text:r,isError:n}}var bl=y(()=>{"use strict";Vr()});function ts(e){return typeof e=="object"&&e!==null}function rt(e){return typeof e=="string"&&e.length>0?e:void 0}function Ve(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Sh(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function dt(e,t){return Ve(e[t])??0}function zk(e){if(ts(e))return{nonFile:dt(e,"nonFile"),missingDownloadUrl:dt(e,"missingDownloadUrl"),oversized:dt(e,"oversized"),binary:dt(e,"binary"),fileLimit:dt(e,"fileLimit"),fetchFailed:dt(e,"fetchFailed"),totalSizeLimit:dt(e,"totalSizeLimit"),pathTraversal:dt(e,"pathTraversal")}}function Bk(e){if(ts(e))return{maxDirectoryFiles:dt(e,"maxDirectoryFiles"),maxTotalSize:dt(e,"maxTotalSize"),maxFileSize:dt(e,"maxFileSize")}}function Uk(e){if(!ts(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of Qk){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function $k(e,t){return`${e}/${t}`}function jk(e,t,n){let r=$k(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function qk(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function Vk(e,t){let n=Uk(e.pagination),r=qk(n,t);return{path:rt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:rt(e.localPath),repoRoot:rt(e.repoRoot),...Ve(e.fileSize)!==void 0?{fileSize:Ve(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:Ve(e.totalLines),sourceChars:Ve(e.sourceChars),sourceBytes:Ve(e.sourceBytes),resolvedBranch:rt(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:Ve(e.startLine),endLine:Ve(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:rt(e.lastModified),lastModifiedBy:rt(e.lastModifiedBy),warnings:Sh(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:rt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function Wk(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(ts).map(c=>({path:rt(c.path)??"",size:Ve(c.size)??0,type:rt(c.type)??"file"})),o=zk(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:rt(e.localPath)??"",repoRoot:rt(e.repoRoot),fileCount:Ve(e.fileCount)??r.length,totalSize:Ve(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ve(e.directoryEntryCount),eligibleFileCount:Ve(e.eligibleFileCount),savedFileCount:Ve(e.savedFileCount),skipped:o,limits:Bk(e.limits),warnings:Sh(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:rt(e.resolvedBranch)}}function Kk(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=jk(n,s,a),l=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(Wk(l,i)),c.directories=d;return}let u=c.files??[];u.push(Vk(l,i)),c.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{...r,data:o}})}function Yk(e,t){return Zi(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error}})}function Ch(){return({queries:e,results:t})=>{let n=Kk(t,e),r=Yk(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),es(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}var Qk,Ph=y(()=>{"use strict";bl();Qk=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function wh(e){let{queries:t,authInfo:n}=e,r=tt(n);return re(t,async(o,i)=>{try{let s=Fe(Sn,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?Xk(a,n,c):Jk(a,n,c)}catch(s){return ve(s,o,void 0,A.GITHUB_FETCH_CONTENT)}},{toolName:A.GITHUB_FETCH_CONTENT,finalize:Ch()},e)}async function Xk(e,t,n){let r=ke();if(!(r.local.enabled&&r.local.enableClone))return F("Directory fetch requires local clone support. Set ENABLE_LOCAL=true and ENABLE_CLONE=true.",e);if(!Yi(n,"fetchDirectoryToDisk"))return ve(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",A.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return F("Directory fetch requires both owner and repo.",e,{rawResponse:0});let o=e.branch??await Ye(e.owner,e.repo,t),i=await ih(e.owner,e.repo,String(e.path),o,t,!!e.forceRefresh),s=(i.skipped?.nonFile??0)>0,a=i.skipped?Object.fromEntries(Object.entries(i.skipped).filter(([,d])=>d>0)):void 0,c={kind:"directory",localPath:i.localPath,repoRoot:i.repoRoot,source:"treeFetch",cached:i.cached,complete:i.complete,verified:i.verified,...i.commitSha?{commitSha:i.commitSha}:{},...s?{hasSubdirectories:!0}:{},...a&&Object.keys(a).length>0?{skippedSummary:a}:{},owner:e.owner,repo:e.repo},l={localSearch:{tool:"localSearchCode",query:{path:i.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:i.localPath}},...s?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:i.localPath,repoRoot:i.repoRoot,fileCount:i.fileCount,totalSize:i.totalSize,complete:i.complete,verified:i.verified,...i.commitSha?{commitSha:i.commitSha}:{},directoryEntryCount:i.directoryEntryCount,eligibleFileCount:i.eligibleFileCount,savedFileCount:i.savedFileCount,skipped:i.skipped,limits:i.limits,...i.warnings?{warnings:i.warnings}:{},files:i.files,...i.cached?{cached:!0}:{},...e.branch!==i.branch?{resolvedBranch:i.branch}:{},location:c,next:l};return Oe(e,u,!0,A.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??Q(i)})}async function Jk(e,t,n){let r=await zt(e,()=>n.provider.getFileContent(hh(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await Zk(e,t):void 0,i={...yh(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Oe(e,i,s,A.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function Zk(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ye(e.owner,e.repo,t);return sh(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var xh=y(()=>{"use strict";pe();$e();Me();vo();ah();Be();ie();qn();cn();Ph();_e()});function eO(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function tO(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function nO(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function Th(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function rO(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:Th(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:Th(r.get(i)),...s?{pagination:s}:{}}}})}function oO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function iO(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${oO(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function sO(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?nO(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:iO(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:aO(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function aO(e,t){return{...e,matches:t}}function Eh(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=eO(p);m.incompleteResults&&(i=!0),m.results.reduce((S,C)=>S+C.matches.length,0)===0&&o.push({id:p.id,...m.nonExistentScope?{nonExistentScope:!0}:{},...m.incompleteResults?{incompleteResults:!0}:{}});let b=m.results;n.push({id:p.id,groups:b}),m.pagination&&r.set(p.id,m.pagination)});let s=Array.from(new Set(e.flatMap(p=>{let f=p.keywords;return Array.isArray(f)?f.filter(m=>typeof m=="string"):[]}))),a=sO(tO(n),s),c=Zi(t),l=e.some(p=>p.concise===!0),u=rO(e,a,r);if(l)for(let p of u)p.data.files=p.data.files.map(f=>`${f.owner}/${f.repo}:${f.path}`);let d={results:u};return o.length>0&&(d.emptyQueries=o.map(({id:p,nonExistentScope:f,incompleteResults:m})=>({id:p,...f?{nonExistentScope:f}:{},...m?{incompleteResults:m}:{}}))),c.length>0&&(d.errors=c),i&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),es(d,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],a.length===0&&c.length>0)}}var kh=y(()=>{"use strict";bl()});function cO(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function lO(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function Oh(e){let{queries:t}=e,n=tt(e.authInfo);return re(t,async(r,o)=>{try{let i=lO(r);if(i)return F(i.error,r);if(!cO(r))return F("At least one search term or scope filter is required.",r);let s=n(),a=await zt(r,()=>s.provider.searchCode(lh(r)));if(a.ok===!1)return a.result;let c=dh(a.response.data,r);return Oe(r,c,c.results.length>0,A.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return ve(i,r,void 0,A.GITHUB_SEARCH_CODE)}},{toolName:A.GITHUB_SEARCH_CODE,finalize:Eh()},e)}var vh=y(()=>{"use strict";pe();$e();Me();qn();cn();kh()});function uO(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function dO(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function pO(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Ah(e){let{content:t,reviewMode:n}=e,r=uO(t,n),o=dO(t,n),i=pO(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}var Lh=y(()=>{"use strict"});function Cl(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function rs(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function Pl(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function is(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Ih(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Fh(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function fO(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function os(e,t,n){return fO({...Fh(e,t),...n})}function _h(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return os(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function Rl(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return os(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function mO(e,t,n){return{target:Fh(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function ns(e){return String(e.path??e.filename??"")}function gO(e,t){return{path:ns(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function hO(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function yO(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=hO(r,n.comments),i=Cl(t),s=i?o.filter(l=>rs(l.body,i)):o,{items:a,pagination:c}=Pl(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=is(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:Ih(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function bO(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=Cl(t);return{reviews:(o?r.filter(s=>rs(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=is(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function RO(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=Pl(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function SO(e){return e.split(`
28
+ `)}async function ug(e,t){let n=await Xc(Yk(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?Jk(n.stdout,n.commandUsed):n.stdout).split(`
29
+ `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function dg(e,t){return Xc(Xk(e,t))}function Zk(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return Rt(lg,e)?[c]:Rt(Yc,e)?[s,a,o,n,r]:Rt(Kc,e)?[o,s,a,n,r]:Rt(Vc,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function pg(e,t){return Xc(Zk(e,t))}var Vc,Kc,Yc,lg,fg=y(()=>{"use strict";Wc();Vc=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Kc=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Yc=[".dmg",".rar",".cpgz"],lg=[".aar",".yaa"]});function rE(e){let t=e.toLowerCase();for(let{ext:n,format:r}of tE)if(t.endsWith(n))return r}async function oE(e){let t=await nr("file",["--mime-type","-b",e]);if(t.success)return nE[t.stdout.trim().toLowerCase()]}async function iE(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await nr(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await nr(r.command,r.args)).stderr,commandUsed:r.command}}async function mg(e,t){let n;if(t!=="auto"?n=t:n=rE(e)??await oE(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=eE[n],o=await iE(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}var eE,tE,nE,gg=y(()=>{"use strict";Wc();eE={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},tE=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],nE={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"}});function hg(e){try{return{success:!0,info:D.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function yg(e,t,n,r=0){try{let o=D.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var bg=y(()=>{"use strict";Ce()});import{promises as rr}from"fs";import{join as Jc,basename as is,dirname as sE,resolve as Rg,sep as aE}from"node:path";import{securityRegistry as cE}from"@octocodeai/octocode-engine/registry";function Pg(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function dE(e){return Jc(ot.unzip,`${is(e)}-${Pg()}`)}function pE(e,t){return Jc(ot.binary,`${is(e)}-${t}-${Pg()}`)}function fE(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function Zc(e,t,n,r){let o=Rg(pE(e,t)),i=Rg(Jc(o,fE(n)));if(!i.startsWith(o+aE)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await rr.mkdir(sE(i),{recursive:!0}),await rr.writeFile(i,r,"utf-8"),i}function gE(){if(!Sg){try{cE.addAllowedCommands(mE)}catch{}Sg=!0}}function el(e,t,n){let r=D.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
30
+ `):null}function tl(e,t,n,r){let s=Zn(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function bE(e,t){let n=hg(e);if(!n.success||!n.info)return M(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function RE(e,t){let n=t.verbose??!1,r=await ug(e,n);if(!r.success)return M(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??hE,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,u=a?Math.ceil(s.length/a):1,d=a?c<u:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:u,hasMore:d,entriesPerPage:a}}}}async function SE(e,t){let n=t.archiveFile,r=await dg(e,n);if(!r.success)return M(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return M("Entry is empty",t);let i=await Zc(e,"extract",n,o);if(t.matchString){let c=el(o,t.matchString,t.matchStringContextLines??3);if(!c)return M(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=it(),a=tl(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function PE(e,t){let n=await mg(e,t.format??"auto");if(!n.success)return M(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return M("Decompressed file is empty",t);let o=await Zc(e,"decompress",`${is(e)}.decompressed.txt`,r);if(t.matchString){let a=el(r,t.matchString,t.matchStringContextLines??3);if(!a)return M(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=it(),s=tl(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function CE(e,t){let n=t.minLength??yE,r=t.includeOffsets??!1,o=t.scanOffset??0,i=yg(e,n,r,o);if(!i.success)return M(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
31
+ `),a=s?await Zc(e,"strings",`${is(e)}.strings.txt`,s):void 0;if(t.matchString){let d=el(s,t.matchString,t.matchStringContextLines??3);if(!d)return M(`No lines match "${t.matchString}" in extracted strings`,t);s=d}let l=!!a&&t.charOffset===void 0&&t.charLength===void 0&&!t.matchString?Math.min(uE,it()):it(),u=tl(s,t.charOffset,t.charLength,l);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function wE(e,t){try{await rr.stat(e)}catch{return M(`File not found: ${e}`,t)}let n=dE(e);await rr.mkdir(n,{recursive:!0});let r=await pg(e,n);if(!r.success)return M(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await rr.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function Cg(e){gE();let t=Ke(e,lE);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await rr.stat(n)).isFile())return M(`Path is not a regular file: ${n}`,e)}catch{return M(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return bE(n,e);case"list":return RE(n,e);case"extract":return SE(n,e);case"decompress":return PE(n,e);case"strings":return CE(n,e);case"unpack":return wE(n,e);default:return M(`Unknown mode: ${String(e.mode)}`,e)}}var lE,uE,mE,Sg,hE,yE,wg=y(()=>{"use strict";Re();Ir();Dt();Ce();Mi();Jr();fg();gg();bg();lE=v.LOCAL_BINARY_INSPECT,uE=4e3;mE=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],Sg=!1;hE=1e3,yE=8});async function xg(e){let{queries:t}=e;return ce(t||[],async n=>Ve({toolName:v.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=He(Hn,n);if(r.ok===!1)return r.error;let o=await Cg(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return U(o,s),o}}),{toolName:v.LOCAL_BINARY_INSPECT},e)}var Tg=y(()=>{"use strict";li();Re();Ge();ze();de();Zt();wg()});function nl(e){return e.data!==void 0&&!e.error}var kg=y(()=>{"use strict"});import{maskSensitiveData as Eg}from"@octocodeai/octocode-engine/mask";function xE(){return ac().provider??sc()}function TE(e){let t=ac(),n=t.provider??sc(),{baseUrl:r,token:o}=t;try{let i=Gc(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=Eg(s);throw new rl(n,`Failed to initialize ${n} provider: ${a}`)}}function at(e){let t;return()=>t??=TE(e)}function ss(e,t){return e.capabilities[t]}async function en(e,t){let n=await t();return nl(n)?{ok:!0,response:n}:{ok:!1,result:ts(n,e)}}async function Og(e,t){let n=t??xE(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:Eg(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)nl(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var rl,Sn=y(()=>{"use strict";Hc();kg();Ur();ze();rl=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});import{existsSync as lo,readFileSync as kE,writeFileSync as EE,mkdirSync as OE,rmSync as co,readdirSync as vE,statSync as AE}from"node:fs";import{join as ct}from"node:path";import{createHash as LE}from"node:crypto";function Lg(e){return ct(e,"tmp","clone")}function _g(e){return ct(e,"tmp","tree")}function ME(e){return e?`__sp_${LE("sha256").update(e).digest("hex").substring(0,6)}`:""}function Ig(e,t,n,r,o){let i=`${r}${ME(o)}`;return ct(Lg(e),t,n,i)}function ol(e,t,n,r){return ct(_g(e),t,n,r)}function DE(e){return typeof e=="object"&&e!==null}function NE(e){if(!DE(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 il(e){let t=ct(e,Ag);if(!lo(t))return null;try{return NE(JSON.parse(kE(t,"utf-8")))}catch{return null}}function uo(e,t){try{EE(ct(e,Ag),JSON.stringify(t,null,2),"utf-8")}catch{}}function Fg(e){return Date.now()<new Date(e.expiresAt).getTime()}function po(e){let t=il(e);return t?Fg(t)?lo(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function GE(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return _E}function HE(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return IE}function zE(){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 FE}function fo(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+GE()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function Cn(e){let t=ct(e,"..");try{lo(t)||OE(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 as(e){try{lo(e)&&co(e,{recursive:!0,force:!0})}catch{}}function ao(e){try{return AE(e).isDirectory()}catch{return!1}}function Pn(e){try{return vE(e)}catch{return[]}}function*Mg(e){for(let t of Pn(e)){let n=ct(e,t);if(ao(n))for(let r of Pn(n)){let o=ct(n,r);if(ao(o))for(let i of Pn(o)){let s=ct(o,i);ao(s)&&(yield s)}}}}function vg(e){for(let t of[...Pn(e)]){let n=ct(e,t);if(ao(n)){for(let r of[...Pn(n)]){let o=ct(n,r);if(ao(o)&&Pn(o).length===0)try{co(o,{recursive:!0,force:!0})}catch{}}if(Pn(n).length===0)try{co(n,{recursive:!0,force:!0})}catch{}}}}function QE(e){let t=0;for(let n of Mg(e))try{let r=il(n);(!r||!Fg(r))&&(co(n,{recursive:!0,force:!0}),t++)}catch{}return t}function BE(e){let t=[];for(let n of Mg(e)){let r=il(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??Ti(n)})}return t}function $E(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{co(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Dg(e){if(!lo(e))return 0;let t=0;try{t+=QE(e)}catch{return t}vg(e);let n=$E(BE(e),HE(),zE());return t+=n,n>0&&vg(e),t}function Ng(e){return Dg(Lg(e))}function sl(e){return Dg(_g(e))}var _E,Sq,IE,FE,Ag,al=y(()=>{"use strict";Lt();_E=1440*60*1e3,Sq=600*1e3,IE=2*1024*1024*1024,FE=50,Ag=".octocode-clone-meta.json"});import{existsSync as jE,mkdirSync as cl,renameSync as UE,rmSync as qE}from"fs";import{join as mo}from"path";import{createHash as WE}from"crypto";async function Qg(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await sO();let a=e.branch??await tt(r,o,t),c=_r(),l=Ig(c,r,o,a,i);return JE(c,l,async()=>{let u=po(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Ng(c),Cn(l);let d=iO(t,n),p=eO(c,l);as(p);try{if(i){if(await oO(r,o,a,p,i,d),!jE(mo(p,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await rO(r,o,a,p,d);let f=fo(r,o,a,"clone",i);return uo(p,f),tO(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw as(p),f}})}async function JE(e,t,n){Cn(t);let r=ZE(e,t);cl(mo(e,"tmp",Hg),{recursive:!0,mode:448});let o=Date.now();for(;;)try{cl(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>KE)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await nO(YE)}try{return await n()}finally{qE(r,{recursive:!0,force:!0})}}function Bg(e){return WE("sha256").update(e).digest("hex").slice(0,16)}function ZE(e,t){return mo(e,"tmp",Hg,Bg(t))}function eO(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=mo(e,"tmp",XE);return cl(r,{recursive:!0,mode:448}),mo(r,`${Bg(t)}-${n}`)}function tO(e,t){as(t),Cn(t),UE(e,t)}function nO(e){return new Promise(t=>setTimeout(t,e))}async function rO(e,t,n,r,o){let i=jg(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",$g(e,t),r),await ll(i,Gg,`full clone of ${e}/${t}`,o)}async function oO(e,t,n,r,o,i){let s=jg(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",$g(e,t),r),await ll(s,Gg,`sparse clone of ${e}/${t}`,i),await ll(["-C",r,"sparse-checkout","set","--skip-checks","--",o],VE,`sparse-checkout set ${o}`,void 0)}function $g(e,t){return`https://github.com/${e}/${t}.git`}function jg(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function iO(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function sO(){try{if(!(await Nt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:zg,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function aO(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function ll(e,t,n,r){let o=await Nt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:zg,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=aO(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var Gg,VE,KE,YE,Hg,XE,zg,Ug=y(()=>{"use strict";Lt();Ue();so();al();Gg=120*1e3,VE=30*1e3,KE=300*1e3,YE=100,Hg="clone-locks",XE="clone-tmp",zg=[...rs,"GIT_TERMINAL_PROMPT"]});async function qg(e){let{queries:t,authInfo:n}=e,r=at(n);return ce(t,async(o,i)=>Ve({toolName:v.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!ss(s,"cloneRepo"))return Me(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",v.GITHUB_CLONE_REPO);let a;try{a=await Qg(o,n,s.token)}catch(p){let f=p instanceof Error?p.message:String(p);return M(`Clone failed for ${o.owner}/${o.repo}: ${f}`,o)}let c=Ti(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={localSearch:{tool:"localSearchCode",query:{path:a.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return Fe(o,d,!0,v.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:v.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}var Wg=y(()=>{"use strict";Lt();Re();Ge();ze();Zt();Sn();Ug()});import{writeFileSync as Xg,mkdirSync as ul,existsSync as go,rmSync as cO,readdirSync as lO,statSync as Jg}from"node:fs";import{join as cs,dirname as Zg,resolve as dl,sep as pl}from"node:path";function Kg(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function fO(e){return Object.values(e).every(t=>t===0)}function Yg(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 nh(e,t,n,r,o,i=!1){let s=_r(),a=ol(s,e,t,r),c=dl(cs(a,n));if(!c.startsWith(a+pl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=po(a);if(l.hit&&!i&&go(c)){let O=yO(c,a),Q=Kg();return{localPath:c,repoRoot:a,files:O.files,fileCount:O.fileCount,totalSize:O.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:O.fileCount,eligibleFileCount:O.fileCount,savedFileCount:O.fileCount,skipped:Q,limits:Vg,warnings:Yg(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await he(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:p}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(p))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=p,m=Kg(),g=[];for(let O of f){if(O.type!=="file"){m.nonFile+=1;continue}if(!O.download_url){m.missingDownloadUrl+=1;continue}if(O.size>th){m.oversized+=1;continue}let Q=wf(O.name,{lowercase:!0,leadingDot:!0});if(pO.has(Q)){m.binary+=1;continue}g.push(O)}m.fileLimit=Math.max(0,g.length-fl);let b=g.slice(0,fl),x=o?.token,S=await mO(b,uO,x);m.fetchFailed=b.length-S.length;let k=0,A=[];for(let O=0;O<S.length;O+=1){let{entry:Q,content:G}=S[O];if(k+G.length>eh){m.totalSizeLimit=S.length-O;break}k+=G.length,A.push({entry:Q,content:G})}sl(s),Cn(a),go(c)&&cO(c,{recursive:!0,force:!0}),ul(c,{recursive:!0,mode:448});let _=[];for(let{entry:O,content:Q}of A){let G=dl(cs(a,O.path));if(!G.startsWith(a+pl)){m.pathTraversal+=1;continue}let Y=Zg(G);go(Y)||ul(Y,{recursive:!0,mode:448}),Xg(G,Q,"utf-8"),_.push({path:O.path,size:Q.length,type:"file"})}let E=fo(e,t,r,"treeFetch",void 0,void 0,d);uo(a,E);let w=fO(m),N=w,F=m.nonFile>0;return{localPath:c,repoRoot:a,files:_,fileCount:_.length,totalSize:k,complete:w,verified:N,...d?{commitSha:d}:{},...F?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:g.length,savedFileCount:_.length,skipped:m,limits:Vg,warnings:Yg(w,N),cached:!1,expiresAt:E.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function rh(e,t,n,r,o,i=!1){let s=_r(),a=ol(s,e,t,r),c=dl(cs(a,n));if(!c.startsWith(a+pl)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=po(a);if(!i&&l.hit&&go(c))return{localPath:c,repoRoot:a,path:n,size:bO(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await Fi({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let m="error"in u?u.error:void 0;throw new Error(m||`Failed to fetch ${e}/${t}/${n}`)}sl(s),Cn(a);let d=Zg(c);go(d)||ul(d,{recursive:!0,mode:448}),Xg(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=fo(e,t,p,"treeFetch");return uo(a,f),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:p}}async function mO(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 hO(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function hO(e,t){try{let o=new URL(e);if(!gO.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(),dO);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 yO(e,t){let n=[],r=0;function o(i){let s;try{s=lO(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=cs(i,a);try{let l=Jg(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function bO(e){try{return Jg(e).size}catch{return 0}}var fl,eh,th,uO,dO,pO,Vg,gO,oh=y(()=>{"use strict";Lt();Ue();Cc();al();Xr();fl=50,eh=5*1024*1024,th=300*1024,uO=5,dO=1e4,pO=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"]),Vg={maxDirectoryFiles:fl,maxTotalSize:eh,maxFileSize:th};gO=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function SO(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function ih(e,t){return e&&t?`${e}/${t}`:void 0}function sh(e){return{keywords:e.keywords??[],projectId:ih(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function ah(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function ch(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function lh(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=ch(a),u=`${c}/${l}`,d=s,p=o.get(u);if(p||(p={id:u,owner:c,repo:l,matches:[]},o.set(u,p)),n||!s.matches?.length){p.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let f=!0,m=!1;for(let g of s.matches){if(!g.context)continue;let b={path:s.path,value:SO(g.context)};g.positions?.length>0&&(b.matchIndices=g.positions.map(([x,S])=>({start:x,end:S,lineOffset:(g.context??"").substring(0,x).split(`
32
+ `).length-1}))),r&&f&&d.url&&(b.url=d.url,f=!1),p.matches.push(b),m=!0}m||p.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...ah(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function uh(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function dh(e){return e.map(t=>{let{owner:n,repo:r}=ch(t.fullPath);return{owner:n||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language}}})}function PO(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function ph(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(PO),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:ih(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function CO(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function wO(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:CO(e)}}function fh(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let s=i.fileChanges,a=s?.length??0,c=Array.isArray(i.comments)?i.comments:void 0,l=wO(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...ah(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function mh(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function gh(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function hh(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??yn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function yh(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([p],[f])=>p==="."?-1:f==="."?1:p.localeCompare(f)).map(([p,f])=>({dir:p,files:f.files,folders:f.folders})),c=e.fileSizeMap,l={};if(c){for(let[p,f]of Object.entries(c))if(n[p]){let m=new Set(n[p].files);for(let[g,b]of Object.entries(f))if(m.has(g)){let x=p==="."?g:`${p}/${g}`;l[x]=b}}}let u=Object.values(n).reduce((p,f)=>(p.totalFiles+=f.files.length,p.totalFolders+=f.folders.length,p),{totalFiles:0,totalFolders:0}),d={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:u.totalFiles,totalFolders:u.totalFolders}};return i&&(d.resolvedBranch=i),s&&(d.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(d.pagination=e.pagination),d}var or=y(()=>{"use strict";Se();Wi()});function ls(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function xO(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e;return{message:typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",status:ls(t.status),retryAfterSeconds:ls(t.retryAfter),rateLimitRemaining:ls(t.rateLimitRemaining),rateLimitReset:ls(t.rateLimitReset)}}return{message:"Provider error"}}function us(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o,retryAfterSeconds:i,rateLimitRemaining:s,rateLimitReset:a}=xO(n.data.error),c=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:c,...o!==void 0?{status:o}:{},...i!==void 0?{retryAfterSeconds:i}:{},...s!==void 0?{rateLimitRemaining:s}:{},...a!==void 0?{rateLimitReset:a}:{}})}return t}function ds(e,t,n){let r=Rn(e,[...t]);return{structuredContent:bt(bn(e)??{}),text:r,isError:n}}var ml=y(()=>{"use strict";er()});function ps(e){return typeof e=="object"&&e!==null}function lt(e){return typeof e=="string"&&e.length>0?e:void 0}function Ye(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function bh(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function St(e,t){return Ye(e[t])??0}function TO(e){if(ps(e))return{nonFile:St(e,"nonFile"),missingDownloadUrl:St(e,"missingDownloadUrl"),oversized:St(e,"oversized"),binary:St(e,"binary"),fileLimit:St(e,"fileLimit"),fetchFailed:St(e,"fetchFailed"),totalSizeLimit:St(e,"totalSizeLimit"),pathTraversal:St(e,"pathTraversal")}}function kO(e){if(ps(e))return{maxDirectoryFiles:St(e,"maxDirectoryFiles"),maxTotalSize:St(e,"maxTotalSize"),maxFileSize:St(e,"maxFileSize")}}function OO(e){if(!ps(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of EO){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function vO(e,t){return`${e}/${t}`}function AO(e,t,n){let r=vO(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function LO(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function _O(e,t){let n=OO(e.pagination),r=LO(n,t);return{path:lt(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:lt(e.localPath),repoRoot:lt(e.repoRoot),...Ye(e.fileSize)!==void 0?{fileSize:Ye(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:Ye(e.totalLines),sourceChars:Ye(e.sourceChars),sourceBytes:Ye(e.sourceBytes),resolvedBranch:lt(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:Ye(e.startLine),endLine:Ye(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:lt(e.lastModified),lastModifiedBy:lt(e.lastModifiedBy),warnings:bh(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:lt(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function IO(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(ps).map(c=>({path:lt(c.path)??"",size:Ye(c.size)??0,type:lt(c.type)??"file"})),o=TO(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:lt(e.localPath)??"",repoRoot:lt(e.repoRoot),fileCount:Ye(e.fileCount)??r.length,totalSize:Ye(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:Ye(e.directoryEntryCount),eligibleFileCount:Ye(e.eligibleFileCount),savedFileCount:Ye(e.savedFileCount),skipped:o,limits:kO(e.limits),warnings:bh(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:lt(e.resolvedBranch)}}function FO(e,t){let n=new Map;return e.forEach(r=>{if(r.status==="error")return;let o=t.get(r.id);if(!o)return;let i=String(o.owner??""),s=String(o.repo??"");if(!i||!s)return;let a=AO(n,i,s),c=r.data;if(o.type==="directory"){let u=a.directories??[];u.push(IO(c,o)),a.directories=u;return}let l=a.files??[];l.push(_O(c,o)),a.files=l}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function MO(e,t){return us(e).map(r=>{let o=t.get(r.id);return{id:r.id,owner:o?.owner,repo:o?.repo,path:o?.path?String(o.path):void 0,error:r.error}})}function Rh(){return({queries:e,results:t})=>{let n=new Map;e.forEach((s,a)=>{n.set(Zi(s,a),s)});let r=FO(t,n),o=MO(t,n),i={results:r};return o&&o.length>0&&(i.errors=o),ds(i,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],r.length===0&&!!(o&&o.length>0))}}var EO,Sh=y(()=>{"use strict";ml();Ge();EO=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function Ph(e){let{queries:t,authInfo:n}=e,r=at(n);return ce(t,async(o,i)=>{try{let s=He(_n,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?DO(a,n,c):NO(a,n,c)}catch(s){return Me(s,o,void 0,v.GITHUB_FETCH_CONTENT)}},{toolName:v.GITHUB_FETCH_CONTENT,finalize:Rh()},e)}async function DO(e,t,n){if(!ss(n,"fetchDirectoryToDisk"))return Me(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",v.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return M("Directory fetch requires both owner and repo.",e,{rawResponse:0});let r=e.branch??await tt(e.owner,e.repo,t),o=await nh(e.owner,e.repo,String(e.path),r,t,!!e.forceRefresh),i=(o.skipped?.nonFile??0)>0,s=o.skipped?Object.fromEntries(Object.entries(o.skipped).filter(([,u])=>u>0)):void 0,a={kind:"directory",localPath:o.localPath,repoRoot:o.repoRoot,source:"treeFetch",cached:o.cached,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},...i?{hasSubdirectories:!0}:{},...s&&Object.keys(s).length>0?{skippedSummary:s}:{},owner:e.owner,repo:e.repo},c={localSearch:{tool:"localSearchCode",query:{path:o.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:o.localPath}},...i?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},l={localPath:o.localPath,repoRoot:o.repoRoot,fileCount:o.fileCount,totalSize:o.totalSize,complete:o.complete,verified:o.verified,...o.commitSha?{commitSha:o.commitSha}:{},directoryEntryCount:o.directoryEntryCount,eligibleFileCount:o.eligibleFileCount,savedFileCount:o.savedFileCount,skipped:o.skipped,limits:o.limits,...o.warnings?{warnings:o.warnings}:{},files:o.files,...o.cached?{cached:!0}:{},...e.branch!==o.branch?{resolvedBranch:o.branch}:{},location:a,next:c};return Fe(e,l,!0,v.GITHUB_FETCH_CONTENT,{rawResponse:o.totalSize??$(o)})}async function NO(e,t,n){let r=await en(e,()=>n.provider.getFileContent(mh(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await GO(e,t):void 0,i={...gh(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Fe(e,i,s,v.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function GO(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await tt(e.owner,e.repo,t);return rh(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var Ch=y(()=>{"use strict";Re();Ge();ze();zo();oh();Ue();de();or();Sn();Sh()});function HO(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function zO(e,t){let n=HO(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function QO(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function BO(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function $O(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function wh(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function jO(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:wh(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:wh(r.get(i)),...s?{pagination:s}:{}}}})}function UO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qO(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${UO(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function WO(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?$O(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:qO(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:VO(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function VO(e,t){return{...e,matches:t}}function xh(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=QO(p);m.incompleteResults&&(i=!0),m.results.reduce((x,S)=>x+S.matches.length,0)===0&&o.push({id:p.id,...m.nonExistentScope?{nonExistentScope:!0}:{},...m.incompleteResults?{incompleteResults:!0}:{}});let b=m.results;n.push({id:p.id,groups:b}),m.pagination&&r.set(p.id,m.pagination)});let s=Array.from(new Set(e.flatMap(p=>{let f=p.keywords;return Array.isArray(f)?f.filter(m=>typeof m=="string"):[]}))),a=WO(BO(n),s),c=us(t),l=e.some(p=>p.concise===!0),u=jO(e,a,r);if(l)for(let p of u)p.data.files=p.data.files.map(f=>`${f.owner}/${f.repo}:${f.path}`);let d={results:u};return o.length>0&&(d.emptyQueries=o.map(({id:p,nonExistentScope:f,incompleteResults:m})=>({id:p,...f?{nonExistentScope:f}:{},...m?{incompleteResults:m}:{}}))),c.length>0&&(d.errors=c),i&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),o.length>0&&zO(o,e)&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding."]),ds(d,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],a.length===0&&c.length>0)}}var Th=y(()=>{"use strict";ml()});function KO(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function YO(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function kh(e){let{queries:t}=e,n=at(e.authInfo);return ce(t,async(r,o)=>{try{let i=YO(r);if(i)return M(i.error,r);if(!KO(r))return M("At least one search term or scope filter is required.",r);let s=n(),a=await en(r,()=>s.provider.searchCode(sh(r)));if(a.ok===!1)return a.result;let c=lh(a.response.data,r);return Fe(r,c,c.results.length>0,v.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Me(i,r,void 0,v.GITHUB_SEARCH_CODE)}},{toolName:v.GITHUB_SEARCH_CODE,finalize:xh()},e)}var Eh=y(()=>{"use strict";Re();Ge();ze();or();Sn();Th()});function XO(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function JO(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function ZO(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Oh(e){let{content:t,reviewMode:n}=e,r=XO(t,n),o=JO(t,n),i=ZO(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}var vh=y(()=>{"use strict"});function yl(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function ms(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function bl(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function hs(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Lh(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function _h(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function ev(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function gs(e,t,n){return ev({..._h(e,t),...n})}function Ah(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return gs(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function gl(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return gs(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function tv(e,t,n){return{target:_h(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function fs(e){return String(e.path??e.filename??"")}function nv(e,t){return{path:fs(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function rv(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function ov(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=rv(r,n.comments),i=yl(t),s=i?o.filter(l=>ms(l.body,i)):o,{items:a,pagination:c}=bl(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=hs(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:Lh(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function iv(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=yl(t);return{reviews:(o?r.filter(s=>ms(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=hs(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function sv(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=bl(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function av(e){return e.split(`
32
33
  `).filter(t=>{if(!t.startsWith("+"))return!0;let n=t.slice(1).trim();return n!==""&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")}).map(t=>t.startsWith("+")?"+"+t.slice(1).replace(/\s*\/\/.*$/,"").trimEnd():t).join(`
33
- `)}function CO(e){return e.replace(/\n{3,}/g,`
34
+ `)}function cv(e){return e.replace(/\n{3,}/g,`
34
35
 
35
- `)}function PO(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(f=>i.includes(ns(f))):o,a=Cl(t),c=a?s.filter(f=>rs(ns(f),a)||rs(f.patch,a)):s,{items:l,pagination:u}=Pl(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=gO(f,!1);if(!d||typeof f.patch!="string")return m;let g=r&&!a?SO(f.patch):f.patch,b=is(g,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:$r(b?.content),...b?{patchPagination:b.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(ns).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function oo(e){return typeof e=="object"&&e!==null}function Sl(e){if(oo(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function wl(e){if(oo(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function wO(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function xO(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!oo(n))continue;let r=wl(n.patchPagination);if(r?.hasMore)return r}}function TO(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!oo(n))continue;let r=wl(n.bodyPagination);if(r?.hasMore)return r}}function EO(e,t,n,r){let o={},i=wl(e.bodyPagination),s=Sl(e.filePagination),a=Sl(e.commentPagination),c=Sl(e.commitPagination),l=xO(e),u=TO(e),d=wO(n);i&&(o.body={...i,nextQuery:_h(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:Rl(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:Rl(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:os(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:Rl(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:_h(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return oo(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?os(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function kO(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Mh(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?CO(s):s,c=n.body?is(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,p=t.prNumber!==void 0||t.verbose===!0,m={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...p?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...p?{updatedAt:e.updatedAt}:{},...p||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...p&&!c?{bodyPreview:Ih(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:mO(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...PO(e,t,n,r),...yO(e,t,n),...bO(e,t,n),...RO(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=EO(m,t,n,i);return kO(m),g&&(m.contentPagination=g),m}var Dh=y(()=>{"use strict";fe();Fi()});function OO(e){return e?e.includes('rel="next"'):!1}function Nh(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function Gh(e,t){try{let n=await ue(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=OO(i),a=o.data.map(u=>{let d=u.commit.author,p=u.commit.committer,f=p?.date??d?.date??"",m=u.commit.message,g=m.split(`
36
- `)[0]??m;return{sha:u.sha,date:f,message:m,messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...p?{committer:{name:p.name??"unknown",email:p.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await Promise.all(a.map(async(u,d)=>{try{let p=o.data[d]?.sha??u.sha,f=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:p});if(e.type==="file"&&e.path){let m=e.path,g=f.data.files?.find(b=>b.filename===m||b.previous_filename===m);if(g){let b=g.patch!==void 0?Nh(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...b!==void 0?{patch:b.patch,...b.patchPagination?{patchPagination:b.patchPagination}:{},diff:$r(b.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let m=e.path,g=(f.data.files??[]).filter(x=>!m||x.filename.startsWith(m)).map(x=>{let H=x.patch!==void 0?Nh(x.patch,e.charOffset,e.charLength):void 0;return{filename:x.filename,status:x.status,additions:x.additions,deletions:x.deletions,...H!==void 0?{patch:H.patch,...H.patchPagination?{patchPagination:H.patchPagination}:{},diff:$r(H.patch)}:{},...x.previous_filename?{previousFilename:x.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),S=Math.max(1,e.itemsPerPage??20),C=g.length,k=Math.max(1,Math.ceil(C/S)),_=Math.min(b,k),E=(_-1)*S,O=g.slice(E,E+S);return{...u,files:O,filesPagination:{currentPage:_,totalPages:k,itemsPerPage:S,totalFiles:C,hasMore:_<k,..._<k?{nextFilePage:_+1}:{}}}}}catch{}return u}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return ne(n)}}var Hh=y(()=>{"use strict";Be();St();Fi()});async function zh(e){let{queries:t,authInfo:n}=e,r=tt(n);return re(t,async(o,i)=>{try{let s=Fe(Pn,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let O=s.data;if(!O.owner||!O.repo)return F("owner and repo are required for commits mode.",o);let x=O.path,H=x&&!x.endsWith("/")?"file":"repo";if(H==="file"&&!x)return F("path is required when querying a specific file in commits mode.",o);let I=await Gh({type:H,owner:O.owner,repo:O.repo,path:x,branch:O.branch,since:O.since,until:O.until,author:O.author,page:Number(O.page)||1,perPage:Number(O.perPage)||30,filePage:typeof O.filePage=="number"?O.filePage:void 0,itemsPerPage:typeof O.itemsPerPage=="number"?O.itemsPerPage:void 0,includeDiff:!!O.includeDiff,charOffset:typeof O.charOffset=="number"?O.charOffset:void 0,charLength:typeof O.charLength=="number"?O.charLength:void 0},n);if(Qn(I))return F(I,o,{toolName:A.GITHUB_SEARCH_PULL_REQUESTS});let{commits:v}=I.data,D=v.length>0;return Oe(o,I.data,D,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:I.rawResponseChars})}let a=r(),c={...s.data},l=Ah(c),u=c.prNumber!==void 0;if(u||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return F("At least one valid search parameter, filter, or PR number is required.",o);let p=await zt(c,()=>a.provider.searchPullRequests(mh(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:g}=gh(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete g.pagination;let b=!u&&(!!o.content||!!o.reviewMode),S={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},C=c.minify==="standard",k=u,_=m.map(O=>Mh(O,c,b?S:l,C,k));g.pull_requests=_,!u&&c.concise===!0&&(g.pull_requests=_.map(O=>{let x=O;return`#${x.number} ${x.title}`}));let E=_.length>0;return Oe(c,g,E,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return ve(s,o,void 0,A.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:A.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var Bh=y(()=>{"use strict";Io();pe();$e();Me();qn();cn();Lh();Dh();Hh();xi()});function Qh(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var Uh=y(()=>{"use strict"});function vO(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function AO(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(vO)}}}function qh(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function Vh(e){return!!(e.keywords&&e.keywords.length>0)}function LO(e){return!!(Vh(e)||qh(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function $h(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function _O(e){let t=qh(e),n=Vh(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:$h(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:$h(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function IO(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function FO(e,t){return[...e].sort((n,r)=>{let o=MO(n,r,t.sort);if(o!==0)return o;let i=jh(r,t)-jh(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:xl(n).localeCompare(xl(r))})}function MO(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return Qh(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function jh(e,t){let n=DO(t),r=xl(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function DO(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function xl(e){return`${e.owner}/${e.repo}`}function NO(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function GO(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function HO(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??Q(n.response.data??n.response)),0)}async function Wh(e){let{queries:t,authInfo:n}=e,r=tt(n);return re(t,async(o,i)=>{try{if(!LO(o))return F("At least one repository search term or filter is required.",o);let s=r(),a=_O(o),{successes:c,failures:l}=await Lg(a.map(E=>({meta:{label:E.label,query:E.query},operation:()=>s.provider.searchRepos(ph(E.query))}))),u=c.map(E=>({label:E.meta.label,query:E.meta.query,response:E.response})),d=l.map(E=>({label:E.meta.label,query:E.meta.query,response:E.response}));if(u.length===0){let E=d[0];return E?$i(E.response,o):ve(new Error("Repository search produced no provider results"),o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=FO(IO(u.flatMap(E=>fh(E.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,g=u.length===1?u[0]:void 0,S=u.length>1?GO(u):g?.response.data.pagination,C=S?NO(S):void 0,k=m.length>0,_=AO({repositories:m,pagination:C},o);return Oe(o,_.data,k,A.GITHUB_SEARCH_REPOSITORIES,{rawResponse:HO([...u,...d])})}catch(s){return ve(s,o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}},{toolName:A.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var Kh=y(()=>{"use strict";pe();$e();Uh();Me();qn();cn();ie()});function zO(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function BO(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Gr(o))continue;let i=r.files.filter(a=>!Bn(a)),s=r.folders.filter(a=>!Gr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function Yh(e){let{queries:t,authInfo:n}=e,r=tt(n);return re(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await zt(o,()=>s.provider.getRepoStructure(bh(o,c)));if(l.ok===!1)return zO(l.result,o);let u=BO(l.response.data.structure),d=Object.keys(u).length>0,p=Rh(l.response.data,o,u,c);return Oe(o,p,d,A.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return ve(s,o,"Failed to explore repository structure",A.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:A.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var Xh=y(()=>{"use strict";pe();$e();Hr();Me();qn();cn()});import{existsSync as Jh}from"fs";import{delimiter as QO,dirname as UO,join as Zh}from"path";function ey(){return process.platform==="win32"?"npm.cmd":"npm"}function $O(){let e=UO(process.execPath);return Zh(e,ey())}function jO(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function qO(){let e=(process.env.PATH??"").split(QO).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...jO()])]}function VO(){let e=$O();if(Jh(e))return{command:process.execPath,argsPrefix:[e]};let t=ey();for(let n of qO()){let r=Zh(n,t);if(Jh(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function ss(e,t,n={}){if(!WO.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Vi(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=VO(),c=await an(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:KO});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var WO,KO,ty=y(()=>{"use strict";Wi();WO=["view","search","ping","config","whoami"],KO=[...qi,...dg]});function so(e){try{return new URL(e).host||e}catch{return e}}function ny(e,t=Date.now()){let n=io.get(so(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Tl)throw new El(so(e),Tl-r);n.state="half-open"}}function kl(e){let t=io.get(so(e));t&&(t.failures=0,t.state="closed")}function ry(e,t=Date.now()){let n=so(e),r=io.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=YO&&(r.state="open",r.openedAt=t)),io.set(n,r)}function oy(e,t=Date.now()){let n=io.get(so(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Tl:!1}var io,YO,Tl,El,Ol=y(()=>{"use strict";io=new Map,YO=5,Tl=3e4;El=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});function iy(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function JO(e,t,n,r){e&&Dt({limit_type:"primary",retry_after_seconds:iy(r),api_method:t,api_url:n,provider:e})}function ZO(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Or.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&nf(r),e.status===429&&JO(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function ev(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=iy(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Bt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=XO,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let b=e.includes("?")?"&":"?";d=`${e}${b}version=${encodeURIComponent(nn)}`}let p={"User-Agent":`Octocode-MCP/${nn}`,...i},f=globalThis.fetch;if(!f)throw new Error(Or.FETCH_NOT_AVAILABLE.message);ny(d);let m,g=n+1;for(let b=1;b<=g;b++){if(c?.aborted)throw new Error("Request aborted");try{let S=await f(d,{method:s,headers:p,signal:c});if(!S.ok)throw ZO(S,s,d,u,l);if(S.status===204)return kl(d),null;let C=await S.json();return kl(d),C}catch(S){let C=S;if(c?.aborted||S instanceof Error&&S.name==="AbortError")throw new Error("Request aborted");if(C&&C.retryable===!1)throw S;if(m=S instanceof Error?S:new Error(String(S)),b===g)break;let k=ev(b,r,o,C);await new Promise(_=>setTimeout(_,k))}}throw ry(d),new Error(Or.FETCH_FAILED_AFTER_RETRIES.message(g,m?.message||""))}var XO,sy=y(()=>{"use strict";bi();gt();Si();Ol();XO=6e4});import{z as L}from"zod";var as,tv,ay,nv,cy=y(()=>{"use strict";as=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),tv=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),ay=L.looseObject({objects:L.array(tv),total:L.union([L.number(),L.string()]).optional()}),nv=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});async function my(){if(cs)return cs;try{let e=await ss("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return cs=t,t}}catch{}return cs=ls,ls}function dn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function Xe(e){return e===void 0?0:Q(e)}async function gy(e){try{let t=`${ov}/${encodeURIComponent(e)}`,n=await Bt(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Xe(n)}}catch{return{rawResponseChars:0}}}function us(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function hy(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function iv(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function sv(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function ly(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function uy(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function av(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function vl(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=dn(e.repository):(e.repository.url&&(r=dn(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:av(e),...o?{repositoryDirectory:o}:{},...ly(e.exports)?{exports:ly(e.exports)}:{},...uy(e.bin,e.name)?{bin:uy(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function cv(e){return typeof e.links?.repository=="string"?dn(e.links.repository):typeof e.repository=="string"?dn(e.repository):typeof e.repository?.url=="string"?dn(e.repository.url):null}function lv(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:cv(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function yy(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function by(e){try{let t=await my(),n=yy(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Bt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Xe(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Bt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Xe(i)}}catch{return{rawResponseChars:0}}}async function Al(e,t,n){let[r,o]=await Promise.all([gy(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):by(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function ds(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function uv(e,t){try{let n=await ss("view",[e,"--json"],{timeout:rv});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...ds(c)?{}:{errorDetail:c},rawResponseChars:Xe(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Xe(o),s=as.safeParse(o);return s.success?{pkg:vl(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...ds(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function dv(e,t){try{let n=await my(),r=yy(e),o=`${n}/${r}/latest`,i;try{i=await Bt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=Xe(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=as.safeParse(i);return a.success?{pkg:vl(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...ds(r)?{}:{errorDetail:r},rawResponseChars:0}}}function pv(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function Ry(e,t){let n=0,r;for(let o of pv(e)){let i;try{i=await Bt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);ds(l)||(r=l);continue}if(n+=Xe(i),!i||typeof i!="object")continue;let s=as.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:vl(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Ll(e,t=!1){let[n,r]=await Promise.allSettled([uv(e,t),dv(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?Al(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function fv(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Ll(e,t);if(!r){if(o){let s=hy(o);if(s&&n){let a=await Ry(e,t);if(a.pkg){let c=await Al(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function mv(e,t,n,r=0){let o=Math.max(t+r,t),i=await ss("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Xe(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Xe(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((m,g)=>{let b=m?.score?.final??0;return(g?.score?.final??0)-b}).slice(r,r+t),d=await Promise.all(u.map(async m=>{if(!m||typeof m!="object")return null;let g=m;if(!g.name)return null;if(n){let b=await Ll(g.name,!0);if(b.pkg)return b}return{pkg:lv(g),rawResponseChars:0}})),p=d.map(m=>m?.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+(g?.rawResponseChars??0),0);return{packages:p,totalFound:a.length,rawResponseChars:c+f}}async function gv(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${ls}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Bt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(m){return{error:`NPM registry search failed: ${m instanceof Error?m.message:String(m)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Xe(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=ay.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((m,g)=>{let b=m.score?.final??0;return(g.score?.final??0)-b}).map(m=>m.package).filter(m=>typeof m.name=="string"&&m.name.length>0).slice(0,t),d=await Promise.all(u.map(async m=>{if(n){let g=await Ll(m.name,!0);if(g.pkg)return g}return{pkg:{name:m.name,npmUrl:(m.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(m.name)}`,repoUrl:m.links?.repository&&typeof m.links.repository=="string"?dn(m.links.repository):null,version:m.version??"unknown",source:"registry",...m.description?{description:m.description}:{},...m.links?.homepage?{homepage:m.links.homepage}:{}},rawResponseChars:0}})),p=d.map(m=>m.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+g.rawResponseChars,0);return{packages:p,totalFound:sv(c.data.total,p.length),rawResponseChars:a+f}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function dy(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await Bt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Xe(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Xe(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?dn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Xe(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function py(e,t,n,r=0){try{let o=await mv(e,t,n,r);if(!("error"in o))return o}catch{}return gv(e,t,n,r)}async function fy(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):gy(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):by(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function Sy(e,t,n,r=0){let o=Qe("npm-search",{name:e,limit:t,metadata:n,from:r});return Ue(o,async()=>{if(oy(ls)){if(r===0&&t===1&&us(e)){let u=await Ry(e,n);if(u.pkg){let d=await Al(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await dy(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&us(e)){let l=await fv(e,n,t===1);if("error"in l){if(!hy(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await py(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return fy(s);let a=iv(e);if(a!==e){let l=await py(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return fy(l)}let c=await dy(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}var ls,rv,cs,ov,Cy=y(()=>{"use strict";ty();sy();Nt();Ol();cy();ie();ls="https://registry.npmjs.org",rv=3e3,cs=null;ov="https://api.npmjs.org/downloads/point/last-week"});async function Py(e){let t=us(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Sy(e.name,n,!0,r)}var wy=y(()=>{"use strict";Cy()});function hv(e){return"error"in e}function ps(e){return"npmUrl"in e}function yv(e){return ps(e)&&e.path?e.path:e.name}function bv(e){return ps(e)?e.repoUrl:e.repository}function Rv(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function Sv(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function Cv(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function Pv(e,t){let n=Cv(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function wv(e){let t=yv(e),n=Sv(bv(e)),r={name:t};ps(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=Rv(ps(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=Pv(n,o);return i&&(r.next=i),r}function xv(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function xy(e){return re(e.queries,async t=>{try{if(!t.packageName)return F("Package name is required for package search",t);let n=await Py({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(hv(n))return F(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(wv),i=o.length>0,s=r.length>1||n.totalFound>1,a=xv(t,n.totalFound,o.length,s);return Oe(t,{packages:o,pagination:a},i,A.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return F(n,t,{toolName:A.PACKAGE_SEARCH})}},{toolName:A.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var Ty=y(()=>{"use strict";wy();$e();Me();pe()});var bt,ao=y(()=>{"use strict";bt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function Ey(e,t){return n=>t}var ky=y(()=>{"use strict"});import{open as Tv,readFile as Ev,stat as kv}from"fs/promises";import{ContentSanitizer as Ov}from"@octocodeai/octocode-engine/contentSanitizer";function _l(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Oy(e,t,n){return{...e,..._l(t,n)}}function vv(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function Av(e,t){try{return{fileStats:await kv(t)}}catch(n){let r=et.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:F(r,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Lv(e,t){return t>bt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function _v(e,t,n){let r=et.fileTooLarge(e.path,n,bt.LARGE_FILE_THRESHOLD_KB);return F(r,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function Iv(e,t){let n=et.binaryFileUnsupported(e.path);return F(n,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function Fv(e){let n=Buffer.alloc(8192),r;try{r=await Tv(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(Ey("binary sample handle close",void 0))}}async function Mv(e,t){try{return{content:await Ev(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?et.fileAccessFailed(e.path,r):et.fileReadFailed(e.path,r);return{errorResult:F(i,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function Dv(e,t){return{status:"empty",errorCode:q.NO_MATCHES,totalLines:t}}function Nv(e,t,n){let r=Li(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:Dv(e,n)};let o=r.lines.join(`
37
- `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let p=r.matchRanges[0],f=r.matchRanges[r.matchRanges.length-1];p&&f&&(l=p.start,u=f.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function Gv(e){return e.startLine!==void 0&&e.endLine!==void 0}function Hv(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:q.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:q.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
38
- `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function zv(e,t,n){let r=t.split(`
39
- `),o=Pt(t);return e.matchString?Nv(e,r,o):Gv(e)?Hv(e,r,o):{resultContent:t,isPartial:!1}}function Bv(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?M.applyContentViewMinification(t.resultContent,c):t.resultContent,u=e.charLength,d=e.charOffset??0,p=u,f=!1,m=d;p===void 0&&l.length>o&&(p=o,f=!0,a.push(`Auto-paginated: Content (${l.length} chars) exceeds ${o} char limit`));let g="char-limit",b=p;if(p!==void 0){let E=Ai(l,m,p,c);g=E.chunkMode,b=E.length}let S=Un(l,m,b,p!==void 0?{pageSize:p}:void 0),C=t.isPartial||S.hasMore,k;if(S.hasMore&&g==="char-limit"&&Oi(S.paginatedContent)){let E=S.charOffset+S.charLength;k=vi(l,E,c)}let _=S.hasMore&&S.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:S.nextCharOffset,charLength:p??S.charLength,minify:e.minify}}}:void 0;return{path:c,content:S.paginatedContent,...s!=="standard"&&{contentView:s},...C&&{isPartial:C},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...(p!==void 0||d>0||f)&&{pagination:{...jf(S),chunkMode:g,...k!==void 0&&{nextBlockChar:k}}},..._?{next:_}:{},...a.length>0&&{warnings:a}}}function Qv(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function fs(e){let t=Ze();try{let n=qe(e,A.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=vv(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await Av(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await Fv(o))return U(Iv(e,o),c);if(Lv(e,l))return U(_v(e,o,l),c);let{content:u,errorResult:d}=await Mv(e,o);if(d||u===void 0)return d;let p=Ov.sanitizeContent(u,i),f=p.content,m=f.length,g=Buffer.byteLength(f,"utf-8"),b=p.hasSecrets?`Secrets detected and redacted: ${p.secretsDetected.join(", ")}`:void 0,S=e.minify,C=S==="standard"||S==="symbols",k=C?"standard":"none",_;if(S==="symbols"){let I=M.extractSignatures(f,i);if(I===null){let v=_i(f,i);if(v!==null)return U({path:e.path,content:v,contentView:"symbols",isSkeleton:!0,totalLines:Pt(f),..._l(m,g),...b?{warnings:[b]}:{}},m);_=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(I!==null){let v=Pt(f),D=M.applyContentViewMinification(I,i);return U({path:e.path,content:D,contentView:"symbols",isSkeleton:!0,totalLines:v,..._l(m,g),...b?{warnings:[b]}:{}},m)}}let E=Pt(f),O=zv(e,f,t),x=I=>{let v=[..._?[_]:[],...b?[b]:[]];if(v.length===0)return I;let D=I.warnings??[];return{...I,warnings:[...D,...v]}};if(O.earlyResult){let I=O.earlyResult.content,v=C&&typeof I=="string"?{...O.earlyResult,content:M.applyContentViewMinification(I,i)}:O.earlyResult;return U(Oy(x(Il(Qv(v,k),e,E)),m,g),m)}let H=Bv(e,O,s,E,t,C,k);return U(Oy(x(Il(H,e,E)),m,g),m)}catch(n){return F(n,e,{toolName:A.LOCAL_FETCH_CONTENT})}}function Il(e,t,n){return e}var ms=y(()=>{"use strict";Ac();ge();ki();vc();ao();Qr();zr();pe();wt();ji();Wr();ky();ie();Ii()});async function vy(e){let{queries:t}=e;return re(t||[],async n=>je({toolName:A.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Fe(wn,n);return r.ok===!1?r.error:await fs(r.data)}}),{toolName:A.LOCAL_FETCH_CONTENT},e)}var Ay=y(()=>{"use strict";pe();$e();ms();Bo();Me();Ht();ms()});function Vn(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function co(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var gs=y(()=>{"use strict"});function jv(e,t){let n=t??$v,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Wn(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=qe(e,A.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:jv(i.path,i.excludeDir)},a=Yv(s),c=e.limit??1e4,l=M.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),u=l.totalDiscovered,d=l.wasCapped,p=l.entries.map(v=>qv(v,r)),f=e.sortBy||"modified";Vv(p,f,r);let m=Wv(p,t,n),g=m.length,b=e.itemsPerPage||20,S=e.page||1,C=Math.max(1,Math.ceil(g/b)),k=(S-1)*b,_=Math.min(k+b,g),O=m.slice(k,_),x=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],H=[...a,...x],I={...g===0?{status:"empty"}:{},path:i.path,files:O,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:g,hasMore:S<C,...S<C?{nextPage:S+1}:{},...d?{totalFilesFound:u}:{}},...H.length>0&&{warnings:H}};return U(Ly(I,e,{totalFiles:g}),l.entries.reduce((v,D)=>v+D.path.length,0))}catch(o){return F(o,e,{toolName:A.LOCAL_FIND_FILES})}}function qv(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function Ly(e,t,n){return e}function Vv(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function Wv(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=Vn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function Yv(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!Kv.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}var $v,Kv,hs=y(()=>{"use strict";wt();gs();ge();pe();fe();ie();$v=[];Kv=/^\d+[hdwm]$/});async function _y(e){let{queries:t}=e;return re(t||[],async n=>je({toolName:A.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Fe(xn,n);return r.ok===!1?r.error:await Wn(r.data)}}),{toolName:A.LOCAL_FIND_FILES},e)}var Iy=y(()=>{"use strict";Uo();pe();$e();hs();Me();Ht();hs()});function Dl(e){return Ny.exec(e)?.[1]?.toLowerCase()??""}function aA(e){let t=Dl(e);if(!t)return!1;for(let n of sA)if(lo[n].extensions.includes(t))return!0;return!1}function cA(e,t,n){if(n&&n!=="auto")return lo[n];let r=Dl(e),o=(t??"").toLowerCase();for(let i of Fy){let s=lo[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Fy){let s=lo[i];if(i!=="generic"&&s.extensions.includes(r))return s}return lo.generic}function Gy(e){return eA.test(e)?"generated":nA.test(e)?"fixture":tA.test(e)?"test":oA.test(e)?"config":rA.test(e)?"docs":!Ml.test(e)&&(iA.test(e)||aA(e))?"source":"unknown"}function lA(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function uA(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function dA(e,t,n,r,o){if(!e||e.length===0)return 0;let i=PA(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=wA(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${zy(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=se.exactWholeWord,p.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=se.exactCaseInsensitive,p.push("case-insensitive match")):u.includes(r)&&(d+=se.substring,p.push("substring match")));let f=c.kind;if(f)d+=pA(f,p);else{let m=xA(u,r,t.id,n.caseSensitive);m!=="code"?(d+=se.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(Fl(t.declaration,u)&&(d+=se.declarationLine,p.push("declaration line")),Fl(t.export,u)&&(d+=se.exportLine,p.push("export/public line")),Fl(t.import,u)&&(d+=se.importLine,p.push("import line")),t.id==="markdown"&&Zv.test(u)&&(d+=se.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&fA(u,r)&&(d+=se.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function pA(e,t){switch(e){case"declaration":return t.push("AST: declaration"),se.declarationLine;case"export":return t.push("AST: export/public"),se.exportLine;case"configKey":return t.push("AST: config key"),se.configKeyLine;case"heading":return t.push("AST: heading"),se.headingLine;case"import":return t.push("AST: import"),se.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),se.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function fA(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function mA(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(Ny,"").includes(l))&&(s+=se.pathSegmentToken,i.push("query token in path"))}let a=Dl(e);return r.extensions.includes(a)&&t.langType&&(s+=se.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=se.sourceDir,i.push("source file")),s}function gA(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),se.lowSignalPathPenalty):0}function hA(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*se.matchCountScale,r=Math.min(n,se.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function yA(e,t){let n=uA(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>bA(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function bA(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${zy(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function RA(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*se.rareQueryTokenScale,se.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function SA(e,t,n){let r=cA(e.path,t.langType,t.profileOverride),o=Gy(e.path),i=lA(t.keyword),s=[],a=0;return a+=dA(e.matches,r,t,i,s),a+=mA(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=se.pathUnderQuery,s.push("under requested subtree")),a+=gA(o,t,s),Ml.test(e.path)&&!t.explicitLowSignal&&(a+=se.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=hA(e.matchCount??0,s),a+=RA(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Hy(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Dy),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,p)=>d.path.localeCompare(p.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Xv,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Dy);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=yA(i,n),l=i.map(d=>{try{return{file:d,s:SA(d,n,c)}}catch{return{file:d,s:CA()}}});l.sort((d,p)=>{if(p.s.score!==d.s.score)return p.s.score-d.s.score;let f=(p.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(p.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function CA(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Dy(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function Fl(e,t){for(let n of e)if(n.test(t))return!0;return!1}function zy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PA(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function wA(e,t,n){if(e.indexOf(`
36
+ `)}function lv(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(f=>i.includes(fs(f))):o,a=yl(t),c=a?s.filter(f=>ms(fs(f),a)||ms(f.patch,a)):s,{items:l,pagination:u}=bl(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=nv(f,!1);if(!d||typeof f.patch!="string")return m;let g=r&&!a?av(f.patch):f.patch,b=hs(g,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:no(b?.content),...b?{patchPagination:b.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(fs).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function ho(e){return typeof e=="object"&&e!==null}function hl(e){if(ho(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Rl(e){if(ho(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function uv(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function dv(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!ho(n))continue;let r=Rl(n.patchPagination);if(r?.hasMore)return r}}function pv(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!ho(n))continue;let r=Rl(n.bodyPagination);if(r?.hasMore)return r}}function fv(e,t,n,r){let o={},i=Rl(e.bodyPagination),s=hl(e.filePagination),a=hl(e.commentPagination),c=hl(e.commitPagination),l=dv(e),u=pv(e),d=uv(n);i&&(o.body={...i,nextQuery:Ah(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:gl(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:gl(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:gs(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:gl(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:Ah(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return ho(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?gs(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function mv(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Ih(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?cv(s):s,c=n.body?hs(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,p=t.prNumber!==void 0||t.verbose===!0,m={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...p?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...p?{updatedAt:e.updatedAt}:{},...p||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...p&&!c?{bodyPreview:Lh(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:tv(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...lv(e,t,n,r),...ov(e,t,n),...iv(e,t,n),...sv(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=fv(m,t,n,i);return mv(m),g&&(m.contentPagination=g),m}var Fh=y(()=>{"use strict";Se();Bi()});function gv(e){return e?e.includes('rel="next"'):!1}function Mh(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function Dh(e,t){try{let n=await he(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=gv(i),a=o.data.map(u=>{let d=u.commit.author,p=u.commit.committer,f=p?.date??d?.date??"",m=u.commit.message,g=m.split(`
37
+ `)[0]??m;return{sha:u.sha,date:f,message:m,messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...p?{committer:{name:p.name??"unknown",email:p.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await Promise.all(a.map(async(u,d)=>{try{let p=o.data[d]?.sha??u.sha,f=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:p});if(e.type==="file"&&e.path){let m=e.path,g=f.data.files?.find(b=>b.filename===m||b.previous_filename===m);if(g){let b=g.patch!==void 0?Mh(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...b!==void 0?{patch:b.patch,...b.patchPagination?{patchPagination:b.patchPagination}:{},diff:no(b.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let m=e.path,g=(f.data.files??[]).filter(w=>!m||w.filename.startsWith(m)).map(w=>{let N=w.patch!==void 0?Mh(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...N!==void 0?{patch:N.patch,...N.patchPagination?{patchPagination:N.patchPagination}:{},diff:no(N.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),x=Math.max(1,e.itemsPerPage??20),S=g.length,k=Math.max(1,Math.ceil(S/x)),A=Math.min(b,k),_=(A-1)*x,E=g.slice(_,_+x);return{...u,files:E,filesPagination:{currentPage:A,totalPages:k,itemsPerPage:x,totalFiles:S,hasMore:A<k,...A<k?{nextFilePage:A+1}:{}}}}}catch{}return u}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return ae(n)}}var Nh=y(()=>{"use strict";Ue();It();Bi()});async function Gh(e){let{queries:t,authInfo:n}=e,r=at(n);return ce(t,async(o,i)=>{try{let s=He(Fn,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let E=s.data;if(!E.owner||!E.repo)return M("owner and repo are required for commits mode.",o);let w=E.path,N=w&&!w.endsWith("/")?"file":"repo";if(N==="file"&&!w)return M("path is required when querying a specific file in commits mode.",o);let F=await Dh({type:N,owner:E.owner,repo:E.repo,path:w,branch:E.branch,since:E.since,until:E.until,author:E.author,page:Number(E.page)||1,perPage:Number(E.perPage)||30,filePage:typeof E.filePage=="number"?E.filePage:void 0,itemsPerPage:typeof E.itemsPerPage=="number"?E.itemsPerPage:void 0,includeDiff:!!E.includeDiff,charOffset:typeof E.charOffset=="number"?E.charOffset:void 0,charLength:typeof E.charLength=="number"?E.charLength:void 0},n);if(Jn(F))return M(F,o,{toolName:v.GITHUB_SEARCH_PULL_REQUESTS});let{commits:O}=F.data,Q=O.length>0;return Fe(o,F.data,Q,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:F.rawResponseChars})}let a=r(),c={...s.data},l=Oh(c),u=c.prNumber!==void 0;if(u||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return M("At least one valid search parameter, filter, or PR number is required.",o);let p=await en(c,()=>a.provider.searchPullRequests(ph(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:g}=fh(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete g.pagination;let b=!u&&(!!o.content||!!o.reviewMode),x={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},S=c.minify==="standard",k=u,A=m.map(E=>Ih(E,c,b?x:l,S,k));g.pull_requests=A,!u&&c.concise===!0&&(g.pull_requests=A.map(E=>{let w=E;return`#${w.number} ${w.title}`}));let _=A.length>0;return Fe(c,g,_,v.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return Me(s,o,void 0,v.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:v.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var Hh=y(()=>{"use strict";jo();Re();Ge();ze();or();Sn();vh();Fh();Nh();_i()});function zh(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var Qh=y(()=>{"use strict"});function hv(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function yv(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(hv)}}}function jh(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function Uh(e){return!!(e.keywords&&e.keywords.length>0)}function bv(e){return!!(Uh(e)||jh(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function Bh(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function Rv(e){let t=jh(e),n=Uh(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:Bh(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:Bh(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function Sv(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function Pv(e,t){return[...e].sort((n,r)=>{let o=Cv(n,r,t.sort);if(o!==0)return o;let i=$h(r,t)-$h(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Sl(n).localeCompare(Sl(r))})}function Cv(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return zh(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function $h(e,t){let n=wv(t),r=Sl(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function wv(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Sl(e){return`${e.owner}/${e.repo}`}function xv(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function Tv(e){return e.length===0?void 0:[`Repository search partially failed: the ${e.map(n=>`'${n.label}'`).join(", ")} query variant(s) returned an error. Results may be incomplete \u2014 retry or narrow the query.`]}function kv(e,t){let n=e.map(r=>r.response.data.pagination).filter(r=>!!r);if(n.length!==0)return{currentPage:n[0].currentPage,totalPages:Math.max(...n.map(r=>r.totalPages)),hasMore:n.some(r=>r.hasMore),entriesPerPage:n[0].entriesPerPage,totalMatches:t,reachableTotalMatches:t,totalMatchesKind:"lowerBound",totalMatchesCapped:n.some(r=>r.totalMatchesCapped===!0)}}function Ev(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??$(n.response.data??n.response)),0)}async function qh(e){let{queries:t,authInfo:n}=e,r=at(n);return ce(t,async(o,i)=>{try{if(!bv(o))return M("At least one repository search term or filter is required.",o);let s=r(),a=Rv(o),{successes:c,failures:l}=await Og(a.map(w=>({meta:{label:w.label,query:w.query},operation:()=>s.provider.searchRepos(uh(w.query))}))),u=c.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response})),d=l.map(w=>({label:w.meta.label,query:w.meta.query,response:w.response}));if(u.length===0){let w=d[0];return w?ts(w.response,o):Me(new Error("Repository search produced no provider results"),o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=Pv(Sv(u.flatMap(w=>dh(w.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,g=u.length===1?u[0]:void 0,x=u.length>1?kv(u,f.length):g?.response.data.pagination,S=x?xv(x):void 0,k=m.length>0,A=yv({repositories:m,pagination:S},o),_=Tv(d),E=_?{...A.data,warnings:_}:A.data;return Fe(o,E,k,v.GITHUB_SEARCH_REPOSITORIES,{rawResponse:Ev([...u,...d])})}catch(s){return Me(s,o,void 0,v.GITHUB_SEARCH_REPOSITORIES)}},{toolName:v.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var Wh=y(()=>{"use strict";Re();Ge();Qh();ze();or();Sn();de()});function Ov(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function vv(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Yr(o))continue;let i=r.files.filter(a=>!Xn(a)),s=r.folders.filter(a=>!Yr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function Vh(e){let{queries:t,authInfo:n}=e,r=at(n);return ce(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await en(o,()=>s.provider.getRepoStructure(hh(o,c)));if(l.ok===!1)return Ov(l.result,o);let u=vv(l.response.data.structure),d=Object.keys(u).length>0,p=yh(l.response.data,o,u,c);return Fe(o,p,d,v.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return Me(s,o,"Failed to explore repository structure",v.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:v.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var Kh=y(()=>{"use strict";Re();Ge();Xr();ze();or();Sn()});import{existsSync as Yh}from"fs";import{delimiter as Av,dirname as Lv,join as Xh}from"path";function Jh(){return process.platform==="win32"?"npm.cmd":"npm"}function _v(){let e=Lv(process.execPath);return Xh(e,Jh())}function Iv(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function Fv(){let e=(process.env.PATH??"").split(Av).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...Iv()])]}function Mv(){let e=_v();if(Yh(e))return{command:process.execPath,argsPrefix:[e]};let t=Jh();for(let n of Fv()){let r=Xh(n,t);if(Yh(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function ys(e,t,n={}){if(!Dv.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=os(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=Mv(),c=await Nt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:Nv});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var Dv,Nv,Zh=y(()=>{"use strict";so();Dv=["view","search","ping","config","whoami"],Nv=[...rs,...cg]});function bo(e){try{return new URL(e).host||e}catch{return e}}function ey(e,t=Date.now()){let n=yo.get(bo(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<Pl)throw new Cl(bo(e),Pl-r);n.state="half-open"}}function wl(e){let t=yo.get(bo(e));t&&(t.failures=0,t.state="closed")}function ty(e,t=Date.now()){let n=bo(e),r=yo.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=Gv&&(r.state="open",r.openedAt=t)),yo.set(n,r)}function ny(e,t=Date.now()){let n=yo.get(bo(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<Pl:!1}var yo,Gv,Pl,Cl,xl=y(()=>{"use strict";yo=new Map,Gv=5,Pl=3e4;Cl=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});function ry(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function zv(e,t,n,r){e&&Xt({limit_type:"primary",retry_after_seconds:ry(r),api_method:t,api_url:n,provider:e})}function Qv(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Qr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&af(r),e.status===429&&zv(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function Bv(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=ry(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function tn(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=Hv,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let b=e.includes("?")?"&":"?";d=`${e}${b}version=${encodeURIComponent(mn)}`}let p={"User-Agent":`Octocode-MCP/${mn}`,...i},f=globalThis.fetch;if(!f)throw new Error(Qr.FETCH_NOT_AVAILABLE.message);ey(d);let m,g=n+1;for(let b=1;b<=g;b++){if(c?.aborted)throw new Error("Request aborted");try{let x=await f(d,{method:s,headers:p,signal:c});if(!x.ok)throw Qv(x,s,d,u,l);if(x.status===204)return wl(d),null;let S=await x.json();return wl(d),S}catch(x){let S=x;if(c?.aborted||x instanceof Error&&x.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw x;if(m=x instanceof Error?x:new Error(String(x)),b===g)break;let k=Bv(b,r,o,S);await new Promise(A=>setTimeout(A,k))}}throw ty(d),new Error(Qr.FETCH_FAILED_AFTER_RETRIES.message(g,m?.message||""))}var Hv,oy=y(()=>{"use strict";ki();xt();Oi();xl();Hv=6e4});import{z as L}from"zod";var bs,$v,iy,jv,sy=y(()=>{"use strict";bs=L.looseObject({name:L.string(),version:L.string(),repository:L.union([L.string(),L.object({url:L.string().optional(),type:L.string().optional(),directory:L.string().optional()})]).optional(),main:L.string().optional(),module:L.string().optional(),type:L.string().optional(),exports:L.unknown().optional(),types:L.string().optional(),typings:L.string().optional(),description:L.string().optional(),keywords:L.array(L.string()).optional(),license:L.union([L.string(),L.object({type:L.string().optional()})]).optional(),homepage:L.string().optional(),author:L.union([L.string(),L.object({name:L.string().optional(),email:L.string().optional(),url:L.string().optional()})]).optional(),maintainers:L.array(L.object({name:L.string().optional(),email:L.string().optional()})).optional(),engines:L.record(L.string(),L.string()).optional(),dependencies:L.record(L.string(),L.string()).optional(),devDependencies:L.record(L.string(),L.string()).optional(),peerDependencies:L.record(L.string(),L.string()).optional(),time:L.record(L.string(),L.string().optional()).optional()}),$v=L.looseObject({package:L.looseObject({name:L.string().nullish(),version:L.string().nullish(),description:L.string().nullish(),links:L.looseObject({npm:L.string().nullish(),homepage:L.string().nullish(),repository:L.string().nullish()}).nullish()}),score:L.looseObject({final:L.number().nullish(),detail:L.looseObject({quality:L.number().nullish(),popularity:L.number().nullish(),maintenance:L.number().nullish()}).nullish()}).nullish()}),iy=L.looseObject({objects:L.array($v),total:L.union([L.number(),L.string()]).optional()}),jv=L.union([L.string(),L.boolean(),L.number(),L.null(),L.record(L.string(),L.unknown())])});async function py(){if(Rs)return Rs;try{let e=await ys("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return Rs=t,t}}catch{}return Rs=Ss,Ss}function wn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function nt(e){return e===void 0?0:$(e)}async function fy(e){try{let t=`${qv}/${encodeURIComponent(e)}`,n=await tn(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:nt(n)}}catch{return{rawResponseChars:0}}}function Ps(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function my(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function Wv(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function Vv(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function ay(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function cy(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function Kv(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Tl(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=wn(e.repository):(e.repository.url&&(r=wn(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:Kv(e),...o?{repositoryDirectory:o}:{},...ay(e.exports)?{exports:ay(e.exports)}:{},...cy(e.bin,e.name)?{bin:cy(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function Yv(e){return typeof e.links?.repository=="string"?wn(e.links.repository):typeof e.repository=="string"?wn(e.repository):typeof e.repository?.url=="string"?wn(e.repository.url):null}function Xv(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:Yv(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function gy(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function hy(e){try{let t=await py(),n=gy(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await tn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=nt(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await tn(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:nt(i)}}catch{return{rawResponseChars:0}}}async function kl(e,t,n){let[r,o]=await Promise.all([fy(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):hy(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function Cs(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function Jv(e,t){try{let n=await ys("view",[e,"--json"],{timeout:Uv});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...Cs(c)?{}:{errorDetail:c},rawResponseChars:nt(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=nt(o),s=bs.safeParse(o);return s.success?{pkg:Tl(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...Cs(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function Zv(e,t){try{let n=await py(),r=gy(e),o=`${n}/${r}/latest`,i;try{i=await tn(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=nt(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=bs.safeParse(i);return a.success?{pkg:Tl(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...Cs(r)?{}:{errorDetail:r},rawResponseChars:0}}}function eA(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function yy(e,t){let n=0,r;for(let o of eA(e)){let i;try{i=await tn(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);Cs(l)||(r=l);continue}if(n+=nt(i),!i||typeof i!="object")continue;let s=bs.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Tl(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function El(e,t=!1){let[n,r]=await Promise.allSettled([Jv(e,t),Zv(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?kl(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function tA(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await El(e,t);if(!r){if(o){let s=my(o);if(s&&n){let a=await yy(e,t);if(a.pkg){let c=await kl(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function nA(e,t,n,r=0){let o=Math.max(t+r,t),i=await ys("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:nt(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=nt(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((m,g)=>{let b=m?.score?.final??0;return(g?.score?.final??0)-b}).slice(r,r+t),d=await Promise.all(u.map(async m=>{if(!m||typeof m!="object")return null;let g=m;if(!g.name)return null;if(n){let b=await El(g.name,!0);if(b.pkg)return b}return{pkg:Xv(g),rawResponseChars:0}})),p=d.map(m=>m?.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+(g?.rawResponseChars??0),0);return{packages:p,totalFound:a.length,rawResponseChars:c+f}}async function rA(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Ss}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await tn(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(m){return{error:`NPM registry search failed: ${m instanceof Error?m.message:String(m)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=nt(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=iy.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((m,g)=>{let b=m.score?.final??0;return(g.score?.final??0)-b}).map(m=>m.package).filter(m=>typeof m.name=="string"&&m.name.length>0).slice(0,t),d=await Promise.all(u.map(async m=>{if(n){let g=await El(m.name,!0);if(g.pkg)return g}return{pkg:{name:m.name,npmUrl:(m.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(m.name)}`,repoUrl:m.links?.repository&&typeof m.links.repository=="string"?wn(m.links.repository):null,version:m.version??"unknown",source:"registry",...m.description?{description:m.description}:{},...m.links?.homepage?{homepage:m.links.homepage}:{}},rawResponseChars:0}})),p=d.map(m=>m.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+g.rawResponseChars,0);return{packages:p,totalFound:Vv(c.data.total,p.length),rawResponseChars:a+f}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function ly(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await tn(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:nt(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:nt(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?wn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:nt(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function uy(e,t,n,r=0){try{let o=await nA(e,t,n,r);if(!("error"in o))return o}catch{}return rA(e,t,n,r)}async function dy(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):fy(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):hy(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function by(e,t,n,r=0){let o=qe("npm-search",{name:e,limit:t,metadata:n,from:r});return We(o,async()=>{if(ny(Ss)){if(r===0&&t===1&&Ps(e)){let u=await yy(e,n);if(u.pkg){let d=await kl(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await ly(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&Ps(e)){let l=await tA(e,n,t===1);if("error"in l){if(!my(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await uy(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return dy(s);let a=Wv(e);if(a!==e){let l=await uy(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return dy(l)}let c=await ly(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}var Ss,Uv,Rs,qv,Ry=y(()=>{"use strict";Zh();oy();Jt();xl();sy();de();Ss="https://registry.npmjs.org",Uv=3e3,Rs=null;qv="https://api.npmjs.org/downloads/point/last-week"});async function Sy(e){let t=Ps(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return by(e.name,n,!0,r)}var Py=y(()=>{"use strict";Ry()});function oA(e){return"error"in e}function ws(e){return"npmUrl"in e}function iA(e){return ws(e)&&e.path?e.path:e.name}function sA(e){return ws(e)?e.repoUrl:e.repository}function aA(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function cA(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function Cy(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function wy(e,t){let n=Cy(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function lA(e){let t=iA(e),n=cA(sA(e)),r={name:t};ws(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=aA(ws(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=wy(n,o);return i&&(r.next=i),r}function uA(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=Cy(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:wy(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...p}=i;return{...p,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function dA(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function xy(e){return ce(e.queries,async t=>{try{if(!t.packageName)return M("Package name is required for package search",t);let n=await Sy({name:t.packageName,page:t.page,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(oA(n))return M(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(lA),i=o.length>0,s=r.length>1||n.totalFound>1,a=dA(t,n.totalFound,o.length,s),l={...uA(o),pagination:a};return Fe(t,l,i,v.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return M(n,t,{toolName:v.PACKAGE_SEARCH})}},{toolName:v.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var Ty=y(()=>{"use strict";Py();Ge();ze();Re()});var Et,Ro=y(()=>{"use strict";Et={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function ky(e,t){return n=>t}var Ey=y(()=>{"use strict"});import{open as pA,readFile as fA,stat as mA}from"fs/promises";import{ContentSanitizer as gA}from"@octocodeai/octocode-engine/contentSanitizer";function Ay(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Oy(e,t,n){return{...e,...Ay(t,n)}}function hA(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(e.minify==="symbols"&&(n||r))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function yA(e,t){try{return{fileStats:await mA(t)}}catch(n){let r=st.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:M(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function bA(e,t){return t>Et.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function RA(e,t,n){let r=st.fileTooLarge(e.path,n,Et.LARGE_FILE_THRESHOLD_KB);return M(r,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function SA(e,t){let n=st.binaryFileUnsupported(e.path);return M(n,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function PA(e){let n=Buffer.alloc(8192),r;try{r=await pA(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(ky("binary sample handle close",void 0))}}async function CA(e,t){try{return{content:await fA(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?st.fileAccessFailed(e.path,r):st.fileReadFailed(e.path,r);return{errorResult:M(i,e,{toolName:v.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function wA(e,t){return{status:"empty",errorCode:z.NO_MATCHES,totalLines:t}}function xA(e,t,n){let r=Hi(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:wA(e,n)};let o=r.lines.join(`
38
+ `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let p=r.matchRanges[0],f=r.matchRanges[r.matchRanges.length-1];p&&f&&(l=p.start,u=f.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function TA(e){return e.startLine!==void 0&&e.endLine!==void 0}function kA(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:z.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:z.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
39
+ `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function EA(e,t,n){let r=t.split(`
40
+ `),o=Mt(t);return e.matchString?xA(e,r,o):TA(e)?kA(e,r,o):{resultContent:t,isPartial:!1}}function Ly(e,t,n){let r=String(t.path),o=t.charLength,i=t.charOffset??0,s=o,a=!1,c,l=i;s===void 0&&!t.fullContent&&e.length>n&&(s=n,a=!0,c=`Auto-paginated: Content (${e.length} chars) exceeds ${n} char limit`);let u="char-limit",d=s;if(s!==void 0){let g=Gi(e,l,s,r);u=g.chunkMode,d=g.length}let p=Zn(e,l,d,s!==void 0?{pageSize:s}:void 0),f;if(p.hasMore&&u==="char-limit"&&Di(p.paginatedContent)){let g=p.charOffset+p.charLength;f=Ni(e,g,r)}let m=p.hasMore&&p.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:r,charOffset:p.nextCharOffset,charLength:s??p.charLength,minify:t.minify}}}:void 0;return{windowedContent:p.paginatedContent,pagination:p,effectiveCharLength:s,explicitCharOffset:i,autoPaginated:a,autoPaginateWarning:c,chunkMode:u,nextBlockChar:f,next:m,showPagination:s!==void 0||i>0||a}}function OA(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?D.applyContentViewMinification(t.resultContent,c):t.resultContent,u=Ly(l,e,o);u.autoPaginateWarning&&a.push(u.autoPaginateWarning);let d=t.isPartial||u.pagination.hasMore;return{path:c,content:u.windowedContent,...s!=="standard"&&{contentView:s},...d&&{isPartial:d},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...u.showPagination&&{pagination:{...Tc(u.pagination),chunkMode:u.chunkMode,...u.nextBlockChar!==void 0&&{nextBlockChar:u.nextBlockChar}}},...u.next?{next:u.next}:{},...a.length>0&&{warnings:a}}}function vy(e,t,n,r,o,i,s){let a=Ly(t,e,s),c=[...a.autoPaginateWarning?[a.autoPaginateWarning]:[],...i?[i]:[]];return{path:e.path,content:a.windowedContent,contentView:"symbols",isSkeleton:!0,...a.pagination.hasMore&&{isPartial:!0},totalLines:n,...Ay(r,o),...a.showPagination&&{pagination:{...Tc(a.pagination),chunkMode:a.chunkMode,...a.nextBlockChar!==void 0&&{nextBlockChar:a.nextBlockChar}}},...a.next?{next:a.next}:{},...c.length>0&&{warnings:c}}}function vA(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function xs(e){let t=it();try{let n=Ke(e,v.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=hA(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await yA(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await PA(o))return U(SA(e,o),c);if(bA(e,l))return U(RA(e,o,l),c);let{content:u,errorResult:d}=await CA(e,o);if(d||u===void 0)return d;let p=gA.sanitizeContent(u,i),f=p.content,m=f.length,g=Buffer.byteLength(f,"utf-8"),b=p.hasSecrets?`Secrets detected and redacted: ${p.secretsDetected.join(", ")}`:void 0,x=e.minify,S=x==="standard"||x==="symbols",k=S?"standard":"none",A;if(x==="symbols"){let F=D.extractSignatures(f,i);if(F===null){let O=zi(f,i);if(O!==null)return U(vy(e,O,Mt(f),m,g,b,t),m);A=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(F!==null){let O=Mt(f),Q=D.applyContentViewMinification(F,i);return U(vy(e,Q,O,m,g,b,t),m)}}let _=Mt(f),E=EA(e,f,t),w=F=>{let O=[...A?[A]:[],...b?[b]:[]];if(O.length===0)return F;let Q=F.warnings??[];return{...F,warnings:[...Q,...O]}};if(E.earlyResult){let F=E.earlyResult.content,O=S&&typeof F=="string"?{...E.earlyResult,content:D.applyContentViewMinification(F,i)}:E.earlyResult;return U(Oy(w(Ol(vA(O,k),e,_)),m,g),m)}let N=OA(e,E,s,_,t,S,k);return U(Oy(w(Ol(N,e,_)),m,g),m)}catch(n){return M(n,e,{toolName:v.LOCAL_FETCH_CONTENT})}}function Ol(e,t,n){return e}var Ts=y(()=>{"use strict";Ec();Ce();Mi();kc();Ro();eo();Jr();Re();Dt();ns();tr();Ey();de();Qi()});async function _y(e){let{queries:t}=e;return ce(t||[],async n=>Ve({toolName:v.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=He(Mn,n);return r.ok===!1?r.error:await xs(r.data)}}),{toolName:v.LOCAL_FETCH_CONTENT,finalize:AA()},e)}function AA(){return({results:e})=>{let t={results:LA(e)},n=Xi(t.results);n&&(t.base=n);let r=Ji(t.results);return r&&(t.shared=r),{structuredContent:bt(t),text:_A(t),isError:t.results.length>0&&t.results.every(o=>o.status==="error")}}}function LA(e){return e.map(t=>({...t,data:structuredClone(t.data)}))}function _A(e){let t=[];e.base&&t.push(`base: ${e.base}`,"");for(let n of e.results){let r=n.data,o=typeof r.content=="string"?r.content:void 0,i={...r};delete i.content,t.push(`result: ${n.id}${n.status?` (${n.status})`:""}`);let s=Rn({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","warnings","error"]).trimEnd();s&&t.push(s),o!==void 0&&t.push("content (copy-safe):",o),t.push("")}return e.shared&&t.push(Rn({shared:e.shared},["shared"]).trimEnd()),t.join(`
41
+ `).trimEnd()+`
42
+ `}var Iy=y(()=>{"use strict";Re();Ge();er();Bc();Ts();Jo();ze();Zt();Ts()});function ir(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function So(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var ks=y(()=>{"use strict"});function MA(e,t){let n=t??FA,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function sr(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Ke(e,v.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:MA(i.path,i.excludeDir)},{warnings:a,query:c}=zA(s),l=e.limit??1e4,u=D.queryFileSystem({path:c.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:c.maxDepth,minDepth:c.minDepth,names:c.names,pathPattern:c.pathPattern,regex:c.regex,entryType:c.entryType,empty:c.empty,modifiedWithin:c.modifiedWithin,modifiedBefore:c.modifiedBefore,accessedWithin:c.accessedWithin,sizeGreater:c.sizeGreater,sizeLess:c.sizeLess,permissions:c.permissions,executable:c.executable,readable:c.readable,writable:c.writable,excludeDir:c.excludeDir,limit:1e4}),d=u.totalDiscovered,p=u.wasCapped,f=u.entries.map(G=>DA(G,r)),m=e.sortBy||"modified";NA(f,m,r);let g=f.slice(0,l),b=GA(g,t,n),x=b.length,S=e.itemsPerPage||20,k=e.page||1,A=Math.max(1,Math.ceil(x/S)),_=(k-1)*S,E=Math.min(_+S,x),N=b.slice(_,E),F=[...u.warnings,...u.skipped>0?[`${u.skipped} entr${u.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],O=[...a,...F],Q={...x===0?{status:"empty"}:{},path:i.path,files:N,pagination:{currentPage:k,totalPages:A,filesPerPage:S,totalFiles:x,hasMore:k<A,...k<A?{nextPage:k+1}:{},...p||d>x?{totalFilesFound:d}:{}},...O.length>0&&{warnings:O}};return U(Fy(Q,e,{totalFiles:x}),u.entries.reduce((G,Y)=>G+Y.path.length,0))}catch(o){return M(o,e,{toolName:v.LOCAL_FIND_FILES})}}function DA(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function Fy(e,t,n){return e}function NA(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function GA(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=ir(r.size),t&&(o.size=r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function zA(e){let t=[],n={...e},r=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:o,value:i}of r)i&&!HA.test(i)&&(t.push(`${o}="${i}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete n[o]);return{warnings:t,query:n}}var FA,HA,Es=y(()=>{"use strict";Dt();ks();Ce();Re();Se();de();FA=[];HA=/^\d+[hdwm]$/});async function My(e){let{queries:t}=e;return ce(t||[],async n=>Ve({toolName:v.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=He(Dn,n);return r.ok===!1?r.error:await sr(r.data)}}),{toolName:v.LOCAL_FIND_FILES},e)}var Dy=y(()=>{"use strict";ei();Re();Ge();Es();ze();Zt();Es()});function Ll(e){return zy.exec(e)?.[1]?.toLowerCase()??""}function XA(e){let t=Ll(e);if(!t)return!1;for(let n of YA)if(Po[n].extensions.includes(t))return!0;return!1}function JA(e,t,n){if(n&&n!=="auto")return Po[n];let r=Ll(e),o=(t??"").toLowerCase();for(let i of Ny){let s=Po[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Ny){let s=Po[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Po.generic}function Qy(e){return jA.test(e)?"generated":qA.test(e)?"fixture":UA.test(e)?"test":VA.test(e)?"config":WA.test(e)?"docs":!Al.test(e)&&(KA.test(e)||XA(e))?"source":"unknown"}function ZA(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function eL(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function tL(e,t,n,r,o){if(!e||e.length===0)return 0;let i=pL(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=fL(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${$y(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=pe.exactWholeWord,p.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=pe.exactCaseInsensitive,p.push("case-insensitive match")):u.includes(r)&&(d+=pe.substring,p.push("substring match")));let f=c.kind;if(f)d+=nL(f,p);else{let m=mL(u,r,t.id,n.caseSensitive);m!=="code"?(d+=pe.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(vl(t.declaration,u)&&(d+=pe.declarationLine,p.push("declaration line")),vl(t.export,u)&&(d+=pe.exportLine,p.push("export/public line")),vl(t.import,u)&&(d+=pe.importLine,p.push("import line")),t.id==="markdown"&&$A.test(u)&&(d+=pe.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&rL(u,r)&&(d+=pe.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function nL(e,t){switch(e){case"declaration":return t.push("AST: declaration"),pe.declarationLine;case"export":return t.push("AST: export/public"),pe.exportLine;case"configKey":return t.push("AST: config key"),pe.configKeyLine;case"heading":return t.push("AST: heading"),pe.headingLine;case"import":return t.push("AST: import"),pe.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),pe.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function rL(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function oL(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(zy,"").includes(l))&&(s+=pe.pathSegmentToken,i.push("query token in path"))}let a=Ll(e);return r.extensions.includes(a)&&t.langType&&(s+=pe.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=pe.sourceDir,i.push("source file")),s}function iL(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),pe.lowSignalPathPenalty):0}function sL(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*pe.matchCountScale,r=Math.min(n,pe.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function aL(e,t){let n=eL(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>cL(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function cL(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${$y(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function lL(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*pe.rareQueryTokenScale,pe.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function uL(e,t,n){let r=JA(e.path,t.langType,t.profileOverride),o=Qy(e.path),i=ZA(t.keyword),s=[],a=0;return a+=tL(e.matches,r,t,i,s),a+=oL(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=pe.pathUnderQuery,s.push("under requested subtree")),a+=iL(o,t,s),Al.test(e.path)&&!t.explicitLowSignal&&(a+=pe.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=sL(e.matchCount??0,s),a+=lL(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function By(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Hy),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,p)=>d.path.localeCompare(p.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??QA,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Hy);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=aL(i,n),l=i.map(d=>{try{return{file:d,s:uL(d,n,c)}}catch{return{file:d,s:dL()}}});l.sort((d,p)=>{if(p.s.score!==d.s.score)return p.s.score-d.s.score;let f=(p.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(p.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function dL(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Hy(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function vl(e,t){for(let n of e)if(n.test(t))return!0;return!1}function $y(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pL(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function fL(e,t,n){if(e.indexOf(`
40
43
  `)<0)return e;let o=e.split(`
41
- `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function xA(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Jv.test(e))return"comment";let o=TA(e,t,r);if(o<0)return"code";let i=EA(e);return i>=0&&o>i?"comment":kA(e,o)?"string":"code"}function TA(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function EA(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function kA(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function By(e){if(!e)return!1;if(Ml.test(e))return!0;let t=Gy(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Fy,se,Xv,Jv,My,lo,Zv,Ml,eA,tA,nA,rA,oA,iA,sA,Ny,Qy=y(()=>{"use strict";Fy=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],se={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Xv=2e3,Jv=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,My={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},lo={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...My},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...My},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},Zv=/^\s*#{1,6}\s/,Ml=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,eA=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,tA=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,nA=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,rA=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,oA=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,iA=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,sA=new Set(["typescript","javascript","rust","python","go","java","scala"]),Ny=/\.([a-z0-9]+)$/i});async function bs(e,t,n,r,o){let i=t.sort??"relevance",s;try{s=Hy(e,i,FA(t),{debug:!!t.debugRanking})}catch{s={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let a=s.files,c=s.debug,l=a.length,u=!!(t.filesOnly||t.filesWithoutMatch),d=!!(t.countLinesPerFile||t.countMatchesPerFile),p=u||d,f=a.reduce((D,B)=>D+(B.matchCount??0),0),m=p?o?.totalOccurrences??o?.totalStructuralMatches??f:f,g=t,b=Math.min(g.itemsPerPage||bt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=g.page||1,C=Math.max(1,Math.ceil(l/b)),k=(S-1)*b,_=Math.min(k+b,l),E=a.slice(k,_),O=g.maxMatchesPerFile||bt.DEFAULT_MATCHES_PER_PAGE,x=E.map(D=>{let B=D.matches?.length??0,Z=Math.ceil(B/O),z=Math.max(1,g.matchPage||1),Ae=(z-1)*O,Pe=Math.min(Ae+O,B),mt=p?void 0:D.matches?.slice(Ae,Pe),Vt=mt?.length,K=c?.get(D.path);return{path:D.path,...u?{}:t.countLinesPerFile?{totalMatchedLines:D.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:D.matchCount||1}:{totalMatchRows:B,...Vt!==void 0?{returnedMatchRows:Vt}:{}},...mt!==void 0&&{matches:mt},...K?{ranking:{score:K.score,profile:K.profile,pathRole:K.pathRole,reasons:K.reasons}}:{},pagination:!p&&B>O?{currentPage:z,totalPages:Z,matchesPerPage:O,totalMatches:B,hasMore:z<Z,...z<Z?{nextMatchPage:z+1}:{}}:void 0}}),H=x.filter(D=>D.pagination?.hasMore),I=AA(x,t,n,{isFileListMode:p,currentPage:S,totalFilePages:C,matchPage:g.matchPage||1,matchesPerPage:O,hasFileWithMoreMatches:H.length>0}),v={searchEngine:n,...o?{stats:o}:{},files:x,pagination:{currentPage:S,totalPages:C,filesPerPage:b,totalFiles:l,...u?{}:{totalMatches:m},hasMore:S<C,...S<C?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(I).length>0?{next:I}:{}};return $y(v,t,{totalMatches:m,totalFiles:l})}function $y(e,t,n){return e}function AA(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=LA(i);s.fetchExact={tool:"localGetFileContent",query:ys({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:ys({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=_A(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:ys({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:ys({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function LA(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-Uy),endLine:n+Uy}}function _A(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return IA(e?.metavars);if(!t.matchWindow)return t.onlyMatching?Nl(e?.value):Nl(t.keywords)}}function IA(e){if(e)for(let t of Object.values(e))for(let n of t){let r=Nl(n);if(r)return r}}function Nl(e){if(typeof e!="string")return;let t=e.trim();if(vA.test(t)&&!OA.has(t))return t}function ys(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function FA(e){let t=e.rankingProfile,n=!!(e.include?.length||By(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var Uy,OA,vA,Rs=y(()=>{"use strict";ao();Qy();Uy=8,OA=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),vA=/^[A-Za-z_$][A-Za-z0-9_$]*$/});function jy(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=M.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&MA(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&DA(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function MA(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function DA(e){return/\(\?[=!<]/.test(e)}var qy=y(()=>{"use strict";ge()});import{validateRipgrepQuery as NA}from"@octocodeai/octocode-core/schemas/runtime";function GA(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function HA(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:GA(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function zA(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function Vy(e){let t=[],n=NA(e);if(!n.isValid)return F(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:A.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=Ot.safeParse(e);if(!r.success){let g=r.error.issues.map(b=>b.message);return F(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:A.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return F(new Error("Path is required for search"),o,{toolName:A.LOCAL_RIPGREP,extra:{warnings:t}});let s=qe(o,A.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=jy({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return F(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:A.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await M.searchRipgrep(HA(a))}catch(g){return F(g instanceof Error?g:new Error(String(g)),o,{toolName:A.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(b=>{let S={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(S.count=b.count),b.kind!==void 0&&(S.kind=b.kind),b.scoreHint!==void 0&&(S.scoreHint=b.scoreHint),S})})),p=zA(d),f={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return U({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>bt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await bs(d,o,"rg",[...t,...l],f);return U(m,p)}var Wy=y(()=>{"use strict";wt();ar();ao();pe();Rs();qy();ie();ge()});function UA(e){return e.trim().replace(/^\./,"").toLowerCase()}function Kn(e){if(!e?.trim())return;let t=UA(e),n=BA[t]??QA[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function $A(e){return[...e??[]].map(t=>`**/*.${t}`)}function Gl(e){return[...e??[]].map(t=>`*.${t}`)}function Ss(e){let t=Kn(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Hl(e){let t=Kn(e);return t?t.kind==="extension"&&t.extension?{include:$A([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function zl(e){let t=Kn(e);return t?t.kind==="extension"&&t.extension?Gl([t.extension]):t.kind==="language"?Gl(t.extensions):t.normalized?Gl([t.normalized]):[]:[]}function Ky(e){let t=Kn(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Bl(e){return Kn(e)?.canonicalLanguage}var BA,QA,Ql=y(()=>{"use strict";BA={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},QA={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});import{readFile as jA,stat as qA}from"node:fs/promises";function YA(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function Xy(e){return e.include?.length?e.include:Ky(e.langType)}async function XA(e){try{return(await qA(e)).isFile()}catch{return!1}}async function JA(e,t){let n=await jA(e,"utf8"),r=M.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Jy(e){let t=qe(e,A.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await XA(t.sanitizedPath)?await JA(t.sanitizedPath,e):M.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...Xy(e)?{include:Xy(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Yy.length?{excludeDir:Yy}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??VA,maxFileBytes:WA})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return F(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:A.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.split(`
42
- `,1)[0],column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(KA+YA(e.pattern)),await bs(r,e,"structural",i,o)}var Yy,VA,WA,KA,Zy=y(()=>{"use strict";ge();wt();pe();Ql();Rs();Yy=[],VA=2e3,WA=1e6,KA="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function ZA(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Qt(e){let t=ZA(e);if(t.mode==="structural")return await Jy(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Vy(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:q.OUTPUT_TOO_LARGE}:F(n,t,{toolName:A.LOCAL_RIPGREP})}}var Ul=y(()=>{"use strict";wt();Wr();pe();Wy();Zy()});async function eb(e){let{queries:t}=e;return re(t||[],async n=>je({toolName:A.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Fe(Ot,n);return r.ok===!1?r.error:await Qt(r.data)}}),{toolName:A.LOCAL_RIPGREP},e)}var tb=y(()=>{"use strict";ar();pe();$e();Ul();Me();Ht();Rs()});function nL(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function nb(e,t){let n=e[t];return n===void 0?!1:eL.has(n)||n==="{"&&iL(e,t)}function rL(e,t,n){let r=n.pop()??!1,o=nb(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?ob(e,t+1):t+1})}function oL(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:ob(e,t)})}function rb(e){if(e.length>tL)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=nL(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=rL(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(nb(e,r)){let i=oL(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function iL(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function ob(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var eL,tL,ib=y(()=>{"use strict";eL=new Set(["+","*","?"]),tL=1e3});function sb(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!rb(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function ab(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function cb(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var lb=y(()=>{"use strict";ib()});function ub(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+co(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Vn(r)})`}function db(e,t){let n=e.length,r=t.itemsPerPage||bt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function pb(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}var fb=y(()=>{"use strict";ao();gs()});async function Cs(e){try{let t=qe(e,A.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return sL(e,t.sanitizedPath,n)}catch(t){let n=et.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function sL(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=cL(e),s=r&&e.limit&&!aL(e,i)?e.limit*2:1e4,a;try{a=M.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:lL(e),limit:s})}catch(k){return pL(k,e,t)}let c=a.entries.map(k=>uL(k,n,e.details??!1)),l=sb(c,e),u=e.sortBy??"name";l=l.sort((k,_)=>{let E=0;switch(u){case"size":{let O=k.sizeBytes??(k.size?co(k.size):0),x=_.sizeBytes??(_.size?co(_.size):0);E=O-x;break}case"time":n&&k.modified&&_.modified?E=k.modified.localeCompare(_.modified):E=k.name.localeCompare(_.name);break;case"extension":E=(k.extension||"").localeCompare(_.extension||"");break;default:E=k.name.localeCompare(_.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=db(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(k=>({...cb(k),path:k.path??`${t.replace(/\/$/,"")}/${k.name}`}))}:{path:t,...ab(p)},b=[...a.warnings,...pb({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],S=d===0,C=ub(l);return U(mb({...S?{status:"empty"}:{},...g,summary:C,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((k,_)=>k+_.path.length,0))}function aL(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function cL(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function lL(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function uL(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:Vn(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=dL(e.permissions)),o}function dL(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function pL(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=et.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return F(a,t,{toolName:A.LOCAL_VIEW_STRUCTURE})}function mb(e,t){return e}var Ps=y(()=>{"use strict";gs();pe();wt();ji();lb();fb();ie();ge()});async function gb(e){let{queries:t}=e;return re(t||[],async n=>je({toolName:A.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Fe(En,n);return r.ok===!1?r.error:await Cs(r.data)}}),{toolName:A.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var hb=y(()=>{"use strict";qo();pe();$e();Ps();Me();Ht();Ps()});import{safeReadFile as fL}from"@octocodeai/octocode-engine/lsp/validation";function uo(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function bb(e,t,n){if(t<=0)return e;let r=await fL(e.uri);if(!r)return e;let o=Br(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
43
- `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function mL(e,t){return Promise.all(e.map(async n=>({...n,from:await bb(n.from,t,n.fromRanges)})))}async function gL(e,t){return Promise.all(e.map(async n=>({...n,to:await bb(n.to,t)})))}async function $l(e,t,n,r,o){if(n<=0||!e)return{calls:[],...yb};try{let i=await e.getIncomingCalls(t),s=o>0?await mL(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=uo(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),$l(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function jl(e,t,n,r,o){if(n<=0||!e)return{calls:[],...yb};try{let i=await e.getOutgoingCalls(t),s=o>0?await gL(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=uo(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),jl(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var yb,Rb=y(()=>{"use strict";Qr();yb={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});import{readFile as hL,stat as yL}from"node:fs/promises";import{SymbolResolver as bL,SymbolResolutionError as RL}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as ws}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function ql(e,t){let n=e.uri,r=qe({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await yL(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:ws.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:ws.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await hL(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:ws.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Sb(e,t){let n=await ql(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new bL({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:SL(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof RL)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:ws.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function SL(e){return{start:e,end:{line:e.line,character:e.character}}}var Cb=y(()=>{"use strict";wt()});import po from"node:path";import{fileURLToPath as CL}from"node:url";import{acquirePooledClient as Ts,isLanguageServerAvailable as Es}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as PL}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Kl}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function Tb(e){return Vl||(Vl=new Set(M.getSupportedJsTsExtensions().map(t=>`.${t}`))),Vl.has(po.extname(e).toLowerCase())}function xL(e,t){let n=e.startsWith("file://")?CL(e):e;return po.isAbsolute(n)?n:po.resolve(t,n)}function Eb(){return[...M.getSupportedJsTsExtensions(),...wL]}function TL(){return Eb().map(e=>`**/*.${e}`)}async function kL(e,t){let n=e.symbolName?.trim();if(n)try{return(await M.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:TL(),excludeDir:[...EL],maxSnippetChars:1})).files[0]?.path}catch{return}}async function OL(e,t){if(e.uri)return xL(e.uri,t);let n=await kL(e,t);if(n)return n;try{let o=M.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Eb(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function vL(e){return e instanceof Error?e.message:String(e)}function AL(e,t){if(!Tb(e))return null;try{let n=M.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}async function Ob(e){return re(e.queries||[],async t=>je({toolName:we,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await QL(t);return IL(FL(t,n))}}),{toolName:we,minQueryTimeoutMs:3e4},e)}function IL(e){return U(e,Q(e))}function FL(e,t){return e.format!=="compact"||!ML(t)?t:DL(t)}function ML(e){return pn(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&pn(e.payload)}function DL(e){return{...e,format:"compact",payload:NL(e.payload)}}function NL(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Pb)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(HL)}:{locations:(e.locations??[]).map(Pb)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:vb(e.root)}:{},direction:e.direction,calls:e.calls.map(zL),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(GL)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function GL(e){if(!pn(e))return String(e);let t=We(e,"line"),n=We(e,"character"),r=We(e,"endLine"),o=xt(e,"kind"),i=xt(e,"name"),s=We(e,"childCount"),a=xt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Pb(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Lb(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function HL(e){if(!pn(e))return String(e);let t=xt(e,"uri"),n=We(e,"firstLine"),r=We(e,"firstCharacter"),o=We(e,"count"),i=Ab(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function zL(e){if(!pn(e))return String(e);let t=xt(e,"direction"),n=vb(e.item),r=Ab(e,"ranges").map(BL).join(","),o=We(e,"rangeCount"),i=We(e,"rangeSampleCount"),s=xt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Lb(s,180)}`:""].filter(Boolean).join(" ")}function vb(e){if(!pn(e))return String(e);let t=xt(e,"name"),n=xt(e,"kind"),r=xt(e,"uri"),o=We(e,"line"),i=We(e,"endLine"),s=We(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function BL(e){return pn(e)?`${We(e,"line")}:${We(e,"character")}`:String(e)}function pn(e){return typeof e=="object"&&e!==null}function xt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function We(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Ab(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Lb(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function QL(e){if(e.type==="documentSymbols")return UL(e);if(e.type==="workspaceSymbol")return WL(e);if(e.type==="diagnostic")return XL(e);let t=await Sb(e,we);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return a_(e,i)}let n=e.workspaceRoot??await Kl(t.value.uri);if(!await Es(t.value.uri,n)){if(e.type==="references"){let i=jL(e,t.value);if(i)return i}return pt(e.type,t.value,"Language server unavailable")}let o=await Ts(n,t.value.uri);if(!o)return pt(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?Wl(e,t.value,"definition","definitionProvider",await PL({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):pt(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?Wl(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):pt(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?Wl(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):pt(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?_b(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):pt(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?qL(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):pt(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?VL(e,t.value,o):pt(e.type,t.value,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return o.hasCapability("typeHierarchyProvider")?YL(e,t.value,o):pt(e.type,t.value,"typeHierarchyProvider unsupported",!0)}}async function UL(e){let t=await ql(e,we);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Kl(t.value.uri),r=await Es(t.value.uri,n),o=r?await Ts(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=AL(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let S=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(S)?S:[],a="lsp"}else{let S=Wf(t.value.content,t.value.uri);S&&(s=S,a="markdown")}let l=a!==void 0,u=e_(s),d=r_(s),{pageItems:p,pagination:f}=fn(u,e.page??1,e.itemsPerPage??ks),m=o_(u,S=>S.kind),b=l?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(l?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable; native outline supports JS/TS only")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:p.length,topLevelSymbols:d,kinds:m},payload:{kind:"documentSymbols",symbols:p,...b?{empty:b}:{}},pagination:f}}function Wl(e,t,n,r,o){let i=o.length>0,s=o.map(ea),{pageItems:a,pagination:c}=fn(s,e.page??1,e.itemsPerPage??kb);return{type:e.type,uri:t.uri,resolvedSymbol:Kt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function _b(e,t,n,r=$L){let o=r.kind==="native",i=n.map(d=>{let p=d.uri===t.uri&&d.range.start.line===t.resolvedSymbol.position.line&&d.range.start.character===t.resolvedSymbol.position.character;return{...d,...p?{isDefinition:!0}:{}}}),s=e.groupByFile?c_(i):void 0,a=s??i.map(ea),{pageItems:c,pagination:l}=fn(a,e.page??1,e.itemsPerPage??kb),u=i.length===0?{category:"noReferences",reason:o?"no in-file references found":"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:Kt(t.resolvedSymbol),lsp:o?{serverAvailable:!1,source:"native"}:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...s?{byFile:c}:{locations:c},totalReferences:i.length,totalFiles:new Set(i.map(d=>d.uri)).size,...u?{empty:u}:{}},pagination:l,...u&&o?{warnings:["source: native (oxc) \u2014 same-file references only; install a language server for cross-file references."]}:{}}}function jL(e,t){if(!Tb(t.uri))return null;let n;try{let i=M.findInFileReferences(t.content,t.uri,t.resolvedSymbol.position.line,t.resolvedSymbol.position.character);if(!i)return null;let s=JSON.parse(i);if(!Array.isArray(s))return null;n=s}catch{return null}let r=t.content.split(`
44
- `),o=n.map(i=>({uri:t.uri,range:i,content:(r[i.start.line]??"").trim()}));return _b(e,t,o,{kind:"native",scope:"file"})}async function qL(e,t,n){let r=l_(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Kt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function VL(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return pt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await $l(n,o,i,new Set([uo(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await jl(n,o,i,new Set([uo(o)]),e.contextLines??0):s,l=C=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(C.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(C=>!l(C)),p=[...a.calls.map(C=>({direction:"incoming",...C})),...d.map(C=>({direction:"outgoing",...C}))],f=p.map(C=>C.direction==="incoming"?i_(C,e.contextLines??0):s_(C,e.contextLines??0)),{pageItems:m,pagination:g}=fn(f,e.page??1,e.itemsPerPage??LL),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",S=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Kt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Yl(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:S,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function WL(e){let t=e.symbolName??"",n=po.resolve(e.workspaceRoot??process.cwd()),r=await OL(e,n);if(!await Es(r,n))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};let i=await Ts(n,r);if(!i)return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};if(!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{po.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${vL(u)}`}}}let a=KL(s),{pageItems:c,pagination:l}=fn(a,e.page??1,e.itemsPerPage??ks);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function KL(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:xs(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function YL(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return pt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=fn(s,e.page??1,e.itemsPerPage??ks);return{type:e.type,uri:t.uri,resolvedSymbol:Kt(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}async function XL(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Kl(t):process.cwd());if(!await Es(t,n))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};let o=await Ts(n,t);if(!o)return{type:"diagnostic",uri:t,lsp:{serverAvailable:!1},payload:{kind:"empty",category:"serverUnavailable",reason:"Language server unavailable"}};if(!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let i=await o.getDiagnostics(t),s=JL(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=fn(s,e.page??1,e.itemsPerPage??ks);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function JL(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>ZL(r))}return[]}function ZL(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}function fn(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function e_(e){let t=[];for(let n of e)Ib(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Ib(e,t,n){if(!e||typeof e!="object")return;let r=e,o=n_(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:xs(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&t_.has(xs(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Ib(s,t,i)}}function n_(e){if(wb(e.range))return e.range;let t=e.location;return t&&wb(t.range)?t.range:void 0}function wb(e){if(!e||typeof e!="object")return!1;let t=e;return xb(t.start)&&xb(t.end)}function xb(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function r_(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function o_(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function i_(e,t){let n=Fb(e.fromRanges);return{direction:"incoming",item:Yl(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Mb(e.from,t)}}function s_(e,t){let n=Fb(e.fromRanges);return{direction:"outgoing",item:Yl(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Mb(e.to,t)}}function Yl(e){return{name:e.name,kind:xs(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function Fb(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=_L))break}return n}function Mb(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function xs(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function Db(e,t){return/unavailable/i.test(t)?"serverUnavailable":/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function a_(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Db(e.type,t),reason:t}}}function pt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Kt(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Db(e,n),reason:n}}}function c_(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function l_(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>u_(r)).join(`
45
- `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function u_(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var Vl,wL,EL,ks,kb,LL,_L,$L,t_,Nb=y(()=>{"use strict";$e();ie();Ht();Rb();yn();Cb();ge();Ii();wL=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];EL=[".git","node_modules","dist","out","coverage","target"];ks=40,kb=40,LL=10,_L=8;$L={kind:"lsp"};t_=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});function w(e,t,n={}){let r=n.severity??(p_.has(e)?"error":"warning"),o=n.blocksAnswer??(d_.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function Gb(e){return e.some(t=>t.blocksAnswer)}var d_,p_,Ut,ft=y(()=>{"use strict";d_=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","budgetExhausted","contentTruncated"]),p_=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed"]);Ut=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});import{z as P}from"zod";function zb(e,t){let n=w_[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var le,Xl,Hb,f_,m_,g_,h_,y_,b_,R_,S_,C_,P_,w_,Bb=y(()=>{"use strict";le=P.number().int().min(1),Xl=P.number().int().min(0),Hb=P.enum(["symbols","files","dependencies","relations"]),f_=P.object({match:P.enum(["file","path"]).optional(),concise:P.boolean().optional(),extension:P.string().optional(),filename:P.string().optional(),page:le.optional(),limit:le.optional()}).passthrough(),m_=P.object({type:P.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:P.string().optional(),symbolName:P.string().optional(),symbolKind:P.string().optional(),lineHint:le.optional(),orderHint:P.number().int().optional(),includeDeclaration:P.boolean().optional(),depth:P.number().int().min(0).max(20).optional(),groupByFile:P.boolean().optional(),workspaceRoot:P.string().optional(),format:P.enum(["structured","compact"]).optional(),page:le.optional(),itemsPerPage:le.optional()}).passthrough(),g_=P.object({keywords:P.array(P.string()).optional(),topicsToSearch:P.union([P.string(),P.array(P.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:P.string().optional(),owner:P.string().optional(),stars:P.union([P.string(),P.number()]).optional(),forks:P.string().optional(),goodFirstIssues:P.string().optional(),size:P.string().optional(),created:P.string().optional(),updated:P.string().optional(),license:P.string().optional(),match:P.array(P.enum(["name","description","readme"])).optional(),visibility:P.enum(["public","private"]).optional(),archived:P.boolean().optional(),sort:P.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:P.boolean().optional(),page:le.optional()}).passthrough(),h_=P.object({packageName:P.string().optional(),keywords:P.array(P.string()).optional(),mode:P.enum(["lean","full"]).optional(),page:le.optional()}).passthrough(),y_=P.object({prNumber:le.optional(),concise:P.boolean().optional(),state:P.enum(["open","closed","merged"]).optional(),author:P.string().optional(),label:P.union([P.string(),P.array(P.string())]).optional(),keywordsToSearch:P.union([P.string(),P.array(P.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:P.string().optional(),base:P.string().optional(),created:P.string().optional(),updated:P.string().optional(),closed:P.string().optional(),"merged-at":P.string().optional(),draft:P.boolean().optional(),archived:P.boolean().optional(),sort:P.enum(["created","updated","best-match","comments","reactions"]).optional(),order:P.enum(["asc","desc"]).optional(),reviewMode:P.string().optional(),filePage:le.optional(),commentPage:le.optional(),commitPage:le.optional(),charOffset:Xl.optional(),charLength:le.optional(),minify:P.enum(["none","standard"]).optional(),limit:le.optional(),page:le.optional(),matchString:P.string().optional(),matchScope:P.enum(["body","title","comments","reviews","all"]).optional(),content:P.record(P.string(),P.unknown()).optional()}).passthrough(),b_=P.object({path:P.string().optional(),branch:P.string().optional(),since:P.string().optional(),until:P.string().optional(),author:P.string().optional(),includeDiff:P.boolean().optional(),limit:le.optional(),page:le.optional()}).passthrough(),R_=P.object({mode:P.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:P.string().optional(),entryPageNumber:le.optional(),maxEntries:le.optional(),entriesPerPage:le.optional(),minLength:P.number().int().min(1).max(128).optional(),scanOffset:Xl.optional(),charOffset:Xl.optional(),charLength:le.optional(),matchString:P.string().optional(),detailed:P.boolean().optional(),format:P.string().optional(),verbose:P.boolean().optional(),includeOffsets:P.boolean().optional()}).passthrough(),S_=P.object({prNumber:le.optional(),files:P.array(P.string()).optional(),baseRef:P.string().optional(),headRef:P.string().optional(),path:P.string().optional()}).passthrough(),C_=P.object({goal:P.string().optional(),intent:P.enum(["general","reachability","dependencies","symbols"]).optional(),facets:P.array(Hb).optional(),mode:P.enum(["plan","analyze","prove"]).optional(),maxFiles:le.optional()}).passthrough(),P_=P.object({goal:P.string().optional(),intent:P.enum(["general","reachability","dependencies","symbols"]).optional(),facets:P.array(Hb).optional(),mode:P.enum(["plan","analyze","prove"]).optional(),maxFiles:le.optional(),subject:P.string().optional(),subjectKind:P.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:P.union([P.string(),P.array(P.string())]).optional(),verdict:P.union([P.string(),P.array(P.string())]).optional(),direction:P.enum(["incoming","outgoing","both"]).optional(),proof:P.enum(["none","lsp"]).optional(),proofLimit:le.max(25).optional(),includePackets:P.boolean().optional(),includeFacts:P.boolean().optional(),includeEdges:P.boolean().optional()}).passthrough(),w_={semantics:m_,repositories:g_,packages:h_,pullRequests:y_,commits:b_,artifacts:R_,diff:S_,research:C_,graph:P_,code:f_}});function X(...e){throw new Ut(e)}function Qb(e){return xd(e)?T_(e):Ub(e)}function T_(e){let t=Dd.safeParse(e);t.success||X(w("invalidQuery",Os(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||X(w("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&X(w("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return Ub(i)}catch(a){throw a instanceof Ut?new Ut(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}function Ub(e){let t=Md.safeParse(e);t.success||X(w("invalidQuery",Os(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??E_(n);r===void 0&&X(w("invalidQuery",`Could not determine \`target\`; specify one of: ${vt.join(", ")}.`,{queryPath:"target"})),Zo.includes(r)&&X(w("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${vt.join(", ")}.`}})),vt.includes(r)||X(w("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))x_.has(m)||X(w("unknownField",`Unknown field "${m}" is not part of OQL.`,{queryPath:m}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=A_(n,r),a=__(n,s),c=I_(n,r),l=H_(n,s,c,r),u=z_(n),d=O_(n,r),p={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(p.target==="code"&&!p.where&&X(w("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.where&&X(w("invalidQuery",`target:"${p.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.from?.kind==="github"&&!(p.from.repo&&p.from.repo.includes("/"))&&X(w("invalidQuery",`target:"${p.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),p.target==="materialize"&&(p.where&&X(w("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),p.from?.kind!=="github"&&p.from?.kind!=="materialized"&&X(w("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),p.params!==void 0){let m=zb(p.target,p.params);m&&X(w("invalidQuery",m,{queryPath:"params"}))}let f=ei.safeParse(p);return f.success||X(w("invalidQuery",Os(f.error))),f.data}function E_(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function O_(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!v_(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function v_(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return k_.some(n=>t.includes(n))}function A_(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&X(w("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),L_(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};wd.includes(t)||X(w("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function L_(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}function __(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&X(w("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}function I_(e,t){let n=D_(e);e.where&&n&&X(w("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Zl(r,"where");let o=Jt.safeParse(r);return o.success||X(w("invalidQuery",Os(o.error),{queryPath:"where"})),o.data}function Jl(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Jl(n),0):e.kind==="not"?1+Jl(e.predicate):1}function M_(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:F_}function D_(e){let t=n=>{let r=Jl(n),o=M_(e);return r>o&&X(w("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(Yn)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(Yn)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(Yn)}};if(Array.isArray(e.xor)){e.xor.length!==2&&X(w("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=Yn(e.xor[0]),r=Yn(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(N_(e.oneOf.map(Yn)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&X(w("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&X(w("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function Yn(e){if(e&&typeof e=="object"&&"kind"in e)return e;X(w("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function N_(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Zl(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&X(w("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Zl(n,`${t}.of[${r}]`));break;case"not":e.predicate||X(w("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Zl(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&X(w("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":G_(e,t);break;default:break}}function G_(e,t){if(e.op==="exists"){e.value!==void 0&&X(w("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&X(w("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&X(w("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function $b(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return $b(e.predicate);default:return!1}}function H_(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:$b(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function z_(e){return e.fetch?{...e.fetch}:void 0}function Os(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var x_,k_,F_,jb=y(()=>{"use strict";lr();ft();Bb();cr();x_=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"]);k_=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"];F_=64});function B_(e){return e?.mode==="auto"||e?.mode==="required"}function Q_(e,t){let n=e.target==="files"?mn:$t;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:$t,exact:!0,reason:`${t.kind} evaluated locally by ${$t}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function U_(e,t,n){let r=B_(e.materialize);if(n)return $_(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:mn,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:Tt,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:mn,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:Tt,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:mn,exact:!0,reason:`${vs(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:mn,exact:!1,reason:`GitHub cannot enumerate files by ${vs(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${vs(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:$t,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:$t,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:Tt,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:Tt,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?eu(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:$t,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:Tt,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return eu(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:mn,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:Tt,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:Tt,exact:!0,reason:"path/name predicate pushed to provider"}:eu(e,`field "${t.field}"`,r)}}function vs(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function $_(e,t,n){let r=vs(t);return n?{route:"ROUTE",backend:e.target==="files"?mn:$t,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:Tt,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function eu(e,t,n){if(n)return{route:"ROUTE",backend:$t,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:Tt,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function qb(e,t,n=!1){return e.sourceKind==="github"?U_(e,t,n):Q_(e,t)}var $t,mn,Tt,Vb=y(()=>{"use strict";$t="localSearchCode",mn="localFindFiles",Tt="ghSearchCode"});function Xn(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var As=y(()=>{"use strict"});function Wb(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&j_.has(e.target)&&t.push(w("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "exact" or "compact".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "exact" or "compact".'}})),t}var j_,Kb=y(()=>{"use strict";ft();j_=new Set(["pullRequests","commits","diff"])});function Yb(e){let t={schema:ot.schema,view:e.view??ot.view,page:e.page??ot.page,itemsPerPage:e.itemsPerPage??ot.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??ot.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??ot.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??ot.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?ot.detailedCodeContext:ot.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??ot.localSearchSort),t}var ot,Xb=y(()=>{"use strict";ot={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function Jb(e){return JSON.stringify(e)}function tu(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${Jb(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${Jb(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...tu(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=tu(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function Zb(e){return["rule:",...tu(e,1)].join(`
46
- `)}var eR=y(()=>{"use strict"});function tR(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function nR(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return tR(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),tR(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=Zb(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function gn(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return nR(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=nR(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var nu=y(()=>{"use strict";eR()});var Ls=y(()=>{"use strict";Ql()});function ru(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function Je(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Jn(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function ou(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var fo=y(()=>{"use strict"});function q_(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function mo(e,t={}){if(!e.where)return{ok:!1,diagnostics:[w("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=q_(e.where);if(n){let p=rR(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=ru(e.from),g=e.params??{},b=typeof g.extension=="string"||typeof n.extension=="string"?{}:Ss(Jn(e.scope)),S=ou(e),C=Je(e.scope);return{ok:!0,diagnostics:[],query:{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...C?{path:C}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...S?{limit:S}:{},...e.page?{page:e.page}:{}}}}let r=gn(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[w("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=rR(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[w("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=ru(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Ss(Jn(e.scope)),u=ou(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return{ok:!0,diagnostics:[],query:{...s?{owner:s}:{},...a?{repo:a}:{},keywords:[i],...l,...Je(e.scope)?{path:Je(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}}}}function rR(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(w("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(w("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var iu=y(()=>{"use strict";nu();ft();Ls();fo()});function Zn(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return su.find(n=>n.id===`${t}.diff.${e.variant}`)}return su.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function au(e){return su.find(t=>t.id===e)}function cu(e){let t=V_(e.source,e.target);if(e.target==="diff"){let n=Xn(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return Zn({sourceKind:t,target:"diff",variant:r})}return Zn({sourceKind:t,target:e.target})}function oR(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function iR(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function V_(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var su,sR=y(()=>{"use strict";As();su=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.artifacts",target:"artifacts",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localBinaryInspect",operation:"inspectArtifact",exact:!0}],rowKind:"record",recordType:"artifact",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeArtifacts"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function W_(e,t){return e.id??t}function lu(e,t,n,r,o,i=!1){let s=W_(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>lu(e,d,`${n}.of[${p}]`,r,o,i)),l=K_(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(w("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=lu(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=qb(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(w(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&aR(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:Y_(e.target),exact:a.exact}),a.route}function K_(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function Y_(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"artifacts":return"inspectArtifact";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function aR(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function uu(e,t){if(!t)return;let n=iR(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function _s(e,t,n){if(!t)return!1;for(let r of oR(t,n))aR(e.backendCalls,r);return!0}function X_(e,t){return cR(e,t,"files")}function cR(e,t,n,r=Zn({sourceKind:"materialized",target:n})){let o=Zn({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),uu(e,o),uu(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),_s(e,o,t),_s(e,r,void 0),!0}function Is(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Is):e.kind==="not"?Is(e.predicate):!1:!1}function J_(e){return e.target==="code"?au(Is(e.where)?"local.code.structural":"local.code.textRegex"):Zn({sourceKind:"materialized",target:e.target})}function Z_(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?au(Is(e.where)?"local.code.structural":"local.code.textRegex")??cu({source:t,target:e.target,params:e.params}):cu({source:t,target:e.target,params:e.params})}function du(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+du(n),0):e.kind==="not"?1+du(e.predicate):1:0}function lR(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=Z_(e,o);if(uu(n,s),e.where)lu(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&cR(n,o,e.target,J_(e));else if(e.target==="diff"){let m=Xn(e.params);m.kind==="prPatch"||m.kind==="directFile"?_s(n,s,o)||n.diagnostics.push(w("unsupportedTarget",`No transformer registered for target:"diff" lane "${m.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(w("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let m=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(m?g&&X_(n,o):_s(n,s,o))&&(!m||g)&&n.diagnostics.push(w("unsupportedTarget",m?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(w("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...eI(e,n.nodes)),n.diagnostics.push(...Wb(e));let a=tI(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??ot.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(w("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=du(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(w("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let p={input:t,normalized:e,defaults:Yb(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},f=!n.nodes.some(m=>m.route==="UNSUPPORTED")&&!n.diagnostics.some(m=>m.severity==="error"&&m.code!=="planTruncated");return{plan:p,executable:f}}function uR(e){return e.kind==="not"&&e.predicate.kind==="not"?uR(e.predicate.predicate):e}function eI(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=uR(e.where),r=mo({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function tI(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(w("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(w("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var dR=y(()=>{"use strict";Vb();As();Kb();ft();Xb();iu();sR()});function Fs(e){let t=rI(e),n=iI(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function rI(e){return!e.executable||e.diagnostics.some(t=>nI.has(t.code))?"unsupported":e.approximate||oI(e.diagnostics)?"candidate":Gb(e.diagnostics)||pR(e)?"partial":"proof"}function oI(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function pR(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function iI(e){return!e.executable||pR(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function fR(e){return e.some(t=>!t.exact)}function pu(e,t,n,r,o){return Fs({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var nI,mR=y(()=>{"use strict";ft();nI=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function Et(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var Ms=y(()=>{"use strict"});function fu(e){return Et(e)}function sI(e){if(e)return Et({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function Ds(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,line:1,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:aI(sI(e.pagination),n.length)}}function aI(e,t){if(e)return e.totalItemsKind!=="files"?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function Ns(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:fu(e.pagination)}}function gR(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:fu(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=lI(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:fu(e.pagination)}}function lI(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=cI[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function hR(e,t,n,r="compact"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var cI,yR=y(()=>{"use strict";Ms();cI={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import zs from"node:path";import uI from"node:fs";function dI(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}function Qs(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function SR(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function Us(e,t,n){if(n){e.langType=n;return}let r=Hl(Jn(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=SR(e.include,r.include))}function pI(e){return zl(Jn(e))}function bR(e){let t=Bs(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function $s(e){return!!(e?.include?.length||e?.exclude?.length)}function hu(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(bR).filter(i=>!!i);n.length>0&&!e.names&&(e.names=SR(e.names,n));let r=(t?.include??[]).filter(i=>!bR(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=pI(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function fI(e,t){if($s(t.scope)){yu(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function yu(e){e.limit=mu,e.itemsPerPage=mu}async function ho(e){let t=e.from,n=dI(e),r=Je(e.scope),o=r?zs.join(n,r):n;if(!uI.existsSync(o))return{results:[],diagnostics:[w("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return yI(e,t,o);case"structure":return kI(e,t,o);case"content":return OI(e,t,o);default:return PR(e,t,o)}}function mI(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?wR(e.predicate):!1}function gI(e){return e.kind==="text"||e.kind==="regex"}function CR(e){return e?.kind==="not"&&gI(e.predicate)}async function PR(e,t,n){let r=e.where;if(mI(r))return TI(e,t,n,r);if(e.view==="discovery"&&CR(r))return SI(e,t,n,r);let o=gn(r);if(o.unsupported)return{results:[],diagnostics:[w(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...Qs(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...vR(e)};Us(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),i.rule!==void 0&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await Qt(s),c=Ds(a,t),l=er(a,"localSearchCode"),u=hI(a);if(u.length>0){let d=u.reduce((f,m)=>f+(m.total??0),0),p=u.reduce((f,m)=>f+m.shown,0);l.push(w("matchTruncated",`${u.length} file(s) have more matches (showed ${p} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(w("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),{...c,diagnostics:l,provenance:[tr("localSearchCode",t,r)]}}function hI(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}async function yI(e,t,n){let r=e.where;if(CR(r))return RI(e,t,n,r);if(r&&wR(r))return bI(e,t,n,r);if(r&&kR(r)){let l=await PR({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};hu(o,e.scope),fI(o,e);let i=[];r&&OR(r,o,i);let s=await Wn(o),a=Ru(s,e,n);return{...Ns(a,t),diagnostics:[...i,...er(a,"localFindFiles")],provenance:[tr("localFindFiles",t,r)]}}function wR(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function bI(e,t,n,r){let o=[],i=[],a=[...(await Gs(e,r,t,n,o,i)).values()].sort((c,l)=>c.path.localeCompare(l.path));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(w("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}async function Gs(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Gs(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:CI(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Gs(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,bu(a.get(l),u));return a}case"not":{let s=await TR(e,n,r,o),a=await Gs(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return ER(e,t,n,r,o,i)}}async function RI(e,t,n,r){let o=await Qt(xR(e,n,r.predicate)),i=er(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[tr("localSearchCode",t,r)]}}async function SI(e,t,n,r){let o=await Qt(xR(e,n,r.predicate));return{...Ds(o,t),diagnostics:er(o,"localSearchCode"),provenance:[tr("localSearchCode",t,r)]}}function xR(e,t,n){let o=gn(n).match,i={path:t,filesWithoutMatch:!0,...Qs(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...vR(e)};return Us(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}function CI(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,bu(o,i))}return n}function PI(e,t){return new Set([...e].filter(n=>t.has(n)))}function bu(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}async function wI(e,t,n){return new Set((await TR(e,e.from,t,n)).keys())}async function TR(e,t,n,r){let o={path:n,entryType:"f"};hu(o,e.scope),$s(e.scope)&&(yu(o),o.page=1);let i=await Wn(o),s=Ru(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),gu(Ns({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function xI(e,t,n,r,o){return new Set((await ER(e,t,e.from,n,r,o)).keys())}async function ER(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};hu(u,e.scope),OR(t,u,i),$s(e.scope)&&(yu(u),u.page=1);let d=await Wn(u),p=Ru(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),gu(Ns(p,n).results)}let s=gn(t);if(s.unsupported)return i.push(w(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:mu,...Qs(e.scope)};Us(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),a.rule!==void 0&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await Qt(c);return o.push({backend:"localSearchCode",source:e.from}),gu((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function gu(e){let t=new Map;for(let n of e)t.set(n.path,bu(t.get(n.path),n));return t}async function TI(e,t,n,r){let o=[],i=[],s=await Hs(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(w("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function Hs(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Hs(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:PI(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Hs(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await wI(e,r,o),a=await Hs(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await xI(e,t,r,o,i),rows:[]};default:{let s=await EI(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function EI(e,t,n,r,o,i){let s=gn(t);if(s.unsupported)return i.push(w(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...Qs(e.scope)};Us(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),a.rule!==void 0&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await Qt(c);return o.push({backend:"localSearchCode",source:n}),Ds(l,n).results}async function kI(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Cs(r);return{...gR(o,t),diagnostics:er(o,"localViewStructure"),provenance:[tr("localViewStructure",t,void 0)]}}async function OI(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=II(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await fs(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...hR(a,t,n,c),diagnostics:er(a,"localGetFileContent"),provenance:[tr("localGetFileContent",t,void 0)]}}function Ru(e,t,n){if(!$s(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>vI(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function vI(e,t,n){let r=Bs(AI(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>RR(r,i))?!1:!(n?.exclude??[]).some(i=>RR(r,i))}function AI(e,t){let n=zs.relative(t,e);return!n||n.startsWith("..")||zs.isAbsolute(n)?e:n}function Bs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function RR(e,t){let n=Bs(t),r=Bs(e),o=LI(n);return o.test(r)?!0:n.includes("/")?!1:o.test(zs.posix.basename(r))}function LI(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=_I(r)}return new RegExp(`${t}$`)}function _I(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function II(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function kR(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?kR(e.predicate):!1}function OR(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(w("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(go(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(go(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(go(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(w("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(go(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(go(i));break}r&&n.push(w("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function go(e){return w("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function vR(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}function er(e,t){let n=[];e.status==="error"?n.push(w("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(w("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(w(FI(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function FI(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function tr(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var mu,Su=y(()=>{"use strict";fe();Ul();hs();Ps();ms();nu();yR();ft();Ls();fo();mu=1e4});function Re(e,t){return qs(e,{queries:[{...MI,...t}]})}var MI,js=y(()=>{"use strict";Cu();MI={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function _R(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function yo(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function DI(e){return e.structuredContent?.results?.[0]?.status}function Vs(e,t){return e>0?[]:[w("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function IR(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function AR(...e){return e.map(IR).filter(Boolean).join("/")}function NI(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function LR(e){return IR(e).split("/").filter(Boolean).length}function GI(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function HI(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function zI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function BI(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(zI).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function QI(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(GI).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!BI(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(HI(o.path)))}function FR(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function UI(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function $I(e){return typeof e=="string"?[]:e.matches??[]}async function MR(e){switch(e.target){case"content":return VI(e);case"structure":return WI(e);case"files":return jI(e);default:return qI(e)}}async function jI(e){let t=mo(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Re("ghSearchCode",t.query),r=yo(n),o=new Set,i=[];for(let a of r?.files??[]){let c=FR(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Ce(e),path:c,entryType:"file"}))}let s=Et(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...Ws(n,"ghSearchCode"),...Vs(i.length,"ghSearchCode"),...i.length>0?[w("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Ce(e)}]}}function Ce(e){return e.from??{kind:"github"}}async function qI(e){let t=mo(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Re("ghSearchCode",t.query),r=yo(n),o=[];for(let s of r?.files??[]){let a=FR(s),c=UI(s),l=$I(s);if(l.length===0){o.push({kind:"code",source:Ce(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Ce(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=Et(r?.pagination);return{results:o,...i?{pagination:i}:{},diagnostics:[...Ws(n,"ghSearchCode"),...Vs(o.length,"ghSearchCode"),...o.length>0?[w("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Ce(e)}]}}async function VI(e){let{owner:t,repo:n}=_R(Ce(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=KI(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Je(e.scope)??"",type:"file",minify:o,...Ce(e).kind==="github"&&Ce(e).ref?{branch:Ce(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Re("ghGetFileContent",s),c=yo(a),l=o==="none"?"exact":o==="symbols"?"symbols":"compact",u=c?.pagination,d=c?.results??c?.files??[],p=d.map(m=>{let g=m.pagination??u,b=typeof g?.charOffset=="number",S={...m.startLine!==void 0?{startLine:m.startLine}:{},...m.endLine!==void 0?{endLine:m.endLine}:{},...b?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Ce(e),path:m.path,content:m.content,contentView:l,...Object.keys(S).length?{range:S}:{}}}),f=u??d.find(m=>m.pagination)?.pagination;return{results:p,...f?.hasMore!==void 0?{pagination:{hasMore:!!f.hasMore,...f.currentPage!==void 0?{currentPage:f.currentPage}:{},...f.totalPages!==void 0?{totalPages:f.totalPages}:{},...f.charLength!==void 0?{itemsPerPage:f.charLength}:{},...f.totalChars!==void 0?{totalItems:f.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...Ws(a,"ghGetFileContent"),...Vs(p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Ce(e)}]}}async function WI(e){let{owner:t,repo:n}=_R(Ce(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Je(e.scope)??"",...Ce(e).kind==="github"&&Ce(e).ref?{branch:Ce(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Re("ghViewRepoStructure",r),i=yo(o),s=[],a=Je(e.scope);for(let u of NI(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=AR(a,d,p);s.push({kind:"tree",source:Ce(e),path:f,entryType:"directory",depth:LR(f)})}for(let p of u.files??[]){let f=AR(a,d,p);s.push({kind:"tree",source:Ce(e),path:f,entryType:"file",depth:LR(f)})}}let c=QI(s,e),l=Et(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...Ws(o,"ghViewRepoStructure"),...Vs(c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Ce(e)}]}}function KI(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function Ws(e,t){let n=DI(e);if(n==="error"){let r=yo(e);return[w("invalidQuery",r?.error??"GitHub backend error",{backend:t})]}return n==="empty"?[w("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}var DR=y(()=>{"use strict";js();Ms();ft();iu();fo()});import NR from"node:path";function GR(e){return[...new Set(e)]}function zR(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function BR(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!NR.isAbsolute(r.localPath)?NR.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function QR(e){if(e.from?.kind!=="github")return ho(e);let t=e.from,{owner:n,repo:r}=zR(t);if(!n||!r)return{results:[],diagnostics:[w("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Je(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await Re("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=BR(s);if(u==="error"||!a)return{results:[],diagnostics:[w("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},p={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:GR([...d.excludeDir??[],".git"]),exclude:GR([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await ho(p);return{...f,diagnostics:[...f.diagnostics,...c?[w("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...f.provenance]}}async function UR(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[HR(f,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[w("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=zR(t);if(!n||!r)return{results:[],diagnostics:[w("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:Je(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await Re("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=BR(a);if(d==="error"||!c)return{results:[],diagnostics:[w("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let p=!i;return{results:[HR(c,t,t.ref,p,l)],diagnostics:l?[w("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function HR(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var $R=y(()=>{"use strict";js();Su();ft();fo()});import{builtinModules as YI}from"node:module";import he from"node:path";import{readFile as Ks,readdir as XI}from"node:fs/promises";async function xu(e){let t=he.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=tF(r,e.intent,e.facets),i=nF(o,e.facets),s=rF(o,i),a=pF();if(n==="plan")return oF({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:qR([],[],a)});let c=await iF(t,e.maxFiles??5e3),l=await sF(c.filter(x=>x.endsWith(JI))),u=await uF(t,c),d=u.map(x=>x.graphFacts).filter(x=>x!==void 0),p=qR(u,d,a);await TF(u);let f=new Set(l.map(x=>x.name).filter(XR)),m=gF(u),g=hF(t,l,u),b=yF(g,m),S=u.filter(x=>!b.has(x.path)).map(x=>({kind:"unusedFile",file:x.rel,retainedBy:[],verdict:"unused-file"})),C=bF(t,l,u,f),k=await SF(u),_=wF(k,u,b),E=_.filter(x=>x.verdict==="candidate-unused-export"||x.verdict==="unused-export").length,O=_.filter(x=>x.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:b.size,unusedFiles:S.length,unlistedDependencies:C.filter(x=>x.kind==="unlistedDependency").length,unusedDependencies:C.filter(x=>x.kind==="unusedDependency").length,duplicateDependencies:C.filter(x=>x.kind==="duplicateDependency").length,exportedSymbols:_.length,candidateUnusedExports:E,transitiveDeadExports:O,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((x,H)=>x+H.declarations.length,0),nativeGraphCalls:d.reduce((x,H)=>x+H.calls.length,0)},manifests:l.map(x=>({manifest:hn(t,x.path),...x.name?{name:x.name}:{},entrypoints:x.entrypoints.map(H=>hn(t,H)),dependencyCount:[...x.deps.keys()].length})),files:S,dependencies:C,symbols:_,graphFacts:d,graphCapabilities:p,caveats:["This is a smart research flow with native AST graph facts where available plus heuristic cross-file reachability. LSP references should be used before destructive cleanup.","Graph capability coverage is explicit: tree-sitter/OXC facts are syntax inventory, not semantic deletion proof.","Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function tF(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function nF(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function rF(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["localSearchCode structural","lspGetSemantics documentSymbols"],produces:["symbols","lineHints"],evidence:"proof"},{id:"reference-proof",purpose:"Use references grouped by file to separate direct, external, and transitive retention.",tools:["lspGetSemantics references","localSearchCode"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"proof"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function oF(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}async function iF(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await XI(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(ZI.has(s.name))continue;await r(he.join(o,s.name));continue}s.isFile()&&n.push(he.join(o,s.name))}}return await r(e),n}async function sF(e){return(await Promise.all(e.map(async n=>aF(n)))).filter(n=>n!==null)}async function aF(e){let t=await cF(e);if(!t)return null;let n=he.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=vF(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:YR(t.name),deps:r,entrypoints:lF(n,t)}}async function cF(e){try{let t=JSON.parse(await Ks(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function lF(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=YR(t[o]);i&&n.add(he.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(he.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(he.resolve(e,o));WR(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(he.resolve(e,o));return[...n]}function WR(e,t,n){if(typeof t=="string"){n.add(he.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))WR(e,r,n)}async function uF(e,t){let n=Tu(),r=t.filter(i=>n.has(he.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await Ks(i,"utf8").catch(()=>""),a=he.extname(i).toLowerCase(),c=dF(s,i,hn(e,i)),l=LF(c?c.imports.map(u=>u.specifier):mF(s));return{path:i,rel:hn(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!KR(u)).map(OF).filter(XR).filter(u=>!eF.has(u)),...c?{graphFacts:c}:{}}}))}function dF(e,t,n){try{let r=M.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??he.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(AF):[]}}catch{return}}function Tu(){if(bo)return bo;try{let e=M.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());bo=new Set(e.length>0?e:jR)}catch{bo=new Set(jR)}return bo}function pF(){if(Ro)return Ro;try{let e=JSON.parse(M.getGraphFactCapabilities());Ro=Array.isArray(e)?e.filter(fF):[]}catch{Ro=[]}return Ro}function fF(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function qR(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...Tu()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=VR(e,l=>l.language),s=VR(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function VR(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function mF(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function gF(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,he.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??he.dirname(o.path);for(let a of o.imports){if(!KR(a))continue;let c=kF(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function hF(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=wu(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let s=wu(he.resolve(e,i),r);s&&o.add(s)}return[...o]}function yF(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function bF(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=RF(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:hn(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:hn(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:hn(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function RF(e,t){return t.filter(r=>e.startsWith(`${r.dir}${he.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function SF(e){return(await Promise.all(e.map(async n=>{let r=CF(n);if(r.length>0)return r;let o=await Ks(n.path,"utf8").catch(()=>"");return PF(n.rel,o)}))).flat()}function CF(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function PF(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:EF(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function wF(e,t,n){let r=new Map(t.map(o=>[o.rel,o]));return e.map(o=>{let i=t.filter(u=>u.rel!==o.file&&xF(u.path,o.symbol)),s=i.filter(u=>n.has(u.path)),a=r.get(o.file),c=a?n.has(a.path):!1,l=s.length>0?"reachable":i.length>0?"transitive-dead":c?"candidate-unused-export":"unused-export";return{symbol:o.symbol,kind:o.kind,file:o.file,line:o.line,evidenceSource:o.evidenceSource,directRefs:i.length,externalRefs:s.length,retainedBy:i.map(u=>u.rel),verdict:l}})}function xF(e,t){return Pu.get(e)?.has(t)??!1}async function TF(e){Pu.clear(),await Promise.all(e.map(async t=>{let n=await Ks(t.path,"utf8").catch(()=>"");Pu.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function EF(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function kF(e,t,n){return wu(he.resolve(e,t),n)}function wu(e,t){let n=Tu(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(he.join(e,`index${o}`));return r.find(o=>t.has(o))}function KR(e){return e.startsWith("./")||e.startsWith("../")}function OF(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function vF(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function YR(e){return typeof e=="string"&&e.trim()?e:void 0}function XR(e){return typeof e=="string"&&e.length>0}function AF(e){return typeof e=="string"}function LF(e){return[...new Set(e)]}function hn(e,t){return he.relative(e,t)||he.basename(t)}var jR,JI,ZI,eF,bo,Ro,Pu,JR=y(()=>{"use strict";ge();jR=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],JI="package.json",ZI=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),eF=new Set(YI.flatMap(e=>[e,`node:${e}`]));Pu=new Map});import Eu from"node:path";function ku(e){let t=e.root,n=[...e.symbols.map(a=>_F(t,a)),...e.files.map(a=>DF(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>NF(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let o={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},i=0,s=0;for(let a of n)o[a.verdict]+=1,i+=a.why.length,s+=a.retainedBy.length+(a.retains?.length??0);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function _F(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=IF(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:"references",source:"ripgrep",confidence:"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:FF(r),next:MF(e,t)}}function IF(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function FF(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via reference scan; likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable references found, but the scan is token-based. Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only referenced from unreachable code. Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function MF(e,t){let n=Eu.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"exact"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function DF(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:Eu.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:Eu.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function NF(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var ZR=y(()=>{"use strict"});import{statSync as GF}from"node:fs";import J from"node:path";function jt(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function eS(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}function Lu(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function HF(e,t){if(!t||J.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?J.join(n.base,t):t}function zF(e,t,n){let r=t??n??".";if(!e)return r;if(J.isAbsolute(e))return e;if(n&&J.isAbsolute(n))return J.resolve(n,e);if(t&&J.isAbsolute(t)){let o=mS(t)?t:J.dirname(t);return J.resolve(o,e)}return e}function tS(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function lS(e){if(!e)return[];for(let t of cS){let n=e[t];if(Array.isArray(n))return n}return[e]}function QF(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))BF.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function Co(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=u0(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function uS(e){return e==="plan"||e==="prove"?e:"analyze"}function Ys(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??UF),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function $F(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;dS.includes(o)&&t.add(o)}return t.size>0?t:void 0}function jF(e,t){let n=$F(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of dS){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=Ys(e,u.length);o[l]=u.slice(d,p),o[`${l}Page`]=f,s=f.itemsPerPage,a=Math.max(a,f.totalPages??1),f.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function qF(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function nS(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function VF(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:nS(e.relation),verdicts:nS(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function WF(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function nr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function pS(e,t){if(!WF(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>nr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>nr(i.relation,t)),o=e.why.some(i=>nr(i.claim,t));return n||r||o}function Ou(e,t){e.set(t.id,t)}function KF(e,t,n){nr(t.claim,n)&&e.set(t.id,t)}function vu(e,t,n,r){nr(n.relation,r)&&(Ou(e,n.from),Ou(e,n.to),t.set(n.id,n))}function YF(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function XF(e,t,n,r,o,i){let s=t.filter(g=>pS(g,r)),a=Ys(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,p=new Map,f={},m={};for(let g of s)f[g.verdict]=(f[g.verdict]??0)+1,m[g.proofStatus]=(m[g.proofStatus]??0)+1;for(let g of c){if(Ou(l,g.subject),r.includeFacts)for(let b of g.why)KF(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of g.retainedBy)vu(l,u,b,r);if(r.direction!=="incoming")for(let b of g.retains??[])vu(l,u,b,r)}for(let b of g.missingProof)p.set(YF(b),b)}return r.includeEdges&&e0(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:p.size,byVerdict:f,proofStatus:m},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...p.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function fS(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function JF(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}function e0(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=t0(a.relation);if(!nr(c,i))continue;let l=rS(a.from,e,a.line),u=rS(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||vu(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function t0(e){let t=e.trim();return ZF.has(t)?t:"references"}function rS(e,t,n){let r=n0(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function n0(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:J.isAbsolute(o)?J.relative(t,o):o,name:i}}function oS(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function r0(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function o0(e,t,n,r,o){let i=n.filter(l=>pS(l,r)),s=Ys(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await s0(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(w(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(w("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),i0(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(w("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function i0(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function s0(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=J.isAbsolute(t.subject.uri)?t.subject.uri:J.resolve(e,t.subject.uri);try{let i=await Re("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=a0(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=jt(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:_u(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,p=So(a?.totalReferences)??So(u?.totalReferences)??So(a?.referenceCount)??So(u?.referenceCount)??So(d?.totalItems)??iS(u)??iS(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:c0(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function a0(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function iS(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function c0(e,t){let n=new Set;return Au(e,n,t),[...n].slice(0,25)}function Au(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)Au(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&l0(i)&&t.add(J.isAbsolute(i)?J.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])Au(r[o],t,n)}function l0(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}function So(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function _u(e){return typeof e=="string"?e:void 0}function sS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function u0(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"));case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:void 0}case"pullRequest":return n("number")?`#${n("number")}`:n("url");case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12);case"artifact":return n("localPath")??n("path");case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename");case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}}function Iu(e,t){let{status:n,data:r}=jt(e);return n==="error"?[w("invalidQuery",Lu(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[w("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function mS(e){try{let t=J.isAbsolute(e)?e:J.resolve(e);return GF(t).isDirectory()}catch{return!1}}function Xs(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function qt(e){return e.params??{}}function d0(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function Fu(e,t){let n={...qt(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}function Js(e,t,n,r){let{data:o,status:i}=jt(e),s=Iu(e,n),a=i==="error"?[]:lS(o);a.length===0&&!s.some(d=>d.code==="zeroMatches"||d.severity==="error")&&s.push(w("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=Et(c,l);return{results:Co(a,t,r,QF(o)),...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function p0(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(w("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.pagination;return o?.hasMore&&n.push(w("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:gS(o,t)})),n}function gS(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function f0(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:gS(n,t)}}async function m0(e){let{owner:t}=Xs(e.from),n=Fu(e,"limit"),r=typeof n.language=="string"?n.language:d0(e),o=Bl(r);o&&(n.language=o);let i=await Re("ghSearchRepos",{...t?{owner:t}:{},...n});return Js(i,"repository","ghSearchRepos",e.from??{kind:"github"})}async function g0(e){let t=await Re("npmSearch",{...Fu(e)});return Js(t,"package","npmSearch",e.from??{kind:"npm"})}async function aS(e){let{owner:t,repo:n}=Xs(e.from),r=e.target==="commits",o=r?void 0:b0(e),i=r?h0(e):void 0,s=Fu(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await Re("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=Js(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?S0(c,o):i?y0(c,i):c}function h0(e){let t=qt(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function y0(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),p=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,p)+(p<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(w("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(w("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function b0(e){let t=qt(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function R0(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
47
- `)}function S0(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=R0(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(w("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(w("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}async function C0(e){let t=qt(e),{owner:n,repo:r}=Xs(e.from),o=Xn(t);if(o.kind==="prPatch"){let i=await Re("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return Js(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?P0(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):w0(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[w("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function P0(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[w("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=f=>Re("localGetFileContent",{path:f,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r),o(t.path)]),a=jt(i),c=jt(s),l=typeof a.data?.content=="string"?a.data.content:void 0,u=typeof c.data?.content=="string"?c.data.content:void 0;if(a.status==="error"||c.status==="error"||l===void 0||u===void 0){let f=Lu(a.data?.error??c.data?.error,"Could not read local file.");return{results:[],diagnostics:[w("invalidQuery",f,{backend:"localGetFileContent"})],provenance:[{backend:"localGetFileContent",source:e.from}]}}let d=hS(l,u);return{results:[{kind:"record",recordType:"diff",id:`${r}..${t.path}`,...e.from?{source:e.from}:{},data:{path:t.path,basePath:r,headPath:t.path,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[w("zeroMatches","Files are identical.",{backend:"localGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"localGetFileContent",source:e.from}]}}async function w0(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[w("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=p=>Re("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:p,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=eS(i),c=eS(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(p=>p.status==="error"||typeof p.content!="string");if(l){let p=Lu(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[w("invalidQuery",p,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=hS(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[w("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function hS(e,t){let n=e===""?[]:e.split(`
44
+ `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function mL(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(BA.test(e))return"comment";let o=gL(e,t,r);if(o<0)return"code";let i=hL(e);return i>=0&&o>i?"comment":yL(e,o)?"string":"code"}function gL(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function hL(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function yL(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function jy(e){if(!e)return!1;if(Al.test(e))return!0;let t=Qy(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Ny,pe,QA,BA,Gy,Po,$A,Al,jA,UA,qA,WA,VA,KA,YA,zy,Uy=y(()=>{"use strict";Ny=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],pe={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},QA=2e3,BA=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Gy={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Po={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Gy},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Gy},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},$A=/^\s*#{1,6}\s/,Al=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,jA=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,UA=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,qA=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,WA=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,VA=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,KA=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,YA=new Set(["typescript","javascript","rust","python","go","java","scala"]),zy=/\.([a-z0-9]+)$/i});async function vs(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=By(e,s,xL(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),p=!!(t.countLinesPerFile||t.countMatchesPerFile),f=d||p,m=c.reduce((G,Y)=>G+(Y.matchCount??0),0),g=f?o?.totalOccurrences??o?.totalStructuralMatches??m:m,b=t,x=Math.min(b.itemsPerPage||Et.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=b.page||1,k=Math.max(1,Math.ceil(u/x)),A=(S-1)*x,_=Math.min(A+x,u),E=c.slice(A,_),w=b.maxMatchesPerFile||Et.DEFAULT_MATCHES_PER_PAGE,N=E.map(G=>{let Y=G.matches?.length??0,j=Math.ceil(Y/w),Oe=Math.max(1,b.matchPage||1),ve=(Oe-1)*w,Bt=Math.min(ve+w,Y),$t=f?void 0:G.matches?.slice(ve,Bt),re=$t?.length,Pt=l?.get(G.path);return{path:G.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:G.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:G.matchCount||1}:{totalMatchRows:Y,...re!==void 0?{returnedMatchRows:re}:{}},...$t!==void 0&&{matches:$t},...Pt?{ranking:{score:Pt.score,profile:Pt.profile,pathRole:Pt.pathRole,reasons:Pt.reasons}}:{},pagination:!f&&Y>w?{currentPage:Oe,totalPages:j,matchesPerPage:w,totalMatches:Y,hasMore:Oe<j,...Oe<j?{nextMatchPage:Oe+1}:{}}:void 0}}),F=N.filter(G=>G.pagination?.hasMore),O=SL(N,t,n,{isFileListMode:f,currentPage:S,totalFilePages:k,matchPage:b.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:F.length>0}),Q={searchEngine:n,...o?{stats:o}:{},files:N,pagination:{currentPage:S,totalPages:k,filesPerPage:x,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<k,...S<k?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(O).length>0?{next:O}:{}};return Wy(Q,t,{totalMatches:g,totalFiles:u})}function Wy(e,t,n){return e}function SL(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=PL(i);s.fetchExact={tool:"localGetFileContent",query:Os({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:Os({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=CL(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Os({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Os({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function PL(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-qy),endLine:n+qy}}function CL(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return wL(e?.metavars);if(!t.matchWindow)return t.onlyMatching?_l(e?.value):_l(t.keywords)}}function wL(e){if(e)for(let t of Object.values(e))for(let n of t){let r=_l(n);if(r)return r}}function _l(e){if(typeof e!="string")return;let t=e.trim();if(RL.test(t)&&!bL.has(t))return t}function Os(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function xL(e){let t=e.rankingProfile,n=!!(e.include?.length||jy(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var qy,bL,RL,As=y(()=>{"use strict";Ro();Uy();qy=8,bL=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),RL=/^[A-Za-z_$][A-Za-z0-9_$]*$/});function Vy(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=D.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&TL(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&kL(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function TL(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e)||e.length>2&&/^\w+$/.test(e))}function kL(e){return/\(\?[=!<]/.test(e)}var Ky=y(()=>{"use strict";Ce()});import{validateRipgrepQuery as EL}from"@octocodeai/octocode-core/schemas/runtime";function OL(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function vL(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:OL(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function AL(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function Yy(e){let t=[],n=EL(e);if(!n.isValid)return M(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=Ut.safeParse(e);if(!r.success){let g=r.error.issues.map(b=>b.message);return M(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return M(new Error("Path is required for search"),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:t}});let s=Ke(o,v.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Vy({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return M(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:v.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await D.searchRipgrep(vL(a))}catch(g){return M(g instanceof Error?g:new Error(String(g)),o,{toolName:v.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(b=>{let x={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(x.count=b.count),b.kind!==void 0&&(x.kind=b.kind),b.scoreHint!==void 0&&(x.scoreHint=b.scoreHint),x})})),p=AL(d),f={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return U({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>Et.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await vs(d,o,"rg",[...t,...l],f);return U(m,p)}var Xy=y(()=>{"use strict";Dt();kr();Ro();Re();As();Ky();de();Ce()});function IL(e){return e.trim().replace(/^\./,"").toLowerCase()}function ar(e){if(!e?.trim())return;let t=IL(e),n=LL[t]??_L[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function FL(e){return[...e??[]].map(t=>`**/*.${t}`)}function Il(e){return[...e??[]].map(t=>`*.${t}`)}function Ls(e){let t=ar(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Fl(e){let t=ar(e);return t?t.kind==="extension"&&t.extension?{include:FL([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function Ml(e){let t=ar(e);return t?t.kind==="extension"&&t.extension?Il([t.extension]):t.kind==="language"?Il(t.extensions):t.normalized?Il([t.normalized]):[]:[]}function Jy(e){let t=ar(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Dl(e){return ar(e)?.canonicalLanguage}var LL,_L,Nl=y(()=>{"use strict";LL={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},_L={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});import{readFile as ML,stat as DL}from"node:fs/promises";function zL(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function eb(e){return e.include?.length?e.include:Jy(e.langType)}async function QL(e){try{return(await DL(e)).isFile()}catch{return!1}}async function BL(e,t){let n=await ML(e,"utf8"),r=D.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function tb(e){let t=Ke(e,v.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await QL(t.sanitizedPath)?await BL(t.sanitizedPath,e):D.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...eb(e)?{include:eb(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Zy.length?{excludeDir:Zy}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??NL,maxFileBytes:GL})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return M(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:v.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.replace(/\s+/g," ").trim().slice(0,300),column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(HL+zL(e.pattern)),await vs(r,e,"structural",i,o)}var Zy,NL,GL,HL,nb=y(()=>{"use strict";Ce();Dt();Re();Nl();As();Zy=[],NL=2e3,GL=1e6,HL="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function $L(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function Ot(e){let t=$L(e);if(t.mode==="structural")return await tb(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Yy(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:z.OUTPUT_TOO_LARGE}:M(n,t,{toolName:v.LOCAL_RIPGREP})}}var _s=y(()=>{"use strict";Dt();tr();Re();Xy();nb()});async function rb(e){let{queries:t}=e;return ce(t||[],async n=>Ve({toolName:v.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=He(Ut,n);return r.ok===!1?r.error:await Ot(r.data)}}),{toolName:v.LOCAL_RIPGREP},e)}var ob=y(()=>{"use strict";kr();Re();Ge();_s();ze();Zt();As()});function qL(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function ib(e,t){let n=e[t];return n===void 0?!1:jL.has(n)||n==="{"&&KL(e,t)}function WL(e,t,n){let r=n.pop()??!1,o=ib(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?ab(e,t+1):t+1})}function VL(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:ab(e,t)})}function sb(e){if(e.length>UL)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=qL(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=WL(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(ib(e,r)){let i=VL(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function KL(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function ab(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var jL,UL,cb=y(()=>{"use strict";jL=new Set(["+","*","?"]),UL=1e3});function lb(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!sb(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function ub(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function db(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var pb=y(()=>{"use strict";cb()});function fb(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+So(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${ir(r)})`}function mb(e,t){let n=e.length,r=t.itemsPerPage||Et.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function gb(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}var hb=y(()=>{"use strict";Ro();ks()});async function Is(e){try{let t=Ke(e,v.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return YL(e,t.sanitizedPath,n)}catch(t){let n=st.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function YL(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=JL(e),s=r&&e.limit&&!XL(e,i)?e.limit*2:1e4,a;try{a=D.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:ZL(e),limit:s})}catch(k){return n_(k,e,t)}let c=a.entries.map(k=>e_(k,n,e.details??!1)),l=lb(c,e),u=e.sortBy??"name";l=l.sort((k,A)=>{let _=0;switch(u){case"size":{let E=k.sizeBytes??(k.size?So(k.size):0),w=A.sizeBytes??(A.size?So(A.size):0);_=E-w;break}case"time":n&&k.modified&&A.modified?_=k.modified.localeCompare(A.modified):_=k.name.localeCompare(A.name);break;case"extension":_=(k.extension||"").localeCompare(A.extension||"");break;default:_=k.name.localeCompare(A.name);break}return e.reverse?-_:_}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=mb(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(k=>({...db(k),path:k.path??`${t.replace(/\/$/,"")}/${k.name}`}))}:{path:t,...ub(p)},b=[...a.warnings,...gb({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],x=d===0,S=fb(l);return U(yb({...x?{status:"empty"}:{},...g,summary:S,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((k,A)=>k+A.path.length,0))}function XL(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function JL(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function ZL(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function e_(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:ir(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=t_(e.permissions)),o}function t_(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function n_(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=st.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return M(a,t,{toolName:v.LOCAL_VIEW_STRUCTURE})}function yb(e,t){return e}var Fs=y(()=>{"use strict";ks();Re();Dt();ns();pb();hb();de();Ce()});async function bb(e){let{queries:t}=e;return ce(t||[],async n=>Ve({toolName:v.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=He(Nn,n);return r.ok===!1?r.error:await Is(r.data)}}),{toolName:v.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var Rb=y(()=>{"use strict";ri();Re();Ge();Fs();ze();Zt();Fs()});import{safeReadFile as r_}from"@octocodeai/octocode-engine/lsp/validation";function Co(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Pb(e,t,n){if(t<=0)return e;let r=await r_(e.uri);if(!r)return e;let o=Zr(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
45
+ `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function o_(e,t){return Promise.all(e.map(async n=>({...n,from:await Pb(n.from,t,n.fromRanges)})))}async function i_(e,t){return Promise.all(e.map(async n=>({...n,to:await Pb(n.to,t)})))}async function Gl(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Sb};try{let i=await e.getIncomingCalls(t),s=o>0?await o_(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Co(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Gl(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function Hl(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Sb};try{let i=await e.getOutgoingCalls(t),s=o>0?await i_(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Co(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Hl(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var Sb,Cb=y(()=>{"use strict";eo();Sb={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});function a_(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function wb(e,t){if(t===void 0||t==="progressIdle")return e;let n=a_(e);if(!n||!s_.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,warnings:[...e.warnings??[],r]}}var s_,xb=y(()=>{"use strict";s_=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"])});import{readFile as c_,stat as l_}from"node:fs/promises";import{SymbolResolver as u_,SymbolResolutionError as d_}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as Ms}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function zl(e,t){let n=e.uri,r=Ke({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await l_(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:Ms.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:Ms.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await c_(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:Ms.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Tb(e,t){let n=await zl(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new u_({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:p_(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof d_)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:Ms.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function p_(e){return{start:e,end:{line:e.line,character:e.character}}}var kb=y(()=>{"use strict";Dt()});import vt from"node:path";import{readFile as f_}from"node:fs/promises";import{fileURLToPath as m_}from"node:url";import{acquirePooledClient as Ns,isLanguageServerAvailable as Gs,unavailableHintFor as g_}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as h_}from"@octocodeai/octocode-engine/lsp/config";import{resolveImportAliasDefinitions as y_}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as $l}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function b_(e){return Ql||(Ql=new Set(D.getSupportedJsTsExtensions().map(t=>`.${t}`))),Ql.has(vt.extname(e).toLowerCase())}function xn(e,t){let n=h_(e),r=g_(n,void 0);throw new Ie(z.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function S_(e,t){let n=e.startsWith("file://")?m_(e):e;return vt.isAbsolute(n)?n:vt.resolve(t,n)}function Lb(){return[...D.getSupportedJsTsExtensions(),...R_]}function P_(){return Lb().map(e=>`**/*.${e}`)}async function w_(e,t){let n=e.symbolName?.trim();if(n)try{return(await D.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:P_(),excludeDir:[...C_],maxSnippetChars:1})).files[0]?.path}catch{return}}async function x_(e,t){if(e.uri)return S_(e.uri,t);let n=await w_(e,t);if(n)return n;try{let o=D.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Lb(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function T_(e){return e instanceof Error?e.message:String(e)}function k_(e,t){if(!b_(e))return null;try{let n=D.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}async function Ib(e){return ce(e.queries||[],async t=>Ve({toolName:De,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await B_(t);return v_(A_(t,n))}}),{toolName:De,minQueryTimeoutMs:3e4},e)}function v_(e){return U(e,$(e))}function A_(e,t){return e.format!=="compact"||!L_(t)?t:__(t)}function L_(e){return Tn(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Tn(e.payload)}function __(e){return{...e,format:"compact",payload:I_(e.payload)}}function I_(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Eb)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(M_)}:{locations:(e.locations??[]).map(Eb)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:Fb(e.root)}:{},direction:e.direction,calls:e.calls.map(D_),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(F_)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function F_(e){if(!Tn(e))return String(e);let t=Xe(e,"line"),n=Xe(e,"character"),r=Xe(e,"endLine"),o=Ht(e,"kind"),i=Ht(e,"name"),s=Xe(e,"childCount"),a=Ht(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Eb(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Db(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function M_(e){if(!Tn(e))return String(e);let t=Ht(e,"uri"),n=Xe(e,"firstLine"),r=Xe(e,"firstCharacter"),o=Xe(e,"count"),i=Mb(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function D_(e){if(!Tn(e))return String(e);let t=Ht(e,"direction"),n=Fb(e.item),r=Mb(e,"ranges").map(N_).join(","),o=Xe(e,"rangeCount"),i=Xe(e,"rangeSampleCount"),s=Ht(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Db(s,180)}`:""].filter(Boolean).join(" ")}function Fb(e){if(!Tn(e))return String(e);let t=Ht(e,"name"),n=Ht(e,"kind"),r=Ht(e,"uri"),o=Xe(e,"line"),i=Xe(e,"endLine"),s=Xe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function N_(e){return Tn(e)?`${Xe(e,"line")}:${Xe(e,"character")}`:String(e)}function Tn(e){return typeof e=="object"&&e!==null}function Ht(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Xe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Mb(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Db(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function Q_(e,t,n){if(typeof e.openDocument=="function")try{let r=vt.extname(t.uri).slice(1),o=Ob.includes(r)?Ob:[r],i=await Ot({path:n,keywords:t.resolvedSymbol.name,fixedString:!0,wholeWord:!0,filesOnly:!0,maxFiles:H_,include:o.filter(Boolean).map(s=>`*.${s}`)});for(let s of i.files??[]){let a=typeof s.path=="string"?s.path:void 0;if(!a)continue;let c=vt.isAbsolute(a)?a:vt.join(n,a);if(vt.resolve(c)!==vt.resolve(t.uri))try{let l=await f_(c,"utf-8");if(l.length>z_)continue;await e.openDocument(c,l)}catch{}}}catch{}}async function B_(e){if(e.type==="documentSymbols")return j_(e);if(e.type==="workspaceSymbol")return V_(e);if(e.type==="diagnostic")return X_(e);let t=await Tb(e,De);if(t.ok===!1){let a=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return aI(e,a)}let n=e.workspaceRoot??await $l(t.value.uri);await Gs(t.value.uri,n)||xn(t.value.uri,e.type);let o=await Ns(n,t.value.uri);o||xn(t.value.uri,e.type),G_.has(e.type)&&await Q_(o,t.value,n);let i=o.getReadiness?.(),s=await $_(e,t.value,o);return wb(s,i)}async function $_(e,t,n){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?Bl(e,t,"definition","definitionProvider",await y_({anchorUri:t.uri,symbolName:t.resolvedSymbol.name,locations:await n.gotoDefinition(t.uri,t.resolvedSymbol.position,t.content)})):Gt(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?Bl(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.uri,t.resolvedSymbol.position,t.content)):Gt(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?Bl(e,t,"implementation","implementationProvider",await n.implementation(t.uri,t.resolvedSymbol.position,t.content)):Gt(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?U_(e,t,await n.findReferences(t.uri,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content)):Gt(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?q_(e,t,await n.hover(t.uri,t.resolvedSymbol.position,t.content)):Gt(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?W_(e,t,n):Gt(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?Y_(e,t,n):Gt(e.type,t,"typeHierarchyProvider unsupported",!0)}}async function j_(e){let t=await zl(e,De);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await $l(t.value.uri),r=await Gs(t.value.uri,n),o=r?await Ns(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=k_(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let b=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(b)?b:[],a="lsp"}else{let b=Xf(t.value.content,t.value.uri);b&&(s=b,a="markdown")}let l=a!==void 0;!l&&!r&&xn(t.value.uri,"documentSymbols");let u=eI(s),d=rI(s),{pageItems:p,pagination:f}=kn(u,e.page??1,e.itemsPerPage??Hs),m=oI(u,b=>b.kind),g=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:p.length,topLevelSymbols:d,kinds:m},payload:{kind:"documentSymbols",symbols:p,...g?{empty:g}:{}},pagination:f}}function Bl(e,t,n,r,o){let i=o.length>0,s=o.map(fa),{pageItems:a,pagination:c}=kn(s,e.page??1,e.itemsPerPage??_b);return{type:e.type,uri:t.uri,resolvedSymbol:cn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function U_(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?cI(r):void 0,i=o??r.map(fa),{pageItems:s,pagination:a}=kn(i,e.page??1,e.itemsPerPage??_b),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:cn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function q_(e,t,n){let r=lI(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:cn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function W_(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Gt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await Gl(n,o,i,new Set([Co(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await Hl(n,o,i,new Set([Co(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),p=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],f=p.map(S=>S.direction==="incoming"?iI(S,e.contextLines??0):sI(S,e.contextLines??0)),{pageItems:m,pagination:g}=kn(f,e.page??1,e.itemsPerPage??E_),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",x=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:cn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:jl(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:x,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function V_(e){let t=e.symbolName??"",n=vt.resolve(e.workspaceRoot??process.cwd()),r=await x_(e,n);await Gs(r,n)||xn(r,"workspaceSymbol");let i=await Ns(n,r);if(i||xn(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{vt.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${T_(u)}`}}}let a=K_(s),{pageItems:c,pagination:l}=kn(a,e.page??1,e.itemsPerPage??Hs);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function K_(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:Ds(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function Y_(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Gt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=kn(s,e.page??1,e.itemsPerPage??Hs);return{type:e.type,uri:t.uri,resolvedSymbol:cn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}async function X_(e){let t=e.uri??"",n=e.workspaceRoot??(t?await $l(t):process.cwd());await Gs(t,n)||xn(t,"diagnostic");let o=await Ns(n,t);if(o||xn(t,"diagnostic"),!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let i=await o.getDiagnostics(t),s=J_(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=kn(s,e.page??1,e.itemsPerPage??Hs);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function J_(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>Z_(r))}return[]}function Z_(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}function kn(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function eI(e){let t=[];for(let n of e)Nb(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Nb(e,t,n){if(!e||typeof e!="object")return;let r=e,o=nI(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Ds(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&tI.has(Ds(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Nb(s,t,i)}}function nI(e){if(vb(e.range))return e.range;let t=e.location;return t&&vb(t.range)?t.range:void 0}function vb(e){if(!e||typeof e!="object")return!1;let t=e;return Ab(t.start)&&Ab(t.end)}function Ab(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function rI(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function oI(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function iI(e,t){let n=Gb(e.fromRanges);return{direction:"incoming",item:jl(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Hb(e.from,t)}}function sI(e,t){let n=Gb(e.fromRanges);return{direction:"outgoing",item:jl(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Hb(e.to,t)}}function jl(e){return{name:e.name,kind:Ds(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function Gb(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=O_))break}return n}function Hb(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Ds(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function zb(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function aI(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:zb(e.type,t),reason:t}}}function Gt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:cn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:zb(e,n),reason:n}}}function cI(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function lI(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>uI(r)).join(`
46
+ `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function uI(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var Ql,R_,C_,Hs,_b,E_,O_,G_,H_,z_,Ob,tI,Qb=y(()=>{"use strict";_s();Ge();de();Zt();es();tr();Cb();Pr();xb();kb();Ce();Qi();R_=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];C_=[".git","node_modules","dist","out","coverage","target"];Hs=40,_b=40,E_=10,O_=8;G_=new Set(["references","callers","callees","callHierarchy","implementation"]),H_=12,z_=512*1024,Ob=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];tI=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});function P(e,t,n={}){let r=n.severity??(pI.has(e)?"error":"warning"),o=n.blocksAnswer??(dI.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function Bb(e){return e.some(t=>t.blocksAnswer)}var dI,pI,nn,ut=y(()=>{"use strict";dI=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","symbolNotFound","budgetExhausted","rateLimited","authRequired","contentTruncated"]),pI=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","authRequired","symbolNotFound"]);nn=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});import{z as C}from"zod";function jb(e,t){let n=wI[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var ge,Ul,$b,fI,mI,gI,hI,yI,bI,RI,SI,PI,CI,wI,Ub=y(()=>{"use strict";ge=C.number().int().min(1),Ul=C.number().int().min(0),$b=C.enum(["symbols","files","dependencies","relations"]),fI=C.object({match:C.enum(["file","path"]).optional(),concise:C.boolean().optional(),extension:C.string().optional(),filename:C.string().optional(),page:ge.optional(),limit:ge.optional()}).passthrough(),mI=C.object({type:C.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:C.string().optional(),symbolName:C.string().optional(),symbolKind:C.string().optional(),lineHint:ge.optional(),orderHint:C.number().int().optional(),includeDeclaration:C.boolean().optional(),depth:C.number().int().min(0).max(20).optional(),groupByFile:C.boolean().optional(),workspaceRoot:C.string().optional(),format:C.enum(["structured","compact"]).optional(),page:ge.optional(),itemsPerPage:ge.optional()}).passthrough(),gI=C.object({keywords:C.array(C.string()).optional(),topicsToSearch:C.union([C.string(),C.array(C.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:C.string().optional(),owner:C.string().optional(),stars:C.union([C.string(),C.number()]).optional(),forks:C.string().optional(),goodFirstIssues:C.string().optional(),size:C.string().optional(),created:C.string().optional(),updated:C.string().optional(),license:C.string().optional(),match:C.array(C.enum(["name","description","readme"])).optional(),visibility:C.enum(["public","private"]).optional(),archived:C.boolean().optional(),sort:C.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:C.boolean().optional(),page:ge.optional()}).passthrough(),hI=C.object({packageName:C.string().optional(),keywords:C.array(C.string()).optional(),mode:C.enum(["lean","full"]).optional(),page:ge.optional()}).passthrough(),yI=C.object({prNumber:ge.optional(),concise:C.boolean().optional(),state:C.enum(["open","closed","merged"]).optional(),author:C.string().optional(),label:C.union([C.string(),C.array(C.string())]).optional(),keywordsToSearch:C.union([C.string(),C.array(C.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:C.string().optional(),base:C.string().optional(),created:C.string().optional(),updated:C.string().optional(),closed:C.string().optional(),"merged-at":C.string().optional(),draft:C.boolean().optional(),archived:C.boolean().optional(),sort:C.enum(["created","updated","best-match","comments","reactions"]).optional(),order:C.enum(["asc","desc"]).optional(),reviewMode:C.string().optional(),filePage:ge.optional(),commentPage:ge.optional(),commitPage:ge.optional(),charOffset:Ul.optional(),charLength:ge.optional(),minify:C.enum(["none","standard"]).optional(),limit:ge.optional(),page:ge.optional(),matchString:C.string().optional(),matchScope:C.enum(["body","title","comments","reviews","all"]).optional(),content:C.record(C.string(),C.unknown()).optional()}).passthrough(),bI=C.object({path:C.string().optional(),branch:C.string().optional(),since:C.string().optional(),until:C.string().optional(),author:C.string().optional(),includeDiff:C.boolean().optional(),limit:ge.optional(),page:ge.optional()}).passthrough(),RI=C.object({mode:C.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:C.string().optional(),entryPageNumber:ge.optional(),maxEntries:ge.optional(),entriesPerPage:ge.optional(),minLength:C.number().int().min(1).max(128).optional(),scanOffset:Ul.optional(),charOffset:Ul.optional(),charLength:ge.optional(),matchString:C.string().optional(),detailed:C.boolean().optional(),format:C.string().optional(),verbose:C.boolean().optional(),includeOffsets:C.boolean().optional()}).passthrough(),SI=C.object({prNumber:ge.optional(),files:C.array(C.string()).optional(),baseRef:C.string().optional(),headRef:C.string().optional(),path:C.string().optional()}).passthrough(),PI=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array($b).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:ge.optional()}).passthrough(),CI=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array($b).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:ge.optional(),subject:C.string().optional(),subjectKind:C.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:C.union([C.string(),C.array(C.string())]).optional(),verdict:C.union([C.string(),C.array(C.string())]).optional(),direction:C.enum(["incoming","outgoing","both"]).optional(),proof:C.enum(["none","lsp"]).optional(),proofLimit:ge.max(25).optional(),includePackets:C.boolean().optional(),includeFacts:C.boolean().optional(),includeEdges:C.boolean().optional()}).passthrough(),wI={semantics:mI,repositories:gI,packages:hI,pullRequests:yI,commits:bI,artifacts:RI,diff:SI,research:PI,graph:CI,code:fI}});function X(...e){throw new nn(e)}function qb(e){return wd(e)?TI(e):Wb(e)}function TI(e){let t=Gd.safeParse(e);t.success||X(P("invalidQuery",zs(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||X(P("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&X(P("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return Wb(i)}catch(a){throw a instanceof nn?new nn(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}function Wb(e){let t=Nd.safeParse(e);t.success||X(P("invalidQuery",zs(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??kI(n);r===void 0&&X(P("invalidQuery",`Could not determine \`target\`; specify one of: ${un.join(", ")}.`,{queryPath:"target"})),ui.includes(r)&&X(P("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${un.join(", ")}.`}})),un.includes(r)||X(P("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))xI.has(m)||X(P("unknownField",`Unknown field "${m}" is not part of OQL.`,{queryPath:m}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=AI(n,r),a=_I(n,s),c=II(n,r),l=HI(n,s,c,r),u=zI(n),d=OI(n,r),p={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(p.target==="code"&&!p.where&&X(P("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.where&&X(P("invalidQuery",`target:"${p.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.from?.kind==="github"&&!(p.from.repo&&p.from.repo.includes("/"))&&X(P("invalidQuery",`target:"${p.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),p.target==="materialize"&&(p.where&&X(P("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),p.from?.kind!=="github"&&p.from?.kind!=="materialized"&&X(P("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),p.params!==void 0){let m=jb(p.target,p.params);m&&X(P("invalidQuery",m,{queryPath:"params"}))}let f=di.safeParse(p);return f.success||X(P("invalidQuery",zs(f.error))),f.data}function kI(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function OI(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!vI(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function vI(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return EI.some(n=>t.includes(n))}function AI(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&X(P("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),LI(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Pd.includes(t)||X(P("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function LI(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}function _I(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&X(P("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}function II(e,t){let n=DI(e);e.where&&n&&X(P("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Wl(r,"where"),Vl(r,"where",new Map);let o=dn.safeParse(r);return o.success||X(P("invalidQuery",zs(o.error),{queryPath:"where"})),o.data}function ql(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+ql(n),0):e.kind==="not"?1+ql(e.predicate):1}function MI(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:FI}function DI(e){let t=n=>{let r=ql(n),o=MI(e);return r>o&&X(P("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(cr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(cr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(cr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&X(P("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=cr(e.xor[0]),r=cr(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(NI(e.oneOf.map(cr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&X(P("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&X(P("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function cr(e){if(e&&typeof e=="object"&&"kind"in e)return e;X(P("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function NI(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Wl(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&X(P("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Wl(n,`${t}.of[${r}]`));break;case"not":e.predicate||X(P("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Wl(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&X(P("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":GI(e,t);break;default:break}}function Vl(e,t,n){if(typeof e.id=="string"){let r=n.get(e.id);r!==void 0&&r.node!==e&&X(P("invalidQuery",`Duplicate predicate id "${e.id}" at ${r.path} and ${t}; ids must be unique across \`where\`.`,{queryPath:t,predicateId:e.id})),r===void 0&&n.set(e.id,{path:t,node:e})}e.kind==="all"||e.kind==="any"?e.of.forEach((r,o)=>Vl(r,`${t}.of[${o}]`,n)):e.kind==="not"&&Vl(e.predicate,`${t}.predicate`,n)}function GI(e,t){if(e.op==="exists"){e.value!==void 0&&X(P("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&X(P("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&X(P("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function Vb(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return Vb(e.predicate);default:return!1}}function HI(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:Vb(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function zI(e){return e.fetch?{...e.fetch}:void 0}function zs(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var xI,EI,FI,Kb=y(()=>{"use strict";Er();ut();Ub();zn();xI=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"]);EI=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"];FI=64});function QI(e){return e?.mode==="auto"||e?.mode==="required"}function BI(e,t){let n=e.target==="files"?En:rn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:rn,exact:!0,reason:`${t.kind} evaluated locally by ${rn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function $I(e,t,n){let r=QI(e.materialize);if(n)return jI(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:En,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:En,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:En,exact:!0,reason:`${Qs(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:En,exact:!1,reason:`GitHub cannot enumerate files by ${Qs(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Qs(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:rn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:rn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?Kl(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:rn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return Kl(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:En,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"path/name predicate pushed to provider"}:Kl(e,`field "${t.field}"`,r)}}function Qs(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function jI(e,t,n){let r=Qs(t);return n?{route:"ROUTE",backend:e.target==="files"?En:rn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:zt,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function Kl(e,t,n){if(n)return{route:"ROUTE",backend:rn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:zt,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function Yb(e,t,n=!1){return e.sourceKind==="github"?$I(e,t,n):BI(e,t)}var rn,En,zt,Xb=y(()=>{"use strict";rn="localSearchCode",En="localFindFiles",zt="ghSearchCode"});function lr(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var Bs=y(()=>{"use strict"});function Jb(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&UI.has(e.target)&&t.push(P("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "exact" or "compact".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "exact" or "compact".'}})),t}var UI,Zb=y(()=>{"use strict";ut();UI=new Set(["pullRequests","commits","diff"])});function eR(e){let t={schema:dt.schema,view:e.view??dt.view,page:e.page??dt.page,itemsPerPage:e.itemsPerPage??dt.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??dt.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??dt.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??dt.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?dt.detailedCodeContext:dt.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??dt.localSearchSort),t}var dt,tR=y(()=>{"use strict";dt={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"}});function nR(e){return JSON.stringify(e)}function Yl(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${nR(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${nR(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Yl(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=Yl(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function rR(e){return["rule:",...Yl(e,1)].join(`
47
+ `)}var oR=y(()=>{"use strict"});function iR(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function sR(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return iR(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),iR(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=rR(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function On(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return sR(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=sR(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var Xl=y(()=>{"use strict";oR()});var $s=y(()=>{"use strict";Nl()});function js(e){return e.kind==="all"||e.kind==="any"?e.of.flatMap(js):e.kind==="not"?js(e.predicate):[e]}function Jl(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function rt(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function ur(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Zl(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var wo=y(()=>{"use strict"});function aR(e,t,n){let r=e.where,o=r?js(r):[],i=r&&qI.has(r.kind)&&o.length===1?[]:o.filter(s=>s!==r);return i.length>0?{ok:!1,diagnostics:i.map(s=>P("lossyTransform","GitHub code search compiled only part of `where`; an unconsumed predicate would be silently dropped \u2014 materialize for local proof.",{backend:n,...s.id?{predicateId:s.id}:{}}))}:{ok:!0,diagnostics:[],query:t}}function WI(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function xo(e,t={}){if(!e.where)return{ok:!1,diagnostics:[P("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=WI(e.where);if(n){let p=cR(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=Jl(e.from),g=e.params??{},b=typeof g.extension=="string"||typeof n.extension=="string"?{}:Ls(ur(e.scope)),x=Zl(e),S=rt(e.scope);return aR(e,{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...x?{limit:x}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}let r=On(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[P("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=cR(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[P("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Jl(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Ls(ur(e.scope)),u=Zl(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return aR(e,{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...rt(e.scope)?{path:rt(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}},t.unsupportedBackend??"ghSearchCode")}function cR(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(P("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(P("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var qI,eu=y(()=>{"use strict";Xl();ut();$s();wo();qI=new Set(["text","regex","structural","field"])});function dr(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return tu.find(n=>n.id===`${t}.diff.${e.variant}`)}return tu.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function nu(e){return tu.find(t=>t.id===e)}function ru(e){let t=VI(e.source,e.target);if(e.target==="diff"){let n=lr(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return dr({sourceKind:t,target:"diff",variant:r})}return dr({sourceKind:t,target:e.target})}function lR(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function uR(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function VI(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var tu,dR=y(()=>{"use strict";Bs();tu=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.artifacts",target:"artifacts",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localBinaryInspect",operation:"inspectArtifact",exact:!0}],rowKind:"record",recordType:"artifact",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeArtifacts"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function KI(e,t){return e.id??t}function ou(e,t,n,r,o,i=!1){let s=KI(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>ou(e,d,`${n}.of[${p}]`,r,o,i)),l=YI(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(P("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=ou(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=Yb(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(P(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&pR(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:XI(e.target),exact:a.exact}),a.route}function YI(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function XI(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"artifacts":return"inspectArtifact";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function pR(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function iu(e,t){if(!t)return;let n=uR(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Us(e,t,n){if(!t)return!1;for(let r of lR(t,n))pR(e.backendCalls,r);return!0}function JI(e,t){return fR(e,t,"files")}function fR(e,t,n,r=dr({sourceKind:"materialized",target:n})){let o=dr({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),iu(e,o),iu(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),Us(e,o,t),Us(e,r,void 0),!0}function qs(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(qs):e.kind==="not"?qs(e.predicate):!1:!1}function ZI(e){return e.target==="code"?nu(qs(e.where)?"local.code.structural":"local.code.textRegex"):dr({sourceKind:"materialized",target:e.target})}function eF(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?nu(qs(e.where)?"local.code.structural":"local.code.textRegex")??ru({source:t,target:e.target,params:e.params}):ru({source:t,target:e.target,params:e.params})}function su(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+su(n),0):e.kind==="not"?1+su(e.predicate):1:0}function mR(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=eF(e,o);if(iu(n,s),e.where)ou(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&fR(n,o,e.target,ZI(e));else if(e.target==="diff"){let m=lr(e.params);m.kind==="prPatch"||m.kind==="directFile"?Us(n,s,o)||n.diagnostics.push(P("unsupportedTarget",`No transformer registered for target:"diff" lane "${m.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(P("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let m=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(m?g&&JI(n,o):Us(n,s,o))&&(!m||g)&&n.diagnostics.push(P("unsupportedTarget",m?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(P("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...nF(e,n.nodes)),n.diagnostics.push(...tF(e)),n.diagnostics.push(...Jb(e));let a=rF(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??dt.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(P("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=su(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(P("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let p={input:t,normalized:e,defaults:eR(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},f=!n.nodes.some(m=>m.route==="UNSUPPORTED")&&!n.diagnostics.some(m=>m.severity==="error"&&m.code!=="planTruncated");return{plan:p,executable:f}}function gR(e){return e.kind==="not"&&e.predicate.kind==="not"?gR(e.predicate.predicate):e}function tF(e){let t=e.controls?.search?.sort;if(!t)return[];let n=e.target==="code"||e.target==="files"?Cd[e.target]:void 0;if(n)return n.includes(t)?[]:[P("lossyTransform",`controls.search.sort:"${t}" has no ${e.target}-lane equivalent and is ignored (default ordering applies). Sorts for target:"${e.target}": ${n.join("|")}.`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})];let r=e.target==="repositories"||e.target==="packages"?` Pass the sort through params.sort instead (validated by the target:"${e.target}" params).`:"";return[P("lossyTransform",`controls.search.sort:"${t}" is not applied for target:"${e.target}" \u2014 only target:"code" and target:"files" support controls.search.sort.${r}`,{queryPath:"controls.search.sort",severity:"warning",blocksAnswer:!1})]}function nF(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=gR(e.where),r=xo({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function rF(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(P("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(P("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var hR=y(()=>{"use strict";Xb();Bs();Zb();ut();tR();eu();dR();zn()});function Ws(e){let t=iF(e),n=aF(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function iF(e){return!e.executable||e.diagnostics.some(t=>oF.has(t.code))?"unsupported":e.approximate||sF(e.diagnostics)?"candidate":Bb(e.diagnostics)||yR(e)?"partial":"proof"}function sF(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function yR(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function aF(e){return!e.executable||yR(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function bR(e){return e.some(t=>!t.exact)}function au(e,t,n,r,o){return Ws({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var oF,RR=y(()=>{"use strict";ut();oF=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function Qt(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var Vs=y(()=>{"use strict"});function cu(e){return Qt(e)}function cF(e){if(e)return Qt({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function Ks(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:lu(cF(e.pagination),n.length)}}function lu(e,t,n=!1){if(e)return e.totalItemsKind!=="files"&&!n?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function Ys(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:cu(e.pagination)}}function SR(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:cu(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=uF(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:cu(e.pagination)}}function uF(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=lF[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function PR(e,t,n,r="compact"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var lF,uu=y(()=>{"use strict";Vs();lF={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import Zs from"node:path";import dF from"node:fs";function pF(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}function ta(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function mF(e){return fF.test(e)}function xR(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function na(e,t,n){if(n){e.langType=n;return}let r=Fl(ur(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=xR(e.include,r.include))}function gF(e){return Ml(ur(e))}function CR(e){let t=ea(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function ra(e){return!!(e?.include?.length||e?.exclude?.length)}function fu(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(CR).filter(i=>!!i);n.length>0&&!e.names&&(e.names=xR(e.names,n));let r=(t?.include??[]).filter(i=>!CR(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=gF(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function hF(e,t){if(ra(t.scope)){mu(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function mu(e){e.limit=du,e.itemsPerPage=du}async function ko(e){let t=e.from,n=pF(e),r=rt(e.scope),o=r?Zs.join(n,r):n;if(!dF.existsSync(o))return{results:[],diagnostics:[P("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return SF(e,t,o);case"structure":return _F(e,t,o);case"content":return IF(e,t,o);default:return kR(e,t,o)}}function yF(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?ER(e.predicate):!1}function bF(e){return e.kind==="text"||e.kind==="regex"}function TR(e){return e?.kind==="not"&&bF(e.predicate)}async function kR(e,t,n){let r=e.where;if(yF(r))return AF(e,t,n,r);if(e.view==="discovery"&&TR(r))return TF(e,t,n,r);let o=On(r);if(o.unsupported)return{results:[],diagnostics:[P(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...ta(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...IR(e)};na(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),typeof i.rule=="string"&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await Ot(s),c=Ks(a,t),l=pr(a,"localSearchCode"),u=RF(a);if(u.length>0){let d=u.reduce((f,m)=>f+(m.total??0),0),p=u.reduce((f,m)=>f+m.shown,0);l.push(P("matchTruncated",`${u.length} file(s) have more matches (showed ${p} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(P("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),i.mode!=="structural"&&i.fixedString===!0&&c.results.length===0&&i.keywords!==void 0&&mF(i.keywords)&&l.push(P("zeroMatches",`Literal search for "${i.keywords}" matched 0 \u2014 a text predicate searches for a FIXED string, so the regex metacharacters in it were matched literally (not as a pattern). This may be a false "not found".`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'If you meant a pattern, use a regex predicate (where = { kind:"regex", value:"<pattern>" }) so metacharacters like | ( ) [ ] ^ $ * + ? \\b are interpreted.'}})),{...c,diagnostics:l,provenance:[fr("localSearchCode",t,r)]}}function RF(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}async function SF(e,t,n){let r=e.where;if(TR(r))return xF(e,t,n,r);if(r&&ER(r))return CF(e,t,n,r);if(r&&LR(r)){let l=await kR({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};fu(o,e.scope),hF(o,e),PF(o,e);let i=[];r&&_R(r,o,i);let s=await sr(o),a=hu(s,e,n);return{...Ys(a,t),diagnostics:[...i,...pr(a,"localFindFiles")],provenance:[fr("localFindFiles",t,r)]}}function PF(e,t){let n=t.controls?.search?.sort;(n==="size"||n==="name"||n==="path"||n==="modified")&&(e.sortBy=n)}function ER(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function CF(e,t,n,r){let o=[],i=[],a=[...(await Xs(e,r,t,n,o,i)).values()].sort(wF(e));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(P("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}function wF(e){let t=e.controls?.search?.sort,n=(r,o)=>r.path.localeCompare(o.path);if(t==="size")return(r,o)=>(o.size??0)-(r.size??0)||n(r,o);if(t==="modified")return(r,o)=>(o.modified??"").localeCompare(r.modified??"")||n(r,o);if(t==="name"){let r=o=>o.slice(o.lastIndexOf("/")+1);return(o,i)=>r(o.path).localeCompare(r(i.path))||n(o,i)}return n}async function Xs(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Xs(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:kF(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Xs(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,gu(a.get(l),u));return a}case"not":{let s=await vR(e,n,r,o),a=await Xs(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return AR(e,t,n,r,o,i)}}async function xF(e,t,n,r){let o=await Ot(OR(e,n,r.predicate)),i=pr(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[fr("localSearchCode",t,r)]}}async function TF(e,t,n,r){let o=await Ot(OR(e,n,r.predicate));return{...Ks(o,t),diagnostics:pr(o,"localSearchCode"),provenance:[fr("localSearchCode",t,r)]}}function OR(e,t,n){let o=On(n).match,i={path:t,filesWithoutMatch:!0,...ta(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...IR(e)};return na(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}function kF(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,gu(o,i))}return n}function EF(e,t){return new Set([...e].filter(n=>t.has(n)))}function gu(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}async function OF(e,t,n){return new Set((await vR(e,e.from,t,n)).keys())}async function vR(e,t,n,r){let o={path:n,entryType:"f"};fu(o,e.scope),ra(e.scope)&&(mu(o),o.page=1);let i=await sr(o),s=hu(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),pu(Ys({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function vF(e,t,n,r,o){return new Set((await AR(e,t,e.from,n,r,o)).keys())}async function AR(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};fu(u,e.scope),_R(t,u,i),ra(e.scope)&&(mu(u),u.page=1);let d=await sr(u),p=hu(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),pu(Ys(p,n).results)}let s=On(t);if(s.unsupported)return i.push(P(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:du,...ta(e.scope)};na(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await Ot(c);return o.push({backend:"localSearchCode",source:e.from}),pu((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function pu(e){let t=new Map;for(let n of e)t.set(n.path,gu(t.get(n.path),n));return t}async function AF(e,t,n,r){let o=[],i=[],s=await Js(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(P("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function Js(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Js(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:EF(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Js(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await OF(e,r,o),a=await Js(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await vF(e,t,r,o,i),rows:[]};default:{let s=await LF(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function LF(e,t,n,r,o,i){let s=On(t);if(s.unsupported)return i.push(P(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...ta(e.scope)};na(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),typeof a.rule=="string"&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await Ot(c);return o.push({backend:"localSearchCode",source:n}),Ks(l,n).results}async function _F(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Is(r);return{...SR(o,t),diagnostics:pr(o,"localViewStructure"),provenance:[fr("localViewStructure",t,void 0)]}}async function IF(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=GF(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await xs(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...PR(a,t,n,c),diagnostics:pr(a,"localGetFileContent"),provenance:[fr("localGetFileContent",t,void 0)]}}function hu(e,t,n){if(!ra(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>FF(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function FF(e,t,n){let r=ea(MF(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>wR(r,i))?!1:!(n?.exclude??[]).some(i=>wR(r,i))}function MF(e,t){let n=Zs.relative(t,e);return!n||n.startsWith("..")||Zs.isAbsolute(n)?e:n}function ea(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function wR(e,t){let n=ea(t),r=ea(e),o=DF(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Zs.posix.basename(r))}function DF(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=NF(r)}return new RegExp(`${t}$`)}function NF(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function GF(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function LR(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?LR(e.predicate):!1}function _R(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(P("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(To(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(To(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(To(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(P("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(To(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(To(i));break}r&&n.push(P("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function To(e){return P("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function IR(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&n.sort!=="size"&&n.sort!=="name"&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}function pr(e,t){let n=[];e.status==="error"?n.push(P("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(P(HF(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function HF(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function fr(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var du,fF,yu=y(()=>{"use strict";Se();_s();Es();Fs();Ts();Xl();uu();ut();$s();wo();du=1e4;fF=/[|()[\]{}^$*+?]|\\[bBdDwWsS]/});function Ee(e,t){return oa(e,{queries:[{...zF,...t}]})}function on(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function mr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Eo(e){return typeof e=="string"?e:void 0}var zF,Oo=y(()=>{"use strict";bu();zF={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function DR(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function vo(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function NR(e){return e.structuredContent?.results?.[0]?.status}function QF(e,t){return e>0?[]:[P("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function GR(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function FR(...e){return e.map(GR).filter(Boolean).join("/")}function BF(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function MR(e){return GR(e).split("/").filter(Boolean).length}function $F(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function jF(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function UF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qF(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(UF).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function WF(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map($F).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!qF(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(jF(o.path)))}function HR(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function VF(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function KF(e){return typeof e=="string"?[]:e.matches??[]}async function zR(e){switch(e.target){case"content":return JF(e);case"structure":return ZF(e);case"files":return YF(e);default:return XF(e)}}async function YF(e){let t=xo(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Ee("ghSearchCode",t.query),r=vo(n),o=new Set,i=[];for(let a of r?.files??[]){let c=HR(a);o.has(c)||(o.add(c),i.push({kind:"file",source:Le(e),path:c,entryType:"file"}))}let s=Qt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...ia(n,i.length,"ghSearchCode"),...i.length>0?[P("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Le(e)}]}}function Le(e){return e.from??{kind:"github"}}async function XF(e){let t=xo(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Ee("ghSearchCode",t.query),r=vo(n),o=[];for(let s of r?.files??[]){let a=HR(s),c=VF(s),l=KF(s);if(l.length===0){o.push({kind:"code",source:Le(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:Le(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=lu(Qt(r?.pagination),o.length,!0);return{results:o,...i?{pagination:i}:{},diagnostics:[...ia(n,o.length,"ghSearchCode"),...o.length>0?[P("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:Le(e)}]}}async function JF(e){let{owner:t,repo:n}=DR(Le(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=e0(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:rt(e.scope)??"",type:"file",minify:o,...Le(e).kind==="github"&&Le(e).ref?{branch:Le(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Ee("ghGetFileContent",s),c=vo(a),l=o==="none"?"exact":o==="symbols"?"symbols":"compact",u=c?.pagination,d=c?.results??c?.files??[],p=d.map(m=>{let g=m.pagination??u,b=typeof g?.charOffset=="number",x={...m.startLine!==void 0?{startLine:m.startLine}:{},...m.endLine!==void 0?{endLine:m.endLine}:{},...b?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:Le(e),path:m.path,content:m.content,contentView:l,...Object.keys(x).length?{range:x}:{}}}),f=u??d.find(m=>m.pagination)?.pagination;return{results:p,...f?.hasMore!==void 0?{pagination:{hasMore:!!f.hasMore,...f.currentPage!==void 0?{currentPage:f.currentPage}:{},...f.totalPages!==void 0?{totalPages:f.totalPages}:{},...f.charLength!==void 0?{itemsPerPage:f.charLength}:{},...f.totalChars!==void 0?{totalItems:f.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...ia(a,p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:Le(e)}]}}async function ZF(e){let{owner:t,repo:n}=DR(Le(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:rt(e.scope)??"",...Le(e).kind==="github"&&Le(e).ref?{branch:Le(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Ee("ghViewRepoStructure",r),i=vo(o),s=[],a=rt(e.scope);for(let u of BF(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=FR(a,d,p);s.push({kind:"tree",source:Le(e),path:f,entryType:"directory",depth:MR(f)})}for(let p of u.files??[]){let f=FR(a,d,p);s.push({kind:"tree",source:Le(e),path:f,entryType:"file",depth:MR(f)})}}let c=WF(s,e),l=Qt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...ia(o,c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:Le(e)}]}}function e0(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function gr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function t0(e){if(NR(e)==="error"){let r=vo(e)?.error;if(typeof r=="string"&&r)return{message:r};if(r&&typeof r=="object"){let o=r;return{message:typeof o.error=="string"&&o.error?o.error:"GitHub backend error",status:gr(o.status),retryAfterSeconds:gr(o.retryAfter),rateLimitRemaining:gr(o.rateLimitRemaining)}}return{message:"GitHub backend error"}}let n=e.structuredContent?.errors?.[0];if(n)return{message:typeof n.error=="string"&&n.error?n.error:"GitHub backend error",status:gr(n.status),retryAfterSeconds:gr(n.retryAfterSeconds),rateLimitRemaining:gr(n.rateLimitRemaining)}}function n0(e,t){let n=/rate limit|secondary rate/i.test(e.message),r=/bad credentials|requires authentication|saml|not accessible by/i.test(e.message);if(e.status===429||e.status===403&&(e.rateLimitRemaining===0||e.retryAfterSeconds!==void 0||n)||e.status===void 0&&n){let o=e.retryAfterSeconds!==void 0?` Retry after ~${e.retryAfterSeconds}s.`:"";return P("rateLimited",`${e.message}${o}`,{backend:t,severity:"warning",repair:{message:"Wait for the rate-limit window to reset and re-run the same query, or authenticate (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) to raise limits."}})}return e.status===401||(e.status===403||e.status===void 0)&&r?P("authRequired",e.message,{backend:t,repair:{message:"Provide a valid token (OCTOCODE_TOKEN/GH_TOKEN/GITHUB_TOKEN) with access to this repo, then re-run the same query."}}):P("invalidQuery",e.message,{backend:t})}function r0(e,t){let n=t0(e);return n?[n0(n,t)]:NR(e)==="empty"?[P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function ia(e,t,n){let r=r0(e,n);return r.some(o=>o.severity!=="info")?r:[...r,...QF(t,n)]}var QR=y(()=>{"use strict";Oo();Vs();uu();ut();eu();wo()});import BR from"node:path";function $R(e){return[...new Set(e)]}function UR(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function qR(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!BR.isAbsolute(r.localPath)?BR.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function WR(e){if(e.from?.kind!=="github")return ko(e);let t=e.from,{owner:n,repo:r}=UR(t);if(!n||!r)return{results:[],diagnostics:[P("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=rt(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await Ee("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=qR(s);if(u==="error"||!a)return{results:[],diagnostics:[P("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},p={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:$R([...d.excludeDir??[],".git"]),exclude:$R([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await ko(p);return{...f,diagnostics:[...f.diagnostics,...c?[P("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...f.provenance]}}async function VR(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[jR(f,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[P("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=UR(t);if(!n||!r)return{results:[],diagnostics:[P("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:rt(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await Ee("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=qR(a);if(d==="error"||!c)return{results:[],diagnostics:[P("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let p=!i;return{results:[jR(c,t,t.ref,p,l)],diagnostics:l?[P("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function jR(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var KR=y(()=>{"use strict";Oo();yu();ut();wo()});import{builtinModules as o0}from"node:module";import we from"node:path";import{readFile as sa,readdir as i0}from"node:fs/promises";async function Pu(e){let t=we.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=l0(r,e.intent,e.facets),i=u0(o,e.facets),s=d0(o,i),a=S0();if(n==="plan")return p0({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:XR([],[],a)});let c=await f0(t,e.maxFiles??5e3),l=await m0(c.filter(w=>w.endsWith(s0))),u=await b0(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),p=XR(u,d,a);await I0(u);let f=new Set(l.map(w=>w.name).filter(nS)),m=w0(u),g=x0(t,l,u),b=T0(g,m),x=u.filter(w=>!b.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=k0(t,l,u,f),k=await O0(u),A=L0(k,u,b),_=A.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,E=A.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:b.size,unusedFiles:x.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:A.length,candidateUnusedExports:_,transitiveDeadExports:E,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,N)=>w+N.declarations.length,0),nativeGraphCalls:d.reduce((w,N)=>w+N.calls.length,0)},manifests:l.map(w=>({manifest:vn(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(N=>vn(t,N)),dependencyCount:[...w.deps.keys()].length})),files:x,dependencies:S,symbols:A,graphFacts:d,graphCapabilities:p,caveats:["This is a smart research flow with native AST graph facts where available plus heuristic cross-file reachability. LSP references should be used before destructive cleanup.","Graph capability coverage is explicit: tree-sitter/OXC facts are syntax inventory, not semantic deletion proof.","Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function l0(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function u0(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function d0(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["localSearchCode structural","lspGetSemantics documentSymbols"],produces:["symbols","lineHints"],evidence:"proof"},{id:"reference-proof",purpose:"Use references grouped by file to separate direct, external, and transitive retention.",tools:["lspGetSemantics references","localSearchCode"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"proof"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function p0(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}async function f0(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await i0(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(a0.has(s.name))continue;await r(we.join(o,s.name));continue}s.isFile()&&n.push(we.join(o,s.name))}}return await r(e),n}async function m0(e){return(await Promise.all(e.map(async n=>g0(n)))).filter(n=>n!==null)}async function g0(e){let t=await h0(e);if(!t)return null;let n=we.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=N0(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:tS(t.name),deps:r,entrypoints:y0(n,t)}}async function h0(e){try{let t=JSON.parse(await sa(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function y0(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=tS(t[o]);i&&n.add(we.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(we.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(we.resolve(e,o));ZR(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(we.resolve(e,o));return[...n]}function ZR(e,t,n){if(typeof t=="string"){n.add(we.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))ZR(e,r,n)}async function b0(e,t){let n=Cu(),r=t.filter(i=>n.has(we.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await sa(i,"utf8").catch(()=>""),a=we.extname(i).toLowerCase(),c=R0(s,i,vn(e,i)),l=H0(c?c.imports.map(u=>u.specifier):C0(s));return{path:i,rel:vn(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!eS(u)).map(D0).filter(nS).filter(u=>!c0.has(u)),...c?{graphFacts:c}:{}}}))}function R0(e,t,n){try{let r=D.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??we.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(G0):[]}}catch{return}}function Cu(){if(Ao)return Ao;try{let e=D.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Ao=new Set(e.length>0?e:YR)}catch{Ao=new Set(YR)}return Ao}function S0(){if(Lo)return Lo;try{let e=JSON.parse(D.getGraphFactCapabilities());Lo=Array.isArray(e)?e.filter(P0):[]}catch{Lo=[]}return Lo}function P0(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function XR(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...Cu()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=JR(e,l=>l.language),s=JR(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function JR(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function C0(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function w0(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,we.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??we.dirname(o.path);for(let a of o.imports){if(!eS(a))continue;let c=M0(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function x0(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=Su(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let s=Su(we.resolve(e,i),r);s&&o.add(s)}return[...o]}function T0(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function k0(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=E0(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:vn(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:vn(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:vn(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function E0(e,t){return t.filter(r=>e.startsWith(`${r.dir}${we.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function O0(e){return(await Promise.all(e.map(async n=>{let r=v0(n);if(r.length>0)return r;let o=await sa(n.path,"utf8").catch(()=>"");return A0(n.rel,o)}))).flat()}function v0(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function A0(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:F0(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function L0(e,t,n){let r=new Map(t.map(o=>[o.rel,o]));return e.map(o=>{let i=t.filter(u=>u.rel!==o.file&&_0(u.path,o.symbol)),s=i.filter(u=>n.has(u.path)),a=r.get(o.file),c=a?n.has(a.path):!1,l=s.length>0?"reachable":i.length>0?"transitive-dead":c?"candidate-unused-export":"unused-export";return{symbol:o.symbol,kind:o.kind,file:o.file,line:o.line,evidenceSource:o.evidenceSource,directRefs:i.length,externalRefs:s.length,retainedBy:i.map(u=>u.rel),verdict:l}})}function _0(e,t){return Ru.get(e)?.has(t)??!1}async function I0(e){Ru.clear(),await Promise.all(e.map(async t=>{let n=await sa(t.path,"utf8").catch(()=>"");Ru.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function F0(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function M0(e,t,n){return Su(we.resolve(e,t),n)}function Su(e,t){let n=Cu(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(we.join(e,`index${o}`));return r.find(o=>t.has(o))}function eS(e){return e.startsWith("./")||e.startsWith("../")}function D0(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function N0(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function tS(e){return typeof e=="string"&&e.trim()?e:void 0}function nS(e){return typeof e=="string"&&e.length>0}function G0(e){return typeof e=="string"}function H0(e){return[...new Set(e)]}function vn(e,t){return we.relative(e,t)||we.basename(t)}var YR,s0,a0,c0,Ao,Lo,Ru,rS=y(()=>{"use strict";Ce();YR=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],s0="package.json",a0=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),c0=new Set(o0.flatMap(e=>[e,`node:${e}`]));Ru=new Map});import wu from"node:path";function xu(e){let t=e.root,n=[...e.symbols.map(a=>z0(t,a)),...e.files.map(a=>j0(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>U0(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let o={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},i=0,s=0;for(let a of n)o[a.verdict]+=1,i+=a.why.length,s+=a.retainedBy.length+(a.retains?.length??0);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function z0(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=Q0(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:"references",source:"ripgrep",confidence:"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:B0(r),next:$0(e,t)}}function Q0(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function B0(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via reference scan; likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable references found, but the scan is token-based. Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only referenced from unreachable code. Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function $0(e,t){let n=wu.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"exact"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function j0(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:wu.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:wu.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function U0(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var oS=y(()=>{"use strict"});import iS from"node:path";function yr(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??q0),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function sS(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function cS(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:sS(e.relation),verdicts:sS(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function W0(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function hr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function Eu(e,t){if(!W0(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>hr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>hr(i.relation,t)),o=e.why.some(i=>hr(i.claim,t));return n||r||o}function Tu(e,t){e.set(t.id,t)}function V0(e,t,n){hr(t.claim,n)&&e.set(t.id,t)}function ku(e,t,n,r){hr(n.relation,r)&&(Tu(e,n.from),Tu(e,n.to),t.set(n.id,n))}function K0(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function lS(e,t,n,r,o,i){let s=t.filter(g=>Eu(g,r)),a=yr(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,p=new Map,f={},m={};for(let g of s)f[g.verdict]=(f[g.verdict]??0)+1,m[g.proofStatus]=(m[g.proofStatus]??0)+1;for(let g of c){if(Tu(l,g.subject),r.includeFacts)for(let b of g.why)V0(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of g.retainedBy)ku(l,u,b,r);if(r.direction!=="incoming")for(let b of g.retains??[])ku(l,u,b,r)}for(let b of g.missingProof)p.set(K0(b),b)}return r.includeEdges&&X0(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:p.size,byVerdict:f,proofStatus:m},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...p.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function Ou(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function uS(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}function X0(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=J0(a.relation);if(!hr(c,i))continue;let l=aS(a.from,e,a.line),u=aS(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||ku(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function J0(e){let t=e.trim();return Y0.has(t)?t:"references"}function aS(e,t,n){let r=Z0(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function Z0(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:iS.isAbsolute(o)?iS.relative(t,o):o,name:i}}var q0,Y0,vu=y(()=>{"use strict";q0=25;Y0=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"])});import aa from"node:path";function Lu(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function pS(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function fS(e,t,n,r,o){let i=n.filter(l=>Eu(l,r)),s=yr(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await tM(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(P(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(P("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),eM(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(P("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function eM(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function tM(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=aa.isAbsolute(t.subject.uri)?t.subject.uri:aa.resolve(e,t.subject.uri);try{let i=await Ee("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=nM(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=on(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:Eo(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,p=mr(a?.totalReferences)??mr(u?.totalReferences)??mr(a?.referenceCount)??mr(u?.referenceCount)??mr(d?.totalItems)??dS(u)??dS(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:rM(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function nM(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function dS(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function rM(e,t){let n=new Set;return Au(e,n,t),[...n].slice(0,25)}function Au(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)Au(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&oM(i)&&t.add(aa.isAbsolute(i)?aa.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])Au(r[o],t,n)}function oM(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}var mS=y(()=>{"use strict";Oo();ut();vu()});import{statSync as iM}from"node:fs";import le from"node:path";function gS(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}function PS(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function sM(e,t){if(!t||le.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?le.join(n.base,t):t}function aM(e,t,n){let r=t??n??".";if(!e)return r;if(le.isAbsolute(e))return e;if(n&&le.isAbsolute(n))return le.resolve(n,e);if(t&&le.isAbsolute(t)){let o=Iu(t)?t:le.dirname(t);return le.resolve(o,e)}return e}function hS(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function wS(e){if(!e)return[];for(let t of CS){let n=e[t];if(Array.isArray(n))return n}return[e]}function lM(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function uM(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))cM.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function _o(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=mM(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function xS(e){return e==="plan"||e==="prove"?e:"analyze"}function dM(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;TS.includes(o)&&t.add(o)}return t.size>0?t:void 0}function pM(e,t){let n=dM(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of TS){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=yr(e,u.length);o[l]=u.slice(d,p),o[`${l}Page`]=f,s=f.itemsPerPage,a=Math.max(a,f.totalPages??1),f.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function fM(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function yS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mM(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"))??br(t);case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:br(t)}case"pullRequest":return n("number")?`#${n("number")}`:n("url")??br(t);case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12)??br(t);case"artifact":return n("localPath")??n("path");case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename")??(n("number")?`#${n("number")}`:br(t));case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}return br(t)}function br(e){return typeof e.value=="string"&&e.value.trim()?e.value.trim().split(/\s+/,1)[0]:void 0}function _u(e,t){let{status:n,data:r}=on(e);return n==="error"?[P("invalidQuery",PS(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[P("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function Iu(e){try{let t=le.isAbsolute(e)?e:le.resolve(e);return iM(t).isDirectory()}catch{return!1}}function ca(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function sn(e){return e.params??{}}function gM(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function Fu(e,t){let n={...sn(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}function la(e,t,n,r){let{data:o,status:i}=on(e),s=_u(e,n),a=i==="error"?[]:wS(o);a.length===0&&!s.some(p=>p.code==="zeroMatches"||p.severity==="error")&&s.push(P("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=Qt(c,l),d=t==="package"?lM(o):void 0;return{results:_o(a,t,r,uM(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function bS(){return P("partialResult",'Zero LSP results after bounded consumer warm-up \u2014 still not proof of unused. Cross-check with a text search (target:"code") for dynamic, re-exported, or string-based usage before concluding.',{backend:"lspGetSemantics",blocksAnswer:!0})}function hM(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(P("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.payload;o?.kind==="empty"?o.category==="symbolNotFound"||o.category==="anchorFailed"?n.push(P("symbolNotFound",`${o.reason??"Symbol anchor resolution failed."} Refresh the lineHint from a search/AST anchor and retry.`,{backend:"lspGetSemantics"})):(o.category==="noReferences"||o.category==="noCalls")&&n.push(bS()):(o?.kind==="references"&&o.totalReferences===0||o?.kind==="callers"&&o.incomingCalls===0||o?.kind==="callees"&&o.outgoingCalls===0||o?.kind==="callHierarchy"&&o.incomingCalls===0&&o.outgoingCalls===0)&&n.push(bS());let i=e?.pagination;return i?.hasMore&&n.push(P("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:kS(i,t)})),n}function kS(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function yM(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:kS(n,t)}}async function bM(e){let{owner:t}=ca(e.from),n=Fu(e,"limit"),r=typeof n.language=="string"?n.language:gM(e),o=Dl(r);o&&(n.language=o);let i=await Ee("ghSearchRepos",{...t?{owner:t}:{},...n}),s=la(i,"repository","ghSearchRepos",e.from??{kind:"github"});return s.results.length===0&&RM(n)&&s.diagnostics.push(P("zeroMatches","GitHub repository search requires EVERY term to match (AND semantics). Zero results for a multi-term query usually means over-constraint, not absence.",{backend:"ghSearchRepos",severity:"info",blocksAnswer:!1,repair:{message:'Retry with the single most distinctive term (e.g. the project name), or move concepts to topic:"..." filters.'}})),s}function RM(e){let t=e.keywords??e.keywordsToSearch;return Array.isArray(t)?t.length>1||t.length===1&&typeof t[0]=="string"&&t[0].trim().includes(" "):typeof t=="string"&&t.trim().includes(" ")}async function SM(e){let t=await Ee("npmSearch",{...Fu(e)});return la(t,"package","npmSearch",e.from??{kind:"npm"})}async function RS(e){let{owner:t,repo:n}=ca(e.from),r=e.target==="commits",o=r?void 0:wM(e),i=r?PM(e):void 0,s=Fu(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await Ee("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=la(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?TM(c,o):i?CM(c,i):c}function PM(e){let t=sn(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function CM(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),p=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,p)+(p<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(P("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(P("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function wM(e){let t=sn(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function xM(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
48
+ `)}function TM(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=xM(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(P("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(P("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}async function kM(e){let t=sn(e),{owner:n,repo:r}=ca(e.from),o=lr(t);if(o.kind==="prPatch"){let i=await Ee("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return la(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?EM(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):OM(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[P("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function EM(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[P("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=f=>({results:[],diagnostics:[P("invalidQuery",f,{backend:"git"})],provenance:[{backend:"git",source:e.from}]}),i=Iu(r)?r:le.dirname(r),s=le.isAbsolute(t.path)?le.relative(i,t.path):t.path;if(!s||s.startsWith("..")||s.startsWith("-"))return o(`params.path must resolve inside from.path for a local ref diff (got "${t.path}").`);if(!SS.test(t.baseRef)||!SS.test(t.headRef))return o("baseRef/headRef must be plain git revisions (branch, tag, sha, HEAD~N).");let a=`./${s.split(le.sep).join("/")}`,c=f=>Nt("git",["-C",i,"show",`${f}:${a}`],{timeout:15e3}),[l,u]=await Promise.all([c(t.baseRef),c(t.headRef)]);if(!l.success||!u.success){let f=l.success?u:l,m=l.success?t.headRef:t.baseRef;return o(`git show ${m}:${a} failed: ${f.stderr.trim().split(`
49
+ `)[0]||f.error?.message||`exit ${f.exitCode}`}. from.path must be inside a git repository and the path must exist at both refs.`)}let d=ES(l.stdout,u.stdout);return{results:[{kind:"record",recordType:"diff",id:`${t.baseRef}..${t.headRef}:${s}`,...e.from?{source:e.from}:{},data:{path:s,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[P("zeroMatches",`${s} is identical at ${t.baseRef} and ${t.headRef}.`,{backend:"git",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"git",source:e.from}]}}async function OM(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[P("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=p=>Ee("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:p,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=gS(i),c=gS(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(p=>p.status==="error"||typeof p.content!="string");if(l){let p=PS(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[P("invalidQuery",p,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=ES(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[P("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function ES(e,t){let n=e===""?[]:e.split(`
48
50
  `),r=t===""?[]:t.split(`
49
51
  `),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let f=o-1;f>=0;f--)for(let m=i-1;m>=0;m--)s[f][m]=n[f]===r[m]?s[f+1][m+1]+1:Math.max(s[f+1][m],s[f][m+1]);let a=[],c=0,l=0,u=0,d=0,p=0;for(;d<o&&p<i;)n[d]===r[p]?(a.push(` ${n[d]}`),u++,d++,p++):s[d+1][p]>=s[d][p+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[p]}`),c++,p++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;p<i;)a.push(`+ ${r[p++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
50
- `)}}async function x0(e){let t=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!t)return{results:[],diagnostics:[w("invalidQuery",'target:"artifacts" needs a local file `from` (path).',{backend:"localBinaryInspect"})],provenance:[]};let n=await Re("localBinaryInspect",{path:t,...qt(e)}),{data:r,status:o}=jt(n),i=Iu(n,"localBinaryInspect");return o==="error"||!r?{results:[],diagnostics:i.length?i:[w("zeroMatches","localBinaryInspect returned no data.",{backend:"localBinaryInspect",severity:"info",blocksAnswer:!1})],provenance:[{backend:"localBinaryInspect",source:e.from}]}:{results:Co([r],"artifact",e.from),diagnostics:[...i,...T0(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function T0(e,t){let n=e.pagination&&typeof e.pagination=="object"?e.pagination:void 0;return e.isPartial!==!0&&n?.hasMore!==!0?[]:[w("partialResult","Artifact text is paginated; follow the artifact continuation before treating the inline content as complete.",{backend:"localBinaryInspect",blocksAnswer:!0,continuation:E0(t,n)})]}function E0(e,t){if(!(t?.hasMore!==!0||typeof t.nextCharOffset!="number"))return{query:{...e,params:{...e.params??{},charOffset:t.nextCharOffset,...typeof t.charLength=="number"?{charLength:t.charLength}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}async function k0(e){let t,n,r=[],o=[],i=qt(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let E=e.from.path,O=mS(E);n=c??(O?J.resolve(E):void 0),t=a??(O?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=tS(e),O=E?J.isAbsolute(E)?E:J.join(e.from.localPath,E):void 0;s?(n=c??e.from.localPath,t=a??O):t=a??O??e.from.localPath}else if(e.from?.kind==="github"){let{owner:E,repo:O}=Xs(e.from);if(!E||!O)return o.push(w("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let x=typeof i.uri=="string"?i.uri:void 0,H=tS(e),I=x&&!J.isAbsolute(x)?x:H,v=await Re("ghCloneRepo",{owner:E,repo:O,...e.from.ref?{branch:e.from.ref}:{},...I?{sparsePath:I}:{}}),D=jt(v).data,B=HF(v,D?.localPath);if(!B)return o.push(w("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:B}),s?(n=c??B,x?t=J.isAbsolute(x)?x:J.join(B,x):H&&(t=J.isAbsolute(H)?H:J.join(B,H))):x?t=J.isAbsolute(x)?x:J.join(B,x):H?t=J.isAbsolute(H)?H:J.join(B,H):t=B}if(!t&&!n)return o.push(w("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...p}=i,f=await Re("lspGetSemantics",{...p,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:m,status:g}=jt(f),b=m,S=f0(b,e),C=zF(_u(b?.uri),t,n),k=A0(e,C),_=v0(O0(b),u);return{results:g==="error"?[]:Co(_,"semantics",k),...S?{pagination:S}:{},diagnostics:[...o,...Iu(f,"lspGetSemantics"),...p0(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:k}]}}function O0(e){if(!e)return[];let n=(sS(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=_u(e.uri);return n.map(o=>sS(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return lS(e)}function v0(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function A0(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}async function L0(e){let t=qt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[w("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=uS(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[w("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await xu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[w("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:ku(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?Ys(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?jF(e,i):{fields:{}},p={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:fS(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=qF(l?.pagination,d.pagination);return{results:Co([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function _0(e){let t=qt(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[w("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=uS(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[w("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await xu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[w("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:ku(i),a=VF(t),c=s?.packets??[],l=oS(i.mode,t)?await o0(n,e,c,a,r0(e,t)):[],u=JF(c),d=XF(e,c,u,a,i.graphFacts,n),p=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[oS(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],f={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:fS(i.graphFacts),caveats:p};return{results:Co([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var cS,BF,UF,dS,ZF,yS,bS=y(()=>{"use strict";js();Ms();ft();As();Ls();JR();ZR();cS=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],BF=new Set([...cS,"pagination","contentPagination","next"]);UF=25;dS=["manifests","files","dependencies","symbols","graphFacts"];ZF=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"]);yS={repositories:m0,packages:g0,pullRequests:aS,commits:aS,diff:C0,artifacts:x0,semantics:k0,research:L0,graph:_0}});var OS={};$S(OS,{buildArtifactContinuations:()=>xS,runOqlSearch:()=>I0});import it from"node:path";import{statSync as SS}from"node:fs";async function I0(e,t={}){let n;try{n=Qb(e)}catch(o){if(o instanceof Ut)return pu(o.diagnostics);throw o}if(Td(n))return pM(n,e,t);let r=await CS(n,e,t);return Mu(r.results),r}function Mu(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function CS(e,t,n,r){let o=lR(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return oM(o,s,e.id,r,n.dryRun,e);let a=await dM(e,o);iM(e,a.results),F0(e,a);let c=H0(e,a);z0(e,a.results);let l=uM(e,a.results);return Fs({queryId:e.id,queryIndex:r,results:a.results,...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:fR(o.plan.backendCalls),plan:s})}function F0(e,t){if(e.target==="content"||e.target==="code"&&t.pagination?.totalItemsKind==="files"&&typeof e.limit!="number")return;let n=typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!n||n<1||t.results.length<=n)return;let r=t.pagination?.totalItems??t.results.length,o=t.pagination?.currentPage??e.page??1;t.results=t.results.slice(0,n),t.pagination={...t.pagination,currentPage:o,itemsPerPage:t.pagination?.itemsPerPage??n,totalItems:r,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(r/n)),hasMore:!0}}function M0(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function D0(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function N0(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function G0(e){let t=N0(e),n=D0(e),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${RS(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${RS(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function RS(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function H0(e,t){let n={};t.pagination?.hasMore&&e.target!=="content"&&(n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:"More result pages remain.",confidence:"exact"}),t.diagnostics.some(o=>o.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(o=>o.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${G0(e)}`,confidence:"heuristic"});let r={query:e,fileFrom:nM(e)};for(let o of t.results){let i=o.kind==="record"?`record:${o.recordType}`:o.kind,s=U0[i];if(!s)continue;let a=s(o,r);a&&Object.keys(a).length&&(o.next=a)}return n}function z0(e,t){for(let n of t)n.proofGrade??=B0(e,n)}function B0(e,t){return t.kind==="code"?Po(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Po(e.where,"text")||Po(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?Zs(t.data)?"missing":"graph":t.recordType==="research"?Zs(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function Po(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Po(n,t)):e.kind==="not"?Po(e.predicate,t):!1:!1}function Zs(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!Q0(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function Q0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $0(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:M0(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"exact",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function j0(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function PS(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function wS(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function xS(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=wS(e);i&&(o==="strings"?n["next.search"]={query:{schema:"oql",target:"code",from:{kind:"local",path:i},where:{kind:"regex",value:"https?://\\S+"},controls:{search:{maxMatchesPerFile:100,matchPage:1}}},why:"Grep this strings dump with local code search (ripgrep) \u2014 swap the regex/pattern for what you need (URLs, hosts, symbols); page noisy hits losslessly with matchPage. For a huge binary this beats reading the capped inline preview.",confidence:"heuristic"}:Object.assign(n,PS(i,"extracted")));let s=typeof r?.nextScanOffset=="number"?r.nextScanOffset:void 0;s!==void 0&&(n["next.artifactStrings"]={query:{...t.query,params:{...t.query.params??{},scanOffset:s}},why:"Scan the next window of printable strings.",confidence:"exact"});let a=r?.pagination&&typeof r.pagination=="object"?r.pagination:void 0,c=typeof a?.nextCharOffset=="number"?a.nextCharOffset:void 0;if(a?.hasMore===!0&&c!==void 0){let l=typeof a.charLength=="number"?a.charLength:void 0;n["next.artifactContent"]={query:{...t.query,params:{...t.query.params??{},charOffset:c,...l!==void 0?{charLength:l}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}return Object.keys(n).length?n:void 0}function q0(e){let t=wS(e);return t?PS(t,"materialized"):void 0}function V0(e,t){return TS(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function W0(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(Zs(r))return TS(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function TS(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!Zs(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=Y0(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function Y0(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&K0.has(o));return r.length>0?r:void 0}function X0(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=eM(e)??tM(t.query),i=J0(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"exact",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function J0(e,t){if(e&&it.isAbsolute(e))return e;if(t&&it.isAbsolute(t)){let n=Z0(t);return e?it.resolve(n,e):t}return t??e}function Z0(e){try{return SS(e).isDirectory()?e:it.dirname(e)}catch{return it.dirname(e)}}function eM(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function tM(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function nM(e){let t=kS(e);if(!t)return;let n=ES(t).slice(0,-it.sep.length);return r=>({kind:"local",path:it.isAbsolute(r)?r:it.join(n,r)})}function rM(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function oM(e,t,n,r,o,i){if(!e.executable){let s=e.plan.nodes.some(a=>a.route==="UNSUPPORTED");return o&&!s?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:e.plan.diagnostics,provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{}}:pu(e.plan.diagnostics,t,n,r,rM(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:e.plan.diagnostics,provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{}}}function ES(e){let t=it.resolve(e);try{if(SS(t).isDirectory())return`${t}${it.sep}`}catch{}return`${it.dirname(t)}${it.sep}`}function kS(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function iM(e,t){let n=kS(e);if(!n)return;let r=ES(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function uM(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):aM.has(c)?o.add(c):cM.has(c)?o.add("data"):lM.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!sM.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[w("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}async function dM(e,t){if(e.target==="materialize")return UR(e);let n=yS[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?ho(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?QR(e):MR(e)}async function pM(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await CS(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=fM(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&Mu(o.merged.results)}else for(let i of r)Mu(i.envelope.results);return o}function fM(e){let t=new Set;for(let c of e)for(let l of c.envelope.results)t.add(l.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s=!1,a=!1;for(let c of e){for(let l of c.envelope.results){let u=gM(l);n.has(u)||(n.add(u),r.push(l))}o.push(...c.envelope.diagnostics),i.push(...c.envelope.provenance),c.envelope.evidence.kind==="candidate"&&(s=!0),mM(c.envelope)&&(a=!0)}return a&&o.push(w("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Fs({results:r,...a?{pagination:{hasMore:!0}}:{},diagnostics:o,provenance:i,executable:e.every(c=>c.envelope.evidence.kind!=="unsupported"),approximate:s})}}function mM(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function gM(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var U0,K0,sM,aM,cM,lM,vS=y(()=>{"use strict";jb();dR();ft();mR();Su();DR();$R();bS();cr();U0={code:$0,content:j0,"record:artifact":xS,"record:materialized":q0,"record:semantics":X0,"record:research":V0,"record:graph":W0};K0=new Set(["symbols","files","dependencies","relations"]);sM=new Set(["kind","source","recordType","id","proofGrade"]),aM=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),cM=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),lM=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});async function LS(e){let t=hM(e),n=An.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(vS(),OS)),o=await r(n.data,{authInfo:e.authInfo});return yM(o)}function hM(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function yM(e){let t=bM(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function bM(e){return Ed(e)?{results:e.children.map(t=>AS(t.envelope,t.queryId)),oql:e,mode:e.mode,...e.merged?{merged:e.merged}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[AS(e,e.queryId??"oqlSearch-1")],oql:e}}function AS(e,t){return{id:e.queryId??t,...RM(e),data:e}}function RM(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var _S=y(()=>{"use strict";lr();cr()});var Du,IS=y(()=>{"use strict";pe();Du={hasTool(e){return xc(e)},getDescription(e){return wc[e]??""},getToolName(e){return A[e]??String(e)}}});function SM(e,t){return t.getToolName(e)}function st(e,t,n){let r=SM(t,e);return{...n,name:r,description:Nu(r,e)}}function CM(e=Du){let t=st(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ao,inputSchema:Lo,executionFn:Oh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=st(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Sn,inputSchema:Oo,executionFn:wh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=st(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Do,inputSchema:No,executionFn:Yh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=st(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Fo,inputSchema:Mo,executionFn:Wh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=st(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Pn,inputSchema:_o,executionFn:zh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=st(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Go,inputSchema:Ho,executionFn:xy,security:"remote",requiresServerRuntime:!0}}),a=st(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:or,inputSchema:ko,executionFn:Kg,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=st(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Ot,inputSchema:$o,executionFn:eb,security:"basic"}}),l=st(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:En,inputSchema:jo,executionFn:gb,security:"basic"}}),u=st(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:xn,inputSchema:Qo,executionFn:_y,security:"basic"}}),d=st(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:wn,inputSchema:zo,executionFn:vy,security:"basic"}}),p={name:we,description:Nu(we,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Ko,inputSchema:Yo,executionFn:Ob,security:"basic",requiresServerRuntime:!0}},f=st(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:On,inputSchema:Xo,executionFn:kg,security:"basic"}}),m={name:Wt,description:Nu(Wt,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:ti,inputSchema:An,executionFn:LS,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}};return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:p,LOCAL_BINARY_INSPECT:f,OQL_SEARCH:m,ALL_TOOLS:[t,n,r,o,i,s,a,c,l,u,d,p,f,m]}}var Nu,De,nY,rY,oY,iY,sY,aY,cY,lY,uY,dY,pY,fY,mY,gY,FS,MS=y(()=>{"use strict";na();vo();ra();Io();oa();ia();sa();Bo();Uo();ar();qo();la();Jo();lr();Og();Yg();xh();vh();Bh();Kh();Xh();Ty();Ay();Iy();tb();hb();Nb();_S();yn();To();IS();Nu=(e,t=Du)=>t.getDescription(e);De=CM(),nY=De.GITHUB_SEARCH_CODE,rY=De.GITHUB_FETCH_CONTENT,oY=De.GITHUB_VIEW_REPO_STRUCTURE,iY=De.GITHUB_SEARCH_REPOSITORIES,sY=De.GITHUB_SEARCH_PULL_REQUESTS,aY=De.PACKAGE_SEARCH,cY=De.GITHUB_CLONE_REPO,lY=De.LOCAL_RIPGREP,uY=De.LOCAL_VIEW_STRUCTURE,dY=De.LOCAL_FIND_FILES,pY=De.LOCAL_FETCH_CONTENT,fY=De.LSP_GET_SEMANTIC_CONTENT,mY=De.LOCAL_BINARY_INSPECT,gY=De.OQL_SEARCH,FS=De.ALL_TOOLS});import{ContentSanitizer as PM}from"@octocodeai/octocode-engine/security";function Gu(e){let t=e;if(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=PM.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:Gt(t.structuredContent)}}catch{}return t}function Hu(e,t){let n=xM(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
51
- message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:wM,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Gu(r)}catch{return r}}function xM(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:TM(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function TM(e){try{return JSON.stringify(e)}catch{return}}var wM,DS=y(()=>{"use strict";Vr();wM="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as EM,withBasicSecurityValidation as kM}from"@octocodeai/octocode-engine/security";function NS(e,t){let n=EM(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function GS(e,t){let n=kM(r=>e(r),t);return(r,o)=>n(r,o)}var HS=y(()=>{"use strict"});import{releaseAllPooledClients as OM}from"@octocodeai/octocode-engine/lsp/manager";function vM(e){return async t=>e(t)}function AM(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:vM(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function _M(e){return LM.find(t=>t.name===e)}async function qs(e,t){let n=_M(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=IM(n,t);return await FM(n),MM(n),await DM(n,r)}catch(r){return Hu(n.name,r)}finally{e===we&&await OM()}}function IM(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function FM(e){e.requiresServerRuntime&&(zu||(zu=Jp()),await zu),e.requiresProviders&&(Bu||(Bu=qm().then(()=>{})),await Bu)}function MM(e){if(!e.isLocal&&!e.isClone)return;let t=ke();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}if(e.isClone&&!(t.local.enabled&&t.local.enableClone)){let n=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true and ENABLE_LOCAL=true to use it.`);throw n.code="cloneDisabled",n}}async function DM(e,t){try{let n=e.security==="remote"?await NM(e,t):await GM(e,t);return Gu(n)}catch(n){return Hu(e.name,n)}}async function NM(e,t){return NS(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function GM(e,t){return GS(e.execute,e.name)(t)}var zu,Bu,LM,zS=y(()=>{"use strict";_r();Qc();_e();yn();MS();DS();HS();Ca();zu=null,Bu=null;LM=FS.map(AM)});var Cu=y(()=>{"use strict";Ca();zS()});Cu();import{completeMetadata as HM}from"@octocodeai/octocode-core";var Qu=null;function zM(){return Qu||(Qu=HM),Qu}async function BM(){return zM()}Vr();export{ma as DIRECT_TOOL_CATEGORIES,Qd as DIRECT_TOOL_DEFINITIONS,ct as DirectToolInputError,cP as buildDirectToolExampleQuery,qs as executeDirectTool,dr as findDirectToolDefinition,HT as formatCallToolResultForOutput,nP as formatDirectToolMetadataSchemaText,iP as formatDirectToolOutputSchemaText,tP as formatDirectToolSchemaText,rP as getDirectToolAutoFilledFields,ur as getDirectToolCategory,sP as getDirectToolDescription,Sa as getDirectToolDisplayFields,oP as getDirectToolOutputFields,BM as loadToolContent,Ud as prepareDirectToolInput,dP as prepareDirectToolInputFromJsonText,eP as sortDirectToolNames};
52
+ `)}}async function vM(e){let t=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!t)return{results:[],diagnostics:[P("invalidQuery",'target:"artifacts" needs a local file `from` (path).',{backend:"localBinaryInspect"})],provenance:[]};let n=await Ee("localBinaryInspect",{path:t,...sn(e)}),{data:r,status:o}=on(n),i=_u(n,"localBinaryInspect");return o==="error"||!r?{results:[],diagnostics:i.length?i:[P("zeroMatches","localBinaryInspect returned no data.",{backend:"localBinaryInspect",severity:"info",blocksAnswer:!1})],provenance:[{backend:"localBinaryInspect",source:e.from}]}:{results:_o([r],"artifact",e.from),diagnostics:[...i,...AM(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function AM(e,t){let n=e.pagination&&typeof e.pagination=="object"?e.pagination:void 0;return e.isPartial!==!0&&n?.hasMore!==!0?[]:[P("partialResult","Artifact text is paginated; follow the artifact continuation before treating the inline content as complete.",{backend:"localBinaryInspect",blocksAnswer:!0,continuation:LM(t,n)})]}function LM(e,t){if(!(t?.hasMore!==!0||typeof t.nextCharOffset!="number"))return{query:{...e,params:{...e.params??{},charOffset:t.nextCharOffset,...typeof t.charLength=="number"?{charLength:t.charLength}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}async function _M(e){let t,n,r=[],o=[],i=sn(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let _=e.from.path,E=Iu(_);n=c??(E?le.resolve(_):void 0),t=a??(E?void 0:_)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let _=hS(e),E=_?le.isAbsolute(_)?_:le.join(e.from.localPath,_):void 0;s?(n=c??e.from.localPath,t=a??E):t=a??E??e.from.localPath}else if(e.from?.kind==="github"){let{owner:_,repo:E}=ca(e.from);if(!_||!E)return o.push(P("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,N=hS(e),F=w&&!le.isAbsolute(w)?w:N,O=await Ee("ghCloneRepo",{owner:_,repo:E,...e.from.ref?{branch:e.from.ref}:{},...F?{sparsePath:F}:{}}),Q=on(O).data,G=sM(O,Q?.localPath);if(!G)return o.push(P("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:G}),s?(n=c??G,w?t=le.isAbsolute(w)?w:le.join(G,w):N&&(t=le.isAbsolute(N)?N:le.join(G,N))):w?t=le.isAbsolute(w)?w:le.join(G,w):N?t=le.isAbsolute(N)?N:le.join(G,N):t=G}if(!t&&!n)return o.push(P("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...p}=i,f=await Ee("lspGetSemantics",{...p,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:m,status:g}=on(f),b=m,x=yM(b,e),S=aM(Eo(b?.uri),t,n),k=MM(e,S),A=FM(IM(b),u);return{results:g==="error"?[]:_o(A,"semantics",k),...x?{pagination:x}:{},diagnostics:[...o,..._u(f,"lspGetSemantics"),...hM(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:k}]}}function IM(e){if(!e)return[];let n=(yS(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=Eo(e.uri);return n.map(o=>yS(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return wS(e)}function FM(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function MM(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}async function DM(e){let t=sn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[P("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=xS(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[P("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await Pu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[P("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:xu(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?yr(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?pM(e,i):{fields:{}},p={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:Ou(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=fM(l?.pagination,d.pagination);return{results:_o([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function NM(e){let t=sn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[P("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=xS(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[P("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await Pu({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[P("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:xu(i),a=cS(t),c=s?.packets??[],l=Lu(i.mode,t)?await fS(n,e,c,a,pS(e,t)):[],u=uS(c),d=lS(e,c,u,a,i.graphFacts,n),p=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[Lu(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],f={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:Ou(i.graphFacts),caveats:p};return{results:_o([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var CS,cM,TS,SS,OS,vS=y(()=>{"use strict";Oo();Vs();ut();Bs();so();$s();rS();oS();vu();mS();CS=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],cM=new Set([...CS,"pagination","contentPagination","next"]);TS=["manifests","files","dependencies","symbols","graphFacts"];SS=/^[A-Za-z0-9][A-Za-z0-9._/@^~-]*$/;OS={repositories:bM,packages:SM,pullRequests:RS,commits:RS,diff:kM,artifacts:vM,semantics:_M,research:DM,graph:NM}});var zS={};rP(zS,{buildArtifactContinuations:()=>DS,runOqlSearch:()=>GM});import pt from"node:path";import{statSync as LS}from"node:fs";async function GM(e,t={}){let n;try{n=qb(e)}catch(o){if(o instanceof nn)return au(o.diagnostics);throw o}if(xd(n))return PD(n,e,t);let r=await _S(n,e,t);return Mu(r.results),r}function Mu(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function _S(e,t,n,r){let o=mR(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return dD(o,s,e.id,r,n.dryRun,e);let a=await SD(e,o);mD(e,a.results),HM(e,a),zM(a);let c=UM(e,a);WM(e,a.results);let l=RD(e,a.results),u=qM(a.results);return Ws({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:bR(o.plan.backendCalls),plan:s})}function HM(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&(t.pagination?.totalItemsKind==="files"||t.pagination?.itemUnit==="files")&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function zM(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}function QM(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function BM(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function $M(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function jM(e){let t=$M(e),n=BM(e),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${AS(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${AS(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function AS(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function UM(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;if(t.pagination?.hasMore&&e.target!=="content"&&!r){let i=t.pagination.totalItemsKind==="files"||t.pagination.itemUnit==="files";n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:i?`More file pages remain (page/itemsPerPage count matched files; rows are per-match \u2014 this page holds ${t.results.length} rows).`:"More result pages remain.",confidence:"exact"}}t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${jM(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:lD(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=YM[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function qM(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||IS(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function IS(e,t){return e.why===t.why&&e.confidence===t.confidence}function WM(e,t){for(let n of t)n.proofGrade??=VM(e,n)}function VM(e,t){return t.kind==="code"?Io(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Io(e.where,"text")||Io(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?ua(t.data)?"missing":"graph":t.recordType==="research"?ua(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function Io(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Io(n,t)):e.kind==="not"?Io(e.predicate,t):!1:!1}function ua(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!KM(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function KM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function XM(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:QM(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"exact",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function JM(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function FS(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function MS(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function DS(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=MS(e);i&&(o==="strings"?n["next.search"]={query:{schema:"oql",target:"code",from:{kind:"local",path:i},where:{kind:"regex",value:"https?://\\S+"},controls:{search:{maxMatchesPerFile:100,matchPage:1}}},why:"Grep this strings dump with local code search (ripgrep) \u2014 swap the regex/pattern for what you need (URLs, hosts, symbols); page noisy hits losslessly with matchPage. For a huge binary this beats reading the capped inline preview.",confidence:"heuristic"}:Object.assign(n,FS(i,"extracted")));let s=typeof r?.nextScanOffset=="number"?r.nextScanOffset:void 0;s!==void 0&&(n["next.artifactStrings"]={query:{...t.query,params:{...t.query.params??{},scanOffset:s}},why:"Scan the next window of printable strings.",confidence:"exact"});let a=r?.pagination&&typeof r.pagination=="object"?r.pagination:void 0,c=typeof a?.nextCharOffset=="number"?a.nextCharOffset:void 0;if(a?.hasMore===!0&&c!==void 0){let l=typeof a.charLength=="number"?a.charLength:void 0;n["next.artifactContent"]={query:{...t.query,params:{...t.query.params??{},charOffset:c,...l!==void 0?{charLength:l}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}return Object.keys(n).length?n:void 0}function ZM(e){let t=MS(e);return t?FS(t,"materialized"):void 0}function eD(e,t){return NS(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function tD(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(ua(r))return NS(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function NS(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!ua(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=rD(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function rD(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&nD.has(o));return r.length>0?r:void 0}function oD(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=aD(e)??cD(t.query),i=iD(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"exact",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function iD(e,t){if(e&&pt.isAbsolute(e))return e;if(t&&pt.isAbsolute(t)){let n=sD(t);return e?pt.resolve(n,e):t}return t??e}function sD(e){try{return LS(e).isDirectory()?e:pt.dirname(e)}catch{return pt.dirname(e)}}function aD(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function cD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function lD(e){let t=HS(e);if(!t)return;let n=GS(t).slice(0,-pt.sep.length);return r=>({kind:"local",path:pt.isAbsolute(r)?r:pt.join(n,r)})}function uD(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function dD(e,t,n,r,o,i){let s=o&&i?pD(i):[],a=o&&i?fD(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:au(e.plan.diagnostics,t,n,r,uD(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function pD(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[P("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function fD(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}function GS(e){let t=pt.resolve(e);try{if(LS(t).isDirectory())return`${t}${pt.sep}`}catch{}return`${pt.dirname(t)}${pt.sep}`}function HS(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function mD(e,t){let n=HS(e);if(!n)return;let r=GS(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function RD(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):hD.has(c)?o.add(c):yD.has(c)?o.add("data"):bD.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!gD.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[P("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}async function SD(e,t){if(e.target==="materialize")return VR(e);let n=OS[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?ko(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?WR(e):zR(e)}async function PD(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await _S(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=CD(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&Mu(o.merged.results)}else for(let i of r)Mu(i.envelope.results);return o}function CD(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let p=kD(d);n.has(p)||(n.add(p),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),wD(s,u.envelope.nextHints),xD(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),TD(u.envelope)&&(l=!0)}return l&&o.push(P("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:Ws({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function wD(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||IS(o,r))&&(e[n]=r)}}function xD(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function TD(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function kD(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var YM,nD,gD,hD,yD,bD,QS=y(()=>{"use strict";Kb();hR();ut();RR();yu();QR();KR();vS();zn();YM={code:XM,content:JM,"record:artifact":DS,"record:materialized":ZM,"record:semantics":oD,"record:research":eD,"record:graph":tD};nD=new Set(["symbols","files","dependencies","relations"]);gD=new Set(["kind","source","recordType","id","proofGrade"]),hD=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),yD=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),bD=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});async function $S(e){let t=ED(e),n=Bn.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(QS(),zS)),o=await r(n.data,{authInfo:e.authInfo});return OD(o)}function ED(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function OD(e){let t=vD(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(t,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function vD(e){return Td(e)?{results:e.children.map(t=>BS(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:jS(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[BS(e,e.queryId??"oqlSearch-1")]}}function BS(e,t){let n=jS(e);return{id:e.queryId??t,...LD(e),data:n}}function jS(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||AD(d,u)){let{why:p,confidence:f,...m}=l;s[c]=m,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function AD(e,t){return e.why===t.why&&e.confidence===t.confidence}function LD(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var US=y(()=>{"use strict";Er();zn()});var Du,qS=y(()=>{"use strict";Re();Du={hasTool(e){return Sc(e)},getDescription(e){return Rc[e]??""},getToolName(e){return v[e]??String(e)}}});function _D(e,t){return t.getToolName(e)}function ft(e,t,n){let r=_D(t,e);return{...n,name:r,description:Nu(r,e)}}function ID(e=Du){let t=ft(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Qo,inputSchema:Bo,executionFn:kh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=ft(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:_n,inputSchema:Ho,executionFn:Ph,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=ft(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Wo,inputSchema:Vo,executionFn:Vh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=ft(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Uo,inputSchema:qo,executionFn:qh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=ft(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Fn,inputSchema:$o,executionFn:Gh,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=ft(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ko,inputSchema:Yo,executionFn:xy,security:"remote",requiresServerRuntime:!0}}),a=ft(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:wr,inputSchema:Go,executionFn:qg,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=ft(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Ut,inputSchema:ti,executionFn:rb,security:"basic"}}),l=ft(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Nn,inputSchema:ni,executionFn:bb,security:"basic"}}),u=ft(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Dn,inputSchema:Zo,executionFn:My,security:"basic"}}),d=ft(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Mn,inputSchema:Xo,executionFn:_y,security:"basic"}}),p={name:De,description:Nu(De,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:si,inputSchema:ai,executionFn:Ib,security:"basic",requiresServerRuntime:!0}},f=ft(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Hn,inputSchema:ci,executionFn:xg,security:"basic"}}),m={name:an,description:Nu(an,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:pi,inputSchema:Bn,executionFn:$S,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}},g=[t,n,r,o,i,s,a,c,l,u,d,p,f,...Sr()?[m]:[]];return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:p,LOCAL_BINARY_INSPECT:f,OQL_SEARCH:m,ALL_TOOLS:g}}var Nu,Qe,NX,GX,HX,zX,QX,BX,$X,jX,UX,qX,WX,VX,KX,YX,WS,VS=y(()=>{"use strict";ga();zo();ha();jo();ya();ba();Ra();Jo();ei();kr();ri();Ca();li();Er();Tg();Wg();Ch();Eh();Hh();Wh();Kh();Ty();Iy();Dy();ob();Rb();Qb();US();Pr();Mo();qS();Nu=(e,t=Du)=>t.getDescription(e);Qe=ID(),NX=Qe.GITHUB_SEARCH_CODE,GX=Qe.GITHUB_FETCH_CONTENT,HX=Qe.GITHUB_VIEW_REPO_STRUCTURE,zX=Qe.GITHUB_SEARCH_REPOSITORIES,QX=Qe.GITHUB_SEARCH_PULL_REQUESTS,BX=Qe.PACKAGE_SEARCH,$X=Qe.GITHUB_CLONE_REPO,jX=Qe.LOCAL_RIPGREP,UX=Qe.LOCAL_VIEW_STRUCTURE,qX=Qe.LOCAL_FIND_FILES,WX=Qe.LOCAL_FETCH_CONTENT,VX=Qe.LSP_GET_SEMANTIC_CONTENT,KX=Qe.LOCAL_BINARY_INSPECT,YX=Qe.OQL_SEARCH,WS=Qe.ALL_TOOLS});import{ContentSanitizer as FD}from"@octocodeai/octocode-engine/security";function Hu(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:bt(t.structuredContent)}}catch{}return DD(t)?ND(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=FD.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function DD(e){return Qa()==="mcp"&&process.env[MD]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function ND(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:GD(e.structuredContent)},...t]}}function GD(e){let t=["structuredContent available"];if(Gu(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=HD(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Gu(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function HD(e){let t=0,n=0;for(let r of e)Gu(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Gu(e){return typeof e=="object"&&e!==null}function zu(e,t){let n=QD(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
53
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:zD,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Hu(r)}catch{return r}}function QD(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:BD(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function BD(e){try{return JSON.stringify(e)}catch{return}}var MD,zD,KS=y(()=>{"use strict";er();wt();MD="OCTOCODE_MCP_FULL_TEXT";zD="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as $D,withBasicSecurityValidation as jD}from"@octocodeai/octocode-engine/security";function YS(e,t){let n=$D(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function XS(e,t){let n=jD(r=>e(r),t);return(r,o)=>n(r,o)}var JS=y(()=>{"use strict"});function qD(e){let t=e;return n=>t(n)}function WD(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:qD(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function KD(e){return VD.find(t=>t.name===e)}async function oa(e,t){let n=KD(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=YD(n,t);return await XD(n),JD(n),await ZD(n,r)}catch(r){return zu(n.name,r)}}function YD(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function XD(e){e.requiresServerRuntime&&(da||(da=UD().catch(t=>{throw da=null,t})),await da),e.requiresProviders&&(pa||(pa=Km().then(()=>{}).catch(t=>{throw pa=null,t})),await pa)}function JD(e){if(!e.isLocal&&!e.isClone)return;let t=yt();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}}async function ZD(e,t){try{let n=e.security==="remote"?await eN(e,t):await tN(e,t);return Hu(n)}catch(n){return zu(e.name,n)}}async function eN(e,t){return YS(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function tN(e,t){return XS(e.execute,e.name)(t)}var da,pa,UD,VD,ZS=y(()=>{"use strict";Ur();Hc();wt();VS();KS();JS();Ia();da=null,pa=null,UD=nf;VD=WS.map(WD)});var bu=y(()=>{"use strict";Ia();ZS()});bu();import{completeMetadata as nN}from"@octocodeai/octocode-core";var Qu=null;function rN(){return Qu||(Qu=nN),Qu}async function oN(){return rN()}er();export{ka as DIRECT_TOOL_CATEGORIES,jd as DIRECT_TOOL_DEFINITIONS,ht as DirectToolInputError,NC as buildDirectToolExampleQuery,oa as executeDirectTool,vr as findDirectToolDefinition,Tk as formatCallToolResultForOutput,LC as formatDirectToolMetadataSchemaText,FC as formatDirectToolOutputSchemaText,AC as formatDirectToolSchemaText,_C as getDirectToolAutoFilledFields,Or as getDirectToolCategory,MC as getDirectToolDescription,_a as getDirectToolDisplayFields,IC as getDirectToolOutputFields,oN as loadToolContent,Ud as prepareDirectToolInput,zC as prepareDirectToolInputFromJsonText,vC as sortDirectToolNames};