@octocodeai/octocode-tools-core 16.5.1 → 16.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +200 -254
  2. package/dist/direct.js +37 -33
  3. package/dist/errors/localToolErrors.d.ts +1 -0
  4. package/dist/github/githubAPI.d.ts +22 -0
  5. package/dist/github/history.d.ts +3 -0
  6. package/dist/github/prTransformation.d.ts +1 -1
  7. package/dist/index.d.ts +6 -8
  8. package/dist/index.js +44 -40
  9. package/dist/oql/adapters/compile.d.ts +25 -0
  10. package/dist/oql/adapters/github.d.ts +3 -0
  11. package/dist/oql/adapters/local.d.ts +8 -0
  12. package/dist/oql/adapters/materialize.d.ts +11 -0
  13. package/dist/oql/adapters/pagination.d.ts +21 -0
  14. package/dist/oql/adapters/researchTargets.d.ts +50 -0
  15. package/dist/oql/adapters/resultMap.d.ts +20 -0
  16. package/dist/oql/adapters/ruleYaml.d.ts +11 -0
  17. package/dist/oql/adapters/runner.d.ts +14 -0
  18. package/dist/oql/adapters/v2.d.ts +32 -0
  19. package/dist/oql/capabilities.d.ts +31 -0
  20. package/dist/oql/defaults.d.ts +26 -0
  21. package/dist/oql/diagnostics.d.ts +25 -0
  22. package/dist/oql/diffLanes.d.ts +29 -0
  23. package/dist/oql/envelope.d.ts +21 -0
  24. package/dist/oql/features.d.ts +7 -0
  25. package/dist/oql/index.d.ts +27 -0
  26. package/dist/oql/index.js +49 -0
  27. package/dist/oql/normalize.d.ts +5 -0
  28. package/dist/oql/planner.d.ts +7 -0
  29. package/dist/oql/research/analyze.d.ts +134 -0
  30. package/dist/oql/research/packets.d.ts +80 -0
  31. package/dist/oql/run.d.ts +32 -0
  32. package/dist/oql/schema.d.ts +1018 -0
  33. package/dist/oql/schemeText.d.ts +154 -0
  34. package/dist/oql/shorthand.d.ts +177 -0
  35. package/dist/oql/targetParams.d.ts +20 -0
  36. package/dist/oql/transformers/contract.d.ts +19 -0
  37. package/dist/oql/transformers/github/code.d.ts +17 -0
  38. package/dist/oql/transformers/github/common.d.ts +8 -0
  39. package/dist/oql/transformers/language.d.ts +1 -0
  40. package/dist/oql/transformers/registry.d.ts +16 -0
  41. package/dist/oql/transformers/types.d.ts +11 -0
  42. package/dist/oql/types.d.ts +640 -0
  43. package/dist/oql/v2params.d.ts +22 -0
  44. package/dist/providers/types.d.ts +1 -1
  45. package/dist/schema.d.ts +13 -0
  46. package/dist/schema.js +9 -0
  47. package/dist/serverConfig.d.ts +0 -1
  48. package/dist/session.d.ts +2 -24
  49. package/dist/shared/config/defaults.d.ts +1 -2
  50. package/dist/shared/config/index.d.ts +2 -3
  51. package/dist/shared/config/index.js +2 -3
  52. package/dist/shared/config/resolverSections.d.ts +1 -3
  53. package/dist/shared/config/runtimeSurface.d.ts +5 -4
  54. package/dist/shared/config/schemas.d.ts +0 -1
  55. package/dist/shared/config/types.d.ts +0 -8
  56. package/dist/shared/credentials/envTokens.d.ts +1 -1
  57. package/dist/shared/credentials/index.js +1 -2
  58. package/dist/shared/credentials/types.d.ts +1 -1
  59. package/dist/shared/index.d.ts +0 -1
  60. package/dist/shared/languageSelectors.d.ts +23 -0
  61. package/dist/shared/paths.d.ts +2 -3
  62. package/dist/shared/paths.js +1 -1
  63. package/dist/shared/session/index.js +1 -2
  64. package/dist/tools/directToolCatalog.d.ts +15 -56
  65. package/dist/tools/directToolCatalog.exec.d.ts +11 -0
  66. package/dist/tools/directToolCatalog.meta.d.ts +83 -0
  67. package/dist/tools/github_clone_repo/cache.d.ts +1 -1
  68. package/dist/tools/github_clone_repo/types.d.ts +2 -0
  69. package/dist/tools/github_fetch_content/scheme.d.ts +81 -59
  70. package/dist/tools/github_fetch_content/types.d.ts +27 -0
  71. package/dist/tools/local_binary_inspect/binaryInspector.d.ts +0 -4
  72. package/dist/tools/lsp/semantic_content/scheme.d.ts +164 -10
  73. package/dist/tools/lsp/shared/resolveSymbolAnchor.d.ts +2 -2
  74. package/dist/tools/lsp/shared/semanticTypes.d.ts +34 -5
  75. package/dist/tools/oql_search/execution.d.ts +7 -0
  76. package/dist/tools/package_search/execution.d.ts +33 -0
  77. package/dist/tools/package_search/scheme.d.ts +8 -0
  78. package/dist/tools/providerMappers.d.ts +7 -7
  79. package/dist/tools/toolConfig.d.ts +1 -0
  80. package/dist/tools/toolNames.d.ts +2 -0
  81. package/dist/types/server.d.ts +1 -2
  82. package/dist/types/session.d.ts +0 -19
  83. package/dist/utils/contextUtils.d.ts +15 -1
  84. package/dist/utils/core/types.d.ts +2 -1
  85. package/dist/utils/markdownOutline.d.ts +10 -0
  86. package/dist/utils/response/groupedFinalizer.d.ts +0 -23
  87. package/package.json +14 -3
  88. package/dist/commands/BaseCommandBuilder.d.ts +0 -14
  89. package/dist/commands/FindCommandBuilder.d.ts +0 -23
  90. package/dist/commands/LsCommandBuilder.d.ts +0 -15
  91. package/dist/shared/logger/index.d.ts +0 -2
  92. package/dist/shared/logger/logger.d.ts +0 -17
  93. package/dist/utils/pagination/outputSizeLimit.d.ts +0 -16
  94. package/dist/utils/ranking/evidenceRanker.d.ts +0 -86
  95. package/dist/utils/response/structuredPagination.d.ts +0 -9
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ var FS=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 MS=(e,t)=>{for(var n in t)FS(e,n,{get:t[n],enumerable:!0})};function Ku(e){return Array.isArray(e.queries)}function Yu(e){return Array.isArray(e.queries)}function Xu(e){return Array.isArray(e.children)}var Ge,Pn,To,_t=y(()=>{"use strict";Ge=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],Pn=["fixes","dataflow"],To=["packages","repositories"]});import{z as h}from"zod";var Eo,aa,DS,Ju,Zu,NS,GS,Xt,ed,HS,zS,It,td,nd,rd,od,lr,id,BS,QS,US,sd,ad,cd,Oo,ca,la,Jt,Cn=y(()=>{"use strict";_t();Eo=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:Eo.optional()}),h.strictObject({kind:h.literal("npm")})])),aa=h.union([h.string(),h.array(h.string()).max(100)]),DS=h.strictObject({path:aa.optional(),language:aa.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(),Ju=h.enum(["smart","sensitive","insensitive"]),Zu=h.string().max(1e4),NS=h.strictObject({id:h.string().optional(),kind:h.literal("text"),value:Zu,case:Ju.optional(),wholeWord:h.boolean().optional()}),GS=h.strictObject({id:h.string().optional(),kind:h.literal("regex"),value:Zu,dialect:h.enum(["rust","pcre2","provider"]).optional(),case:Ju.optional(),wholeWord:h.boolean().optional(),multiline:h.boolean().optional(),dotAll:h.boolean().optional()}),Xt=h.lazy(()=>h.strictObject({pattern:h.string().optional(),kind:h.string().optional(),inside:Xt.optional(),has:Xt.optional(),not:Xt.optional(),all:h.array(Xt).optional(),any:h.array(Xt).optional(),stopBy:h.literal("end").optional()})),ed=h.union([Xt,h.string().min(1)]),HS=h.strictObject({id:h.string().optional(),kind:h.literal("structural"),lang:h.string().min(1),pattern:h.string().optional(),rule:ed.optional()}),zS=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()}),It=h.lazy(()=>h.discriminatedUnion("kind",[h.strictObject({kind:h.literal("all"),id:h.string().optional(),of:h.array(It).min(1)}),h.strictObject({kind:h.literal("any"),id:h.string().optional(),of:h.array(It).min(1)}),h.strictObject({kind:h.literal("not"),id:h.string().optional(),predicate:It}),NS,GS,HS,zS])),td=h.strictObject({mode:h.enum(["never","auto","required"]),strategy:h.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:h.boolean().optional(),forceRefresh:h.boolean().optional()}),nd=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()}),rd=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()}),od=h.enum(["discovery","paginated","detailed"]),lr=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),target:h.enum(Ge),from:Eo.optional(),scope:DS,where:It.optional(),materialize:td.optional(),fetch:nd.optional(),select:h.array(h.string()).optional(),view:od.optional(),controls:rd.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()}),id=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),queries:h.array(lr).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()}),BS=h.union([lr,id]),QS=Ge,US=[...Ge,...Pn],sd={schema:h.literal("oql").optional(),id:h.string().optional(),mainResearchGoal:h.string().optional(),researchGoal:h.string().optional(),reasoning:h.string().optional()},ad={...sd,target:h.enum(US).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:Eo.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:It.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([td,h.enum(["never","auto","required"])]).optional(),fetch:nd.optional(),select:h.array(h.string()).optional(),view:od.optional(),controls:rd.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:aa.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:ed.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()},cd={...ad,target:h.enum(QS).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.")},Oo=h.object(cd).catchall(h.unknown()),ca=h.object(ad).catchall(h.unknown()),la=h.object({...sd,queries:h.array(h.unknown()).min(1)}).catchall(h.unknown()),Jt=h.object({...cd,queries:h.array(h.unknown()).min(1).max(5).optional(),combine:h.enum(["independent","merge"]).optional()}).catchall(h.unknown())});function w(e,t,n={}){let r=n.severity??(jS.has(e)?"error":"warning"),o=n.blocksAnswer??($S.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 ua(e){return e.some(t=>t.blocksAnswer)}function qS(e){return e.some(t=>t.severity==="error")}var $S,jS,Rt,tt=y(()=>{"use strict";$S=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","budgetExhausted","contentTruncated"]),jS=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed"]);Rt=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 ud(e,t){let n=rP[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 ae,da,ld,VS,WS,KS,YS,XS,JS,ZS,eP,tP,nP,rP,dd=y(()=>{"use strict";ae=C.number().int().min(1),da=C.number().int().min(0),ld=C.enum(["symbols","files","dependencies","relations"]),VS=C.object({match:C.enum(["file","path"]).optional(),concise:C.boolean().optional(),extension:C.string().optional(),filename:C.string().optional(),page:ae.optional(),limit:ae.optional()}).passthrough(),WS=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:ae.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:ae.optional(),itemsPerPage:ae.optional()}).passthrough(),KS=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:ae.optional()}).passthrough(),YS=C.object({packageName:C.string().optional(),keywords:C.array(C.string()).optional(),mode:C.enum(["lean","full"]).optional(),page:ae.optional()}).passthrough(),XS=C.object({prNumber:ae.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:ae.optional(),commentPage:ae.optional(),commitPage:ae.optional(),charOffset:da.optional(),charLength:ae.optional(),minify:C.enum(["none","standard"]).optional(),limit:ae.optional(),page:ae.optional(),matchString:C.string().optional(),matchScope:C.enum(["body","title","comments","reviews","all"]).optional(),content:C.record(C.string(),C.unknown()).optional()}).passthrough(),JS=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:ae.optional(),page:ae.optional()}).passthrough(),ZS=C.object({mode:C.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:C.string().optional(),entryPageNumber:ae.optional(),maxEntries:ae.optional(),entriesPerPage:ae.optional(),minLength:C.number().int().min(1).max(128).optional(),scanOffset:da.optional(),charOffset:da.optional(),charLength:ae.optional(),matchString:C.string().optional(),detailed:C.boolean().optional(),format:C.string().optional(),verbose:C.boolean().optional(),includeOffsets:C.boolean().optional()}).passthrough(),eP=C.object({prNumber:ae.optional(),files:C.array(C.string()).optional(),baseRef:C.string().optional(),headRef:C.string().optional(),path:C.string().optional()}).passthrough(),tP=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array(ld).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:ae.optional()}).passthrough(),nP=C.object({goal:C.string().optional(),intent:C.enum(["general","reachability","dependencies","symbols"]).optional(),facets:C.array(ld).optional(),mode:C.enum(["plan","analyze","prove"]).optional(),maxFiles:ae.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:ae.max(25).optional(),includePackets:C.boolean().optional(),includeFacts:C.boolean().optional(),includeEdges:C.boolean().optional()}).passthrough(),rP={semantics:WS,repositories:KS,packages:YS,pullRequests:XS,commits:JS,artifacts:ZS,diff:eP,research:tP,graph:nP,code:VS}});function Y(...e){throw new Rt(e)}function ma(e){return Ku(e)?iP(e):ga(e)}function iP(e){let t=la.safeParse(e);t.success||Y(w("invalidQuery",vo(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)||Y(w("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&Y(w("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return ga(i)}catch(a){throw a instanceof Rt?new Rt(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 ga(e){let t=ca.safeParse(e);t.success||Y(w("invalidQuery",vo(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??sP(n);r===void 0&&Y(w("invalidQuery",`Could not determine \`target\`; specify one of: ${Ge.join(", ")}.`,{queryPath:"target"})),Pn.includes(r)&&Y(w("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${Ge.join(", ")}.`}})),Ge.includes(r)||Y(w("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))oP.has(m)||Y(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=uP(n,r),a=pP(n,s),c=fP(n,r),l=RP(n,s,c,r),u=SP(n),d=cP(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&&Y(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&&Y(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("/"))&&Y(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&&Y(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"&&Y(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=ud(p.target,p.params);m&&Y(w("invalidQuery",m,{queryPath:"params"}))}let f=lr.safeParse(p);return f.success||Y(w("invalidQuery",vo(f.error))),f.data}function sP(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 cP(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!lP(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function lP(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 aP.some(n=>t.includes(n))}function uP(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&Y(w("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),dP(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"};To.includes(t)||Y(w("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function dP(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 pP(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&&Y(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 fP(e,t){let n=hP(e);e.where&&n&&Y(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;fa(r,"where");let o=It.safeParse(r);return o.success||Y(w("invalidQuery",vo(o.error),{queryPath:"where"})),o.data}function pa(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+pa(n),0):e.kind==="not"?1+pa(e.predicate):1}function gP(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:mP}function hP(e){let t=n=>{let r=pa(n),o=gP(e);return r>o&&Y(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(wn)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(wn)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(wn)}};if(Array.isArray(e.xor)){e.xor.length!==2&&Y(w("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=wn(e.xor[0]),r=wn(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(yP(e.oneOf.map(wn)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&Y(w("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&Y(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 wn(e){if(e&&typeof e=="object"&&"kind"in e)return e;Y(w("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function yP(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 fa(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&Y(w("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>fa(n,`${t}.of[${r}]`));break;case"not":e.predicate||Y(w("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),fa(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&Y(w("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":bP(e,t);break;default:break}}function bP(e,t){if(e.op==="exists"){e.value!==void 0&&Y(w("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&Y(w("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&Y(w("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function pd(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 pd(e.predicate);default:return!1}}function RP(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:pd(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function SP(e){return e.fetch?{...e.fetch}:void 0}function vo(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 oP,aP,mP,ha=y(()=>{"use strict";Cn();tt();dd();_t();oP=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"]);aP=["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"];mP=64});function PP(e){return e?.mode==="auto"||e?.mode==="required"}function CP(e,t){let n=e.target==="files"?Zt:Ft;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:Ft,exact:!0,reason:`${t.kind} evaluated locally by ${Ft}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function wP(e,t,n){let r=PP(e.materialize);if(n)return xP(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:Zt,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:St,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:Zt,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:St,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:Zt,exact:!0,reason:`${Ao(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:Zt,exact:!1,reason:`GitHub cannot enumerate files by ${Ao(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${Ao(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:Ft,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:Ft,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:St,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:St,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?ya(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:Ft,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:St,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 ya(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:Zt,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:St,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:St,exact:!0,reason:"path/name predicate pushed to provider"}:ya(e,`field "${t.field}"`,r)}}function Ao(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 xP(e,t,n){let r=Ao(t);return n?{route:"ROUTE",backend:e.target==="files"?Zt:Ft,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:St,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 ya(e,t,n){if(n)return{route:"ROUTE",backend:Ft,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:St,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 fd(e,t,n=!1){return e.sourceKind==="github"?wP(e,t,n):CP(e,t)}var Ft,Zt,St,md=y(()=>{"use strict";Ft="localSearchCode",Zt="localFindFiles",St="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 Lo=y(()=>{"use strict"});function gd(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&kP.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 kP,hd=y(()=>{"use strict";tt();kP=new Set(["pullRequests","commits","diff"])});function ba(e){let t={schema:Le.schema,view:e.view??Le.view,page:e.page??Le.page,itemsPerPage:e.itemsPerPage??Le.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??Le.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??Le.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??Le.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?Le.detailedCodeContext:Le.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??Le.localSearchSort),t}var Le,_o=y(()=>{"use strict";Le={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 yd(e){return JSON.stringify(e)}function Ra(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${yd(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${yd(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Ra(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=Ra(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 bd(e){return["rule:",...Ra(e,1)].join(`
9
+ `)}var Rd=y(()=>{"use strict"});function Sd(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function Pd(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return Sd(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),Sd(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=bd(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 en(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return Pd(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=Pd(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 Sa=y(()=>{"use strict";Rd()});function OP(e){return e.trim().replace(/^\./,"").toLowerCase()}function kn(e){if(!e?.trim())return;let t=OP(e),n=TP[t]??EP[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function vP(e){return[...e??[]].map(t=>`**/*.${t}`)}function Pa(e){return[...e??[]].map(t=>`*.${t}`)}function Io(e){let t=kn(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Ca(e){let t=kn(e);return t?t.kind==="extension"&&t.extension?{include:vP([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function wa(e){let t=kn(e);return t?t.kind==="extension"&&t.extension?Pa([t.extension]):t.kind==="language"?Pa(t.extensions):t.normalized?Pa([t.normalized]):[]:[]}function Cd(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 xa(e){return kn(e)?.canonicalLanguage}var TP,EP,ka=y(()=>{"use strict";TP={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"]}},EP={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"]}}});var Fo=y(()=>{"use strict";ka()});function Ta(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 Xe(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Tn(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Ea(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var ur=y(()=>{"use strict"});function AP(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 dr(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=AP(e.where);if(n){let p=wd(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=Ta(e.from),g=e.params??{},b=typeof g.extension=="string"||typeof n.extension=="string"?{}:Io(Tn(e.scope)),P=Ea(e),S=Xe(e.scope);return{ok:!0,diagnostics:[],query:{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...P?{limit:P}:{},...e.page?{page:e.page}:{}}}}let r=en(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=wd(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}=Ta(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:Io(Tn(e.scope)),u=Ea(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return{ok:!0,diagnostics:[],query:{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...Xe(e.scope)?{path:Xe(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 wd(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 Oa=y(()=>{"use strict";Sa();tt();Fo();ur()});function LP(){return Mo}function tn(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return Mo.find(n=>n.id===`${t}.diff.${e.variant}`)}return Mo.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function Do(e){return Mo.find(t=>t.id===e)}function va(e){let t=_P(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 tn({sourceKind:t,target:"diff",variant:r})}return tn({sourceKind:t,target:e.target})}function Aa(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function xd(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function _P(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var Mo,La=y(()=>{"use strict";Lo();Mo=[{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 IP(e,t){return e.id??t}function _a(e,t,n,r,o,i=!1){let s=IP(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>_a(e,d,`${n}.of[${p}]`,r,o,i)),l=FP(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=_a(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=fd(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"&&kd(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:MP(e.target),exact:a.exact}),a.route}function FP(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 MP(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 kd(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Ia(e,t){if(!t)return;let n=xd(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function No(e,t,n){if(!t)return!1;for(let r of Aa(t,n))kd(e.backendCalls,r);return!0}function DP(e,t){return Td(e,t,"files")}function Td(e,t,n,r=tn({sourceKind:"materialized",target:n})){let o=tn({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Ia(e,o),Ia(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}`)),No(e,o,t),No(e,r,void 0),!0}function Go(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(Go):e.kind==="not"?Go(e.predicate):!1:!1}function NP(e){return e.target==="code"?Do(Go(e.where)?"local.code.structural":"local.code.textRegex"):tn({sourceKind:"materialized",target:e.target})}function GP(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?Do(Go(e.where)?"local.code.structural":"local.code.textRegex")??va({source:t,target:e.target,params:e.params}):va({source:t,target:e.target,params:e.params})}function Fa(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Fa(n),0):e.kind==="not"?1+Fa(e.predicate):1:0}function Ma(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=GP(e,o);if(Ia(n,s),e.where)_a(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&Td(n,o,e.target,NP(e));else if(e.target==="diff"){let m=xn(e.params);m.kind==="prPatch"||m.kind==="directFile"?No(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&&DP(n,o):No(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(...HP(e,n.nodes)),n.diagnostics.push(...gd(e));let a=zP(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??Le.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=Fa(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:ba(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 Ed(e){return e.kind==="not"&&e.predicate.kind==="not"?Ed(e.predicate.predicate):e}function HP(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=Ed(e.where),r=dr({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function zP(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 Da=y(()=>{"use strict";md();Lo();hd();tt();_o();Oa();La()});function pr(e){let t=QP(e),n=$P(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 QP(e){return!e.executable||e.diagnostics.some(t=>BP.has(t.code))?"unsupported":e.approximate||UP(e.diagnostics)?"candidate":ua(e.diagnostics)||Od(e)?"partial":"proof"}function UP(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function Od(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function $P(e){return!e.executable||Od(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function Na(e){return e.some(t=>!t.exact)}function Ho(e,t,n,r,o){return pr({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var BP,Ga=y(()=>{"use strict";tt();BP=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});var fe=y(()=>{"use strict"});var B,vd,En=y(()=>{"use strict";B={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"},vd={[B.PATH_VALIDATION_FAILED]:{code:B.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[B.FILE_ACCESS_FAILED]:{code:B.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[B.FILE_READ_FAILED]:{code:B.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[B.FILE_TOO_LARGE]:{code:B.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[B.BINARY_FILE_UNSUPPORTED]:{code:B.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[B.NO_MATCHES]:{code:B.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[B.OUTPUT_TOO_LARGE]:{code:B.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[B.COMMAND_NOT_AVAILABLE]:{code:B.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[B.COMMAND_EXECUTION_FAILED]:{code:B.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[B.COMMAND_TIMEOUT]:{code:B.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[B.TOOL_EXECUTION_FAILED]:{code:B.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[B.LSP_SERVER_UNAVAILABLE]:{code:B.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 Ha(e){return e instanceof xe}function Ad(e,t=B.TOOL_EXECUTION_FAILED,n){if(Ha(e))return e;if(e instanceof Error)return new xe(t,e.message,n,e);let r=String(e);return new xe(t,r,n)}var xe,zo=y(()=>{"use strict";En();xe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=vd[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
10
+ 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}}}});import{redactPath as fr}from"@octocodeai/octocode-engine/pathUtils";var Ld=y(()=>{"use strict"});var nt,Bo=y(()=>{"use strict";zo();En();Ld();nt={pathValidationFailed:(e,t,n)=>new xe(B.PATH_VALIDATION_FAILED,t||`Path validation failed: ${fr(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=fr(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new xe(B.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new xe(B.FILE_READ_FAILED,`Failed to read file: ${fr(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new xe(B.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 xe(B.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${fr(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new xe(B.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new xe(B.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new xe(B.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new xe(B.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});function Q(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Id(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?Id(t):Q(t);if(n===void 0)return e;try{Object.defineProperty(e,_d,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ce(e){if(!(typeof e!="object"||e===null))return Id(e[_d])}var _d,oe=y(()=>{"use strict";_d=Symbol.for("octocode.rawResponseChars")});function jP(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(jP(e))o.error=e;else if(Ha(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Ad(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:$(o,n.rawResponse)}function _e(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 za=y(()=>{"use strict";zo();oe()});function Mt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function On(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 Qo(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Uo=y(()=>{"use strict"});function VP(e){let t=Mt(e),n=mr.get(t);return!n||Date.now()-n.cachedAt>=qP?!1:n.credentials?!On(n.credentials):!0}function Ba(e){e?mr.delete(Mt(e)):mr.clear()}function Fd(e){let t=Mt(e);if(VP(t))return mr.get(t).credentials}function Md(e,t){let n=Mt(e);mr.set(n,{credentials:t,cachedAt:Date.now()})}var mr,qP,Dd=y(()=>{"use strict";Uo();mr=new Map,qP=300*1e3});import $o from"node:os";import WP from"node:path";function Ua(){return jo?process.env.APPDATA||WP.join(vn,"AppData","Roaming"):vn}var jo,Qa,KP,vn,Nd=y(()=>{"use strict";jo=$o.platform()==="win32",Qa=$o.platform()==="darwin",KP=$o.platform()==="linux",vn=$o.homedir()});var $a=y(()=>{"use strict";Nd()});import{existsSync as YP,mkdirSync as XP}from"node:fs";import{join as ke,resolve as JP}from"node:path";function Gd(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function eC(){let e=Gd("OCTOCODE_HOME");return e?JP(e):jo?ke(Ua(),ja):Qa?ke(vn,ja):ke(Gd("XDG_CONFIG_HOME")??ke(vn,".config"),ja)}function Hd(){YP(Ie.home)||XP(Ie.home,{recursive:!0,mode:ZP})}var ja,ZP,He,Ie,An=y(()=>{"use strict";$a();ja=".octocode",ZP=448;He=eC(),Ie={home:He,config:ke(He,".octocoderc"),credentials:ke(He,"credentials.json"),key:ke(He,".key"),session:ke(He,"session.json"),stats:ke(He,"stats.json"),tmp:ke(He,"tmp"),clone:ke(He,"tmp","clone"),tree:ke(He,"tmp","tree"),binary:ke(He,"tmp","binary"),repos:ke(He,"tmp","clone"),unzip:ke(He,"tmp","unzip"),cliConfig:ke(He,"config.json"),lspConfig:ke(He,"lsp-servers.json")}});import{z as Ce}from"zod";var tC,nC,zd,Bd=y(()=>{"use strict";tC=Ce.object({token:Ce.string(),tokenType:Ce.literal("oauth"),scopes:Ce.array(Ce.string()).optional(),refreshToken:Ce.string().optional(),expiresAt:Ce.string().optional(),refreshTokenExpiresAt:Ce.string().optional()}),nC=Ce.object({hostname:Ce.string(),username:Ce.string(),token:tC,gitProtocol:Ce.enum(["ssh","https"]),createdAt:Ce.string(),updatedAt:Ce.string()}),zd=Ce.object({version:Ce.number(),credentials:Ce.record(Ce.string(),nC)})});import{existsSync as Qd,readFileSync as Ud,writeFileSync as $d,unlinkSync as fN,statSync as rC,chmodSync as oC}from"node:fs";import{createCipheriv as iC,createDecipheriv as sC,randomBytes as jd}from"node:crypto";function rn(){Hd()}function Wd(){if(rn(),Qd(nn))return rC(nn).mode&511&63&&oC(nn,384),Buffer.from(Ud(nn,"utf8"),"hex");let e=jd(32);return $d(nn,e.toString("hex"),{mode:384}),e}function qa(e){let t=Wd(),n=jd(aC),r=iC(Vd,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 Va(e){let t=Wd(),[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=sC(Vd,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function qo(){if(rn(),!Qd(gr))return{version:1,credentials:{}};try{let e=Ud(gr,"utf8"),t=Va(e),n=JSON.parse(t),r=zd.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Kd(e){rn();let t=qa(JSON.stringify(e,null,2));$d(gr,t,{mode:384})}var qd,gr,nn,Vd,aC,Yd=y(()=>{"use strict";An();Bd();qd=Ie.home,gr=Ie.credentials,nn=Ie.key,Vd="aes-256-gcm",aC=16});var hr,Ln,Wa=y(()=>{"use strict";hr="178c6fc778ccc68e1d6a",Ln="github.com"});import{refreshToken as cC}from"@octokit/oauth-methods";import{request as lC}from"@octokit/request";function uC(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 dC(e){return e==="github.com"||e===Ln?"https://api.github.com":`https://${e}/api/v3`}async function Xd(e,t=Ln,n=hr){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(Qo(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await cC({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:lC.defaults({baseUrl:dC(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?uC(o.message):"Token refresh failed"}}}async function Jd(e,t=Ln,n=hr){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!On(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Xd(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 Zd=y(()=>{"use strict";Uo();Wa()});function ep(){for(let e of Ka){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}var Ka,Ya=y(()=>{"use strict";Ka=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN"]});import{execFile as pC}from"child_process";function Xa(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=fC.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;pC("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var fC,Ja=y(()=>{"use strict";fC=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function tp(e){Za=e}function mC(){if(!Za)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Za}async function Vo(e){let t=e?.hostname??Ln,n=e?.clientId??hr,r=e?.getGhCliToken??Xa,o=ep();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await mC().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 Za,np=y(()=>{"use strict";Ya();Ja();Wa();Za=null});async function rp(e){let t=Mt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=qo();return r.credentials[t]=n,Kd(r),Ba(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function ec(e="github.com",t){let n=Mt(e);if(!t?.bypassCache){let i=Fd(n);if(i!==void 0)return i}let o=qo().credentials[n]||null;return Md(n,o),o}async function op(e,t){let n=await ec(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await rp(n),!0):!1}async function ip(e,t){return Jd({getCredentials:ec,updateToken:op},e,t)}var tc=y(()=>{"use strict";Dd();Yd();Zd();np();Ya();Uo();tp({getTokenWithRefresh:ip})});var sp=y(()=>{"use strict";tc();Ja()});import{z as W}from"zod";var PC,CC,Wo,wC,Ko,ap,cp,lp=y(()=>{"use strict";PC=W.object({rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),calls:W.number()}),CC=W.object({hits:W.record(W.string(),W.number()).default({}),rateLimits:W.number().default(0)}),Wo=W.record(W.string(),W.number()).default({}),wC=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Wo,rawChars:W.number(),responseChars:W.number(),savedChars:W.number(),charSavingsCalls:W.number(),githubCacheHits:W.number(),githubCacheRateLimits:W.number(),packageRegistryFailures:W.number().default(0),packageRegistryFailuresByRegistry:Wo}),Ko=W.object({toolCalls:W.number(),errors:W.number(),rateLimits:W.number(),rateLimitsByProvider:Wo,charsSavedByTool:W.record(W.string(),PC).default({}),githubCacheHits:CC.default({hits:{},rateLimits:0}),packageRegistryFailures:Wo,totalUsage:wC.optional()}),ap=W.object({version:W.literal(1),sessionId:W.string(),createdAt:W.string(),lastActiveAt:W.string(),stats:Ko.optional()}),cp=W.object({version:W.literal(1),stats:Ko})});function up(e){return Object.values(e).reduce((t,n)=>t+n,0)}function xC(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:up(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:up(o),packageRegistryFailuresByRegistry:o}}function Pt(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:xC(t)}}function nc(){return Pt({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var rc=y(()=>{"use strict"});import{existsSync as pp,readFileSync as fp,writeFileSync as kC,unlinkSync as oG,renameSync as TC}from"node:fs";function dp(e,t){let n=`${e}.tmp`;kC(n,JSON.stringify(t,null,2),{mode:384}),TC(n,e)}function EC(e){let{stats:t,...n}=e;return n}function OC(e){let t=JSON.parse(e),n=cp.safeParse(t);if(n.success)return Pt(n.data.stats);let r=Ko.safeParse(t);return r.success?Pt(r.data):null}function vC(e){let t=e?Pt(e):nc();if(!pp(br))return t;try{let n=fp(br,"utf8"),r=OC(n);return r||t}catch{return t}}function oc(e){rn(),dp(br,{version:e.version,stats:Pt(e.stats)}),dp(yr,EC(e))}function mp(){if(!pp(yr))return null;try{let e=fp(yr,"utf8"),t=JSON.parse(e),n=ap.safeParse(t);return n.success?{...n.data,stats:vC(n.data.stats)}:null}catch{return null}}var yr,br,Yo=y(()=>{"use strict";tc();An();lp();rc();yr=Ie.session,br=Ie.stats});function LC(){gp||(gp=!0,hp=()=>{Xo()},yp=()=>{Xo()},bp=()=>{Xo()},process.on("exit",hp),process.on("SIGINT",yp),process.on("SIGTERM",bp))}function _C(){ic||(ic=setInterval(()=>{Rr&&Dt&&(oc(Dt),Rr=!1)},AC),ic.unref())}function Rp(){if(Dt)return Dt;let e=mp();return e&&(Dt=e),e}function Sp(e){Dt=e,Rr=!0,LC(),_C()}function Xo(){if(!sc&&Rr&&Dt){sc=!0;try{oc(Dt),Rr=!1}catch{}finally{sc=!1}}}var AC,Dt,Rr,ic,gp,hp,yp,bp,sc,Pp=y(()=>{"use strict";Yo();AC=6e4,Dt=null,Rr=!1,ic=null,gp=!1,hp=null,yp=null,bp=null,sc=!1});import{randomUUID as RG}from"node:crypto";function IC(e){return Pt(e)}function FC(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 Cp(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 MC(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 Nt(e){let t=Rp();if(!t)return{success:!1,session:null};let n=IC(t.stats),r=Pt({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Cp(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:FC(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:MC(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Cp(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return Sp(o),{success:!0,session:o}}function ac(e=1){return Nt({rateLimits:e})}function cc(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Nt({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function lc(e,t=1){return Nt({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function uc(e=1){return Nt({githubCacheHits:{hits:{},rateLimits:e}})}var Sr=y(()=>{"use strict";Yo();rc();Pp();Yo()});var wp=y(()=>{"use strict";Sr();Sr();Sr();Sr()});var dc=y(()=>{"use strict"});var Jo,on,_n,Pr,Zo,Gt,pc,Cr,wr,xr,kr,Tr,Er,Or=y(()=>{"use strict";Jo={apiUrl:"https://api.github.com"},on={enabled:!0,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},_n={enabled:null,enableAdditional:null,disabled:null},Pr={timeout:3e4,maxRetries:3},Zo={configPath:void 0},Gt={format:"yaml",pagination:{defaultCharLength:2e4}},pc={version:1,github:Jo,local:on,tools:_n,network:Pr,lsp:Zo,output:Gt},Cr=5e3,wr=3e5,xr=0,kr=10,Tr=1e3,Er=5e4});import{z as me}from"zod";var fc,mc=y(()=>{"use strict";fc=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 DC,readFileSync as NC}from"node:fs";function GC(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]!==`
11
+ `;)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 HC(e){let t=GC(e);return JSON.parse(t)}function gc(){let e=xp;if(!DC(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=NC(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=HC(t),r=fc.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 In(){return Ie.home}var xp,ei=y(()=>{"use strict";An();mc();xp=Ie.config});function zC(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 bc(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 kp(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function Tp(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 BC(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 hc(e,t){return e===void 0||e===null?null:Tp(e,t)}function Ep(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function QC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=zC(e.apiUrl,"github.apiUrl");r&&t.push(r)}function UC(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=kp(n.enabled,"local.enabled");r&&t.push(r);let o=kp(n.enableClone,"local.enableClone");o&&t.push(o);let i=Tp(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=BC(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=Ep(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 $C(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=hc(n.enabled,"tools.enabled");r&&t.push(r);let o=hc(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=hc(n.disabled,"tools.disabled");i&&t.push(i)}function jC(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=bc(n.timeout,"network.timeout",Cr,wr);r&&t.push(r);let o=bc(n.maxRetries,"network.maxRetries",xr,kr);o&&t.push(o)}function qC(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=Ep(e.configPath,"lsp.configPath");r&&t.push(r)}function VC(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=bc(r.defaultCharLength,"output.pagination.defaultCharLength",Tr,Er);o&&t.push(o)}}function Rc(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}`)),QC(r.github,t),UC(r.local,t),$C(r.tools,t),jC(r.network,t),qC(r.lsp,t),VC(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 Sc=y(()=>{"use strict";dc();Or()});function vr(){return globalThis[WC]??"mcp"}var WC,ti=y(()=>{"use strict";WC="__octocodeRuntimeSurface__"});function Op(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 Pc(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function ni(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function vp(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||Jo.apiUrl}}function Ap(e){let t=vr()==="cli",n=Op(process.env.ENABLE_LOCAL),r=Op(process.env.ENABLE_CLONE),o=ni(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??on.enabled,enableClone:r??e?.enableClone??(t?!0:on.enableClone),allowedPaths:o??e?.allowedPaths??on.allowedPaths,workspaceRoot:i??e?.workspaceRoot??on.workspaceRoot}}function Lp(e){let t=ni(process.env.TOOLS_TO_RUN),n=ni(process.env.ENABLE_TOOLS),r=ni(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??_n.enabled,enableAdditional:n??e?.enableAdditional??_n.enableAdditional,disabled:r??e?.disabled??_n.disabled}}function _p(e){let t=Pc(process.env.REQUEST_TIMEOUT),n=Pc(process.env.MAX_RETRIES),r=t??e?.timeout??Pr.timeout;r=Math.max(Cr,Math.min(wr,r));let o=n??e?.maxRetries??Pr.maxRetries;return o=Math.max(xr,Math.min(kr,o)),{timeout:r,maxRetries:o}}function Ip(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??Zo.configPath}}function Fp(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=Pc(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||Gt.format,o=n??e?.pagination?.defaultCharLength??Gt.pagination.defaultCharLength,i=Math.max(Tr,Math.min(Er,o));return{format:KC.has(r)?r:Gt.format,pagination:{defaultCharLength:i}}}var KC,Mp=y(()=>{"use strict";Or();ti();KC=new Set(["yaml","json"])});function Cc(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??pc.version,github:vp(e?.github),local:Ap(e?.local),tools:Lp(e?.tools),network:_p(e?.network),lsp:Ip(e?.lsp),output:Fp(e?.output),source:o,configPath:n?t:void 0}}function wc(){let e=gc();return e.success&&e.config&&Rc(e.config).valid?Cc(e.config,e.path):Cc(void 0)}function Oe(){let e=Date.now();return ri&&e-Dp<YC||(ri=wc(),Dp=e),ri}var ri,Dp,YC,xc=y(()=>{"use strict";Or();ei();Sc();Mp();ri=null,Dp=0,YC=6e4});var Gp=y(()=>{"use strict";xc();xc()});var Hp=y(()=>{"use strict";dc();Or();ei();ei();Sc();Gp();ti();mc()});import{existsSync as nw,readdirSync as rw,lstatSync as ow}from"node:fs";import{join as iw}from"node:path";function oi(e){if(!nw(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=rw(r)}catch{continue}for(let i of o){let s=iw(r,i);try{let a=ow(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}var zp=y(()=>{"use strict"});var Fe=y(()=>{"use strict";sp();$a();wp();Hp();An();zp()});import Bp from"path";import{pathValidator as sw}from"@octocodeai/octocode-engine/pathValidator";function ze(e,t){if(!e.path?.trim()){let s=nt.pathValidationFailed("","path is required");return{isValid:!1,errorResult:F(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||Oe().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Bp.isAbsolute(r)?r:Bp.resolve(n,r),i=sw.validate(o);if(!i.isValid){let s=nt.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 Ct=y(()=>{"use strict";Bo();za();Fe()});import{completeMetadata as kc}from"@octocodeai/octocode-core";var A,Qp=y(()=>{"use strict";A=new Proxy({},{get(e,t){return kc.toolNames[t]},ownKeys(){return Object.keys(kc.toolNames)},getOwnPropertyDescriptor(e,t){let n=kc.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as aw}from"@octocodeai/octocode-core";var Tc,Up=y(()=>{"use strict";Tc=new Proxy({},{get(e,t){return aw.tools[t]?.description??""}})});import{completeMetadata as cw}from"@octocodeai/octocode-core";function Ec(e){return Object.prototype.hasOwnProperty.call(cw.tools,e)}var $p=y(()=>{"use strict"});import{completeMetadata as lw}from"@octocodeai/octocode-core";function Oc(){return lw.baseSchema}var uw,jp=y(()=>{"use strict";uw=new Proxy({},{get(e,t){return Oc()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Oc())]))},getOwnPropertyDescriptor(e,t){let n=Oc();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var de=y(()=>{"use strict";Qp();Up();$p();jp()});import{z as ii}from"zod";function G(e,t){return ii.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,ii.number().int().min(e).max(t))}function te(e,t={}){let{maxQueries:n=5}=t;return ii.object({queries:ii.array(e).min(1).max(n).describe("Parallel queries."),...pw}).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 ie,Fn,Mn,pw,Be=y(()=>{"use strict";fe();ie=G(1,1e3).optional().default(1),Fn=G(0,100).optional(),Mn=G(1,1e9).optional(),pw={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 qp}from"zod";function fw(e,t){return e?.description&&!t.description?t.describe(e.description):t}function Vp(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=fw(e.shape[r],o);return n}function mw(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Wp(e,t){if(!t?.length)return e;let n=new Set(t);return qp.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function le(e,t={},n={}){let r=Wp(e,n.omit),o=mw(r,Vp(r,t));return n.strict?o.strict():o}function pe(e,t={},n={}){let r=Wp(e,n.omit),o=qp.object({...r.shape,...Vp(r,t)});return n.strict?o.strict():o}var Je=y(()=>{"use strict"});import{z as Dn}from"zod";import{RipgrepQuerySchema as Kp}from"@octocodeai/octocode-core/schemas";var gw,hw,Yp,yw,bw,Rw,Ht,si,Ar=y(()=>{"use strict";fe();Be();Je();gw=["paginated","discovery","detailed","structural"],hw=["semanticRanking"],Yp={mode:Dn.enum(gw).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:Dn.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:Dn.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:Fn,matchContentLength:G(1,1e5).optional().default(500),maxMatchesPerFile:G(1,1e5).optional(),maxFiles:G(1,1e5).optional(),matchPage:ie.optional(),itemsPerPage:G(1,1e3).optional(),page:ie.default(1),unique:Dn.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:Dn.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},yw={...Yp,semanticRanking:Dn.never().optional()},bw=pe(Kp,yw),Rw=le(Kp,Yp,{strict:!0,omit:hw}),Ht=Rw.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"]})}),si=te(bw,{maxQueries:5})});var ft,Lr=y(()=>{"use strict";ft={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 Ic(e){return ef.exec(e)?.[1]?.toLowerCase()??""}function Aw(e){let t=Ic(e);if(!t)return!1;for(let n of vw)if(_r[n].extensions.includes(t))return!0;return!1}function Lw(e,t,n){if(n&&n!=="auto")return _r[n];let r=Ic(e),o=(t??"").toLowerCase();for(let i of Xp){let s=_r[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Xp){let s=_r[i];if(i!=="generic"&&s.extensions.includes(r))return s}return _r.generic}function tf(e){return ww.test(e)?"generated":kw.test(e)?"fixture":xw.test(e)?"test":Ew.test(e)?"config":Tw.test(e)?"docs":!_c.test(e)&&(Ow.test(e)||Aw(e))?"source":"unknown"}function _w(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function Iw(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function Fw(e,t,n,r,o){if(!e||e.length===0)return 0;let i=jw(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=qw(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${rf(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+=Mw(f,p);else{let m=Vw(u,r,t.id,n.caseSensitive);m!=="code"?(d+=se.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(Lc(t.declaration,u)&&(d+=se.declarationLine,p.push("declaration line")),Lc(t.export,u)&&(d+=se.exportLine,p.push("export/public line")),Lc(t.import,u)&&(d+=se.importLine,p.push("import line")),t.id==="markdown"&&Cw.test(u)&&(d+=se.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&Dw(u,r)&&(d+=se.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function Mw(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 Dw(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 Nw(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(ef,"").includes(l))&&(s+=se.pathSegmentToken,i.push("query token in path"))}let a=Ic(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 Gw(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),se.lowSignalPathPenalty):0}function Hw(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 zw(e,t){let n=Iw(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>Bw(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 Bw(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${rf(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function Qw(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 Uw(e,t,n){let r=Lw(e.path,t.langType,t.profileOverride),o=tf(e.path),i=_w(t.keyword),s=[],a=0;return a+=Fw(e.matches,r,t,i,s),a+=Nw(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=se.pathUnderQuery,s.push("under requested subtree")),a+=Gw(o,t,s),_c.test(e.path)&&!t.explicitLowSignal&&(a+=se.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=Hw(e.matchCount??0,s),a+=Qw(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function nf(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Zp),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??Sw,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Zp);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=zw(i,n),l=i.map(d=>{try{return{file:d,s:Uw(d,n,c)}}catch{return{file:d,s:$w()}}});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 $w(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Zp(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function Lc(e,t){for(let n of e)if(n.test(t))return!0;return!1}function rf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jw(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function qw(e,t,n){if(e.indexOf(`
12
+ `)<0)return e;let o=e.split(`
13
+ `);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 Vw(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(Pw.test(e))return"comment";let o=Ww(e,t,r);if(o<0)return"code";let i=Kw(e);return i>=0&&o>i?"comment":Yw(e,o)?"string":"code"}function Ww(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function Kw(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 Yw(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 of(e){if(!e)return!1;if(_c.test(e))return!0;let t=tf(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var Xp,se,Sw,Pw,Jp,_r,Cw,_c,ww,xw,kw,Tw,Ew,Ow,vw,ef,sf=y(()=>{"use strict";Xp=["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},Sw=2e3,Pw=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Jp={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},_r={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Jp},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Jp},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},Cw=/^\s*#{1,6}\s/,_c=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,ww=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,xw=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,kw=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,Tw=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,Ew=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,Ow=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,vw=new Set(["typescript","javascript","rust","python","go","java","scala"]),ef=/\.([a-z0-9]+)$/i});async function ci(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=nf(e,s,rx(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((H,K)=>H+(K.matchCount??0),0),g=f?o?.totalOccurrences??o?.totalStructuralMatches??m:m,b=t,P=Math.min(b.itemsPerPage||ft.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=b.page||1,T=Math.max(1,Math.ceil(u/P)),L=(S-1)*P,E=Math.min(L+P,u),O=c.slice(L,E),x=b.maxMatchesPerFile||ft.DEFAULT_MATCHES_PER_PAGE,N=O.map(H=>{let K=H.matches?.length??0,U=Math.ceil(K/x),Se=Math.max(1,b.matchPage||1),Pe=(Se-1)*x,At=Math.min(Pe+x,K),Lt=f?void 0:H.matches?.slice(Pe,At),Z=Lt?.length,pt=l?.get(H.path);return{path:H.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:H.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:H.matchCount||1}:{totalMatchRows:K,...Z!==void 0?{returnedMatchRows:Z}:{}},...Lt!==void 0&&{matches:Lt},...pt?{ranking:{score:pt.score,profile:pt.profile,pathRole:pt.pathRole,reasons:pt.reasons}}:{},pagination:!f&&K>x?{currentPage:Se,totalPages:U,matchesPerPage:x,totalMatches:K,hasMore:Se<U,...Se<U?{nextMatchPage:Se+1}:{}}:void 0}}),I=N.filter(H=>H.pagination?.hasMore),v=Zw(N,t,n,{isFileListMode:f,currentPage:S,totalFilePages:T,matchPage:b.matchPage||1,matchesPerPage:x,hasFileWithMoreMatches:I.length>0}),z={searchEngine:n,...o?{stats:o}:{},files:N,pagination:{currentPage:S,totalPages:T,filesPerPage:P,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<T,...S<T?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(v).length>0?{next:v}:{}};return cf(z,t,{totalMatches:g,totalFiles:u})}function cf(e,t,n){return e}function Zw(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=ex(i);s.fetchExact={tool:"localGetFileContent",query:ai({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:ai({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=tx(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:ai({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:ai({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function ex(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-af),endLine:n+af}}function tx(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return nx(e?.metavars);if(!t.matchWindow)return t.onlyMatching?Fc(e?.value):Fc(t.keywords)}}function nx(e){if(e)for(let t of Object.values(e))for(let n of t){let r=Fc(n);if(r)return r}}function Fc(e){if(typeof e!="string")return;let t=e.trim();if(Jw.test(t)&&!Xw.has(t))return t}function ai(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function rx(e){let t=e.rankingProfile,n=!!(e.include?.length||of(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var af,Xw,Jw,li=y(()=>{"use strict";Lr();sf();af=8,Xw=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"]),Jw=/^[A-Za-z_$][A-Za-z0-9_$]*$/});import{createRequire as ox}from"node:module";function X(){if(ui)return ui;try{return ui=sx(),ui}catch(e){throw new Mc(e)}}var ix,lf,ui,sx,Mc,M,ge=y(()=>{"use strict";ix=ox(import.meta.url),lf="@octocodeai/octocode-engine",sx=()=>ix(lf),Mc=class extends Error{constructor(n){super(`Failed to load native dependency ${lf}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};M={applyContentViewMinification(e,t){return X().applyContentViewMinification(e,t)},applyMinification(e,t){return X().applyMinification(e,t)},minifyContent(e,t){return X().minifyContent(e,t)},minifyContentSync(e,t){return X().minifyContentSync(e,t)},minifyContentResult(e,t){return X().minifyContentResult(e,t)},minifyMarkdownCore(e){return X().minifyMarkdownCore(e)},extractSignatures(e,t){return X().extractSignatures(e,t)},extractJsSymbols(e,t){return X().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return X().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return X().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return X().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return X().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return X().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return X().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return X().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return X().getSupportedStructuralExtensions()},inspectBinaryNative(e){return X().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return X().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return X().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return X().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return X().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return X().parseRipgrepJson(e,t)},searchRipgrep(e){return X().searchRipgrep(e)},queryFileSystem(e){return X().queryFileSystem(e)},extractMatchingLines(e,t,n){return X().extractMatchingLines(e,t,n)},filterPatch(e,t){return X().filterPatch(e,t)},charToByteOffset(e,t){return X().charToByteOffset(e,t)},byteToCharOffset(e,t){return X().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return X().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return X().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return X().SIGNATURES_ONLY_HINT}}});function uf(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&&ax(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&cx(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function ax(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function cx(e){return/\(\?[=!<]/.test(e)}var df=y(()=>{"use strict";ge()});import{validateRipgrepQuery as lx}from"@octocodeai/octocode-core/schemas/runtime";function ux(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function dx(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:ux(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 px(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 pf(e){let t=[],n=lx(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=Ht.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=ze(o,A.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=uf({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(dx(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 P={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(P.count=b.count),b.kind!==void 0&&(P.kind=b.kind),b.scoreHint!==void 0&&(P.scoreHint=b.scoreHint),P})})),p=px(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 $({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>ft.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await ci(d,o,"rg",[...t,...l],f);return $(m,p)}var ff=y(()=>{"use strict";Ct();Ar();Lr();de();li();df();oe();ge()});import{readFile as fx,stat as mx}from"node:fs/promises";function bx(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function gf(e){return e.include?.length?e.include:Cd(e.langType)}async function Rx(e){try{return(await mx(e)).isFile()}catch{return!1}}async function Sx(e,t){let n=await fx(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 hf(e){let t=ze(e,A.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await Rx(t.sanitizedPath)?await Sx(t.sanitizedPath,e):M.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...gf(e)?{include:gf(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:mf.length?{excludeDir:mf}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??gx,maxFileBytes:hx})}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(`
14
+ `,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(yx+bx(e.pattern)),await ci(r,e,"structural",i,o)}var mf,gx,hx,yx,yf=y(()=>{"use strict";ge();Ct();de();ka();li();mf=[],gx=2e3,hx=1e6,yx="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 Px(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 zt(e){let t=Px(e);if(t.mode==="structural")return await hf(t);t.contextLines===void 0&&(t.contextLines=2);try{return await pf(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:B.OUTPUT_TOO_LARGE}:F(n,t,{toolName:A.LOCAL_RIPGREP})}}var Dc=y(()=>{"use strict";Ct();En();de();ff();yf()});function Nn(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 Ir(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 di=y(()=>{"use strict"});function xx(e,t){let n=t??wx,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Gn(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=ze(e,A.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:xx(i.path,i.excludeDir)},a=vx(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:1e4}),u=l.totalDiscovered,d=l.wasCapped,p=l.entries.map(z=>kx(z,r)),f=e.sortBy||"modified";Tx(p,f,r);let m=p.slice(0,c),g=Ex(m,t,n),b=g.length,P=e.itemsPerPage||20,S=e.page||1,T=Math.max(1,Math.ceil(b/P)),L=(S-1)*P,E=Math.min(L+P,b),x=g.slice(L,E),N=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],I=[...a,...N],v={...b===0?{status:"empty"}:{},path:i.path,files:x,pagination:{currentPage:S,totalPages:T,filesPerPage:P,totalFiles:b,hasMore:S<T,...S<T?{nextPage:S+1}:{},...d||u>b?{totalFilesFound:u}:{}},...I.length>0&&{warnings:I}};return $(bf(v,e,{totalFiles:b}),l.entries.reduce((z,H)=>z+H.path.length,0))}catch(o){return F(o,e,{toolName:A.LOCAL_FIND_FILES})}}function kx(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 bf(e,t,n){return e}function Tx(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 Ex(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=Nn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function vx(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&&!Ox.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 wx,Ox,pi=y(()=>{"use strict";Ct();di();ge();de();fe();oe();wx=[];Ox=/^\d+[hdwm]$/});function _x(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function Rf(e,t){let n=e[t];return n===void 0?!1:Ax.has(n)||n==="{"&&Mx(e,t)}function Ix(e,t,n){let r=n.pop()??!1,o=Rf(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?Pf(e,t+1):t+1})}function Fx(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:Pf(e,t)})}function Sf(e){if(e.length>Lx)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=_x(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=Ix(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(Rf(e,r)){let i=Fx(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function Mx(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 Pf(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}var Ax,Lx,Cf=y(()=>{"use strict";Ax=new Set(["+","*","?"]),Lx=1e3});function wf(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(!Sf(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 xf(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 kf(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 Tf=y(()=>{"use strict";Cf()});function Ef(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+Ir(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${Nn(r)})`}function Of(e,t){let n=e.length,r=t.itemsPerPage||ft.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 vf(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 Af=y(()=>{"use strict";Lr();di()});async function fi(e){try{let t=ze(e,A.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return Dx(e,t.sanitizedPath,n)}catch(t){let n=nt.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function Dx(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=Gx(e),s=r&&e.limit&&!Nx(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:Hx(e),limit:s})}catch(T){return Qx(T,e,t)}let c=a.entries.map(T=>zx(T,n,e.details??!1)),l=wf(c,e),u=e.sortBy??"name";l=l.sort((T,L)=>{let E=0;switch(u){case"size":{let O=T.sizeBytes??(T.size?Ir(T.size):0),x=L.sizeBytes??(L.size?Ir(L.size):0);E=O-x;break}case"time":n&&T.modified&&L.modified?E=T.modified.localeCompare(L.modified):E=T.name.localeCompare(L.name);break;case"extension":E=(T.extension||"").localeCompare(L.extension||"");break;default:E=T.name.localeCompare(L.name);break}return e.reverse?-E:E}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=Of(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(T=>({...kf(T),path:T.path??`${t.replace(/\/$/,"")}/${T.name}`}))}:{path:t,...xf(p)},b=[...a.warnings,...vf({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.`]:[]],P=d===0,S=Ef(l);return $(Lf({...P?{status:"empty"}:{},...g,summary:S,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((T,L)=>T+L.path.length,0))}function Nx(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function Gx(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function Hx(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function zx(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:Nn(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=Bx(e.permissions)),o}function Bx(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 Qx(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=nt.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 Lf(e,t){return e}var mi=y(()=>{"use strict";di();de();Ct();Bo();Tf();Af();oe();ge()});function gi(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(`
15
+ `),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 Nc=y(()=>{"use strict";ge()});function Gc(e,t){return M.byteToCharOffset(e,t)}function _f(e,t){return M.charToByteOffset(e,t)}function If(e){return M.charToByteOffset(e,e.length)}function Hc(e,t,n,r){return M.sliceContent(e,t,n,r)}var Ff=y(()=>{"use strict";ge()});function Hn(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=If(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),P=Math.min(b+n,s);d=Gc(e,b),p=Gc(e,P),p<i&&_f(e,p)<P&&(p+=1);let S=Hc(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 T=r.actualOffset??b;m=Math.floor(T/a)+1,g=Math.max(m,Math.ceil(s/a))}else{let b=Hc(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 P=r.actualOffset??d;m=Math.floor(P/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 Mf(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 hi=y(()=>{"use strict";Ff()});function jx(e){return e&&e.trim().length>0?e:$x}function Df(e,t){return M.getSemanticBoundaryOffsets(e,jx(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function qx(e,t){let n=e.indexOf(`
16
+ `,t);return n===-1?void 0:n+1}function yi(e){let t=e.trimEnd().split(`
17
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function bi(e,t,n){let r=qx(e,Math.max(0,t));if(r!==void 0)return Df(e,n).find(o=>o>=r&&o>t)}function Ri(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=Df(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<=Ux?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var Ux,$x,zc=y(()=>{"use strict";ge();Ux=8e3,$x="__octocode_generic__.unknown"});function Fr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function wt(e){return Fr(e).length}var Mr=y(()=>{"use strict"});function rt(){try{return Oe().output.pagination.defaultCharLength}catch{return Gt.pagination.defaultCharLength}}var Dr=y(()=>{"use strict";Fe();Fe()});function Nf(e,t){return n=>t}var Gf=y(()=>{"use strict"});function Wx(e){return Vx.test(e.split(/[?#]/,1)[0]??e)}function Hf(e,t){return Wx(t)?Yx(Kx(e)):null}function Si(e,t){let n=Hf(e,t);if(n===null||n.length===0)return null;let r=[];return Bf(n,r),r.join(`
18
+ `)}function zf(e,t){let n=Hf(e,t);return n===null?null:n.map(Qf)}function Kx(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 Yx(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 Bf(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}`),Bf(n.children,t)}}function Qf(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(Qf)}}var Vx,Pi=y(()=>{"use strict";Vx=/\.(?:md|markdown|mdx)$/i});import{open as Xx,readFile as Jx,stat as Zx}from"fs/promises";import{ContentSanitizer as ek}from"@octocodeai/octocode-engine/contentSanitizer";function Bc(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Uf(e,t,n){return{...e,...Bc(t,n)}}function tk(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 nk(e,t){try{return{fileStats:await Zx(t)}}catch(n){let r=nt.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:F(r,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function rk(e,t){return t>ft.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function ok(e,t,n){let r=nt.fileTooLarge(e.path,n,ft.LARGE_FILE_THRESHOLD_KB);return F(r,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function ik(e,t){let n=nt.binaryFileUnsupported(e.path);return F(n,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function sk(e){let n=Buffer.alloc(8192),r;try{r=await Xx(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(Nf("binary sample handle close",void 0))}}async function ak(e,t){try{return{content:await Jx(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?nt.fileAccessFailed(e.path,r):nt.fileReadFailed(e.path,r);return{errorResult:F(i,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function ck(e,t){return{status:"empty",errorCode:B.NO_MATCHES,totalLines:t}}function lk(e,t,n){let r=gi(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:ck(e,n)};let o=r.lines.join(`
19
+ `),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 uk(e){return e.startLine!==void 0&&e.endLine!==void 0}function dk(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:B.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:B.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(`
20
+ `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function pk(e,t,n){let r=t.split(`
21
+ `),o=wt(t);return e.matchString?lk(e,r,o):uk(e)?dk(e,r,o):{resultContent:t,isPartial:!1}}function fk(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&&!e.fullContent&&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=Ri(l,m,p,c);g=E.chunkMode,b=E.length}let P=Hn(l,m,b,p!==void 0?{pageSize:p}:void 0),S=t.isPartial||P.hasMore,T;if(P.hasMore&&g==="char-limit"&&yi(P.paginatedContent)){let E=P.charOffset+P.charLength;T=bi(l,E,c)}let L=P.hasMore&&P.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:P.nextCharOffset,charLength:p??P.charLength,minify:e.minify}}}:void 0;return{path:c,content:P.paginatedContent,...s!=="standard"&&{contentView:s},...S&&{isPartial:S},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:{...Mf(P),chunkMode:g,...T!==void 0&&{nextBlockChar:T}}},...L?{next:L}:{},...a.length>0&&{warnings:a}}}function mk(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function Ci(e){let t=rt();try{let n=ze(e,A.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=tk(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await nk(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await sk(o))return $(ik(e,o),c);if(rk(e,l))return $(ok(e,o,l),c);let{content:u,errorResult:d}=await ak(e,o);if(d||u===void 0)return d;let p=ek.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,P=e.minify,S=P==="standard"||P==="symbols",T=S?"standard":"none",L;if(P==="symbols"){let I=M.extractSignatures(f,i);if(I===null){let v=Si(f,i);if(v!==null)return $({path:e.path,content:v,contentView:"symbols",isSkeleton:!0,totalLines:wt(f),...Bc(m,g),...b?{warnings:[b]}:{}},m);L=`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=wt(f),z=M.applyContentViewMinification(I,i);return $({path:e.path,content:z,contentView:"symbols",isSkeleton:!0,totalLines:v,...Bc(m,g),...b?{warnings:[b]}:{}},m)}}let E=wt(f),O=pk(e,f,t),x=I=>{let v=[...L?[L]:[],...b?[b]:[]];if(v.length===0)return I;let z=I.warnings??[];return{...I,warnings:[...z,...v]}};if(O.earlyResult){let I=O.earlyResult.content,v=S&&typeof I=="string"?{...O.earlyResult,content:M.applyContentViewMinification(I,i)}:O.earlyResult;return $(Uf(x(Qc(mk(v,T),e,E)),m,g),m)}let N=fk(e,O,s,E,t,S,T);return $(Uf(x(Qc(N,e,E)),m,g),m)}catch(n){return F(n,e,{toolName:A.LOCAL_FETCH_CONTENT})}}function Qc(e,t,n){return e}var wi=y(()=>{"use strict";Nc();ge();hi();zc();Lr();Mr();Dr();de();Ct();Bo();En();Gf();oe();Pi()});function xt(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 xi=y(()=>{"use strict"});function Uc(e){return xt(e)}function gk(e){if(e)return xt({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 ki(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:hk(gk(e.pagination),n.length)}}function hk(e,t){if(e)return e.totalItemsKind!=="files"?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function Ti(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:Uc(e.pagination)}}function $f(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:Uc(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=bk(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:Uc(e.pagination)}}function bk(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=yk[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function jf(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 yk,qf=y(()=>{"use strict";xi();yk={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import vi from"node:path";import Rk from"node:fs";function Sk(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 Li(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 Kf(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function _i(e,t,n){if(n){e.langType=n;return}let r=Ca(Tn(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=Kf(e.include,r.include))}function Pk(e){return wa(Tn(e))}function Vf(e){let t=Ai(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function Ii(e){return!!(e?.include?.length||e?.exclude?.length)}function qc(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(Vf).filter(i=>!!i);n.length>0&&!e.names&&(e.names=Kf(e.names,n));let r=(t?.include??[]).filter(i=>!Vf(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=Pk(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function Ck(e,t){if(Ii(t.scope)){Vc(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function Vc(e){e.limit=$c,e.itemsPerPage=$c}async function Gr(e){let t=e.from,n=Sk(e),r=Xe(e.scope),o=r?vi.join(n,r):n;if(!Rk.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 Tk(e,t,o);case"structure":return Dk(e,t,o);case"content":return Nk(e,t,o);default:return Xf(e,t,o)}}function wk(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?Jf(e.predicate):!1}function xk(e){return e.kind==="text"||e.kind==="regex"}function Yf(e){return e?.kind==="not"&&xk(e.predicate)}async function Xf(e,t,n){let r=e.where;if(wk(r))return Fk(e,t,n,r);if(e.view==="discovery"&&Yf(r))return vk(e,t,n,r);let o=en(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,...Li(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...om(e)};_i(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 zt(s),c=ki(a,t),l=zn(a,"localSearchCode"),u=kk(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:[Bn("localSearchCode",t,r)]}}function kk(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 Tk(e,t,n){let r=e.where;if(Yf(r))return Ok(e,t,n,r);if(r&&Jf(r))return Ek(e,t,n,r);if(r&&nm(r)){let l=await Xf({...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};qc(o,e.scope),Ck(o,e);let i=[];r&&rm(r,o,i);let s=await Gn(o),a=Kc(s,e,n);return{...Ti(a,t),diagnostics:[...i,...zn(a,"localFindFiles")],provenance:[Bn("localFindFiles",t,r)]}}function Jf(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function Ek(e,t,n,r){let o=[],i=[],a=[...(await Ei(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 Ei(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Ei(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:Ak(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Ei(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,Wc(a.get(l),u));return a}case"not":{let s=await em(e,n,r,o),a=await Ei(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return tm(e,t,n,r,o,i)}}async function Ok(e,t,n,r){let o=await zt(Zf(e,n,r.predicate)),i=zn(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[Bn("localSearchCode",t,r)]}}async function vk(e,t,n,r){let o=await zt(Zf(e,n,r.predicate));return{...ki(o,t),diagnostics:zn(o,"localSearchCode"),provenance:[Bn("localSearchCode",t,r)]}}function Zf(e,t,n){let o=en(n).match,i={path:t,filesWithoutMatch:!0,...Li(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...om(e)};return _i(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 Ak(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,Wc(o,i))}return n}function Lk(e,t){return new Set([...e].filter(n=>t.has(n)))}function Wc(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 _k(e,t,n){return new Set((await em(e,e.from,t,n)).keys())}async function em(e,t,n,r){let o={path:n,entryType:"f"};qc(o,e.scope),Ii(e.scope)&&(Vc(o),o.page=1);let i=await Gn(o),s=Kc(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),jc(Ti({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function Ik(e,t,n,r,o){return new Set((await tm(e,t,e.from,n,r,o)).keys())}async function tm(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};qc(u,e.scope),rm(t,u,i),Ii(e.scope)&&(Vc(u),u.page=1);let d=await Gn(u),p=Kc(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),jc(Ti(p,n).results)}let s=en(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:$c,...Li(e.scope)};_i(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 zt(c);return o.push({backend:"localSearchCode",source:e.from}),jc((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function jc(e){let t=new Map;for(let n of e)t.set(n.path,Wc(t.get(n.path),n));return t}async function Fk(e,t,n,r){let o=[],i=[],s=await Oi(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 Oi(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Oi(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:Lk(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Oi(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 _k(e,r,o),a=await Oi(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await Ik(e,t,r,o,i),rows:[]};default:{let s=await Mk(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function Mk(e,t,n,r,o,i){let s=en(t);if(s.unsupported)return i.push(w(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...Li(e.scope)};_i(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 zt(c);return o.push({backend:"localSearchCode",source:n}),ki(l,n).results}async function Dk(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 fi(r);return{...$f(o,t),diagnostics:zn(o,"localViewStructure"),provenance:[Bn("localViewStructure",t,void 0)]}}async function Nk(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=Qk(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 Ci(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...jf(a,t,n,c),diagnostics:zn(a,"localGetFileContent"),provenance:[Bn("localGetFileContent",t,void 0)]}}function Kc(e,t,n){if(!Ii(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>Gk(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 Gk(e,t,n){let r=Ai(Hk(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>Wf(r,i))?!1:!(n?.exclude??[]).some(i=>Wf(r,i))}function Hk(e,t){let n=vi.relative(t,e);return!n||n.startsWith("..")||vi.isAbsolute(n)?e:n}function Ai(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Wf(e,t){let n=Ai(t),r=Ai(e),o=zk(n);return o.test(r)?!0:n.includes("/")?!1:o.test(vi.posix.basename(r))}function zk(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+=Bk(r)}return new RegExp(`${t}$`)}function Bk(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function Qk(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 nm(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?nm(e.predicate):!1}function rm(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(Nr(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(Nr(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(Nr(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(Nr(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(Nr(i));break}r&&n.push(w("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function Nr(e){return w("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function om(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 zn(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(Uk(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function Uk(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 Bn(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var $c,Yc=y(()=>{"use strict";fe();Dc();pi();mi();wi();Sa();qf();tt();Fo();ur();$c=1e4});import{completeMetadata as $k}from"@octocodeai/octocode-core";var J,Me,Qn,lQ,Fi=y(()=>{"use strict";J=$k.toolNames,Me=J.LSP_GET_SEMANTIC_CONTENT,Qn="oqlSearch",lQ=new Set([J.LOCAL_RIPGREP,J.LOCAL_FETCH_CONTENT,J.LOCAL_FIND_FILES,J.LOCAL_VIEW_STRUCTURE,J.LOCAL_BINARY_INSPECT,Me])});function sn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Xc(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 im,Un=y(()=>{"use strict";Fi();im=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{z as Te}from"zod";var jk,Qe,Qt=y(()=>{"use strict";jk=Te.object({currentPage:Te.number(),totalPages:Te.number(),hasMore:Te.boolean(),charOffset:Te.number(),charLength:Te.number(),totalChars:Te.number(),nextCharOffset:Te.number().optional()}).optional(),Qe={hints:Te.array(Te.string()).optional(),base:Te.string().optional(),shared:Te.record(Te.string(),Te.union([Te.string(),Te.number(),Te.boolean()])).optional(),responsePagination:jk}});import{CloneRepoQuerySchema as qk}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as Vk}from"@octocodeai/octocode-core/schemas/outputs";var Hr,Mi,SQ,Jc=y(()=>{"use strict";Be();Je();Qt();Hr=le(qk),Mi=te(Hr),SQ=Vk.extend(Qe)});import{z as k}from"zod";import{FileContentQuerySchema as sm}from"@octocodeai/octocode-core/schemas";var Wk,Kk,Yk,Xk,am,Jk,$n,Di,OQ,Ni=y(()=>{"use strict";fe();Be();Je();Qt();Wk=k.enum(["none","standard","symbols"]).optional().default("standard"),Kk=k.object({currentPage:k.number(),totalPages:k.number(),hasMore:k.boolean(),nextPage:k.number().optional(),nextMatchPage:k.number().optional(),charOffset:k.number().optional(),charLength:k.number().optional(),totalChars:k.number().optional(),nextCharOffset:k.number().optional(),filesPerPage:k.number().optional(),totalFiles:k.number().optional(),entriesPerPage:k.number().optional(),totalEntries:k.number().optional(),matchesPerPage:k.number().optional(),totalMatches:k.number().optional()}),Yk=k.object({path:k.string(),content:k.string(),localPath:k.string().optional(),repoRoot:k.string().optional(),contentView:k.enum(["none","standard","symbols"]).optional(),isSkeleton:k.boolean().optional(),totalLines:k.number().optional(),sourceChars:k.number().optional(),sourceBytes:k.number().optional(),resolvedBranch:k.string().optional(),pagination:Kk.optional(),isPartial:k.boolean().optional(),startLine:k.number().optional(),endLine:k.number().optional(),matchRanges:k.array(k.object({start:k.number(),end:k.number()})).optional(),lastModified:k.string().optional(),lastModifiedBy:k.string().optional(),warnings:k.array(k.string()).optional(),matchNotFound:k.boolean().optional(),searchedFor:k.string().optional(),cached:k.boolean().optional()}),Xk=k.object({path:k.string(),localPath:k.string(),repoRoot:k.string().optional(),fileCount:k.number(),totalSize:k.number(),complete:k.boolean().optional(),directoryEntryCount:k.number().optional(),eligibleFileCount:k.number().optional(),savedFileCount:k.number().optional(),skipped:k.object({nonFile:k.number(),missingDownloadUrl:k.number(),oversized:k.number(),binary:k.number(),fileLimit:k.number(),fetchFailed:k.number(),totalSizeLimit:k.number(),pathTraversal:k.number()}).optional(),limits:k.object({maxDirectoryFiles:k.number(),maxTotalSize:k.number(),maxFileSize:k.number()}).optional(),warnings:k.array(k.string()).optional(),files:k.array(k.object({path:k.string(),size:k.number(),type:k.string()})).optional(),cached:k.boolean().optional(),resolvedBranch:k.string().optional()}),am={startLine:Mn,endLine:Mn,contextLines:Fn,charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:Wk},Jk=pe(sm,am),$n=le(sm,am),Di=te(Jk),OQ=k.object({base:k.string().optional(),shared:k.record(k.string(),k.union([k.string(),k.number(),k.boolean()])).optional(),responsePagination:Qe.responsePagination,results:k.array(k.object({id:k.string(),data:k.object({owner:k.string(),repo:k.string(),files:k.array(Yk).optional(),directories:k.array(Xk).optional()}).optional()})),errors:k.array(k.object({id:k.string(),owner:k.string().optional(),repo:k.string().optional(),path:k.string().optional(),error:k.string()})).optional()})});import{z as D}from"zod";import{GitHubCodeSearchQuerySchema as cm}from"@octocodeai/octocode-core/schemas";var lm,Gi,Hi,DQ,Zc=y(()=>{"use strict";fe();Be();Je();Qt();lm={limit:G(1,100).optional(),page:ie.default(1)},Gi=le(cm,lm),Hi=te(pe(cm,lm)),DQ=D.object({base:D.string().optional(),shared:D.record(D.string(),D.union([D.string(),D.number(),D.boolean()])).optional(),responsePagination:Qe.responsePagination,results:D.array(D.object({id:D.string(),data:D.object({files:D.array(D.object({owner:D.string(),repo:D.string(),path:D.string(),queryId:D.string().optional(),matches:D.array(D.object({value:D.string().optional(),pathOnly:D.boolean().optional(),matchIndices:D.array(D.object({start:D.number(),end:D.number(),lineOffset:D.number()})).optional(),url:D.string().optional()}))})),pagination:D.object({currentPage:D.number(),totalPages:D.number(),perPage:D.number(),totalMatches:D.number(),reportedTotalMatches:D.number().optional(),reachableTotalMatches:D.number().optional(),totalMatchesKind:D.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:D.boolean().optional(),hasMore:D.boolean(),nextPage:D.number().optional(),uniqueFileCount:D.number().optional()}).optional()})})),emptyQueries:D.array(D.object({id:D.string(),nonExistentScope:D.literal(!0).optional(),incompleteResults:D.literal(!0).optional()})).optional(),warnings:D.array(D.string()).optional(),errors:D.array(D.object({id:D.string(),error:D.string()})).optional()})});import{z as an}from"zod";import{GitHubPullRequestSearchQuerySchema as um}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as eT}from"@octocodeai/octocode-core/schemas/outputs";var dm,tT,qn,zi,jQ,Bi=y(()=>{"use strict";fe();Be();Je();Qt();dm={perPage:G(1,100).optional().default(30),prNumber:G(1,1e9).optional(),limit:G(1,100).optional().default(30),page:ie.default(1),filePage:ie.optional(),commentPage:ie.optional(),commitPage:ie.optional(),itemsPerPage:G(1,100).optional().default(20),charOffset:G(0,1e8).optional(),commentBodyOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional()},tT=pe(um,dm),qn=le(um,dm),zi=te(tT),jQ=eT.extend({results:an.array(an.object({id:an.string().optional(),status:an.string().optional(),data:an.object({pull_requests:an.array(an.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Qe})});import{z as q}from"zod";import{GitHubReposSearchSingleQuerySchema as pm}from"@octocodeai/octocode-core/schemas";var fm,Qi,Ui,nT,rT,oT,ZQ,el=y(()=>{"use strict";fe();Be();Je();Qt();fm={limit:G(1,100).optional(),page:ie.default(1)},Qi=le(pm,fm),Ui=te(pe(pm,fm)),nT=q.object({owner:q.string(),repo:q.string(),stars:q.number().optional(),forks:q.number().optional(),openIssuesCount:q.number().optional(),language:q.string().optional(),license:q.string().optional(),description:q.string().optional(),homepage:q.string().optional(),pushedAt:q.string().optional(),createdAt:q.string().optional(),defaultBranch:q.string().optional(),topics:q.array(q.string()).optional(),visibility:q.string().optional(),url:q.string().optional(),updatedAt:q.string().optional()}),rT=q.object({currentPage:q.number(),totalPages:q.number(),hasMore:q.boolean(),perPage:q.number().optional(),totalMatches:q.number().optional(),reportedTotalMatches:q.number().optional(),reachableTotalMatches:q.number().optional(),totalMatchesKind:q.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:q.boolean().optional(),nextPage:q.number().optional()}).optional(),oT=q.object({repositories:q.array(q.union([q.string(),nT])).optional(),pagination:rT}).passthrough(),ZQ=q.object({results:q.array(q.object({id:q.string().optional(),status:q.string().optional(),data:oT.optional()}).passthrough()).optional()}).extend(Qe)});import{GitHubViewRepoStructureQuerySchema as mm}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as sT}from"@octocodeai/octocode-core/schemas/outputs";var gm,$i,ji,cU,tl=y(()=>{"use strict";fe();fe();Be();Je();Qt();gm={maxDepth:G(0,20).optional(),page:ie.default(1),itemsPerPage:G(1,200).optional()},$i=le(mm,gm),ji=te(pe(mm,gm)),cU=sT.extend(Qe)});import{z as V}from"zod";import{NpmPackageQuerySchema as hm}from"@octocodeai/octocode-core/schemas";var ym,qi,Vi,gU,nl=y(()=>{"use strict";Be();Je();Qt();ym={page:ie,mode:V.enum(["lean","full"]).optional()},qi=le(hm,ym),Vi=te(pe(hm,ym,{strict:!0}),{maxQueries:5}),gU=V.object({results:V.array(V.looseObject({id:V.string(),data:V.looseObject({packages:V.array(V.object({name:V.string(),version:V.string().optional(),description:V.string().optional(),license:V.string().optional(),downloads:V.number().optional(),repository:V.string().optional(),repositoryDirectory:V.string().optional(),repositoryId:V.string().optional(),next:V.record(V.string(),V.unknown()).optional()}).passthrough()).optional(),repositories:V.record(V.string(),V.object({repository:V.string(),owner:V.string(),repo:V.string(),repositoryDirectory:V.string().optional(),next:V.record(V.string(),V.unknown())}).passthrough()).optional(),pagination:V.object({currentPage:V.number(),totalPages:V.number(),perPage:V.number(),totalFound:V.number(),returned:V.number(),hasMore:V.boolean(),nextPage:V.number().optional()}).optional()}).optional(),status:V.string().optional()})).optional()}).extend(Qe)});import{z as aT}from"zod";import{FetchContentQuerySchema as bm}from"@octocodeai/octocode-core/schemas";var cT,Rm,lT,Vn,Wi,Ki=y(()=>{"use strict";fe();Be();Je();cT=aT.enum(["none","standard","symbols"]).optional().default("standard"),Rm={startLine:Mn,endLine:Mn,contextLines:Fn.default(5),charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:cT},lT=pe(bm,Rm),Vn=le(bm,Rm),Wi=te(lT,{maxQueries:5})});import{z as uT}from"zod";import{FindFilesQuerySchema as dT}from"@octocodeai/octocode-core/schemas";function pT(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 Sm,Pm,fT,Wn,Yi,Xi=y(()=>{"use strict";fe();Be();Je();Sm={maxDepth:G(0,100).optional(),minDepth:G(0,100).optional(),limit:G(1,1e4).optional(),page:ie.default(1),itemsPerPage:G(1,50).optional()},Pm=uT.object(Object.fromEntries(Object.entries(dT.shape).filter(([e])=>e!=="regexType")));fT=pe(Pm,Sm),Wn=le(Pm,Sm).superRefine(pT),Yi=te(fT,{maxQueries:5})});import{ViewStructureQuerySchema as Cm}from"@octocodeai/octocode-core/schemas";var wm,mT,Kn,Ji,Zi=y(()=>{"use strict";fe();Be();Je();wm={maxDepth:G(0,20).optional(),limit:G(1,1e4).optional(),page:ie.default(1),itemsPerPage:G(1,50).optional()},mT=pe(Cm,wm),Kn=le(Cm,wm),Ji=te(mT,{maxQueries:5})});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as Tm}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as gT}from"@octocodeai/octocode-core/schemas/outputs";var hT,yT,bT,Em,RT,ns,rs,xm,ST,PT,es,ts,CT,wT,Om,Yn,xT,kT,TT,vm,ET,OT,vT,AT,LT,_T,IT,km,BU,ol=y(()=>{"use strict";fe();Be();Je();Un();hT=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."),yT=G(0,1e5).optional(),bT=["structured","compact"],Em={type:R.enum(im).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:hT.optional(),orderHint:yT,depth:G(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:ie,itemsPerPage:G(1,100).optional(),contextLines:G(0,100).optional(),format:R.enum(bT).optional().default("structured")},RT=pe(Tm,Em),ns=le(Tm,Em),rs=te(RT,{maxQueries:5}),xm=R.object({line:R.number(),character:R.number()}),ST=R.object({start:xm,end:xm}),PT=R.object({startLine:R.number(),endLine:R.number()}),es=R.object({uri:R.string(),content:R.string().optional(),displayRange:PT.optional(),isDefinition:R.boolean().optional()}),ts=R.string(),CT=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),wT=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),Om=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Yn=R.object({category:Om,reason:R.string()}),xT=R.object({currentPage:R.number(),totalPages:R.number(),totalResults:R.number(),hasMore:R.boolean(),itemsPerPage:R.number(),nextPage:R.number().optional()}),kT=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),TT=R.string(),vm=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),ET=R.string(),OT=R.object({direction:R.enum(["incoming","outgoing"]),item:vm,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),vT=R.string(),AT=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),LT=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),_T=R.string(),IT=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([es,ts]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([es,ts]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([es,ts]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([es,ts])).optional(),byFile:R.array(R.union([LT,_T])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:Yn.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([vm,ET]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([OT,vT])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:AT,empty:Yn.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:ST.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([kT,TT])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:Yn.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:Yn.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:Yn.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:Yn.optional()}),R.object({kind:R.literal("empty"),category:Om,reason:R.string()})]),km=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:CT.optional(),lsp:wT,payload:IT,pagination:xT.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),BU=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:km}),R.object({id:R.string().min(1),status:R.literal("error"),data:gT}),R.object({id:R.string().min(1),data:km})]))})});import{z as Am}from"zod";import{LocalBinaryInspectQuerySchema as FT}from"@octocodeai/octocode-core/schemas";var MT,Lm,Xn,os,is=y(()=>{"use strict";Be();MT={entryPageNumber:ie.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:ie.default(1).describe("1-based page for paginated entry/content listings."),detailed:Am.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Lm=Am.object({...FT.shape,...MT}),Xn=Lm.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".'})}),os=te(Lm,{maxQueries:5})});import{z as WU}from"zod";var d$,DT,p$,f$,il=y(()=>{"use strict";Fi();Un();Jc();Ni();Zc();Bi();el();tl();nl();Ki();Xi();Ar();Zi();ol();is();Cn();d$=new Map([J.GITHUB_SEARCH_CODE,J.GITHUB_SEARCH_REPOSITORIES,J.GITHUB_SEARCH_PULL_REQUESTS,J.GITHUB_FETCH_CONTENT,J.GITHUB_VIEW_REPO_STRUCTURE,J.GITHUB_CLONE_REPO,J.LOCAL_RIPGREP,J.LOCAL_FIND_FILES,J.LOCAL_FETCH_CONTENT,J.LOCAL_VIEW_STRUCTURE,Me,J.PACKAGE_SEARCH,Qn].map((e,t)=>[e,t])),DT=["id","mainResearchGoal","researchGoal","reasoning"],p$=new Set([...DT]),f$=[{name:J.GITHUB_SEARCH_CODE,schema:Gi,inputSchema:Hi},{name:J.GITHUB_FETCH_CONTENT,schema:$n,inputSchema:Di},{name:J.GITHUB_VIEW_REPO_STRUCTURE,schema:$i,inputSchema:ji},{name:J.GITHUB_SEARCH_REPOSITORIES,schema:Qi,inputSchema:Ui},{name:J.GITHUB_SEARCH_PULL_REQUESTS,schema:qn,inputSchema:zi},{name:J.PACKAGE_SEARCH,schema:qi,inputSchema:Vi},{name:J.GITHUB_CLONE_REPO,schema:Hr,inputSchema:Mi},{name:J.LOCAL_RIPGREP,schema:Ht,inputSchema:si},{name:J.LOCAL_VIEW_STRUCTURE,schema:Kn,inputSchema:Ji},{name:J.LOCAL_FIND_FILES,schema:Wn,inputSchema:Yi},{name:J.LOCAL_FETCH_CONTENT,schema:Vn,inputSchema:Wi},{name:Me,schema:ns,inputSchema:rs},{name:J.LOCAL_BINARY_INSPECT,schema:Xn,inputSchema:os},{name:Qn,schema:Oo,inputSchema:Jt}]});var cn,ss=y(()=>{cn="16.6.2"});var sl,Qr,Ur,GT,Ut,Jn,Ue,HT,$r,zT,h$,mt=y(()=>{"use strict";sl={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},Qr={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"}},Ur={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})`}},GT={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"}},Ut={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}`}},Jn={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"}},Ue={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}`}},HT={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}`}},$r={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"}},zT={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}`}},h$={...sl,...Qr,...Ur,...GT,...Ut,...Jn,...Ue,...HT,...$r,...zT}});import{maskSensitiveData as BT}from"@octocodeai/octocode-engine/mask";async function _m(){try{let e=await QT({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:UT.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Im(){if(qr!==null)return;if(jr!==null)return jr;let e=(async()=>{let t=Oe(),n=await _m();qr={version:cn,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}})();jr=e;try{await e}catch(t){throw jr===e&&(qr=null,jr=null),t}}function Fm(){if(!qr){let e=BT(sl.NOT_INITIALIZED.message);throw new Error(e)}return qr}async function Mm(){return(await _m()).token}function al(){return"github"}function cl(){let e=Oe().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var qr,jr,QT,UT,Vr=y(()=>{"use strict";Fe();ss();mt();qr=null,jr=null,QT=Vo,UT=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});function $t(e){(e.provider?Nt({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):ac(1)).session&&e.provider==="github"&&uc(1)}function Dm(e){Nt({packageRegistryFailures:{[e]:1}})}var as=y(()=>{"use strict";Fe()});import{Octokit as $T}from"octokit";import{throttling as jT}from"@octokit/plugin-throttling";import{createHash as qT}from"crypto";function VT(e){return qT("sha256").update(e).digest("hex").substring(0,16)}function Bm(e){return Date.now()-e.createdAt>KT}function Qm(){for(let[e,t]of kt.entries())Bm(t)&&kt.delete(e);if(kt.size>ll){let e=[...kt.entries()].sort((n,r)=>n[1].createdAt-r[1].createdAt),t=kt.size-ll;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&kt.delete(r[0])}}}function XT(){Wr||(Wr=setInterval(Qm,YT),typeof Wr=="object"&&"unref"in Wr&&Wr.unref())}function Hm(e,t,n){$t({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function ZT(e){let t=Fm(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${cn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:JT(),log:r,...e&&{auth:e}};return new WT(o)}async function ue(e){XT();let t=e?.token??await Mm(),n=t?VT(t):"ANONYMOUS",r=kt.get(n);if(r&&!Bm(r))return r.client;kt.size>=ll&&Qm();let o=ZT(t??void 0);return kt.set(n,{client:o,createdAt:Date.now()}),o}async function Ze(e,t,n){let r=`${e}/${t}`,o=Kr.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 zm(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}),zm(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 zm(e,t){if(Kr.size>=eE){let n=Kr.keys().next().value;n!==void 0&&Kr.delete(n)}Kr.set(e,t)}var WT,KT,ll,YT,kt,Wr,Nm,Gm,JT,eE,Kr,$e=y(()=>{"use strict";Vr();Vr();ss();as();WT=$T.plugin(jT),KT=300*1e3,ll=50,YT=60*1e3;kt=new Map,Wr=null;Nm=3,Gm=60;JT=()=>({onRateLimit:(e,t,n,r)=>(Hm("primary",e,t),r<Nm&&e<Gm),onSecondaryRateLimit:(e,t,n,r)=>(Hm("secondary",e,t),r<Nm&&e<Gm)});eE=200,Kr=new Map});var j,ye,Um,ul,dl,cs,$m=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."}},Um={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},ul={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},dl={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},cs={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as jm}from"octokit";function ln(e){if(!(e instanceof jm)||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 tE.some(o=>r.includes(o))})}function ne(e){return e instanceof jm?nE(e):e instanceof Error?uE(e):{error:typeof e=="string"?e:ye[j.UNKNOWN].message,type:"unknown"}}function nE(e){let{status:t,message:n,response:r}=e;if(t===403)return oE(n,r);if(t===429)return rE(n,r);let o=Um[t];return o?lE(o,t):Zn(j.UNKNOWN,{error:n||ye[j.UNKNOWN].message,status:t})}function pl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function rE(e,t){let n=t?.headers,r=pl(n,"retry-after"),o=pl(n,"x-ratelimit-reset"),i=pl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+cs.RESET_BUFFER_SECONDS,0):void 0);return $t({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),Zn(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 oE(e,t){let n=t?.headers;if(dl.SECONDARY.test(e))return iE(n);let r=n?.["x-ratelimit-remaining"],o=cE(t);return r!==void 0&&String(r)==="0"||o?sE(n):aE(n)}function iE(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?cs.SECONDARY_FALLBACK_SECONDS:t;return $t({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),Zn(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 sE(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)+cs.RESET_BUFFER_SECONDS,0):void 0,i=r?ye[j.RATE_LIMIT_PRIMARY].messageWithTime(r,o):ye[j.RATE_LIMIT_PRIMARY].messageWithoutTime;return $t({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),Zn(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 aE(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=ye[j.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=dE(String(t),String(n))),Zn(j.FORBIDDEN_PERMISSIONS,{error:ye[j.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function cE(e){return e?.data?.errors?.some(n=>n.type===dl.GRAPHQL_TYPE)??!1}function lE(e,t){let n=ye[e];return Zn(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function uE(e){return ul.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:ye[j.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:ye[j.NETWORK_CONNECTION_FAILED].suggestion}:ul.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 Zn(e,t){return{type:"http",...t}}function dE(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 tE,Tt=y(()=>{"use strict";$m();as();tE=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function pE(e){return`user:${e}`}function qm(e){return e.startsWith('"')||gE.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function Vm(e){return new fl().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function Wm(e){return new ml().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function Km(e){return new gl().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ym(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 fE,mE,gE,Yr,fl,ml,gl,ls=y(()=>{"use strict";fE=/[@/]/,mE=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,gE=/^[A-Za-z0-9_-]+$/;Yr=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(pE(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=fE.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},fl=class extends Yr{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(qm))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(mE):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}},ml=class extends Yr{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(qm)),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}},gl=class extends Yr{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 hE from"node-cache";import yE from"crypto";function SE(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function PE(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function CE(e){let t=SE(e);if(!(!t||!PE(t)))try{lc(t,1)}catch{}}function wE(){let e=Date.now();for(let[t,n]of Xr.entries())e-n.startedAt>RE&&Xr.delete(t)}function kE(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(xE.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function je(e,t,n){let r=hl(kE(t)),o=n?`${n}:${r}`:r,i=yE.createHash("sha256").update(o).digest("hex");return`${bE}-${e}:${i}`}function hl(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=>hl(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${hl(i,t)}`}).join(",")}}`)}function TE(e){return Xm[e]||Xm.default}function EE(e,t,n){try{return un.set(e,t,n),er.sets++,er.totalKeys=un.keys().length,!0}catch{try{let r=un.keys();for(let o of r)un.get(o);return un.set(e,t,n),er.sets++,er.totalKeys=un.keys().length,!0}catch{return!1}}}async function qe(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=un.get(e);if(i!==void 0)return er.hits++,CE(e),i}catch{}wE();let r=Xr.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||er.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=TE(l)}EE(e,i,a)}return i}finally{Xr.delete(e)}})();return Xr.set(e,{promise:o,startedAt:Date.now()}),o}var bE,RE,un,er,Xm,Xr,xE,jt=y(()=>{"use strict";Fe();bE="v1",RE=300*1e3,un=new hE({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),er={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Xm={"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},Xr=new Map;xE=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as j$,DISCOVERY_IGNORED_FILE_NAMES as q$,DISCOVERY_IGNORED_FOLDER_NAMES as V$,getDiscoveryExtension as Jm,shouldIgnoreDiscoveryDir as Jr,shouldIgnoreDiscoveryFile as tr}from"@octocodeai/octocode-engine/security";var Zr=y(()=>{"use strict"});function us(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 yl=y(()=>{"use strict"});import{ContentSanitizer as OE}from"@octocodeai/octocode-engine/contentSanitizer";async function eg(e,t,n){let r=je("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 qe(r,async()=>await vE(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function vE(e,t){try{let n=await ue(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(P=>P&&P.trim()).length===0)return{error:Ue.QUERY_EMPTY.message,type:"http",status:400};let r=Vm(e);if(!r.trim())return{error:Ue.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Zm,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 AE(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:us(a.headers),rawResponseChars:Q(a.data)}}catch(n){if(ln(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Zm,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 AE(e,t){let n=LE(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!tr(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 L=>{let E=L.fragment,O=OE.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:L.matches?.map(x=>Array.isArray(x.indices)&&x.indices.length>=2?[x.indices[0],x.indices[1]]:[0,0])||[]}})),b=g.filter(L=>L.status==="fulfilled").map(L=>L.value),P=g.filter(L=>L.status==="rejected").length;P>0&&(l+=P);let S=f,T=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},...T.length>0&&{minificationType:T.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 LE(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 Zm,tg=y(()=>{"use strict";ge();$e();Tt();ls();jt();Zr();mt();oe();yl();fe();Zm=30});function rg(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 og(e,t,n){let r=je("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 qe(r,async()=>await IE(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function _E(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]||"",P=g[1]||"";return{owner:b,repo:P,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},...rg(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 IE(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 _E({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=Wm(e);if(!i.trim())return{error:Ue.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||ng,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 L=S.full_name.split("/"),E=L[0]||"",O=L[1]||"";return{owner:E,repo:O,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},...rg(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,P=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:P,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:g+1}:{}}},status:200,headers:us(u.headers),rawResponseChars:Q(u.data)}}catch(n){if(ln(n)){let r=Math.min(e.limit||ng,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 ng,ig=y(()=>{"use strict";$e();Tt();ls();jt();mt();oe();yl();fe();ng=30});function nr(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}var ds=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 FE(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 Et(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:FE(e)}}function ps(e){return ME(e)?Et({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 ME(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||DE(n)}function DE(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var gt=y(()=>{"use strict"});function sg(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 NE(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,...sg(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function GE(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,...sg(e.pagination)},nonExistentScope:e.nonExistentScope}}async function ag(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 eg(s,t);return nr(a)?Et(a):a.data?{data:NE(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 cg(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 og(n,t);return"error"in r?ps(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:GE(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??Q(r.data)}}var lg=y(()=>{"use strict";tg();ig();ds();oe();gt();gt()});import{RequestError as ug}from"octokit";async function zE(e,t,n,r,o,i,s,a){let c=await Ze(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 mg(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...fg(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function BE(e,t,n,r,o,i){let s=ne(t),a=await mg(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...fg(o,a)]),s}async function dg(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:Ut.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:Ut.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:Ut.DECODE_FAILED.message,type:"unknown",status:422}}}async function pg(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"?dg(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 QE(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 Ze(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 pg(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 fs(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 ug&&d.status===404)if(s){let p=await zE(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await BE(n,d,r,o,i,s);else{if(d instanceof ug&&d.status===413)return await QE(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:Ut.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 dg(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await pg(n,r,o,u.sha,i);else return{error:Ut.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await Ze(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:Q(u)}}return{error:Ut.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return ne(n)}}function fg(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 mg(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 bl=y(()=>{"use strict";$e();Tt();de();mt();oe()});import{ContentSanitizer as gg}from"@octocodeai/octocode-engine/contentSanitizer";function $E(){let e=rt();return Math.min(e,8e3)}function eo(e,t){return{sourceChars:e,sourceBytes:t}}function hg(e,t,n){let r=e.content??"",o=n??$E();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=Ri(r,t,o,i),c=Hn(r,t,s),l;if(c.hasMore&&a==="char-limit"&&yi(c.paginatedContent)){let u=c.charOffset+c.charLength;l=bi(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 yg(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 bg(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",P;if(p==="symbols"){let K=M.extractSignatures(e,o);if(K===null){let U=Si(e,o);if(U!==null)return{owner:t,repo:n,path:o,content:U,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:wt(e),...eo(f,m),isPartial:!1,signaturesExtracted:!0,hints:[M.SIGNATURES_ONLY_HINT]};P=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(K!==null){let U=gg.sanitizeContent(K,o),Se=M.applyContentViewMinification(U.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.'),U.hasSecrets&&Pe.push(`Secrets detected and redacted: ${U.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Se,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:wt(e),...eo(f,m),isPartial:!1,signaturesExtracted:!0,hints:Pe}}}let S=new Set,T=e,L=T.split(`
22
+ `),E=wt(T),O=e,x,N,I=!1,v;if(i)O=e;else if(l){let K=d===!0,U;try{U=gi(L,l,c,u??!1,K)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...eo(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(U.matchCount===0){let Z=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${K?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${K?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:E,...eo(f,m),matchNotFound:!0,searchedFor:l,hints:Z}}O=U.lines.join(`
23
+ `);let Se=U.matchRanges[0],Pe=U.matchRanges[U.matchRanges.length-1];s=Se.start,a=Pe.end,x=Se.start,N=Pe.end,I=!0,U.matchRanges.length>1&&(v=U.matchRanges);let At=U.matchingLines.slice(0,5).join(", "),Lt=U.matchingLines.length>5?` and ${U.matchingLines.length-5} more`:"";S.add(U.matchCount>1?`Found ${U.matchCount} occurrences of "${l}" on lines ${At}${Lt} \u2014 all shown as ${U.matchRanges.length} slice${U.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${U.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let K=s||1,U=a||E;if(K<1||K>E)O=e;else if(U<K)O=e;else{let Se=Math.max(1,K),Pe=Math.min(E,U),At=L.slice(Se-1,Pe);x=Se,N=Pe,I=!0,O=At.join(`
24
+ `),U>E&&S.add(`Requested endLine ${U} adjusted to ${E} (file end)`)}}let z=gg.sanitizeContent(O,o);if(O=g?M.applyContentViewMinification(z.content,o):z.content,z.hasSecrets&&S.add(`Secrets detected and redacted: ${z.secretsDetected.join(", ")}`),z.warnings.length>0&&z.warnings.forEach(K=>S.add(K)),E>2e3&&p!=="symbols"&&!l&&!s&&!a&&!i){let K=Math.max(1,E-200);S.add(`Large file (${E} lines) \u2014 minify:"symbols" for an export index, or startLine=${K} for the tail.`)}let H=Array.from(S);return{owner:t,repo:n,path:o,content:O,...b!=="standard"&&{contentView:b},branch:r,totalLines:E,...eo(f,m),...I&&{startLine:x,endLine:N,isPartial:I},...v&&{matchRanges:v},...H.length>0&&{matchLocations:H},...(H.length>0||P)&&{warnings:[...P?[P]:[],...H]}}}var Rg=y(()=>{"use strict";Dr();fe();ge();Mr();hi();zc();Nc();Pi()});async function Sg(e,t,n){let r=je("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await qe(r,async()=>await fs(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 bg(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:hg(c,l,u),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let m=await ue(t),g=await qe(je("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>yg(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 Pg=y(()=>{"use strict";$e();jt();bl();Rg()});function jE(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:qE(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function qE(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 Cg(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 Sg(i,t);if(nr(s))return Et(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:jE(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s.data),...a?.length?{hints:a}:{}}}var wg=y(()=>{"use strict";Pg();ds();oe();gt();gt()});function to(e,t=KE){let n=e?Fr(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function xg(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 kg(e){return e?M.filterPatch(e,{trimContext:!0,contextLines:WE}):""}var WE,KE,ms=y(()=>{"use strict";ge();Mr();WE=2,KE=20});import{ContentSanitizer as Tg}from"@octocodeai/octocode-engine/contentSanitizer";function Rl(e){let t=Tg.sanitizeContent(e.title??""),n=e.body?Tg.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 Og(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 no(e,t={}){let n=t.charOffset??0,r=t.charLength??YE,o=t.charLength??XE,i=typeof e.body=="string"?M.minifyMarkdownCore(e.body):e.body,s=Og(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((m,g)=>{let b=m.commentType==="review_inline"?0:1,P=g.commentType==="review_inline"?0:1;return b-P}),c=a.filter(m=>m.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Eg),d=u.map(m=>{let g=Og(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 ${Eg} 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 ro(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 gs(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?xg(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?kg(a.patch):a.patch}))}var YE,XE,Eg,hs=y(()=>{"use strict";ms();ge();Dr();YE=rt(),XE=Math.round(rt()/4),Eg=3});import{ContentSanitizer as Sl}from"@octocodeai/octocode-engine/contentSanitizer";function ys(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function vg(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Ag(e){let t=vg(e);return t?t.discussion!==!1:!1}function Lg(e){let t=vg(e);return t?t.reviewInline!==!1:!1}function _g(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function Ig(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Fg(e){return!!e.content?.comments?.includeBots}function Mg(e){let t=e.toLowerCase();return t.endsWith("[bot]")||JE.has(t.replace(/\[bot\]$/,""))}function Pl(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
25
+
26
+ `).trim()}async function Dg(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=>!Mg(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=M.minifyMarkdownCore(Pl(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:Sl.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:$(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Ng(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Cl(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return $(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Sl.sanitizeContent(M.minifyMarkdownCore(Pl(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return $([],0)}}async function Gg(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=>!Mg(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=M.minifyMarkdownCore(Pl(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:Sl.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:$(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:$([],0)}}}async function Hg(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Rl(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=ro(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,ys(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),ys(t))){let p=await zg(l,u,e.number);p&&(s+=ce(p)??0,p.files=gs(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=Ag(t),c=Lg(t);if(a||c){let{owner:l,repo:u}=ro(t);if(l&&u){let d=Fg(t),p=()=>Promise.resolve({comments:$([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([a?Dg(n,l,u,e.number,d):p(),c?Gg(n,l,u,e.number,d):p()]);o.comments=[...f,...g],s+=(ce(f)??0)+(ce(g)??0);let P=[m,b].filter(S=>typeof S=="string");P.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...P])}}if(Ig(t))try{let{owner:l,repo:u}=ro(t);if(l&&u){let d=await Ng(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(_g(t))try{let{owner:l,repo:u}=ro(t);if(l&&u){let d=await Bg(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 $(o,s)}async function Cl(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 zg(e,t,n,r){let o=await ue(r),{items:i,rawResponseChars:s}=await Cl(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $({total_count:i.length,files:i},s)}async function ZE(e,t,n,r){let o=await ue(r),{items:i,rawResponseChars:s}=await Cl(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $(i,s)}async function eO(e,t,n,r){try{let i=await(await ue(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return $(i.data.files||[],i.data)}catch{return null}}async function Bg(e,t,n,r,o){let i=await ZE(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 eO(e,t,l.sha,o),d=[];return u&&(s+=ce(u)??0,d=gs(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return $(c,s)}async function bs(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Rl(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,ys(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),ys(t))try{let d=await zg(a,c,e.number,r);d&&(s+=ce(d)??0,d.files=gs(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=Ag(t),u=Lg(t);if(l||u){let d=Fg(t),p=()=>Promise.resolve({comments:$([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([l?Dg(n,a,c,e.number,d):p(),u?Gg(n,a,c,e.number,d):p()]);o.comments=[...f,...g],s+=(ce(f)??0)+(ce(g)??0);let P=[m,b].filter(S=>typeof S=="string");P.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...P])}if(Ig(t))try{let d=await Ng(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(_g(t))try{let d=await Bg(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 $(o,s)}var JE,wl=y(()=>{"use strict";ge();$e();hs();oe();JE=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function tO(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 Qg(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:Ue.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:Ue.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 bs(a,e,i,t);return{pull_requests:[no(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:Q(s.data)+(ce(c)??0)}}catch(i){let s=ne(i);return tO(s,Ue.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 Ug=y(()=>{"use strict";mt();$e();Tt();jt();hs();wl();oe()});function $g(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 jg(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 nO(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 qg(e,t,n){let r=je("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 qe(r,async()=>await rO(e,t,n),{shouldCache:i=>!i.error})}async function rO(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Qg(e,t);let r=await ue(t);if(!Ym(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await oO(r,e);let i=await nO(r,e),s=Km(i);if(!s)return{pull_requests:[],total_count:0,error:Ue.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 Hg(O,i,r))),m=f.reduce((O,x)=>O+(ce(x)??0),0),g=f.map(O=>no(O,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,P=Math.min(b,1e3),S=Math.min(Math.ceil(P/c),10),T=Math.min(l,Math.max(1,S)),L=T<S,E=Math.min(P,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:T,totalPages:S,perPage:c,totalMatches:P,reportedTotalMatches:b,reachableTotalMatches:E,totalMatchesKind:"reported",totalMatchesCapped:b>P,hasMore:L,...L?{nextPage:T+1}:{}},rawResponseChars:Q(d.data)+m}}catch(r){if(ln(r))return jg(e);let o=ne(r);return $g(o,Ue.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function oO(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 bs(p,t,e))),c=a.reduce((p,f)=>p+(ce(f)??0),0),l=a.map(p=>no(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(ln(n))return jg(t);let r=ne(n);return $g(r,Ue.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var Vg=y(()=>{"use strict";fe();mt();$e();Tt();ls();jt();oe();hs();wl();Ug()});function iO(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 sO(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,...iO(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Wg(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 qg(s,t);return a.error?Et({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:sO(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??Q(a)}}var Kg=y(()=>{"use strict";Vg();oe();gt();gt()});var dn,Rs=y(()=>{"use strict";dn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function Ss(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var xl=y(()=>{"use strict"});function Yg(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:I,...v}=e;return v}let r=t.itemsPerPage??dn.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 z=v.lastIndexOf("/");return z===-1?".":v.slice(0,z)},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 z=f(I.path);I.type==="file"?u[v].files.push(z):u[v].folders.push(z)}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,P=l.filter(I=>I.type==="dir").length,S=n.filter(I=>I.type==="file").length,T=n.filter(I=>I.type==="dir").length,L=o<s,E={currentPage:o,totalPages:s,hasMore:L,...L?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},O=Ss(E,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:P,allFiles:S,allFolders:T}),x,N=e._cachedFileSizeMap;if(N){let I=new Set(l.filter(H=>H.type==="file").map(H=>H.path)),v=e.path==="/"?"":e.path,z=Object.create(null);for(let[H,K]of Object.entries(N))for(let[U,Se]of Object.entries(K)){let Pe=H==="."?v?`${v}/${U}`:U:v?`${v}/${H}/${U}`:`${H}/${U}`;I.has(Pe)&&(z[H]||(z[H]=Object.create(null)),z[H][U]=Se)}Object.keys(z).length>0&&(x=z)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:T,truncated:L,filtered:!0,originalCount:i},structure:m,...x!==void 0&&{fileSizeMap:x},...N!==void 0&&{_cachedFileSizeMap:N},pagination:E,hints:O,rawResponseChars:e.rawResponseChars}}var Xg=y(()=>{"use strict";Rs();xl()});import{RequestError as cO}from"octokit";function Jg(e){return e instanceof cO&&lO.has(e.status)}function kl(e,t){try{Object.defineProperty(e,Zg,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function Tl(e){if(typeof e!="object"||e===null)return 0;let t=e[Zg];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function El(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return kl($([],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(Jg(m))throw m;return kl($([],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 P=m.slice(b,b+g),S=await Promise.allSettled(P.map(T=>El(e,t,n,r,T.path,i+1,s,a)));for(let T of S)if(T.status==="fulfilled"){let L=T.value;l+=ce(L)??0,f+=Tl(L),p.push(...L)}else{if(Jg(T.reason))throw T.reason;f+=1}}}return kl($(p,l),f)}var Zg,lO,eh=y(()=>{"use strict";oe();Zg=Symbol.for("octocode.recursiveFetchFailures"),lO=new Set([401,403,429])});import{RequestError as uO}from"octokit";async function dO(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await Ze(t,n,i),s=a)}catch(c){let l=ne(c);return{error:Jn.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 uO&&c.status===404)){let u=ne(c);return{error:Jn.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:Jn.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function pO(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 fO(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 th(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 nh(e,t,n){let r=je("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await qe(r,async()=>await mO({...e,itemsPerPage:e.itemsPerPage??dn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Yg(o,e):o}async function mO(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 dO(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=pO(m),b=0;if(a>1){let Z=await El(n,r,o,d,c,1,a);b=Tl(Z),f+=ce(Z)??0,g=[...g,...Z].filter((cr,ko,_S)=>_S.findIndex(IS=>IS.path===cr.path)===ko)}let P=g.filter(Z=>Z.type==="dir"?!Jr(Z.name):!tr(Z.path));P.sort((Z,pt)=>{if(Z.type!==pt.type)return Z.type==="dir"?-1:1;let cr=Z.path.split("/").length,ko=pt.path.split("/").length;return cr!==ko?cr-ko:Z.path.localeCompare(pt.path)});let S=e.itemsPerPage??dn.ENTRIES_PER_PAGE,T=e.page??1,L=P.length,E=Math.max(1,Math.ceil(L/S)),O=(T-1)*S,x=Math.min(O+S,L),N=P.slice(O,x),I=fO(N,c),v=e.includeSizes===!0?th(P,c):void 0,z=v!==void 0?th(N,c):void 0,H=N.filter(Z=>Z.type==="file").length,K=N.filter(Z=>Z.type==="dir").length,U=P.filter(Z=>Z.type==="file").length,Se=P.filter(Z=>Z.type==="dir").length,Pe=T<E,At={currentPage:T,totalPages:E,hasMore:Pe,...Pe?{nextPage:T+1}:{},entriesPerPage:S,totalEntries:L},Lt=Ss(At,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:H,pageFolders:K,allFiles:U,allFolders:Se});return b>0&&Lt.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:U,totalFolders:Se,truncated:Pe,filtered:!0,originalCount:P.length},structure:I,...z!==void 0&&{fileSizeMap:z},...v!==void 0&&{_cachedFileSizeMap:v},pagination:At,hints:Lt,rawResponseChars:f,_cachedItems:P.map(Z=>({path:Z.path,type:Z.type}))}}catch(n){let r=ne(n);return{error:Jn.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var rh=y(()=>{"use strict";Rs();$e();Tt();jt();xl();Zr();mt();oe();Xg();eh()});function gO(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 oh(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 nh(i,t);return"error"in s?ps(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:gO(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??Q(s)}}var ih=y(()=>{"use strict";rh();oe();gt();gt()});var sh,ah=y(()=>{"use strict";sh={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});var Ps,ch=y(()=>{"use strict";lg();wg();Kg();ih();Tt();$e();ah();gt();Ps=class{type="github";capabilities=sh.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await ag(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Cg(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await cg(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Wg(t,this.authInfo,be)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await oh(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 Ze(n,r,this.authInfo)}handleError(t){let n=ne(t);return Et(n)}}});import{createHash as yO}from"crypto";function lh(e){return Date.now()-e.createdAt<bO}function RO(){for(let[e,t]of ht.entries())lh(t)||ht.delete(e);if(ht.size>Ol){let e=[...ht.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=ht.size-Ol;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&ht.delete(r[0])}}}function SO(e){return e?yO("sha256").update(e).digest("hex").slice(0,16):"default"}function PO(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 CO(e,t){let n=PO(t?.baseUrl||"default"),r=SO(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function vl(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=CO(e,t),r=ht.get(n);if(r&&lh(r))return r.lastAccessedAt=Date.now(),r.provider;r&&ht.delete(n),ht.size>=Ol&&RO();let o=new Ps({...t,type:e}),i=Date.now();return ht.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}async function uh(){try{return vl("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}
27
+ `),[{provider:"github",ok:!1,error:t}]}}var bO,Ol,ht,Al=y(()=>{"use strict";ch();bO=3600*1e3,Ol=20,ht=new Map});async function dh(e,t={}){if(!Array.isArray(e))throw new Error(Qr.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(Qr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(Qr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error($r.NOT_A_FUNCTION.message(l))));if(r<i.length)return wO(i,r,n,o);let s=i.map((c,l)=>ph(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 ph(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($r.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 wO(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($r.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await ph(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 fh=y(()=>{"use strict";mt()});var mh=y(()=>{"use strict"});import{ContentSanitizer as xO}from"@octocodeai/octocode-engine/contentSanitizer";function kO(){try{return Oe().output.format}catch{return"yaml"}}function yt(e){if(e==null)return e;if(typeof e=="string")return xO.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>yt(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=yt(r);return t}return e}function ws(e,t){let n=Ll(e)??{},r=yt(n),o=kO(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Cs(r,t||i),null,2):M.jsonToYamlString(r,{keysPriority:t||i})}function Cs(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Cs(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Cs(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Cs(n[o],t));return r}function EO(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=>TO.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 Ll(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=>Ll(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(EO(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Ll(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 TO,oo=y(()=>{"use strict";Fe();ge();mh();TO=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 OO(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 _l(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)_l(o,t,n+1);return}let r=e;for(let o of Il){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))gh.has(o)||i&&typeof i=="object"&&_l(i,t,n+1)}function hh(e){let t=[];for(let i of e)_l(i?.data,t,0);if(t.length===0)return;let n=OO(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 vO(e,r),n}function vO(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(gh.has(s))continue;let a=i[s];typeof a=="string"?!Il.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function AO(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 LO(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function yh(e){let t=AO(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(_O.has(i))continue;let s=n[i];LO(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 Il,gh,_O,bh=y(()=>{"use strict";Il=["path","uri"],gh=new Set(["next","location"]);_O=new Set([...Il,"owner","repo","name","id"])});function DO(e,t,n){if(e<=1)return Rh;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(FO/o),s=Math.max(MO,Math.min(i,Rh));return n?Math.max(s,n):s}async function re(e,t,n,r){let o=n.concurrency??IO,{results:i,errors:s}=await zO(e,t,o,n.minQueryTimeoutMs);return NO(n,i,s,e,r)}function NO(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:wh(g.originalQuery,g.queryIndex),...b!==void 0?{status:b}:{},data:BO(g.result)}}),n.forEach(g=>{let b=r[g.queryIndex];b&&(c[g.queryIndex]={id:wh(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=Sh(g.text,o),P=Ph(g.structuredContent,b.pagination);return Ch(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:P,isError:g.isError??(l.length>0&&l.every(T=>T.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let g=hh(u.results);g&&(u.base=g);let b=yh(u.results);b&&(u.shared=b)}let d=ws(u,a),p=Sh(d,o),f=Ph(yt(u),p.pagination);return Ch(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 Fl(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(`
28
+ `,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 GO(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Fl(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function HO(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Fl(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 Sh(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=Fl(e,s,i),c=a<o,l=GO(e,s,i),u=HO(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
29
+ `:`# Response page ${l}/${u}.
30
+ `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Ph(e,t){return t?{...e,responsePagination:t}:e}function Ch(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{cc(e,o,r)}catch{}}async function zO(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 dh(s,{timeout:DO(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 BO(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 wh(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 IO,Rh,FO,MO,Ve=y(()=>{"use strict";Fe();fh();oo();oe();bh();IO=3,Rh=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,FO=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,MO=5e3});function ve(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:$(s,o.rawResponse)}function xs(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 Ae(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return F(i,t)}var De=y(()=>{"use strict";za();oe()});async function We({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Ae(o,t,r,e)}}var qt=y(()=>{"use strict";De()});import{spawn as QO}from"child_process";function jO(e={},t=Ml){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 pn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Ml,maxOutputSize:a=UO}=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:jO(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=QO(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{}},$O),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)},P=()=>{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 T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!P()&&l.stdoutChunks.push(T)}),f.stderr?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!P()&&l.stderrChunks.push(T)}),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 Ts(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 Ml,ks,xh,UO,$O,zq,Es=y(()=>{"use strict";Ml=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],ks=[...Ml,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],xh=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],UO=10*1024*1024,$O=5e3;zq=1*1024*1024});import{validateCommand as qO}from"@octocodeai/octocode-engine/commandValidator";async function rr(e,t=[],n={}){let r=qO(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Ts(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 pn(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 Dl=y(()=>{"use strict";Es()});function ut(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function VO(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(kh,e)?[p]:ut(Hl,e)?[u,d,l,c,a]:ut(Gl,e)?[l,u,d,c,a]:ut(Nl,e)?[a,c,l,u,d]:[c,a,l,u,d]}function WO(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(Hl,e)?[s,a,o,r,n]:ut(Gl,e)?[o,s,a,r,n]:ut(Nl,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function zl(e){let t=[];for(let n of e){let r=await rr(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 KO(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
31
+ `).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
32
+ `)}async function Th(e,t){let n=await zl(VO(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?KO(n.stdout,n.commandUsed):n.stdout).split(`
33
+ `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function Eh(e,t){return zl(WO(e,t))}function YO(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(kh,e)?[c]:ut(Hl,e)?[s,a,o,n,r]:ut(Gl,e)?[o,s,a,n,r]:ut(Nl,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Oh(e,t){return zl(YO(e,t))}var Nl,Gl,Hl,kh,vh=y(()=>{"use strict";Dl();Nl=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Gl=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Hl=[".dmg",".rar",".cpgz"],kh=[".aar",".yaa"]});function ev(e){let t=e.toLowerCase();for(let{ext:n,format:r}of JO)if(t.endsWith(n))return r}async function tv(e){let t=await rr("file",["--mime-type","-b",e]);if(t.success)return ZO[t.stdout.trim().toLowerCase()]}async function nv(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 rr(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 rr(r.command,r.args)).stderr,commandUsed:r.command}}async function Ah(e,t){let n;if(t!=="auto"?n=t:n=ev(e)??await tv(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=XO[n],o=await nv(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 XO,JO,ZO,Lh=y(()=>{"use strict";Dl();XO={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"]}},JO=[{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"}],ZO={"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 _h(e){try{return{success:!0,info:M.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function Ih(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 Fh=y(()=>{"use strict";ge()});import{promises as or}from"fs";import{join as Bl,basename as Os,dirname as rv,resolve as Mh,sep as ov}from"node:path";import{securityRegistry as iv}from"@octocodeai/octocode-engine/registry";function Nh(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function cv(e){return Bl(Ie.unzip,`${Os(e)}-${Nh()}`)}function lv(e,t){return Bl(Ie.binary,`${Os(e)}-${t}-${Nh()}`)}function uv(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function Ql(e,t,n,r){let o=Mh(lv(e,t)),i=Mh(Bl(o,uv(n)));if(!i.startsWith(o+ov)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await or.mkdir(rv(i),{recursive:!0}),await or.writeFile(i,r,"utf-8"),i}function pv(){if(!Dh){try{iv.addAllowedCommands(dv)}catch{}Dh=!0}}function Ul(e,t,n){let r=M.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
34
+ `):null}function $l(e,t,n,r){let s=Hn(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 gv(e,t){let n=_h(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 hv(e,t){let n=t.verbose??!1,r=await Th(e,n);if(!r.success)return F(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??fv,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 yv(e,t){let n=t.archiveFile,r=await Eh(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 Ql(e,"extract",n,o);if(t.matchString){let c=Ul(o,t.matchString,t.matchStringContextLines??3);if(!c)return F(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=rt(),a=$l(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 bv(e,t){let n=await Ah(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 Ql(e,"decompress",`${Os(e)}.decompressed.txt`,r);if(t.matchString){let a=Ul(r,t.matchString,t.matchStringContextLines??3);if(!a)return F(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=rt(),s=$l(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 Rv(e,t){let n=t.minLength??mv,r=t.includeOffsets??!1,o=t.scanOffset??0,i=Ih(e,n,r,o);if(!i.success)return F(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
35
+ `),a=s?await Ql(e,"strings",`${Os(e)}.strings.txt`,s):void 0;if(t.matchString){let d=Ul(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(av,rt()):rt(),u=$l(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 Sv(e,t){try{await or.stat(e)}catch{return F(`File not found: ${e}`,t)}let n=cv(e);await or.mkdir(n,{recursive:!0});let r=await Oh(e,n);if(!r.success)return F(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await or.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function Gh(e){pv();let t=ze(e,sv);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await or.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 gv(n,e);case"list":return hv(n,e);case"extract":return yv(n,e);case"decompress":return bv(n,e);case"strings":return Rv(n,e);case"unpack":return Sv(n,e);default:return F(`Unknown mode: ${String(e.mode)}`,e)}}var sv,av,dv,Dh,fv,mv,Hh=y(()=>{"use strict";de();An();Ct();ge();hi();Dr();vh();Lh();Fh();sv=A.LOCAL_BINARY_INSPECT,av=4e3;dv=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],Dh=!1;fv=1e3,mv=8});async function zh(e){let{queries:t}=e;return re(t||[],async n=>We({toolName:A.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=_e(Xn,n);if(r.ok===!1)return r.error;let o=await Gh(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 $(o,s),o}}),{toolName:A.LOCAL_BINARY_INSPECT},e)}var Bh=y(()=>{"use strict";is();de();Ve();De();oe();qt();Hh()});function jl(e){return e.data!==void 0&&!e.error}var Qh=y(()=>{"use strict"});import{maskSensitiveData as Uh}from"@octocodeai/octocode-engine/mask";function Pv(){return cl().provider??al()}function Cv(e){let t=cl(),n=t.provider??al(),{baseUrl:r,token:o}=t;try{let i=vl(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=Uh(s);throw new ql(n,`Failed to initialize ${n} provider: ${a}`)}}function ot(e){let t;return()=>t??=Cv(e)}function vs(e,t){return e.capabilities[t]}async function Vt(e,t){let n=await t();return jl(n)?{ok:!0,response:n}:{ok:!1,result:xs(n,e)}}async function $h(e,t){let n=t??Pv(),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:Uh(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)jl(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var ql,fn=y(()=>{"use strict";Al();Qh();Vr();De();ql=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});import{existsSync as ao,readFileSync as wv,writeFileSync as xv,mkdirSync as kv,rmSync as so,readdirSync as Tv,statSync as Ev}from"node:fs";import{join as it}from"node:path";import{createHash as Ov}from"node:crypto";function Vh(e){return it(e,"tmp","clone")}function Wh(e){return it(e,"tmp","tree")}function _v(e){return e?`__sp_${Ov("sha256").update(e).digest("hex").substring(0,6)}`:""}function Kh(e,t,n,r,o){let i=`${r}${_v(o)}`;return it(Vh(e),t,n,i)}function Vl(e,t,n,r){return it(Wh(e),t,n,r)}function Iv(e){return typeof e=="object"&&e!==null}function Fv(e){if(!Iv(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 Wl(e){let t=it(e,qh);if(!ao(t))return null;try{return Fv(JSON.parse(wv(t,"utf-8")))}catch{return null}}function co(e,t){try{xv(it(e,qh),JSON.stringify(t,null,2),"utf-8")}catch{}}function Yh(e){return Date.now()<new Date(e.expiresAt).getTime()}function lo(e){let t=Wl(e);return t?Yh(t)?ao(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Mv(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return vv}function Dv(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Av}function Nv(){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 Lv}function uo(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Mv()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function gn(e){let t=it(e,"..");try{ao(t)||kv(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{ao(e)&&so(e,{recursive:!0,force:!0})}catch{}}function io(e){try{return Ev(e).isDirectory()}catch{return!1}}function mn(e){try{return Tv(e)}catch{return[]}}function*Xh(e){for(let t of mn(e)){let n=it(e,t);if(io(n))for(let r of mn(n)){let o=it(n,r);if(io(o))for(let i of mn(o)){let s=it(o,i);io(s)&&(yield s)}}}}function jh(e){for(let t of[...mn(e)]){let n=it(e,t);if(io(n)){for(let r of[...mn(n)]){let o=it(n,r);if(io(o)&&mn(o).length===0)try{so(o,{recursive:!0,force:!0})}catch{}}if(mn(n).length===0)try{so(n,{recursive:!0,force:!0})}catch{}}}}function Gv(e){let t=0;for(let n of Xh(e))try{let r=Wl(n);(!r||!Yh(r))&&(so(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Hv(e){let t=[];for(let n of Xh(e)){let r=Wl(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??oi(n)})}return t}function zv(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{so(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Jh(e){if(!ao(e))return 0;let t=0;try{t+=Gv(e)}catch{return t}jh(e);let n=zv(Hv(e),Dv(),Nv());return t+=n,n>0&&jh(e),t}function Zh(e){return Jh(Vh(e))}function Kl(e){return Jh(Wh(e))}var vv,vV,Av,Lv,qh,Yl=y(()=>{"use strict";Fe();vv=1440*60*1e3,vV=600*1e3,Av=2*1024*1024*1024,Lv=50,qh=".octocode-clone-meta.json"});import{existsSync as Bv,mkdirSync as Xl,renameSync as Qv,rmSync as Uv}from"fs";import{join as po}from"path";import{createHash as $v}from"crypto";async function ry(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await rA();let a=e.branch??await Ze(r,o,t),c=In(),l=Kh(c,r,o,a,i);return Kv(c,l,async()=>{let u=lo(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Zh(c),gn(l);let d=nA(t,n),p=Xv(c,l);As(p);try{if(i){if(await tA(r,o,a,p,i,d),!Bv(po(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 eA(r,o,a,p,d);let f=uo(r,o,a,"clone",i);return co(p,f),Jv(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw As(p),f}})}async function Kv(e,t,n){gn(t);let r=Yv(e,t);Xl(po(e,"tmp",ty),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Xl(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>qv)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await Zv(Vv)}try{return await n()}finally{Uv(r,{recursive:!0,force:!0})}}function oy(e){return $v("sha256").update(e).digest("hex").slice(0,16)}function Yv(e,t){return po(e,"tmp",ty,oy(t))}function Xv(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=po(e,"tmp",Wv);return Xl(r,{recursive:!0,mode:448}),po(r,`${oy(t)}-${n}`)}function Jv(e,t){As(t),gn(t),Qv(e,t)}function Zv(e){return new Promise(t=>setTimeout(t,e))}async function eA(e,t,n,r,o){let i=sy(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",iy(e,t),r),await Jl(i,ey,`full clone of ${e}/${t}`,o)}async function tA(e,t,n,r,o,i){let s=sy(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",iy(e,t),r),await Jl(s,ey,`sparse clone of ${e}/${t}`,i),await Jl(["-C",r,"sparse-checkout","set","--skip-checks","--",o],jv,`sparse-checkout set ${o}`,void 0)}function iy(e,t){return`https://github.com/${e}/${t}.git`}function sy(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function nA(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function rA(){try{if(!(await pn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:ny,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 oA(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 Jl(e,t,n,r){let o=await pn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:ny,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=oA(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var ey,jv,qv,Vv,ty,Wv,ny,ay=y(()=>{"use strict";Fe();$e();Es();Yl();ey=120*1e3,jv=30*1e3,qv=300*1e3,Vv=100,ty="clone-locks",Wv="clone-tmp",ny=[...ks,"GIT_TERMINAL_PROMPT"]});async function cy(e){let{queries:t,authInfo:n}=e,r=ot(n);return re(t,async(o,i)=>We({toolName:A.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!vs(s,"cloneRepo"))return Ae(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",A.GITHUB_CLONE_REPO);let a;try{a=await ry(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=oi(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 ve(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 ly=y(()=>{"use strict";Fe();de();Ve();De();qt();fn();ay()});import{writeFileSync as fy,mkdirSync as Zl,existsSync as fo,rmSync as iA,readdirSync as sA,statSync as my}from"node:fs";import{join as Ls,dirname as gy,resolve as eu,sep as tu}from"node:path";function dy(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function uA(e){return Object.values(e).every(t=>t===0)}function py(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 by(e,t,n,r,o,i=!1){let s=In(),a=Vl(s,e,t,r),c=eu(Ls(a,n));if(!c.startsWith(a+tu)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=lo(a);if(l.hit&&!i&&fo(c)){let v=mA(c,a),z=dy();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:z,limits:uy,warnings:py(!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=dy(),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>yy){m.oversized+=1;continue}let z=Jm(v.name,{lowercase:!0,leadingDot:!0});if(lA.has(z)){m.binary+=1;continue}g.push(v)}m.fileLimit=Math.max(0,g.length-nu);let b=g.slice(0,nu),P=o?.token,S=await dA(b,aA,P);m.fetchFailed=b.length-S.length;let T=0,L=[];for(let v=0;v<S.length;v+=1){let{entry:z,content:H}=S[v];if(T+H.length>hy){m.totalSizeLimit=S.length-v;break}T+=H.length,L.push({entry:z,content:H})}Kl(s),gn(a),fo(c)&&iA(c,{recursive:!0,force:!0}),Zl(c,{recursive:!0,mode:448});let E=[];for(let{entry:v,content:z}of L){let H=eu(Ls(a,v.path));if(!H.startsWith(a+tu)){m.pathTraversal+=1;continue}let K=gy(H);fo(K)||Zl(K,{recursive:!0,mode:448}),fy(H,z,"utf-8"),E.push({path:v.path,size:z.length,type:"file"})}let O=uo(e,t,r,"treeFetch",void 0,void 0,d);co(a,O);let x=uA(m),N=x,I=m.nonFile>0;return{localPath:c,repoRoot:a,files:E,fileCount:E.length,totalSize:T,complete:x,verified:N,...d?{commitSha:d}:{},...I?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:g.length,savedFileCount:E.length,skipped:m,limits:uy,warnings:py(x,N),cached:!1,expiresAt:O.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function Ry(e,t,n,r,o,i=!1){let s=In(),a=Vl(s,e,t,r),c=eu(Ls(a,n));if(!c.startsWith(a+tu)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=lo(a);if(!i&&l.hit&&fo(c))return{localPath:c,repoRoot:a,path:n,size:gA(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await fs({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}`)}Kl(s),gn(a);let d=gy(c);fo(d)||Zl(d,{recursive:!0,mode:448}),fy(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=uo(e,t,p,"treeFetch");return co(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 dA(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 fA(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 fA(e,t){try{let o=new URL(e);if(!pA.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(),cA);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 mA(e,t){let n=[],r=0;function o(i){let s;try{s=sA(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Ls(i,a);try{let l=my(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 gA(e){try{return my(e).size}catch{return 0}}var nu,hy,yy,aA,cA,lA,uy,pA,Sy=y(()=>{"use strict";Fe();$e();bl();Yl();Zr();nu=50,hy=5*1024*1024,yy=300*1024,aA=5,cA=1e4,lA=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"]),uy={maxDirectoryFiles:nu,maxTotalSize:hy,maxFileSize:yy};pA=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function yA(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 Py(e,t){return e&&t?`${e}/${t}`:void 0}function Cy(e){return{keywords:e.keywords??[],projectId:Py(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 wy(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 bA(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function xy(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=bA(a),u=`${c}/${l}`,d=s,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:yA(g.context)};g.positions?.length>0&&(b.matchIndices=g.positions.map(([P,S])=>({start:P,end:S,lineOffset:(g.context??"").substring(0,P).split(`
36
+ `).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,...wy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function ky(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 Ty(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 RA(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Ey(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(RA),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Py(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 SA(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function PA(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 CA(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:PA(e)}}function Oy(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=SA(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=CA(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}:{},...wy(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 vy(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 Ay(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 Ly(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??dn.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 _y(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 ir=y(()=>{"use strict";fe();Rs()});function wA(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 _s(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=wA(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function Is(e,t,n){let r=ws(e,[...t]);return{structuredContent:yt(e),text:r,isError:n}}var ru=y(()=>{"use strict";oo()});function Fs(e){return typeof e=="object"&&e!==null}function st(e){return typeof e=="string"&&e.length>0?e:void 0}function Ke(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Iy(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 Ke(e[t])??0}function xA(e){if(Fs(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 kA(e){if(Fs(e))return{maxDirectoryFiles:dt(e,"maxDirectoryFiles"),maxTotalSize:dt(e,"maxTotalSize"),maxFileSize:dt(e,"maxFileSize")}}function EA(e){if(!Fs(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 TA){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function OA(e,t){return`${e}/${t}`}function vA(e,t,n){let r=OA(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 AA(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 LA(e,t){let n=EA(e.pagination),r=AA(n,t);return{path:st(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:st(e.localPath),repoRoot:st(e.repoRoot),...Ke(e.fileSize)!==void 0?{fileSize:Ke(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:Ke(e.totalLines),sourceChars:Ke(e.sourceChars),sourceBytes:Ke(e.sourceBytes),resolvedBranch:st(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:Ke(e.startLine),endLine:Ke(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:st(e.lastModified),lastModifiedBy:st(e.lastModifiedBy),warnings:Iy(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:st(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function _A(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Fs).map(c=>({path:st(c.path)??"",size:Ke(c.size)??0,type:st(c.type)??"file"})),o=xA(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:st(e.localPath)??"",repoRoot:st(e.repoRoot),fileCount:Ke(e.fileCount)??r.length,totalSize:Ke(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:Ke(e.directoryEntryCount),eligibleFileCount:Ke(e.eligibleFileCount),savedFileCount:Ke(e.savedFileCount),skipped:o,limits:kA(e.limits),warnings:Iy(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:st(e.resolvedBranch)}}function IA(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=vA(n,s,a),l=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(_A(l,i)),c.directories=d;return}let u=c.files??[];u.push(LA(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{id:r.id,data:o}})}function FA(e,t){return _s(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 Fy(){return({queries:e,results:t})=>{let n=IA(t,e),r=FA(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),Is(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}var TA,My=y(()=>{"use strict";ru();TA=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function Dy(e){let{queries:t,authInfo:n}=e,r=ot(n);return re(t,async(o,i)=>{try{let s=_e($n,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?MA(a,n,c):DA(a,n,c)}catch(s){return Ae(s,o,void 0,A.GITHUB_FETCH_CONTENT)}},{toolName:A.GITHUB_FETCH_CONTENT,finalize:Fy()},e)}async function MA(e,t,n){let r=Oe();if(!(r.local.enabled&&r.local.enableClone))return F("Directory fetch requires local clone support. Set ENABLE_CLONE=true and make sure ENABLE_LOCAL is not false.",e);if(!vs(n,"fetchDirectoryToDisk"))return Ae(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 Ze(e.owner,e.repo,t),i=await by(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 ve(e,u,!0,A.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??Q(i)})}async function DA(e,t,n){let r=await Vt(e,()=>n.provider.getFileContent(vy(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await NA(e,t):void 0,i={...Ay(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 ve(e,i,s,A.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function NA(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ze(e.owner,e.repo,t);return Ry(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var Ny=y(()=>{"use strict";de();Ve();De();Ni();Sy();$e();oe();ir();fn();My();Fe()});function GA(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function HA(e,t){let n=GA(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function zA(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 BA(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 QA(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function Gy(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 UA(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:Gy(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:Gy(r.get(i)),...s?{pagination:s}:{}}}})}function $A(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jA(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${$A(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function qA(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?QA(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:jA(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:VA(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 VA(e,t){return{...e,matches:t}}function Hy(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=zA(p);m.incompleteResults&&(i=!0),m.results.reduce((P,S)=>P+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=qA(BA(n),s),c=_s(t),l=e.some(p=>p.concise===!0),u=UA(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&&HA(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."]),Is(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 zy=y(()=>{"use strict";ru()});function WA(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function KA(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 By(e){let{queries:t}=e,n=ot(e.authInfo);return re(t,async(r,o)=>{try{let i=KA(r);if(i)return F(i.error,r);if(!WA(r))return F("At least one search term or scope filter is required.",r);let s=n(),a=await Vt(r,()=>s.provider.searchCode(Cy(r)));if(a.ok===!1)return a.result;let c=xy(a.response.data,r);return ve(r,c,c.results.length>0,A.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Ae(i,r,void 0,A.GITHUB_SEARCH_CODE)}},{toolName:A.GITHUB_SEARCH_CODE,finalize:Hy()},e)}var Qy=y(()=>{"use strict";de();Ve();De();ir();fn();zy()});function YA(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 XA(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 JA(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Uy(e){let{content:t,reviewMode:n}=e,r=YA(t,n),o=XA(t,n),i=JA(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 $y=y(()=>{"use strict"});function su(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Ds(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function au(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 Gs(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 qy(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Vy(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function ZA(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Ns(e,t,n){return ZA({...Vy(e,t),...n})}function jy(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Ns(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function ou(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Ns(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function eL(e,t,n){return{target:Vy(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 Ms(e){return String(e.path??e.filename??"")}function tL(e,t){return{path:Ms(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function nL(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 rL(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=nL(r,n.comments),i=su(t),s=i?o.filter(l=>Ds(l.body,i)):o,{items:a,pagination:c}=au(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=Gs(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:qy(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function oL(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=su(t);return{reviews:(o?r.filter(s=>Ds(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Gs(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 iL(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=au(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 sL(e){return e.split(`
37
+ `).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(`
38
+ `)}function aL(e){return e.replace(/\n{3,}/g,`
39
+
40
+ `)}function cL(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(Ms(f))):o,a=su(t),c=a?s.filter(f=>Ds(Ms(f),a)||Ds(f.patch,a)):s,{items:l,pagination:u}=au(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=tL(f,!1);if(!d||typeof f.patch!="string")return m;let g=r&&!a?sL(f.patch):f.patch,b=Gs(g,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:to(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(Ms).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function mo(e){return typeof e=="object"&&e!==null}function iu(e){if(mo(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function cu(e){if(mo(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function lL(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function uL(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!mo(n))continue;let r=cu(n.patchPagination);if(r?.hasMore)return r}}function dL(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!mo(n))continue;let r=cu(n.bodyPagination);if(r?.hasMore)return r}}function pL(e,t,n,r){let o={},i=cu(e.bodyPagination),s=iu(e.filePagination),a=iu(e.commentPagination),c=iu(e.commitPagination),l=uL(e),u=dL(e),d=lL(n);i&&(o.body={...i,nextQuery:jy(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:ou(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:ou(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:Ns(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:ou(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:jy(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return mo(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?Ns(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function fL(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Wy(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?aL(s):s,c=n.body?Gs(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:qy(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:eL(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...cL(e,t,n,r),...rL(e,t,n),...oL(e,t,n),...iL(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=pL(m,t,n,i);return fL(m),g&&(m.contentPagination=g),m}var Ky=y(()=>{"use strict";fe();ms()});function mL(e){return e?e.includes('rel="next"'):!1}function Yy(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 Xy(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=mL(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(`
41
+ `)[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?Yy(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:to(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 N=x.patch!==void 0?Yy(x.patch,e.charOffset,e.charLength):void 0;return{filename:x.filename,status:x.status,additions:x.additions,deletions:x.deletions,...N!==void 0?{patch:N.patch,...N.patchPagination?{patchPagination:N.patchPagination}:{},diff:to(N.patch)}:{},...x.previous_filename?{previousFilename:x.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),P=Math.max(1,e.itemsPerPage??20),S=g.length,T=Math.max(1,Math.ceil(S/P)),L=Math.min(b,T),E=(L-1)*P,O=g.slice(E,E+P);return{...u,files:O,filesPagination:{currentPage:L,totalPages:T,itemsPerPage:P,totalFiles:S,hasMore:L<T,...L<T?{nextFilePage:L+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 Jy=y(()=>{"use strict";$e();Tt();ms()});async function Zy(e){let{queries:t,authInfo:n}=e,r=ot(n);return re(t,async(o,i)=>{try{let s=_e(qn,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,N=x&&!x.endsWith("/")?"file":"repo";if(N==="file"&&!x)return F("path is required when querying a specific file in commits mode.",o);let I=await Xy({type:N,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(nr(I))return F(I,o,{toolName:A.GITHUB_SEARCH_PULL_REQUESTS});let{commits:v}=I.data,z=v.length>0;return ve(o,I.data,z,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:I.rawResponseChars})}let a=r(),c={...s.data},l=Uy(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 Vt(c,()=>a.provider.searchPullRequests(Ey(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:g}=Oy(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete g.pagination;let b=!u&&(!!o.content||!!o.reviewMode),P={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},S=c.minify==="standard",T=u,L=m.map(O=>Wy(O,c,b?P:l,S,T));g.pull_requests=L,!u&&c.concise===!0&&(g.pull_requests=L.map(O=>{let x=O;return`#${x.number} ${x.title}`}));let E=L.length>0;return ve(c,g,E,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return Ae(s,o,void 0,A.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:A.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var eb=y(()=>{"use strict";Bi();de();Ve();De();ir();fn();$y();Ky();Jy();ds()});function tb(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 nb=y(()=>{"use strict"});function gL(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 hL(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(gL)}}}function ib(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function sb(e){return!!(e.keywords&&e.keywords.length>0)}function yL(e){return!!(sb(e)||ib(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 rb(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function bL(e){let t=ib(e),n=sb(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:rb(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:rb(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function RL(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 SL(e,t){return[...e].sort((n,r)=>{let o=PL(n,r,t.sort);if(o!==0)return o;let i=ob(r,t)-ob(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:lu(n).localeCompare(lu(r))})}function PL(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 tb(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function ob(e,t){let n=CL(t),r=lu(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 CL(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function lu(e){return`${e.owner}/${e.repo}`}function wL(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 xL(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 kL(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??Q(n.response.data??n.response)),0)}async function ab(e){let{queries:t,authInfo:n}=e,r=ot(n);return re(t,async(o,i)=>{try{if(!yL(o))return F("At least one repository search term or filter is required.",o);let s=r(),a=bL(o),{successes:c,failures:l}=await $h(a.map(E=>({meta:{label:E.label,query:E.query},operation:()=>s.provider.searchRepos(ky(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?xs(E.response,o):Ae(new Error("Repository search produced no provider results"),o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=SL(RL(u.flatMap(E=>Ty(E.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,g=u.length===1?u[0]:void 0,P=u.length>1?xL(u):g?.response.data.pagination,S=P?wL(P):void 0,T=m.length>0,L=hL({repositories:m,pagination:S},o);return ve(o,L.data,T,A.GITHUB_SEARCH_REPOSITORIES,{rawResponse:kL([...u,...d])})}catch(s){return Ae(s,o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}},{toolName:A.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var cb=y(()=>{"use strict";de();Ve();nb();De();ir();fn();oe()});function TL(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 EL(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Jr(o))continue;let i=r.files.filter(a=>!tr(a)),s=r.folders.filter(a=>!Jr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function lb(e){let{queries:t,authInfo:n}=e,r=ot(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 Vt(o,()=>s.provider.getRepoStructure(Ly(o,c)));if(l.ok===!1)return TL(l.result,o);let u=EL(l.response.data.structure),d=Object.keys(u).length>0,p=_y(l.response.data,o,u,c);return ve(o,p,d,A.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return Ae(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 ub=y(()=>{"use strict";de();Ve();Zr();De();ir();fn()});import{existsSync as db}from"fs";import{delimiter as OL,dirname as vL,join as pb}from"path";function fb(){return process.platform==="win32"?"npm.cmd":"npm"}function AL(){let e=vL(process.execPath);return pb(e,fb())}function LL(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function _L(){let e=(process.env.PATH??"").split(OL).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...LL()])]}function IL(){let e=AL();if(db(e))return{command:process.execPath,argsPrefix:[e]};let t=fb();for(let n of _L()){let r=pb(n,t);if(db(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function Hs(e,t,n={}){if(!FL.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Ts(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=IL(),c=await pn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:ML});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var FL,ML,mb=y(()=>{"use strict";Es();FL=["view","search","ping","config","whoami"],ML=[...ks,...xh]});function ho(e){try{return new URL(e).host||e}catch{return e}}function gb(e,t=Date.now()){let n=go.get(ho(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<uu)throw new du(ho(e),uu-r);n.state="half-open"}}function pu(e){let t=go.get(ho(e));t&&(t.failures=0,t.state="closed")}function hb(e,t=Date.now()){let n=ho(e),r=go.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=DL&&(r.state="open",r.openedAt=t)),go.set(n,r)}function yb(e,t=Date.now()){let n=go.get(ho(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<uu:!1}var go,DL,uu,du,fu=y(()=>{"use strict";go=new Map,DL=5,uu=3e4;du=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 bb(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function GL(e,t,n,r){e&&$t({limit_type:"primary",retry_after_seconds:bb(r),api_method:t,api_url:n,provider:e})}function HL(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Ur.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&Dm(r),e.status===429&&GL(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function zL(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=bb(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function Wt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=NL,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(cn)}`}let p={"User-Agent":`Octocode-MCP/${cn}`,...i},f=globalThis.fetch;if(!f)throw new Error(Ur.FETCH_NOT_AVAILABLE.message);gb(d);let m,g=n+1;for(let b=1;b<=g;b++){if(c?.aborted)throw new Error("Request aborted");try{let P=await f(d,{method:s,headers:p,signal:c});if(!P.ok)throw HL(P,s,d,u,l);if(P.status===204)return pu(d),null;let S=await P.json();return pu(d),S}catch(P){let S=P;if(c?.aborted||P instanceof Error&&P.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw P;if(m=P instanceof Error?P:new Error(String(P)),b===g)break;let T=zL(b,r,o,S);await new Promise(L=>setTimeout(L,T))}}throw hb(d),new Error(Ur.FETCH_FAILED_AFTER_RETRIES.message(g,m?.message||""))}var NL,Rb=y(()=>{"use strict";ss();mt();as();fu();NL=6e4});import{z as _}from"zod";var zs,BL,Sb,QL,Pb=y(()=>{"use strict";zs=_.looseObject({name:_.string(),version:_.string(),repository:_.union([_.string(),_.object({url:_.string().optional(),type:_.string().optional(),directory:_.string().optional()})]).optional(),main:_.string().optional(),module:_.string().optional(),type:_.string().optional(),exports:_.unknown().optional(),types:_.string().optional(),typings:_.string().optional(),description:_.string().optional(),keywords:_.array(_.string()).optional(),license:_.union([_.string(),_.object({type:_.string().optional()})]).optional(),homepage:_.string().optional(),author:_.union([_.string(),_.object({name:_.string().optional(),email:_.string().optional(),url:_.string().optional()})]).optional(),maintainers:_.array(_.object({name:_.string().optional(),email:_.string().optional()})).optional(),engines:_.record(_.string(),_.string()).optional(),dependencies:_.record(_.string(),_.string()).optional(),devDependencies:_.record(_.string(),_.string()).optional(),peerDependencies:_.record(_.string(),_.string()).optional(),time:_.record(_.string(),_.string().optional()).optional()}),BL=_.looseObject({package:_.looseObject({name:_.string().nullish(),version:_.string().nullish(),description:_.string().nullish(),links:_.looseObject({npm:_.string().nullish(),homepage:_.string().nullish(),repository:_.string().nullish()}).nullish()}),score:_.looseObject({final:_.number().nullish(),detail:_.looseObject({quality:_.number().nullish(),popularity:_.number().nullish(),maintenance:_.number().nullish()}).nullish()}).nullish()}),Sb=_.looseObject({objects:_.array(BL),total:_.union([_.number(),_.string()]).optional()}),QL=_.union([_.string(),_.boolean(),_.number(),_.null(),_.record(_.string(),_.unknown())])});async function Eb(){if(Bs)return Bs;try{let e=await Hs("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 Bs=t,t}}catch{}return Bs=Qs,Qs}function hn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function et(e){return e===void 0?0:Q(e)}async function Ob(e){try{let t=`${$L}/${encodeURIComponent(e)}`,n=await Wt(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:et(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 vb(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 jL(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function qL(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 Cb(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 wb(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 VL(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function mu(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=hn(e.repository):(e.repository.url&&(r=hn(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:VL(e),...o?{repositoryDirectory:o}:{},...Cb(e.exports)?{exports:Cb(e.exports)}:{},...wb(e.bin,e.name)?{bin:wb(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 WL(e){return typeof e.links?.repository=="string"?hn(e.links.repository):typeof e.repository=="string"?hn(e.repository):typeof e.repository?.url=="string"?hn(e.repository.url):null}function KL(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:WL(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 Ab(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function Lb(e){try{let t=await Eb(),n=Ab(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await Wt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=et(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await Wt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:et(i)}}catch{return{rawResponseChars:0}}}async function gu(e,t,n){let[r,o]=await Promise.all([Ob(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Lb(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 $s(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function YL(e,t){try{let n=await Hs("view",[e,"--json"],{timeout:UL});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,...$s(c)?{}:{errorDetail:c},rawResponseChars:et(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=et(o),s=zs.safeParse(o);return s.success?{pkg:mu(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,...$s(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function XL(e,t){try{let n=await Eb(),r=Ab(e),o=`${n}/${r}/latest`,i;try{i=await Wt(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=et(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=zs.safeParse(i);return a.success?{pkg:mu(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,...$s(r)?{}:{errorDetail:r},rawResponseChars:0}}}function JL(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function _b(e,t){let n=0,r;for(let o of JL(e)){let i;try{i=await Wt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);$s(l)||(r=l);continue}if(n+=et(i),!i||typeof i!="object")continue;let s=zs.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:mu(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function hu(e,t=!1){let[n,r]=await Promise.allSettled([YL(e,t),XL(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?gu(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function ZL(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await hu(e,t);if(!r){if(o){let s=vb(o);if(s&&n){let a=await _b(e,t);if(a.pkg){let c=await gu(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 e_(e,t,n,r=0){let o=Math.max(t+r,t),i=await Hs("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:et(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=et(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 hu(g.name,!0);if(b.pkg)return b}return{pkg:KL(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 t_(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${Qs}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await Wt(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=et(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=Sb.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 hu(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"?hn(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:qL(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 xb(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 Wt(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:et(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:et(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"?hn(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:et(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function kb(e,t,n,r=0){try{let o=await e_(e,t,n,r);if(!("error"in o))return o}catch{}return t_(e,t,n,r)}async function Tb(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}):Ob(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):Lb(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 Ib(e,t,n,r=0){let o=je("npm-search",{name:e,limit:t,metadata:n,from:r});return qe(o,async()=>{if(yb(Qs)){if(r===0&&t===1&&Us(e)){let u=await _b(e,n);if(u.pkg){let d=await gu(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await xb(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 ZL(e,n,t===1);if("error"in l){if(!vb(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await kb(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return Tb(s);let a=jL(e);if(a!==e){let l=await kb(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return Tb(l)}let c=await xb(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 Qs,UL,Bs,$L,Fb=y(()=>{"use strict";mb();Rb();jt();fu();Pb();oe();Qs="https://registry.npmjs.org",UL=3e3,Bs=null;$L="https://api.npmjs.org/downloads/point/last-week"});async function Mb(e){let t=Us(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return Ib(e.name,n,!0,r)}var Db=y(()=>{"use strict";Fb()});function n_(e){return"error"in e}function js(e){return"npmUrl"in e}function r_(e){return js(e)&&e.path?e.path:e.name}function o_(e){return js(e)?e.repoUrl:e.repository}function i_(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function s_(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 Nb(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 Gb(e,t){let n=Nb(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 a_(e){let t=r_(e),n=s_(o_(e)),r={name:t};js(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=i_(js(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=Gb(n,o);return i&&(r.next=i),r}function c_(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=Nb(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:Gb(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 l_(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 Hb(e){return re(e.queries,async t=>{try{if(!t.packageName)return F("Package name is required for package search",t);let n=await Mb({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(n_(n))return F(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(a_),i=o.length>0,s=r.length>1||n.totalFound>1,a=l_(t,n.totalFound,o.length,s),l={...c_(o),pagination:a};return ve(t,l,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 zb=y(()=>{"use strict";Db();Ve();De();de()});async function Bb(e){let{queries:t}=e;return re(t||[],async n=>We({toolName:A.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=_e(Vn,n);return r.ok===!1?r.error:await Ci(r.data)}}),{toolName:A.LOCAL_FETCH_CONTENT},e)}var Qb=y(()=>{"use strict";de();Ve();wi();Ki();De();qt();wi()});async function Ub(e){let{queries:t}=e;return re(t||[],async n=>We({toolName:A.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=_e(Wn,n);return r.ok===!1?r.error:await Gn(r.data)}}),{toolName:A.LOCAL_FIND_FILES},e)}var $b=y(()=>{"use strict";Xi();de();Ve();pi();De();qt();pi()});async function jb(e){let{queries:t}=e;return re(t||[],async n=>We({toolName:A.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=_e(Ht,n);return r.ok===!1?r.error:await zt(r.data)}}),{toolName:A.LOCAL_RIPGREP},e)}var qb=y(()=>{"use strict";Ar();de();Ve();Dc();De();qt();li()});async function Vb(e){let{queries:t}=e;return re(t||[],async n=>We({toolName:A.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=_e(Kn,n);return r.ok===!1?r.error:await fi(r.data)}}),{toolName:A.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var Wb=y(()=>{"use strict";Zi();de();Ve();mi();De();qt();mi()});import{safeReadFile as u_}from"@octocodeai/octocode-engine/lsp/validation";function yo(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Yb(e,t,n){if(t<=0)return e;let r=await u_(e.uri);if(!r)return e;let o=Fr(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(`
42
+ `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function d_(e,t){return Promise.all(e.map(async n=>({...n,from:await Yb(n.from,t,n.fromRanges)})))}async function p_(e,t){return Promise.all(e.map(async n=>({...n,to:await Yb(n.to,t)})))}async function yu(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Kb};try{let i=await e.getIncomingCalls(t),s=o>0?await d_(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=yo(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),yu(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 bu(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Kb};try{let i=await e.getOutgoingCalls(t),s=o>0?await p_(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=yo(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),bu(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 Kb,Xb=y(()=>{"use strict";Mr();Kb={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});import{readFile as f_,stat as m_}from"node:fs/promises";import{SymbolResolver as g_,SymbolResolutionError as h_}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as qs}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function Ru(e,t){let n=e.uri,r=ze({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await m_(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:qs.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:qs.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 f_(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:qs.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Jb(e,t){let n=await Ru(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 g_({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:y_(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof h_)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:qs.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 y_(e){return{start:e,end:{line:e.line,character:e.character}}}var Zb=y(()=>{"use strict";Ct()});import bo from"node:path";import{fileURLToPath as b_}from"node:url";import{acquirePooledClient as Ws,isLanguageServerAvailable as Ks,unavailableHintFor as R_}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as S_}from"@octocodeai/octocode-engine/lsp/config";import{resolveImportAliasDefinitions as P_}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Cu}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function C_(e){return Su||(Su=new Set(M.getSupportedJsTsExtensions().map(t=>`.${t}`))),Su.has(bo.extname(e).toLowerCase())}function yn(e,t){let n=S_(e),r=R_(n,void 0);throw new xe(B.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 x_(e,t){let n=e.startsWith("file://")?b_(e):e;return bo.isAbsolute(n)?n:bo.resolve(t,n)}function rR(){return[...M.getSupportedJsTsExtensions(),...w_]}function k_(){return rR().map(e=>`**/*.${e}`)}async function E_(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:k_(),excludeDir:[...T_],maxSnippetChars:1})).files[0]?.path}catch{return}}async function O_(e,t){if(e.uri)return x_(e.uri,t);let n=await E_(e,t);if(n)return n;try{let o=M.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:rR(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function v_(e){return e instanceof Error?e.message:String(e)}function A_(e,t){if(!C_(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 iR(e){return re(e.queries||[],async t=>We({toolName:Me,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await Q_(t);return I_(F_(t,n))}}),{toolName:Me,minQueryTimeoutMs:3e4},e)}function I_(e){return $(e,Q(e))}function F_(e,t){return e.format!=="compact"||!M_(t)?t:D_(t)}function M_(e){return bn(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&bn(e.payload)}function D_(e){return{...e,format:"compact",payload:N_(e.payload)}}function N_(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(eR)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(H_)}:{locations:(e.locations??[]).map(eR)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:sR(e.root)}:{},direction:e.direction,calls:e.calls.map(z_),...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(G_)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function G_(e){if(!bn(e))return String(e);let t=Ye(e,"line"),n=Ye(e,"character"),r=Ye(e,"endLine"),o=vt(e,"kind"),i=vt(e,"name"),s=Ye(e,"childCount"),a=vt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function eR(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${cR(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function H_(e){if(!bn(e))return String(e);let t=vt(e,"uri"),n=Ye(e,"firstLine"),r=Ye(e,"firstCharacter"),o=Ye(e,"count"),i=aR(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 z_(e){if(!bn(e))return String(e);let t=vt(e,"direction"),n=sR(e.item),r=aR(e,"ranges").map(B_).join(","),o=Ye(e,"rangeCount"),i=Ye(e,"rangeSampleCount"),s=vt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${cR(s,180)}`:""].filter(Boolean).join(" ")}function sR(e){if(!bn(e))return String(e);let t=vt(e,"name"),n=vt(e,"kind"),r=vt(e,"uri"),o=Ye(e,"line"),i=Ye(e,"endLine"),s=Ye(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function B_(e){return bn(e)?`${Ye(e,"line")}:${Ye(e,"character")}`:String(e)}function bn(e){return typeof e=="object"&&e!==null}function vt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ye(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function aR(e,t){let n=e[t];return Array.isArray(n)?n:[]}function cR(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){if(e.type==="documentSymbols")return U_(e);if(e.type==="workspaceSymbol")return V_(e);if(e.type==="diagnostic")return Y_(e);let t=await Jb(e,Me);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return sI(e,i)}let n=e.workspaceRoot??await Cu(t.value.uri);await Ks(t.value.uri,n)||yn(t.value.uri,e.type);let o=await Ws(n,t.value.uri);switch(o||yn(t.value.uri,e.type),e.type){case"definition":return o.hasCapability("definitionProvider")?Pu(e,t.value,"definition","definitionProvider",await P_({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):Ot(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?Pu(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ot(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?Pu(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ot(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?$_(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):Ot(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?j_(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Ot(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?q_(e,t.value,o):Ot(e.type,t.value,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return o.hasCapability("typeHierarchyProvider")?K_(e,t.value,o):Ot(e.type,t.value,"typeHierarchyProvider unsupported",!0)}}async function U_(e){let t=await Ru(e,Me);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Cu(t.value.uri),r=await Ks(t.value.uri,n),o=r?await Ws(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=A_(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=zf(t.value.content,t.value.uri);b&&(s=b,a="markdown")}let l=a!==void 0;!l&&!r&&yn(t.value.uri,"documentSymbols");let u=Z_(s),d=nI(s),{pageItems:p,pagination:f}=Rn(u,e.page??1,e.itemsPerPage??Ys),m=rI(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 Pu(e,t,n,r,o){let i=o.length>0,s=o.map(Xc),{pageItems:a,pagination:c}=Rn(s,e.page??1,e.itemsPerPage??oR);return{type:e.type,uri:t.uri,resolvedSymbol:sn(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 $_(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?aI(r):void 0,i=o??r.map(Xc),{pageItems:s,pagination:a}=Rn(i,e.page??1,e.itemsPerPage??oR),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:sn(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 j_(e,t,n){let r=cI(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:sn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function q_(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Ot(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 yu(n,o,i,new Set([yo(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await bu(n,o,i,new Set([yo(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"?oI(S,e.contextLines??0):iI(S,e.contextLines??0)),{pageItems:m,pagination:g}=Rn(f,e.page??1,e.itemsPerPage??L_),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",P=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:sn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:wu(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:P,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=bo.resolve(e.workspaceRoot??process.cwd()),r=await O_(e,n);await Ks(r,n)||yn(r,"workspaceSymbol");let i=await Ws(n,r);if(i||yn(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{bo.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: ${v_(u)}`}}}let a=W_(s),{pageItems:c,pagination:l}=Rn(a,e.page??1,e.itemsPerPage??Ys);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 W_(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:Vs(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function K_(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Ot(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}=Rn(s,e.page??1,e.itemsPerPage??Ys);return{type:e.type,uri:t.uri,resolvedSymbol:sn(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 Y_(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Cu(t):process.cwd());await Ks(t,n)||yn(t,"diagnostic");let o=await Ws(n,t);if(o||yn(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=X_(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Rn(s,e.page??1,e.itemsPerPage??Ys);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 X_(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>J_(r))}return[]}function J_(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 Rn(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 Z_(e){let t=[];for(let n of e)lR(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function lR(e,t,n){if(!e||typeof e!="object")return;let r=e,o=tI(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:Vs(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)&&eI.has(Vs(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)lR(s,t,i)}}function tI(e){if(tR(e.range))return e.range;let t=e.location;return t&&tR(t.range)?t.range:void 0}function tR(e){if(!e||typeof e!="object")return!1;let t=e;return nR(t.start)&&nR(t.end)}function nR(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function nI(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function rI(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function oI(e,t){let n=uR(e.fromRanges);return{direction:"incoming",item:wu(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...dR(e.from,t)}}function iI(e,t){let n=uR(e.fromRanges);return{direction:"outgoing",item:wu(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...dR(e.to,t)}}function wu(e){return{name:e.name,kind:Vs(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 uR(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>=__))break}return n}function dR(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function Vs(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 pR(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 sI(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:pR(e.type,t),reason:t}}}function Ot(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:sn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:pR(e,n),reason:n}}}function aI(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 cI(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=>lI(r)).join(`
43
+ `).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 lI(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 Su,w_,T_,Ys,oR,L_,__,eI,fR=y(()=>{"use strict";Ve();oe();qt();zo();En();Xb();Un();Zb();ge();Pi();w_=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];T_=[".git","node_modules","dist","out","coverage","target"];Ys=40,oR=40,L_=10,__=8;eI=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});async function gR(e){let t=uI(e),n=Jt.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(xu(),bR)),o=await r(n.data,{authInfo:e.authInfo});return dI(o)}function uI(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function dI(e){let t=pI(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 pI(e){return Xu(e)?{results:e.children.map(t=>mR(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:hR(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[mR(e,e.queryId??"oqlSearch-1")]}}function mR(e,t){let n=hR(e);return{id:e.queryId??t,...mI(e),data:n}}function hR(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||fI(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 fI(e,t){return e.why===t.why&&e.confidence===t.confidence}function mI(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var yR=y(()=>{"use strict";Cn();_t()});var ku,RR=y(()=>{"use strict";de();ku={hasTool(e){return Ec(e)},getDescription(e){return Tc[e]??""},getToolName(e){return A[e]??String(e)}}});function gI(e,t){return t.getToolName(e)}function at(e,t,n){let r=gI(t,e);return{...n,name:r,description:Tu(r,e)}}function hI(e=ku){let t=at(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Gi,inputSchema:Hi,executionFn:By,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=at(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:$n,inputSchema:Di,executionFn:Dy,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=at(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:$i,inputSchema:ji,executionFn:lb,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=at(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:Qi,inputSchema:Ui,executionFn:ab,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=at(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:qn,inputSchema:zi,executionFn:Zy,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=at(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:qi,inputSchema:Vi,executionFn:Hb,security:"remote",requiresServerRuntime:!0}}),a=at(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Hr,inputSchema:Mi,executionFn:cy,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=at(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Ht,inputSchema:si,executionFn:jb,security:"basic"}}),l=at(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Kn,inputSchema:Ji,executionFn:Vb,security:"basic"}}),u=at(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Wn,inputSchema:Yi,executionFn:Ub,security:"basic"}}),d=at(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Vn,inputSchema:Wi,executionFn:Bb,security:"basic"}}),p={name:Me,description:Tu(Me,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:ns,inputSchema:rs,executionFn:iR,security:"basic",requiresServerRuntime:!0}},f=at(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Xn,inputSchema:os,executionFn:zh,security:"basic"}}),m={name:Qn,description:Tu(Qn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:Oo,inputSchema:Jt,executionFn:gR,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 Tu,Ne,x4,k4,T4,E4,O4,v4,A4,L4,_4,I4,F4,M4,D4,N4,SR,PR=y(()=>{"use strict";Jc();Ni();Zc();Bi();el();tl();nl();Ki();Xi();Ar();Zi();ol();is();Cn();Bh();ly();Ny();Qy();eb();cb();ub();zb();Qb();$b();qb();Wb();fR();yR();Un();Fi();RR();Tu=(e,t=ku)=>t.getDescription(e);Ne=hI(),x4=Ne.GITHUB_SEARCH_CODE,k4=Ne.GITHUB_FETCH_CONTENT,T4=Ne.GITHUB_VIEW_REPO_STRUCTURE,E4=Ne.GITHUB_SEARCH_REPOSITORIES,O4=Ne.GITHUB_SEARCH_PULL_REQUESTS,v4=Ne.PACKAGE_SEARCH,A4=Ne.GITHUB_CLONE_REPO,L4=Ne.LOCAL_RIPGREP,_4=Ne.LOCAL_VIEW_STRUCTURE,I4=Ne.LOCAL_FIND_FILES,F4=Ne.LOCAL_FETCH_CONTENT,M4=Ne.LSP_GET_SEMANTIC_CONTENT,D4=Ne.LOCAL_BINARY_INSPECT,N4=Ne.OQL_SEARCH,SR=Ne.ALL_TOOLS});import{ContentSanitizer as yI}from"@octocodeai/octocode-engine/security";function Ou(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:yt(t.structuredContent)}}catch{}return RI(t)?SI(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}=yI.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function RI(e){return vr()==="mcp"&&process.env[bI]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function SI(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:PI(e.structuredContent)},...t]}}function PI(e){let t=["structuredContent available"];if(Eu(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=CI(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Eu(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function CI(e){let t=0,n=0;for(let r of e)Eu(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Eu(e){return typeof e=="object"&&e!==null}function vu(e,t){let n=xI(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
44
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:wI,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Ou(r)}catch{return r}}function xI(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:kI(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 kI(e){try{return JSON.stringify(e)}catch{return}}var bI,wI,CR=y(()=>{"use strict";oo();ti();bI="OCTOCODE_MCP_FULL_TEXT";wI="TOOL_CALLBACK_EXCEPTION"});import{withSecurityValidation as TI,withBasicSecurityValidation as EI}from"@octocodeai/octocode-engine/security";function wR(e,t){let n=TI(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function xR(e,t){let n=EI(r=>e(r),t);return(r,o)=>n(r,o)}var kR=y(()=>{"use strict"});import{releaseAllPooledClients as OI}from"@octocodeai/octocode-engine/lsp/manager";function vI(e){return async t=>e(t)}function AI(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:vI(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function _I(e){return LI.find(t=>t.name===e)}async function _u(e,t){let n=_I(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=II(n,t);return await FI(n),MI(n),await DI(n,r)}catch(r){return vu(n.name,r)}finally{e===Me&&await OI()}}function II(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function FI(e){e.requiresServerRuntime&&(Au||(Au=Im()),await Au),e.requiresProviders&&(Lu||(Lu=uh().then(()=>{})),await Lu)}function MI(e){if(!e.isLocal&&!e.isClone)return;let t=Oe();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 make sure ENABLE_LOCAL is not false.`);throw n.code="cloneDisabled",n}}async function DI(e,t){try{let n=e.security==="remote"?await NI(e,t):await GI(e,t);return Ou(n)}catch(n){return vu(e.name,n)}}async function NI(e,t){return wR(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function GI(e,t){return xR(e.execute,e.name)(t)}var Au,Lu,LI,TR=y(()=>{"use strict";Vr();Al();Fe();Un();PR();CR();kR();il();Au=null,Lu=null;LI=SR.map(AI)});var ER=y(()=>{"use strict";il();TR()});function Re(e,t){return _u(e,{queries:[{...HI,...t}]})}var HI,Xs=y(()=>{"use strict";ER();HI={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function AR(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 Ro(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function zI(e){return e.structuredContent?.results?.[0]?.status}function Js(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 LR(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function OR(...e){return e.map(LR).filter(Boolean).join("/")}function BI(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function vR(e){return LR(e).split("/").filter(Boolean).length}function QI(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function UI(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function $I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jI(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($I).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(QI).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!jI(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(UI(o.path)))}function _R(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function VI(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 WI(e){return typeof e=="string"?[]:e.matches??[]}async function IR(e){switch(e.target){case"content":return XI(e);case"structure":return JI(e);case"files":return KI(e);default:return YI(e)}}async function KI(e){let t=dr(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=Ro(n),o=new Set,i=[];for(let a of r?.files??[]){let c=_R(a);o.has(c)||(o.add(c),i.push({kind:"file",source:we(e),path:c,entryType:"file"}))}let s=xt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...Zs(n,"ghSearchCode"),...Js(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:we(e)}]}}function we(e){return e.from??{kind:"github"}}async function YI(e){let t=dr(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Re("ghSearchCode",t.query),r=Ro(n),o=[];for(let s of r?.files??[]){let a=_R(s),c=VI(s),l=WI(s);if(l.length===0){o.push({kind:"code",source:we(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:we(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=xt(r?.pagination);return{results:o,...i?{pagination:i}:{},diagnostics:[...Zs(n,"ghSearchCode"),...Js(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:we(e)}]}}async function XI(e){let{owner:t,repo:n}=AR(we(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=ZI(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:Xe(e.scope)??"",type:"file",minify:o,...we(e).kind==="github"&&we(e).ref?{branch:we(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=Ro(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",P={...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:we(e),path:m.path,content:m.content,contentView:l,...Object.keys(P).length?{range:P}:{}}}),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:[...Zs(a,"ghGetFileContent"),...Js(p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:we(e)}]}}async function JI(e){let{owner:t,repo:n}=AR(we(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:Xe(e.scope)??"",...we(e).kind==="github"&&we(e).ref?{branch:we(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=Ro(o),s=[],a=Xe(e.scope);for(let u of BI(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=OR(a,d,p);s.push({kind:"tree",source:we(e),path:f,entryType:"directory",depth:vR(f)})}for(let p of u.files??[]){let f=OR(a,d,p);s.push({kind:"tree",source:we(e),path:f,entryType:"file",depth:vR(f)})}}let c=qI(s,e),l=xt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...Zs(o,"ghViewRepoStructure"),...Js(c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:we(e)}]}}function ZI(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 Zs(e,t){let n=zI(e);if(n==="error"){let r=Ro(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 FR=y(()=>{"use strict";Xs();xi();tt();Oa();ur()});import MR from"node:path";function DR(e){return[...new Set(e)]}function GR(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 HR(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!MR.isAbsolute(r.localPath)?MR.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function zR(e){if(e.from?.kind!=="github")return Gr(e);let t=e.from,{owner:n,repo:r}=GR(t);if(!n||!r)return{results:[],diagnostics:[w("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=Xe(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}=HR(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:DR([...d.excludeDir??[],".git"]),exclude:DR([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await Gr(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 BR(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[NR(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}=GR(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:Xe(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}=HR(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:[NR(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 NR(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 QR=y(()=>{"use strict";Xs();Yc();tt();ur()});import{builtinModules as eF}from"node:module";import he from"node:path";import{readFile as ea,readdir as tF}from"node:fs/promises";async function ta(e){let t=he.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=iF(r,e.intent,e.facets),i=sF(o,e.facets),s=aF(o,i),a=hF();if(n==="plan")return cF({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:$R([],[],a)});let c=await lF(t,e.maxFiles??5e3),l=await uF(c.filter(x=>x.endsWith(nF))),u=await mF(t,c),d=u.map(x=>x.graphFacts).filter(x=>x!==void 0),p=$R(u,d,a);await vF(u);let f=new Set(l.map(x=>x.name).filter(KR)),m=RF(u),g=SF(t,l,u),b=PF(g,m),P=u.filter(x=>!b.has(x.path)).map(x=>({kind:"unusedFile",file:x.rel,retainedBy:[],verdict:"unused-file"})),S=CF(t,l,u,f),T=await xF(u),L=EF(T,u,b),E=L.filter(x=>x.verdict==="candidate-unused-export"||x.verdict==="unused-export").length,O=L.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:P.length,unlistedDependencies:S.filter(x=>x.kind==="unlistedDependency").length,unusedDependencies:S.filter(x=>x.kind==="unusedDependency").length,duplicateDependencies:S.filter(x=>x.kind==="duplicateDependency").length,exportedSymbols:L.length,candidateUnusedExports:E,transitiveDeadExports:O,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((x,N)=>x+N.declarations.length,0),nativeGraphCalls:d.reduce((x,N)=>x+N.calls.length,0)},manifests:l.map(x=>({manifest:Sn(t,x.path),...x.name?{name:x.name}:{},entrypoints:x.entrypoints.map(N=>Sn(t,N)),dependencyCount:[...x.deps.keys()].length})),files:P,dependencies:S,symbols:L,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 iF(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 sF(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 aF(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 cF(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 lF(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await tF(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(rF.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 uF(e){return(await Promise.all(e.map(async n=>dF(n)))).filter(n=>n!==null)}async function dF(e){let t=await pF(e);if(!t)return null;let n=he.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=IF(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:WR(t.name),deps:r,entrypoints:fF(n,t)}}async function pF(e){try{let t=JSON.parse(await ea(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function fF(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=WR(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));qR(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 qR(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))qR(e,r,n)}async function mF(e,t){let n=Mu(),r=t.filter(i=>n.has(he.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await ea(i,"utf8").catch(()=>""),a=he.extname(i).toLowerCase(),c=gF(s,i,Sn(e,i)),l=MF(c?c.imports.map(u=>u.specifier):bF(s));return{path:i,rel:Sn(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!VR(u)).map(_F).filter(KR).filter(u=>!oF.has(u)),...c?{graphFacts:c}:{}}}))}function gF(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(FF):[]}}catch{return}}function Mu(){if(So)return So;try{let e=M.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());So=new Set(e.length>0?e:UR)}catch{So=new Set(UR)}return So}function hF(){if(Po)return Po;try{let e=JSON.parse(M.getGraphFactCapabilities());Po=Array.isArray(e)?e.filter(yF):[]}catch{Po=[]}return Po}function yF(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 $R(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...Mu()].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 bF(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 RF(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(!VR(a))continue;let c=LF(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function SF(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=Fu(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=Fu(he.resolve(e,i),r);s&&o.add(s)}return[...o]}function PF(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 CF(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=wF(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:Sn(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:Sn(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:Sn(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function wF(e,t){return t.filter(r=>e.startsWith(`${r.dir}${he.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function xF(e){return(await Promise.all(e.map(async n=>{let r=kF(n);if(r.length>0)return r;let o=await ea(n.path,"utf8").catch(()=>"");return TF(n.rel,o)}))).flat()}function kF(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 TF(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:AF(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 EF(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&&OF(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 OF(e,t){return Iu.get(e)?.has(t)??!1}async function vF(e){Iu.clear(),await Promise.all(e.map(async t=>{let n=await ea(t.path,"utf8").catch(()=>"");Iu.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function AF(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function LF(e,t,n){return Fu(he.resolve(e,t),n)}function Fu(e,t){let n=Mu(),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 VR(e){return e.startsWith("./")||e.startsWith("../")}function _F(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function IF(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function WR(e){return typeof e=="string"&&e.trim()?e:void 0}function KR(e){return typeof e=="string"&&e.length>0}function FF(e){return typeof e=="string"}function MF(e){return[...new Set(e)]}function Sn(e,t){return he.relative(e,t)||he.basename(t)}var UR,nF,rF,oF,So,Po,Iu,Du=y(()=>{"use strict";ge();UR=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],nF="package.json",rF=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),oF=new Set(eF.flatMap(e=>[e,`node:${e}`]));Iu=new Map});import Nu from"node:path";function na(e){let t=e.root,n=[...e.symbols.map(a=>DF(t,a)),...e.files.map(a=>zF(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>BF(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 DF(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=NF(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:GF(r),next:HF(e,t)}}function NF(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 GF(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 HF(e,t){let n=Nu.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 zF(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:Nu.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:Nu.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function BF(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 Gu=y(()=>{"use strict"});import{statSync as QF}from"node:fs";import ee from"node:path";function Kt(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function YR(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 Qu(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 UF(e,t){if(!t||ee.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?ee.join(n.base,t):t}function $F(e,t,n){let r=t??n??".";if(!e)return r;if(ee.isAbsolute(e))return e;if(n&&ee.isAbsolute(n))return ee.resolve(n,e);if(t&&ee.isAbsolute(t)){let o=uS(t)?t:ee.dirname(t);return ee.resolve(o,e)}return e}function XR(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function iS(e){if(!e)return[];for(let t of oS){let n=e[t];if(Array.isArray(n))return n}return[e]}function qF(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 VF(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))jF.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 wo(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=g0(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function sS(e){return e==="plan"||e==="prove"?e:"analyze"}function ra(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??WF),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 KF(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;aS.includes(o)&&t.add(o)}return t.size>0?t:void 0}function YF(e,t){let n=KF(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 aS){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=ra(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 XF(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 JR(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 JF(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:JR(e.relation),verdicts:JR(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 ZF(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 sr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function cS(e,t){if(!ZF(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=>sr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>sr(i.relation,t)),o=e.why.some(i=>sr(i.claim,t));return n||r||o}function Hu(e,t){e.set(t.id,t)}function e0(e,t,n){sr(t.claim,n)&&e.set(t.id,t)}function zu(e,t,n,r){sr(n.relation,r)&&(Hu(e,n.from),Hu(e,n.to),t.set(n.id,n))}function t0(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function n0(e,t,n,r,o,i){let s=t.filter(g=>cS(g,r)),a=ra(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(Hu(l,g.subject),r.includeFacts)for(let b of g.why)e0(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of g.retainedBy)zu(l,u,b,r);if(r.direction!=="incoming")for(let b of g.retains??[])zu(l,u,b,r)}for(let b of g.missingProof)p.set(t0(b),b)}return r.includeEdges&&i0(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 lS(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 r0(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 i0(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=s0(a.relation);if(!sr(c,i))continue;let l=ZR(a.from,e,a.line),u=ZR(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||zu(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 s0(e){let t=e.trim();return o0.has(t)?t:"references"}function ZR(e,t,n){let r=a0(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 a0(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:ee.isAbsolute(o)?ee.relative(t,o):o,name:i}}function eS(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function c0(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 l0(e,t,n,r,o){let i=n.filter(l=>cS(l,r)),s=ra(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 d0(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"),u0(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 u0(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 d0(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=ee.isAbsolute(t.subject.uri)?t.subject.uri:ee.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=p0(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=Kt(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:Uu(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=Co(a?.totalReferences)??Co(u?.totalReferences)??Co(a?.referenceCount)??Co(u?.referenceCount)??Co(d?.totalItems)??tS(u)??tS(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:f0(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 p0(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 tS(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 f0(e,t){let n=new Set;return Bu(e,n,t),[...n].slice(0,25)}function Bu(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)Bu(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"&&m0(i)&&t.add(ee.isAbsolute(i)?ee.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])Bu(r[o],t,n)}function m0(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}function Co(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Uu(e){return typeof e=="string"?e:void 0}function nS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function g0(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 $u(e,t){let{status:n,data:r}=Kt(e);return n==="error"?[w("invalidQuery",Qu(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[w("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function uS(e){try{let t=ee.isAbsolute(e)?e:ee.resolve(e);return QF(t).isDirectory()}catch{return!1}}function oa(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 Yt(e){return e.params??{}}function h0(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function ju(e,t){let n={...Yt(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 ia(e,t,n,r){let{data:o,status:i}=Kt(e),s=$u(e,n),a=i==="error"?[]:iS(o);a.length===0&&!s.some(p=>p.code==="zeroMatches"||p.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=xt(c,l),d=t==="package"?qF(o):void 0;return{results:wo(a,t,r,VF(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function y0(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:dS(o,t)})),n}function dS(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 b0(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:dS(n,t)}}async function R0(e){let{owner:t}=oa(e.from),n=ju(e,"limit"),r=typeof n.language=="string"?n.language:h0(e),o=xa(r);o&&(n.language=o);let i=await Re("ghSearchRepos",{...t?{owner:t}:{},...n});return ia(i,"repository","ghSearchRepos",e.from??{kind:"github"})}async function S0(e){let t=await Re("npmSearch",{...ju(e)});return ia(t,"package","npmSearch",e.from??{kind:"npm"})}async function rS(e){let{owner:t,repo:n}=oa(e.from),r=e.target==="commits",o=r?void 0:w0(e),i=r?P0(e):void 0,s=ju(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=ia(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?k0(c,o):i?C0(c,i):c}function P0(e){let t=Yt(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function C0(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 w0(e){let t=Yt(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 x0(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(`
45
+ `)}function k0(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=x0(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 T0(e){let t=Yt(e),{owner:n,repo:r}=oa(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 ia(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?E0(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):O0(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 E0(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=Kt(i),c=Kt(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=Qu(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=pS(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 O0(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=YR(i),c=YR(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=Qu(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=pS(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 pS(e,t){let n=e===""?[]:e.split(`
46
+ `),r=t===""?[]:t.split(`
47
+ `),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(`
48
+ `)}}async function v0(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,...Yt(e)}),{data:r,status:o}=Kt(n),i=$u(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:wo([r],"artifact",e.from),diagnostics:[...i,...A0(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function A0(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:L0(t,n)})]}function L0(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 _0(e){let t,n,r=[],o=[],i=Yt(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=uS(E);n=c??(O?ee.resolve(E):void 0),t=a??(O?void 0:E)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let E=XR(e),O=E?ee.isAbsolute(E)?E:ee.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}=oa(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,N=XR(e),I=x&&!ee.isAbsolute(x)?x:N,v=await Re("ghCloneRepo",{owner:E,repo:O,...e.from.ref?{branch:e.from.ref}:{},...I?{sparsePath:I}:{}}),z=Kt(v).data,H=UF(v,z?.localPath);if(!H)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:H}),s?(n=c??H,x?t=ee.isAbsolute(x)?x:ee.join(H,x):N&&(t=ee.isAbsolute(N)?N:ee.join(H,N))):x?t=ee.isAbsolute(x)?x:ee.join(H,x):N?t=ee.isAbsolute(N)?N:ee.join(H,N):t=H}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}=Kt(f),b=m,P=b0(b,e),S=$F(Uu(b?.uri),t,n),T=M0(e,S),L=F0(I0(b),u);return{results:g==="error"?[]:wo(L,"semantics",T),...P?{pagination:P}:{},diagnostics:[...o,...$u(f,"lspGetSemantics"),...y0(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:T}]}}function I0(e){if(!e)return[];let n=(nS(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=Uu(e.uri);return n.map(o=>nS(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return iS(e)}function F0(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 M0(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 D0(e){let t=Yt(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=sS(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 ta({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}:na(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?ra(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"?YF(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:lS(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=XF(l?.pagination,d.pagination);return{results:wo([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function N0(e){let t=Yt(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=sS(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 ta({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:na(i),a=JF(t),c=s?.packets??[],l=eS(i.mode,t)?await l0(n,e,c,a,c0(e,t)):[],u=r0(c),d=n0(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"?[eS(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:lS(i.graphFacts),caveats:p};return{results:wo([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var oS,jF,WF,aS,o0,fS,mS=y(()=>{"use strict";Xs();xi();tt();Lo();Fo();Du();Gu();oS=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],jF=new Set([...oS,"pagination","contentPagination","next"]);WF=25;aS=["manifests","files","dependencies","symbols","graphFacts"];o0=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"]);fS={repositories:R0,packages:S0,pullRequests:rS,commits:rS,diff:T0,artifacts:v0,semantics:_0,research:D0,graph:N0}});var bR={};MS(bR,{buildArtifactContinuations:()=>CS,runOqlSearch:()=>yS});import ct from"node:path";import{statSync as hS}from"node:fs";async function yS(e,t={}){let n;try{n=ma(e)}catch(o){if(o instanceof Rt)return Ho(o.diagnostics);throw o}if(Yu(n))return SM(n,e,t);let r=await bS(n,e,t);return qu(r.results),r}function qu(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 bS(e,t,n,r){let o=Ma(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return uM(o,s,e.id,r,n.dryRun,e);let a=await RM(e,o);fM(e,a.results),G0(e,a),H0(a);let c=$0(e,a);q0(e,a.results);let l=bM(e,a.results),u=j0(a.results);return pr({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:Na(o.plan.backendCalls),plan:s})}function G0(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&t.pagination?.totalItemsKind==="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 H0(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 z0(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 B0(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function Q0(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 U0(e){let t=Q0(e),n=B0(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 ${gS(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 ${gS(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 gS(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function $0(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;t.pagination?.hasMore&&e.target!=="content"&&!r&&(n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:"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. ${U0(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:cM(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=K0[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function j0(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||RS(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function RS(e,t){return e.why===t.why&&e.confidence===t.confidence}function q0(e,t){for(let n of t)n.proofGrade??=V0(e,n)}function V0(e,t){return t.kind==="code"?xo(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":xo(e.where,"text")||xo(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"?sa(t.data)?"missing":"graph":t.recordType==="research"?sa(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function xo(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>xo(n,t)):e.kind==="not"?xo(e.predicate,t):!1:!1}function sa(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(!W0(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function W0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Y0(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:z0(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 X0(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 SS(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 PS(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function CS(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=PS(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,SS(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 J0(e){let t=PS(e);return t?SS(t,"materialized"):void 0}function Z0(e,t){return wS(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function eM(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(sa(r))return wS(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function wS(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!sa(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=nM(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 nM(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"&&tM.has(o));return r.length>0?r:void 0}function rM(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=sM(e)??aM(t.query),i=oM(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 oM(e,t){if(e&&ct.isAbsolute(e))return e;if(t&&ct.isAbsolute(t)){let n=iM(t);return e?ct.resolve(n,e):t}return t??e}function iM(e){try{return hS(e).isDirectory()?e:ct.dirname(e)}catch{return ct.dirname(e)}}function sM(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function aM(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function cM(e){let t=kS(e);if(!t)return;let n=xS(t).slice(0,-ct.sep.length);return r=>({kind:"local",path:ct.isAbsolute(r)?r:ct.join(n,r)})}function lM(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 uM(e,t,n,r,o,i){let s=o&&i?dM(i):[],a=o&&i?pM(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}:{}}:Ho(e.plan.diagnostics,t,n,r,lM(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 dM(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[w("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function pM(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 xS(e){let t=ct.resolve(e);try{if(hS(t).isDirectory())return`${t}${ct.sep}`}catch{}return`${ct.dirname(t)}${ct.sep}`}function kS(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function fM(e,t){let n=kS(e);if(!n)return;let r=xS(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function bM(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):gM.has(c)?o.add(c):hM.has(c)?o.add("data"):yM.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(!mM.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 RM(e,t){if(e.target==="materialize")return BR(e);let n=fS[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?Gr(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"?zR(e):IR(e)}async function SM(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await bS(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=PM(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&qu(o.merged.results)}else for(let i of r)qu(i.envelope.results);return o}function PM(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=kM(d);n.has(p)||(n.add(p),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),CM(s,u.envelope.nextHints),wM(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),xM(u.envelope)&&(l=!0)}return l&&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:pr({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 CM(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||RS(o,r))&&(e[n]=r)}}function wM(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 xM(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function kM(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var K0,tM,mM,gM,hM,yM,xu=y(()=>{"use strict";ha();Da();tt();Ga();Yc();FR();QR();mS();_t();K0={code:Y0,content:X0,"record:artifact":CS,"record:materialized":J0,"record:semantics":rM,"record:research":Z0,"record:graph":eM};tM=new Set(["symbols","files","dependencies","relations"]);mM=new Set(["kind","source","recordType","id","proofGrade"]),gM=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),hM=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),yM=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});_t();Cn();ha();Da();_o();tt();Ga();xu();_t();function TM(e){let t=EM(e);if("error"in t)return t;let n=t.target;if(e.search==="both"){let o=Vu({...e,target:"files",search:"path"});if("error"in o)return o;let i=Vu({...e,target:n==="files"?"code":n,search:"content"});return"error"in i?i:{input:{schema:"oql",queries:[o.query,i.query],combine:"independent",...e.limit!==void 0?{limit:e.limit}:{},...e.page!==void 0?{page:e.page}:{},...e.itemsPerPage!==void 0?{itemsPerPage:e.itemsPerPage}:{}}}}let r=Vu({...e,target:n});return"error"in r?r:{input:r.query}}function Vu(e){let t=GM(e.view);if("error"in t)return t;let n=vM(e),o=e.target==="code"||e.target==="files"?AM(e):{};if("error"in o)return o;if(["code","files"].includes(e.target)&&o.where===void 0&&!e.filesOnly&&!e.filesWithoutMatch)return{error:"No search term: provide text, --regex, --pattern, or --rule."};let s={schema:"oql",target:e.target,...n};o.where&&(s.where=o.where),t.view&&(s.view=t.view),e.limit!==void 0&&(s.limit=e.limit),e.page!==void 0&&(s.page=e.page),e.itemsPerPage!==void 0&&(s.itemsPerPage=e.itemsPerPage);let a=NM(e);a&&(s.materialize=a);let c=FM(e);c&&(s.fetch=c);let l=IM(e);l&&(s.controls=l);let u=MM(e);return Object.keys(u).length>0&&(s.params=u),{query:s}}function EM(e){let t=e.target;return t?OM(t)?{target:t}:{error:`--target must be one of: ${Ge.join(", ")}.`}:e.op||e.symbol||e.uri||e.workspaceRoot?{target:"semantics"}:e.tree?{target:"structure"}:HM(e)?{target:"content"}:e.search==="path"?{target:"files"}:e.corpus.kind==="npm"?{target:"packages"}:{target:"code"}}function OM(e){return Ge.includes(e)}function vM(e){let t={};if(e.lang&&(t.language=e.lang),e.include?.length&&(t.include=e.include),e.excludeDir?.length&&(t.excludeDir=e.excludeDir),e.extension){let n=e.extension.replace(/^\./,"");t.include=[...t.include??[],`**/*.${n}`]}if(e.exclude?.length&&(t.exclude=e.exclude),e.hidden&&(t.hidden=!0),e.noIgnore&&(t.noIgnore=!0),e.minDepth!==void 0&&(t.minDepth=e.minDepth),e.maxDepth!==void 0&&(t.maxDepth=e.maxDepth),To.includes(e.target)&&e.corpus.kind==="local")return Object.keys(t).length>0?{scope:t}:{};if(e.corpus.kind==="npm")return{from:{kind:"npm"},...Object.keys(t).length>0?{scope:t}:{}};if(e.corpus.kind==="github"){let n={kind:"github",repo:e.corpus.repo,...e.branch||e.corpus.ref?{ref:e.branch??e.corpus.ref}:{}};return e.corpus.path&&(t.path=e.corpus.path),{from:n,...Object.keys(t).length>0?{scope:t}:{}}}return{from:{kind:"local",path:e.corpus.path},...Object.keys(t).length>0?{scope:t}:{}}}function AM(e){let t=LM(e);if(e.filesWithoutMatch){let r=TS(e);if("error"in r||!r.where)return r;let o={kind:"not",predicate:r.where};return{where:t.length?{kind:"all",of:[...t,o]}:o}}let n=e.search==="path"?_M(e):TS(e);return"error"in n?n:t.length&&n.where?{where:{kind:"all",of:[...t,n.where]}}:t.length===1?{where:t[0]}:t.length>1?{where:{kind:"all",of:t}}:n}function LM(e){let t=[];e.filesOnly?t.push({kind:"field",field:"entryType",op:"=",value:"file"}):(e.directoriesOnly||e.entryType)&&t.push({kind:"field",field:"entryType",op:"=",value:e.directoriesOnly?"directory":e.entryType}),e.extension&&t.push({kind:"field",field:"extension",op:"=",value:e.extension.replace(/^\./,"")}),e.filename&&t.push({kind:"field",field:"basename",op:"glob",value:ES(e.filename)}),e.pathPattern&&t.push({kind:"field",field:"path",op:"glob",value:ES(e.pathPattern)}),e.sizeGreater&&t.push({kind:"field",field:"size",op:">",value:e.sizeGreater}),e.sizeLess&&t.push({kind:"field",field:"size",op:"<",value:e.sizeLess}),e.modifiedWithin&&t.push({kind:"field",field:"modified",op:"within",value:e.modifiedWithin}),e.modifiedBefore&&t.push({kind:"field",field:"modified",op:"before",value:e.modifiedBefore}),e.accessedWithin&&t.push({kind:"field",field:"accessed",op:"within",value:e.accessedWithin}),e.empty&&t.push({kind:"field",field:"empty",op:"=",value:!0}),e.permissions&&t.push({kind:"field",field:"permissions",op:"=",value:e.permissions});for(let[n,r]of[["executable",e.executable],["readable",e.readable],["writable",e.writable]])r&&t.push({kind:"field",field:n,op:"=",value:!0});return t}function TS(e){let t=e.lang;return e.pattern!==void 0?t?{where:{kind:"structural",lang:t,pattern:e.pattern}}:{error:"--pattern requires --lang (e.g. --lang ts)."}:e.rule!==void 0?t?{where:{kind:"structural",lang:t,rule:e.rule}}:{error:"--rule requires --lang (e.g. --lang ts)."}:e.regex!==void 0?e.fixedString?{where:{kind:"text",value:e.regex,...Wu(e),...e.wholeWord?{wholeWord:!0}:{}}}:{where:{kind:"regex",value:e.regex,...e.pcre2?{dialect:"pcre2"}:{},...Wu(e),...e.wholeWord?{wholeWord:!0}:{},...e.multiline?{multiline:!0}:{},...e.multilineDotall?{dotAll:!0}:{}}}:e.text!==void 0&&e.text!==""?{where:{kind:"text",value:e.text,...Wu(e),...e.wholeWord?{wholeWord:!0}:{}}}:{}}function _M(e){if(e.regex!==void 0)return{where:{kind:"field",field:"path",op:"regex",value:e.regex}};if(e.text!==void 0&&e.text!==""){let t=/[/*?[\]]/.test(e.text);return{where:{kind:"field",field:t?"path":"basename",op:"glob",value:t?e.text:`*${e.text}*`}}}return{}}function ES(e){return/[*?[\]]/.test(e)?e:`*${e}*`}function Wu(e){return e.caseSensitive?{case:"sensitive"}:e.caseInsensitive?{case:"insensitive"}:{}}function IM(e){let t={};e.countLinesPerFile&&(t.countLinesPerFile=!0),e.countMatchesPerFile&&(t.countMatchesPerFile=!0),e.onlyMatching&&(t.onlyMatching=!0),e.unique&&(t.unique=!0),e.countUnique&&(t.countUnique=!0),e.contextLines!==void 0&&(t.contextLines=e.contextLines),e.invertMatch&&(t.invertMatch=!0),e.matchWindow!==void 0&&(t.matchWindow=e.matchWindow),e.matchContentLength!==void 0&&(t.matchContentLength=e.matchContentLength),e.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=e.maxMatchesPerFile),e.matchPage!==void 0&&(t.matchPage=e.matchPage),OS(e.target)&&e.sort&&(t.sort=e.sort),OS(e.target)&&e.sortReverse&&(t.sortReverse=!0),e.rankingProfile&&(t.rankingProfile=e.rankingProfile),e.debugRanking&&(t.debugRanking=!0);let n={};e.maxFiles!==void 0&&(n.maxFiles=e.maxFiles);let r={};return Object.keys(t).length>0&&(r.search=t),Object.keys(n).length>0&&(r.budget=n),Object.keys(r).length>0?r:void 0}function OS(e){return e==="code"||e==="files"}function FM(e){let t={},n=vS(e.contentView);n&&(t.contentView=n),(e.startLine!==void 0||e.endLine!==void 0||e.contextLines!==void 0)&&(t.range={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...e.contextLines!==void 0?{contextLines:e.contextLines}:{}}),e.matchString&&(t.match={text:e.matchString,...e.matchRegex?{regex:!0}:{},...e.matchCaseSensitive?{caseSensitive:!0}:{}}),e.charOffset!==void 0&&(t.charOffset=e.charOffset),e.charLength!==void 0&&(t.charLength=e.charLength),e.fullContent&&(t.fullContent=!0);let r={};e.maxDepth!==void 0?r.maxDepth=e.maxDepth:e.tree&&e.depth!==void 0&&(r.maxDepth=e.depth),(e.pattern||e.filename)&&(r.pattern=e.pattern??e.filename),e.includeSizes&&(r.includeSizes=!0),e.extension&&(r.extensions=zM(e.extension)),e.filesOnly&&(r.filesOnly=!0),(e.directoriesOnly||e.entryType==="directory")&&(r.directoriesOnly=!0),BM(e.sort)&&(r.sortBy=e.sort),e.sortReverse&&(r.reverse=!0);let o={};return Object.keys(t).length>0&&(o.content=t),Object.keys(r).length>0&&(o.tree=r),Object.keys(o).length>0?o:void 0}function MM(e){switch(e.target){case"code":return bt({concise:e.concise,extension:e.extension,filename:e.filename});case"semantics":return bt({type:e.op??"documentSymbols",uri:e.uri,symbolName:e.symbol,symbolKind:e.symbolKind,lineHint:e.line,orderHint:e.order,depth:e.depth,workspaceRoot:e.workspaceRoot,format:e.format});case"repositories":return bt({keywords:e.text?e.text.includes(" ")?e.text.split(/\s+/).filter(Boolean):[e.text]:void 0,topicsToSearch:e.topic?.length?e.topic:void 0,language:e.lang,owner:e.owner,stars:e.stars,forks:e.forks,goodFirstIssues:e.goodFirstIssues,license:e.license,created:e.created,updated:e.updated,size:e.size,match:e.match,archived:e.archived,visibility:e.visibility,concise:e.concise,sort:e.sort,limit:e.limit,page:e.page});case"packages":return bt({packageName:e.text,page:e.page});case"pullRequests":return bt({keywordsToSearch:e.text?[e.text]:void 0,query:void 0,concise:e.concise,state:e.state,author:e.author,label:e.label,prNumber:e.prNumber,head:e.head,base:e.base,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,draft:e.draft,archived:e.archived,sort:e.sort,order:e.orderDirection,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,charOffset:e.charOffset,charLength:e.charLength,content:DM(e),limit:e.limit,page:e.page,matchString:e.matchString,matchScope:e.matchString?"all":void 0});case"commits":return bt({path:e.corpus.kind==="github"?e.corpus.path:void 0,branch:e.branch,since:e.since,until:e.until,author:e.author,includeDiff:e.patches,limit:e.limit,page:e.page,filePage:e.filePage,itemsPerPage:e.itemsPerPage});case"artifacts":return bt({mode:e.artifactMode??"inspect",detailed:e.detailed,verbose:e.verbose,maxEntries:e.maxEntries,entriesPerPage:e.itemsPerPage,minLength:e.minLength,entryPageNumber:e.entryPageNumber,scanOffset:e.scanOffset,charOffset:e.charOffset,charLength:e.charLength,matchString:e.matchString,format:e.format,includeOffsets:e.includeOffsets,archiveFile:e.archiveFile});case"diff":{let t=e.corpus.kind==="local"&&e.diffPath!==void 0;return bt({prNumber:e.prNumber,baseRef:e.baseRef??(t?"base":void 0),headRef:e.headRef??(t?"head":void 0),path:e.diffPath??(e.corpus.kind==="github"?e.corpus.path:void 0)})}case"research":case"graph":return bt({goal:e.text,intent:e.intent,facets:e.facets,proof:e.proof,proofLimit:e.proofLimit,includePackets:e.includePackets,includeFacts:e.includeFacts,includeEdges:e.includeEdges,maxFiles:e.maxFiles});default:return{}}}function DM(e){if(!(!e.patches&&!e.patchFile&&!e.commentsContent&&!e.commitsContent&&!e.deep))return bt({metadata:!0,body:e.deep?!0:void 0,changedFiles:e.deep||e.patches||e.patchFile?!0:void 0,patches:e.patchFile?{mode:"selected",files:[e.patchFile]}:e.deep||e.patches?{mode:"all"}:void 0,comments:e.deep||e.commentsContent?{discussion:!0,reviewInline:!0}:void 0,reviews:e.deep?!0:void 0,commits:e.deep||e.commitsContent?{list:!0}:void 0})}function NM(e){if(!e.materialize&&!e.forceRefresh)return;let t=e.materialize??"auto";return e.forceRefresh?{mode:t,forceRefresh:!0}:t}function GM(e){return e?e==="discovery"||e==="paginated"||e==="detailed"?{view:e}:{error:`--view must be discovery, paginated, or detailed (got "${e}").`}:{}}function vS(e){switch(e){case"exact":return"exact";case"compact":return"compact";case"symbols":return"symbols";default:return}}function HM(e){return!!(vS(e.contentView)||e.matchString||e.startLine!==void 0||e.endLine!==void 0||e.charOffset!==void 0||e.charLength!==void 0||e.fullContent)}function bt(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function zM(e){return e.split(",").map(t=>t.trim().replace(/^\./,"")).filter(Boolean)}function BM(e){return e==="name"||e==="size"||e==="time"||e==="extension"}La();_o();_t();var ar={schema:"oql",description:"octocode search \u2014 typed read-only queries over code, files, symbols, repos, packages, history, artifacts, diffs, and graph evidence. Think source + answer type + filters + read/output options; use --explain for routing; follow next.* for pages, exact reads, materialization, or proof.",activeTargets:Ge,reservedTargets:Pn,sourceGuide:{local:'from:{kind:"local",path:"./src"}; shorthand: search "term" ./src, search ./src --tree, search file.ts --op documentSymbols. Best for local code/content/files/tree/LSP/artifacts/diff.',github:'from:{kind:"github",repo:"owner/repo",ref?}; shorthand: search "term" owner/repo, search owner/repo --tree, search owner/repo#123 --target pullRequests. GitHub code is indexed/default-branch scoped; materialize for AST/LSP/local proof.',npm:'from:{kind:"npm"} with target:"packages"; shorthand: search zod --target packages. Use to resolve package metadata and source repo, then continue with GitHub or local/materialized proof.',materialized:'from:{kind:"materialized",localPath:"/abs/path"} after target:"materialize", clone, or cache fetch. Use when a remote repo/subtree must behave like local code.'},plainLanguage:{source:"`from` = where to look: local path, GitHub repo, npm, or a materialized checkout.",answerType:"`target` = what kind of answer you want: code matches, file content, tree, files, symbols, repos, packages, PRs, commits, artifacts, diffs, research packets, graph proof, or materialization.",filters:"`where` = match/filter conditions for code and file discovery only: text, regex, AST shape, file fields, and boolean combinations.",readOptions:"`fetch` = what to read once you know the file/tree: exact content, compact content, symbol outline, ranges, match slices, or tree depth.",targetOptions:"`params` = options that belong to one answer type, such as LSP operation, PR number, package name, artifact mode, research intent, or graph proof.",output:"`view`, `select`, and `controls` = response shape, projected fields, search tuning, and cost limits.",paging:"`page` + `itemsPerPage` page the target's primary result domain. For code search that may be matched files; per-file match paging uses `controls.search.matchPage` / `--match-page`."},targetDecisionTree:{"find a string/pattern in code":"target:code (shorthand default for text/regex/--pattern/--rule; needs a where filter)","read or slice a known file":"target:content (file positional + --content-view, --start-line/--end-line, or --match-string)","see the file/dir layout":"target:structure (--tree)","find files by name/glob/ext/size/mtime":"target:files (--search path, --name/--ext/--size-greater/--modified-within)","symbol defs/refs/callers/hover":"target:semantics (--op \u2026; local or materialized only)","search GitHub repos":"target:repositories (--stars/--lang/--topic)","resolve an npm package":"target:packages","PR list or deep-read":"target:pullRequests (owner/repo#N)","commit history":"target:commits (--since/--until)","a diff":"target:diff ({prNumber} for a PR patch, {baseRef,headRef,path} for two refs)","inspect a binary/archive":"target:artifacts (--inspect/--list/--strings/--extract)","dead-code / reachability sweep":'target:research, then upgrade with target:graph proof:"lsp"',"make a remote repo behave like local (AST/LSP/negation)":"target:materialize (or clone / cache fetch)"},agentBestPractices:["Start with cheap orientation: --tree, --search path, --view discovery, or --content-view symbols.","Then narrow and read exact evidence: --match-string, --start-line/--end-line, --char-offset/--char-length, or --content-view exact.","Use snippets as discovery only; make decisions from exact content, PR/commit metadata, or LSP/graph proof.","For semantics, run documentSymbols first to get line anchors, then references/callers/hover with symbolName + lineHint.","For GitHub zero rows / providerUnindexed, do NOT claim absence \u2014 follow evidenceSemantics.providerUnindexed (verify path with structure, then materialize a bounded path).","Read evidence.answerReady, evidence.complete, diagnostics, pagination, and next.* before concluding."],quickStart:{"text search (local)":'search "functionName" ./src',"text search (GitHub)":'search "functionName" facebook/react',"package lookup (npm)":"search zod --target packages","PR deep read (GitHub)":"search facebook/react#1 --target pullRequests --comments --patches","commit history (GitHub)":"search facebook/react/packages/react/src --target commits --since 2024-01-01T00:00:00Z","browse a tree (local dir or owner/repo)":"search ./src --tree | search facebook/react --tree","read a file (local or owner/repo/path)":"search ./src/index.ts | search facebook/react/packages/react/src/index.js","read a remote file (exact)":"search facebook/react/README.md --content-view exact","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","artifact inspect/list":"search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect","PR diff (GitHub)":"search facebook/react#123 --target diff | search facebook/react --target diff --pr 123","two-ref / two-file diff":"search src/a.ts src/b.ts --target diff | search owner/repo --target diff --base-ref <sha> --head-ref <sha> --path <file>","structural AST (local \u2014 needs full node shape)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" ./src --lang ts',"structural AST (GitHub \u2014 clones bounded subtree)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" facebook/react/packages --lang js --materialize auto',"GitHub index miss recovery":"search useState packages/react/src --repo facebook/react --materialize required | clone facebook/react/packages/react/src | cache fetch facebook/react packages/react/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},semanticsGuide:{documentSymbols:"list a file's symbols to get line anchors first (run before references/callers/hover)",references:"all usages of a symbol across the workspace (often includes its declaration)",callers:"incoming calls to a function/method (call sites only) \u2014 narrower than references",hover:"type, signature, and docs at a symbol"},query:{schema:'"oql" (inserted by normalization)',target:Ge.join(" | "),from:'{ kind:"local", path } | { kind:"github", repo?, owner?, ref? } | { kind:"materialized", localPath, source? } | { kind:"npm" } \u2014 local row.path is relative to from.path; the pre-filled next.fetch carries the resolved ABSOLUTE path, so follow it directly rather than re-joining paths yourself',scope:"{ path?, language?, include?, exclude?, excludeDir?, hidden?, noIgnore?, minDepth?, maxDepth? } \u2014 minDepth/maxDepth bound directory recursion depth (0-64)",where:"filters for code/files only: text | regex | structural | field | all | any | not. To read a matched file slice, use fetch.content.match. For PR/commit/artifact text narrowing, use that target params hint.",materialize:'{ mode:"never"|"auto"|"required", strategy?:"file"|"tree"|"subtree"|"repo", allowFullRepo?, forceRefresh? }',fetch:'{ content?: { contentView:"exact"|"compact"|"symbols", fullContent?, match?:{text|regex,case?}, range?:{startLine?,endLine?,contextLines?}, charOffset?, charLength? }, tree?:{ maxDepth?, pattern?, includeSizes?, extensions?, filesOnly?, directoriesOnly?, sortBy?:"name"|"size"|"time"|"extension", reverse? } } \u2014 read options for known files/trees; fetch.content.fullContent:true returns the WHOLE file in one shot (lossless, no char-window paging); to read the region around a string, anchor with fetch.content.match (NOT a top-level where, which is code/files only)',params:"target options (validated by OQL for common fields and by the backing tool exhaustively) \u2014 see params hints below",select:"string[] projection of result/continuation fields",view:"discovery | paginated | detailed",controls:"{ search?: { countLinesPerFile?, countMatchesPerFile?, onlyMatching?, unique?, countUnique?, contextLines?, invertMatch?, matchWindow?, matchContentLength?, maxMatchesPerFile?, matchPage?, sort?, sortReverse?, rankingProfile?, debugRanking? }, budget?: { maxFiles?, maxCandidates?, maxBytes?, maxMaterializedBytes?, maxPlanNodes?, maxBooleanExpansion?, timeoutMs? } } \u2014 output/cost controls",limit:"number \u2014 total result cap where supported. Prefer itemsPerPage for paged research/graph/file-history continuations.",page:"number \u2014 top-level page number for OQL windowing/continuations",itemsPerPage:"number \u2014 page size for the target primary result domain. For code search this may be matched files, not individual matches; per-file match paging uses controls.search.matchPage. Per-target params expose backing-tool sub-pages only (filePage/commentPage/commitPage, entryPageNumber, scanOffset, etc.).",explain:"boolean"},params:{semantics:'{ type:"definition"|"references"|"callers"|"callees"|"callHierarchy"|"hover"|"documentSymbols"|"typeDefinition"|"implementation"|"workspaceSymbol"|"supertypes"|"subtypes"|"diagnostic", uri?, symbolName?, symbolKind?, lineHint?, orderHint?, depth?, contextLines?, includeDeclaration?, groupByFile?, workspaceRoot?, format? } \u2014 backing tool lspGetSemantics; contextLines adds call-flow snippets; symbolKind filters returned symbol rows after documentSymbols/workspaceSymbol',repositories:"{ keywords?: string[], topicsToSearch?: string[], language?, owner?, stars?, license?, sort?, archived?, limit?, page? } \u2014 backing tool ghSearchRepos; keywords/topicsToSearch are arrays even for one term",packages:'{ packageName?: string | keywords?: string[], mode?:"lean"|"full", page? } \u2014 backing tool npmSearch',pullRequests:'{ state?:"open"|"closed"|"merged", author?, label?, keywordsToSearch?, prNumber?, reviewMode?, filePage?, commentPage?, commitPage?, limit?, page?, matchString?, matchScope?:"body"|"title"|"comments"|"reviews"|"all", content? } \u2014 backing tool ghHistoryResearch; matchString filters fetched PR title/body/comments/reviews per matchScope (default body), not a search-index query \u2014 no match \u2192 zeroMatches',commits:'{ path?, branch?, since?, until?, includeDiff?, limit?, page?, filePage?, itemsPerPage?, matchString? } \u2014 backing tool ghHistoryResearch type:"commits"; matchString filters commit messages; repo/directory diffs page changed files per commit with filePage/itemsPerPage',artifacts:'{ mode:"inspect"|"list"|"extract"|"decompress"|"strings"|"unpack", minLength?, entryPageNumber?, scanOffset?, charOffset?, charLength?, matchString? } \u2014 localBinaryInspect. matchString filters text-producing modes (extract/decompress/strings) over the current fetched payload. For large strings dumps, follow next.search on data.localPath for lossless ripgrep paging; next.artifactContent (charOffset) = next inline text window; next.artifactStrings (scanOffset) = next binary scan window. extract/unpack/decompress \u2192 tree at data.localPath (next.structure/next.files).',diff:"{ prNumber, files? } (PR patch via ghHistoryResearch) | { baseRef, headRef, path } (direct two-ref file diff via ghGetFileContent + local line diff); neither shape -> invalidQuery repair",research:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:("symbols"|"files"|"dependencies"|"relations")[], mode?:"plan"|"analyze"|"prove", maxFiles? } \u2014 TWO-PHASE: page:1+itemsPerPage:1 \u2192 data.summary (full-scope counts) and may include a bounded first packet page; page:2+ \u2192 data.packets[] continuation pages (candidates w/ retainedBy edges + per-packet next.*). Always evidence:"candidate"/answerReady:false (normal). Follow the row's pre-filled next.graph (proof:"lsp", proofLimit-bounded) to upgrade a page to LSP-proven proofStatus.`,graph:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:(\u2026)[], mode?:"plan"|"analyze"|"prove", maxFiles?, subject?, subjectKind?, relation?, verdict?, direction?:"incoming"|"outgoing"|"both", proof?:"none"|"lsp", proofLimit?, includePackets?, includeFacts?, includeEdges? } \u2014 UPGRADE PATH: run a research row's pre-filled next.graph directly. proof:"lsp" sets per-row proofStatus: "confirmed-by-lsp" (refs=0 in bounded workspace; still inspect entrypoints/exports before deletion), "conflicting-evidence" (refs>0 \u2192 retained, check retainedBy), "needs-framework-graph" (maybe an entrypoint). answerReady:false is normal \u2014 follow next.* for more pages/proof.`,materialize:'(no params; no `where`) clone/cache a bounded corpus (from:{kind:"github",repo} + scope.path) and return a stable materialized checkpoint row (localPath/repoRoot/ref/cache/complete) with next.structure/next.files. Use after GitHub providerUnindexed; for CLI alternatives use clone owner/repo[/path] or cache fetch owner/repo [path] --depth file|tree|clone.'},predicates:{text:'{ kind:"text", value, case?, wholeWord? }',regex:'{ kind:"regex", value, dialect?:"rust"|"pcre2"|"provider", case?, wholeWord?, multiline?, dotAll? }',structural:'{ kind:"structural", lang, pattern? | rule? } (exactly one; rule is a JSON object or grep-compatible YAML rule string) \u2014 pattern must match the COMPLETE node, so include the parts the real node has: a fn WITH a return type only matches if the pattern has one too (`function $N($$$A): $R { $$$B }`); omitting it returns 0. Shapes: `function $N($$$A) { $$$B }` (no-return-type fn), `($$$A) => $$$B` (arrow, block+expression), `$F($$$A)` (call), `$O.$M($$$A)` (method). For "find symbol X" the ROBUST form is a rule, not a pattern: `{ kind:"function_declaration", has:{ pattern:"X" } }`. 0 matches + no parse error = pattern shape \u2260 real node (add `: $R`, or switch to a rule). Note: $$$-only patterns skip files with no literal anchor \u2192 low counts; add a literal name or use a regex where.',field:'{ kind:"field", field:"path"|"basename"|"extension"|"size"|"modified"|"accessed"|"empty"|"permissions"|"executable"|"readable"|"writable"|"entryType", op:"="|"!="|"in"|"exists"|"glob"|"regex"|">"|">="|"<"|"<="|"within"|"before", value? } (use symbolic ops like "="; aliases such as "eq" are invalid; there is no "contains" op \u2014 use op:"glob", value:"*term*" or op:"regex"; "within"/"before" compare modified/accessed times; empty/executable/readable/writable are boolean file attributes paired with op:"exists" or op:"=")',boolean:'{ kind:"all"|"any", of: Predicate[] } | { kind:"not", predicate }'},batch:{queries:"OqlQuery[] (1-5)",combine:"independent | merge"},explainRoutes:{PUSHDOWN:"Backend evaluates this predicate exactly \u2014 good. No residual work.",RESIDUAL:"Backend narrows candidates but OQL must finish evaluation locally.",ROUTE:"OQL must use a different lane, often materialization.",UNSUPPORTED:"OQL cannot execute this predicate safely on the chosen source."},defaults:Le};function QM(){return JSON.stringify(ar,null,2)}function AS(e){let t="shorthand: ",n=e.indexOf(t);if(n===-1)return null;let r=e.slice(n+t.length).trim(),o=r.length,i=r.indexOf(",");i!==-1&&(o=Math.min(o,i));let s=r.search(/\.\s/);return s!==-1&&(o=Math.min(o,s)),r.slice(0,o).trim().replace(/\.$/,"")||null}function LS(){let e=[],t=new Set;for(let[n,r]of Object.entries(ar.targetDecisionTree))for(let o of r.matchAll(/target:"?(\w+)"?/g)){let i=o[1];!i||t.has(i)||(t.add(i),e.push({target:i,task:n}))}for(let n of ar.activeTargets)t.has(n)||(t.add(n),e.push({target:n,task:"advanced target; see full schema"}));return e}function UM(){let e=ar,t=["local","github","npm","materialized"],n=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],r=e.quickStart,o=e.agentBestPractices.find(i=>/snippet/i.test(i));return{schema:"oql",kind:"octocode.search.compactScheme",description:e.description,sources:Object.fromEntries(t.map(i=>[i,AS(e.sourceGuide[i])??"a prior clone / cache fetch / materialize localPath"])),targets:LS(),recipes:Object.fromEntries(n.map(i=>[i,r[i]]).filter(i=>typeof i[1]=="string")),semantics:e.semanticsGuide,proof:{snippets:o,providerUnindexed:e.evidenceSemantics.providerUnindexed},commands:{explain:"search --explain --query '{...}'",fullSchema:"search --scheme"}}}function $M(){return JSON.stringify(UM(),null,2)}function jM(){let e=ar,t=["octocode search \u2014 compact agent guide (full reference: search --scheme)","","SOURCE \u2014 where to look (choose one):"],n=["local","github","npm","materialized"];for(let s of n){let a=AS(e.sourceGuide[s]);t.push(` ${s.padEnd(13)}${a??"a prior clone / cache fetch / materialize localPath"}`)}t.push("","TARGET \u2014 answer type (--target, or inferred from the args):");for(let{target:s,task:a}of LS())t.push(` ${s.padEnd(13)}${a}`);t.push("","COMMON RECIPES:");let r=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],o=e.quickStart;for(let s of r){let a=o[s];a&&t.push(` ${a}`)}t.push("","LSP SEMANTICS (run documentSymbols first, then narrow):");for(let[s,a]of Object.entries(e.semanticsGuide))t.push(` ${s.padEnd(16)}${a}`);t.push("","PROOF \u2014 snippets are discovery, not proof:");let i=e.agentBestPractices.find(s=>/snippet/i.test(s));return i&&t.push(` ${i}`),t.push(` ${e.evidenceSemantics.providerUnindexed}`),t.push("","Routing debug: search --explain --query '{...}'","Full schema: search --scheme"),t.join(`
49
+ `)}oo();Du();Gu();export{Ge as ACTIVE_TARGETS,To as CORPUS_OPTIONAL_TARGETS,Le as DEFAULTS,ar as OQL_SCHEMA_DOC,id as OqlBatchSchema,BS as OqlCanonicalInputSchema,la as OqlInputBatchSchema,ca as OqlInputQuerySchema,lr as OqlQuerySchema,Jt as OqlSearchInputSchema,Rt as OqlValidationError,It as PredicateSchema,Eo as QuerySourceSchema,Pn as RESERVED_TARGETS,Xt as StructuralRuleSchema,ta as analyzeResearchFlow,ba as appliedDefaults,Aa as backendCallsForTransformer,Na as backendsApproximate,ua as blocksAnswer,pr as buildEnvelope,na as buildResearchPackets,TM as buildShorthandInput,w as diagnostic,Do as findTransformerById,tn as findTransformerEntry,qS as hasErrors,Xu as isBatchEnvelope,Ku as isBatchInput,Yu as isCanonicalBatch,LP as listTransformerEntries,ma as normalizeInput,ga as normalizeQuery,$M as oqlCompactSchemeJson,jM as oqlCompactSchemeText,QM as oqlSchemaText,Ma as planQuery,yS as runOqlSearch,yt as sanitizeStructuredContent,Ho as unsupportedEnvelope};