@octocodeai/octocode-tools-core 18.1.2 → 18.2.0

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 (224) hide show
  1. package/README.md +113 -162
  2. package/dist/cacheMaintenance.d.ts +8 -0
  3. package/dist/direct.js +41 -51
  4. package/dist/github/client.d.ts +1 -1
  5. package/dist/github/codeSearch.d.ts +2 -2
  6. package/dist/github/commit.d.ts +48 -0
  7. package/dist/github/compare.d.ts +2 -2
  8. package/dist/github/directoryFetch/fetchDirectoryContents.d.ts +1 -1
  9. package/dist/github/directoryFetch/fetchFileContentToDisk.d.ts +1 -1
  10. package/dist/github/directoryFetch/refResolution.d.ts +6 -0
  11. package/dist/github/fileContent.d.ts +1 -1
  12. package/dist/github/fileContentRaw/fetch.d.ts +2 -2
  13. package/dist/github/githubAPI.d.ts +1 -2
  14. package/dist/github/history/commitFiles.d.ts +5 -0
  15. package/dist/github/history.d.ts +1 -1
  16. package/dist/github/issues/fetchers.d.ts +1 -1
  17. package/dist/github/issues/orchestrator.d.ts +1 -1
  18. package/dist/github/issues/types.d.ts +5 -0
  19. package/dist/github/prByNumber.d.ts +1 -1
  20. package/dist/github/prContentFetcher/commits.d.ts +1 -1
  21. package/dist/github/prContentFetcher/transform.d.ts +1 -1
  22. package/dist/github/pullRequestSearch.d.ts +1 -1
  23. package/dist/github/queryBuilders/codeAndRepo.d.ts +1 -1
  24. package/dist/github/repoSearch.d.ts +2 -2
  25. package/dist/github/repoStructure/contentResolution.d.ts +1 -1
  26. package/dist/github/repoStructure/fetchOrchestration.d.ts +2 -2
  27. package/dist/github/repoStructurePagination.d.ts +1 -1
  28. package/dist/graph/advancedOperations.d.ts +22 -0
  29. package/dist/{tools/local_dead_code/graphBuilder.d.ts → graph/buildFileGraph.d.ts} +6 -5
  30. package/dist/graph/cycleOperations.d.ts +12 -0
  31. package/dist/{tools/local_dead_code → graph}/importResolver.d.ts +1 -1
  32. package/dist/graph/operations.d.ts +7 -0
  33. package/dist/{tools/local_dead_code → graph}/reachability.d.ts +1 -1
  34. package/dist/{tools/local_dead_code → graph}/types.d.ts +11 -0
  35. package/dist/graph/workspacePackageResolver.d.ts +2 -0
  36. package/dist/index.d.ts +11 -30
  37. package/dist/index.js +45 -55
  38. package/dist/providers/github/githubContent.d.ts +1 -1
  39. package/dist/providers/github/githubPullRequests.d.ts +1 -1
  40. package/dist/providers/github/githubSearch.d.ts +1 -1
  41. package/dist/providers/github/githubStructure.d.ts +1 -1
  42. package/dist/providers/github/paginationMetadata.d.ts +4 -5
  43. package/dist/providers/providerQueries.d.ts +1 -3
  44. package/dist/providers/providerResults.d.ts +4 -0
  45. package/dist/providers/types.d.ts +1 -1
  46. package/dist/responses.d.ts +1 -1
  47. package/dist/schema.d.ts +2 -0
  48. package/dist/schema.js +13 -1
  49. package/dist/scheme/conditionalSchemas.d.ts +12 -0
  50. package/dist/scheme/fields.d.ts +2 -1
  51. package/dist/security/bridge.d.ts +7 -10
  52. package/dist/shared/credentials/index.js +2 -2
  53. package/dist/shared/paths.d.ts +1 -0
  54. package/dist/shared/paths.js +1 -1
  55. package/dist/shared/session/index.js +1 -1
  56. package/dist/toolContract/descriptions.d.ts +14 -0
  57. package/dist/toolContract/input/resources/global.d.ts +15 -0
  58. package/dist/toolContract/input/resources/toolRelations.d.ts +1 -0
  59. package/dist/toolContract/input/resources/toolVariants.d.ts +9 -0
  60. package/dist/toolContract/input/resources/tools/_toolkit.d.ts +75 -0
  61. package/dist/toolContract/input/resources/tools/ghCloneRepo.d.ts +12 -0
  62. package/dist/toolContract/input/resources/tools/ghGetFileContent.d.ts +30 -0
  63. package/dist/toolContract/input/resources/tools/ghSearch.d.ts +76 -0
  64. package/dist/toolContract/input/resources/tools/githubCodeOperation.d.ts +29 -0
  65. package/dist/toolContract/input/resources/tools/githubHistorySchema.d.ts +114 -0
  66. package/dist/toolContract/input/resources/tools/githubRepositoriesOperation.d.ts +54 -0
  67. package/dist/toolContract/input/resources/tools/githubTreeOperation.d.ts +26 -0
  68. package/dist/toolContract/input/resources/tools/historyCommitInput.d.ts +21 -0
  69. package/dist/toolContract/input/resources/tools/historyIssueInput.d.ts +59 -0
  70. package/dist/toolContract/input/resources/tools/historyPullRequestInput.d.ts +98 -0
  71. package/dist/toolContract/input/resources/tools/localAnalyzeGraph.d.ts +75 -0
  72. package/dist/toolContract/input/resources/tools/localFilesOperation.d.ts +70 -0
  73. package/dist/toolContract/input/resources/tools/localGetFileContent.d.ts +22 -0
  74. package/dist/toolContract/input/resources/tools/localSearch.d.ts +258 -0
  75. package/dist/toolContract/input/resources/tools/localTextOperation.d.ts +113 -0
  76. package/dist/toolContract/input/resources/tools/localTreeOperation.d.ts +44 -0
  77. package/dist/toolContract/input/resources/tools/lspGetSemantics.d.ts +37 -0
  78. package/dist/toolContract/input/resources/tools/npmSearch.d.ts +10 -0
  79. package/dist/toolContract/input/types/index.d.ts +24 -0
  80. package/dist/toolContract/metadata.d.ts +11 -0
  81. package/dist/toolContract/runtime.d.ts +11 -0
  82. package/dist/toolContract/schemas.d.ts +31 -0
  83. package/dist/toolContract/types.d.ts +11 -0
  84. package/dist/tools/directToolCatalog/toolCatalogDefinitions.d.ts +6 -16
  85. package/dist/tools/directToolCatalog/toolCatalogFormatters.d.ts +1 -1
  86. package/dist/tools/directToolCatalog/toolCommandPatternUnifiedSearchQueries.d.ts +6 -0
  87. package/dist/tools/directToolCatalog/toolInputPreparation.d.ts +2 -2
  88. package/dist/tools/directToolCatalog/toolSchemaIntrospection.d.ts +10 -0
  89. package/dist/tools/directToolCatalog/toolSchemaRelations.d.ts +9 -0
  90. package/dist/tools/directToolCatalog/toolSpecifications.d.ts +13 -0
  91. package/dist/tools/directToolCatalog.exec.d.ts +1 -1
  92. package/dist/tools/directToolCatalog.meta.d.ts +1 -0
  93. package/dist/tools/executionGuard.d.ts +1 -2
  94. package/dist/tools/github_clone_repo/cache.d.ts +1 -2
  95. package/dist/tools/github_clone_repo/cacheArtifacts.d.ts +3 -0
  96. package/dist/tools/github_clone_repo/cachePaths.d.ts +1 -1
  97. package/dist/tools/github_clone_repo/cloneRepo.d.ts +1 -1
  98. package/dist/tools/github_clone_repo/execution.d.ts +1 -1
  99. package/dist/tools/github_clone_repo/scheme.d.ts +24 -24
  100. package/dist/tools/github_fetch_content/execution.d.ts +1 -1
  101. package/dist/tools/github_fetch_content/finalizer/types.d.ts +19 -16
  102. package/dist/tools/github_fetch_content/scheme.d.ts +19 -16
  103. package/dist/tools/github_fetch_content/types.d.ts +4 -3
  104. package/dist/tools/github_search/execution.d.ts +4 -0
  105. package/dist/tools/github_search/finalizer.d.ts +3 -0
  106. package/dist/tools/github_search/scheme.d.ts +79 -0
  107. package/dist/tools/github_search_code/execution.d.ts +4 -2
  108. package/dist/tools/github_search_code/finalizer/groups.d.ts +3 -3
  109. package/dist/tools/github_search_code/finalizer/ranking.d.ts +1 -2
  110. package/dist/tools/github_search_code/scheme.d.ts +10 -16
  111. package/dist/tools/github_search_pull_requests/contentRequest.d.ts +1 -4
  112. package/dist/tools/github_search_pull_requests/contentResponse/commentsShaping.d.ts +8 -4
  113. package/dist/tools/github_search_pull_requests/contentResponse/fileSurfaces.d.ts +13 -10
  114. package/dist/tools/github_search_pull_requests/contentResponse/nextCalls.d.ts +3 -2
  115. package/dist/tools/github_search_pull_requests/contentResponse/pagination.d.ts +10 -3
  116. package/dist/tools/github_search_pull_requests/execution/commitsMode.d.ts +2 -2
  117. package/dist/tools/github_search_pull_requests/execution/issuesMode.d.ts +2 -2
  118. package/dist/tools/github_search_pull_requests/execution/pullRequestsMode.d.ts +1 -1
  119. package/dist/tools/github_search_pull_requests/execution.d.ts +1 -1
  120. package/dist/tools/github_search_pull_requests/historyContinuations.d.ts +15 -0
  121. package/dist/tools/github_search_pull_requests/historyExecutions.d.ts +6 -0
  122. package/dist/tools/github_search_pull_requests/historyPartialContinuations.d.ts +5 -0
  123. package/dist/tools/github_search_pull_requests/historySchemes.d.ts +58 -0
  124. package/dist/tools/github_search_pull_requests/historySearchPagination.d.ts +3 -0
  125. package/dist/tools/github_search_pull_requests/scheme.d.ts +14 -30
  126. package/dist/tools/github_search_pull_requests/splitExecutions.d.ts +1 -2
  127. package/dist/tools/github_search_pull_requests/splitSchemes.d.ts +197 -181
  128. package/dist/tools/github_search_repos/execution/pagination.d.ts +4 -4
  129. package/dist/tools/github_search_repos/execution/queryVariants.d.ts +3 -1
  130. package/dist/tools/github_search_repos/execution.d.ts +3 -1
  131. package/dist/tools/github_search_repos/scheme.d.ts +5 -7
  132. package/dist/tools/github_view_repo_structure/execution.d.ts +4 -2
  133. package/dist/tools/github_view_repo_structure/scheme.d.ts +2 -4
  134. package/dist/tools/github_view_repo_structure/types.d.ts +3 -0
  135. package/dist/tools/local_analyze_graph/analysisTypes.d.ts +46 -0
  136. package/dist/tools/local_analyze_graph/analyzeGraph.d.ts +3 -0
  137. package/dist/tools/{local_dead_code → local_analyze_graph}/deadCodeScan.d.ts +2 -1
  138. package/dist/tools/{local_dead_code → local_analyze_graph}/entrypoints.d.ts +1 -0
  139. package/dist/tools/local_analyze_graph/execution.d.ts +4 -0
  140. package/dist/tools/local_analyze_graph/pagination.d.ts +3 -0
  141. package/dist/tools/{local_dead_code → local_analyze_graph}/retention.d.ts +1 -1
  142. package/dist/tools/{local_dead_code → local_analyze_graph}/scheme.d.ts +31 -15
  143. package/dist/tools/local_fetch_content/execution.d.ts +1 -1
  144. package/dist/tools/local_fetch_content/scheme.d.ts +2 -4
  145. package/dist/tools/local_find_files/execution.d.ts +1 -1
  146. package/dist/tools/local_find_files/findFiles.d.ts +1 -1
  147. package/dist/tools/local_find_files/findFilesNext.d.ts +3 -3
  148. package/dist/tools/local_find_files/scheme.d.ts +6 -2
  149. package/dist/tools/local_ripgrep/captureBudget.d.ts +1 -0
  150. package/dist/tools/local_ripgrep/execution.d.ts +1 -1
  151. package/dist/tools/local_ripgrep/rankingProfile/rankingLexical.d.ts +20 -0
  152. package/dist/tools/local_ripgrep/rankingProfile/rankingResults.d.ts +1 -18
  153. package/dist/tools/local_ripgrep/rankingProfile.d.ts +5 -4
  154. package/dist/tools/local_ripgrep/ripgrepResultBuilder/searchNext.d.ts +4 -1
  155. package/dist/tools/local_ripgrep/scheme.d.ts +9 -7
  156. package/dist/tools/local_ripgrep/structuralSearch.d.ts +1 -1
  157. package/dist/tools/local_search/execution.d.ts +5 -0
  158. package/dist/tools/local_search/scheme.d.ts +260 -0
  159. package/dist/tools/local_view_structure/execution.d.ts +1 -1
  160. package/dist/tools/local_view_structure/scheme.d.ts +8 -5
  161. package/dist/tools/local_view_structure/viewStructureNext.d.ts +3 -3
  162. package/dist/tools/lsp/semantic_content/execution.d.ts +1 -1
  163. package/dist/tools/lsp/semantic_content/scheme.d.ts +4 -42
  164. package/dist/tools/lsp/semantic_content/semanticEnvelopes/envelopeHelpers.d.ts +1 -1
  165. package/dist/tools/lsp/semantic_content/semanticFileOps/anchor.d.ts +1 -1
  166. package/dist/tools/lsp/semantic_content/semanticPresentation.d.ts +0 -1
  167. package/dist/tools/lsp/shared/semanticTypes.d.ts +6 -3
  168. package/dist/tools/package_search/execution.d.ts +6 -13
  169. package/dist/tools/package_search/pagination.d.ts +21 -0
  170. package/dist/tools/package_search/queryHelpers.d.ts +3 -5
  171. package/dist/tools/package_search/scheme.d.ts +12 -7
  172. package/dist/tools/providerExecution.d.ts +3 -4
  173. package/dist/tools/providerMappers/codeSearch.d.ts +3 -4
  174. package/dist/tools/providerMappers/fileContent.d.ts +1 -2
  175. package/dist/tools/providerMappers/pullRequests.d.ts +6 -6
  176. package/dist/tools/providerMappers/repoSearch.d.ts +7 -4
  177. package/dist/tools/providerMappers/repoStructure.d.ts +2 -3
  178. package/dist/tools/toolCatalogFactory.d.ts +5 -6
  179. package/dist/tools/toolConfig.d.ts +6 -17
  180. package/dist/tools/toolMetadata/baseSchema.d.ts +1 -2
  181. package/dist/tools/toolMetadata/descriptions.d.ts +1 -1
  182. package/dist/tools/toolMetadata/names.d.ts +18 -2
  183. package/dist/tools/toolMetadata/state.d.ts +3 -3
  184. package/dist/tools/toolMetadata/types.d.ts +1 -1
  185. package/dist/tools/toolNames.d.ts +16 -3
  186. package/dist/tools/toolSchemaImports.d.ts +5 -4
  187. package/dist/tools/utils.d.ts +3 -6
  188. package/dist/types/bulk.d.ts +11 -1
  189. package/dist/types/execution.d.ts +6 -1
  190. package/dist/types/server.d.ts +0 -2
  191. package/dist/types/toolOutput.d.ts +10 -9
  192. package/dist/types/toolResults.d.ts +17 -1
  193. package/dist/utils/contextUtils.d.ts +4 -2
  194. package/dist/utils/file/toolHelpers.d.ts +1 -1
  195. package/dist/utils/http/cache/conditional.d.ts +9 -4
  196. package/dist/utils/http/cache/dataCache.d.ts +7 -2
  197. package/dist/utils/http/cache/diskStore.d.ts +30 -0
  198. package/dist/utils/http/cache/management.d.ts +5 -0
  199. package/dist/utils/http/cache/store.d.ts +1 -0
  200. package/dist/utils/http/cache/trace.d.ts +10 -0
  201. package/dist/utils/http/cache.d.ts +1 -0
  202. package/dist/utils/package/types.d.ts +5 -2
  203. package/dist/utils/pagination/charLimit.d.ts +0 -2
  204. package/dist/utils/response/bulk/pagination.d.ts +2 -1
  205. package/dist/utils/response/bulk/paginationDiagnostics.d.ts +2 -0
  206. package/dist/utils/response/bulk/queries.d.ts +0 -9
  207. package/dist/utils/response/bulk/response.d.ts +3 -2
  208. package/dist/utils/response/bulk.d.ts +1 -1
  209. package/dist/utils/response/callToolResult.d.ts +1 -1
  210. package/dist/utils/response/error.d.ts +3 -4
  211. package/dist/utils/response/groupedFinalizer.d.ts +2 -6
  212. package/dist/utils/response/normalizedError.d.ts +6 -0
  213. package/dist/utils/response/responseChannels.d.ts +4 -0
  214. package/package.json +7 -6
  215. package/dist/github/discussions.d.ts +0 -45
  216. package/dist/github/releases.d.ts +0 -45
  217. package/dist/scheme/responseEnvelope.d.ts +0 -88
  218. package/dist/tools/github_search_discussions/execution.d.ts +0 -15
  219. package/dist/tools/github_search_discussions/scheme.d.ts +0 -16
  220. package/dist/tools/github_search_pull_requests/execution/releasesMode.d.ts +0 -4
  221. package/dist/tools/local_dead_code/execution.d.ts +0 -4
  222. package/dist/tools/local_dead_code/local_dead_code.d.ts +0 -5
  223. package/dist/tools/local_find_files/pathPatternBraces.d.ts +0 -20
  224. package/dist/tools/toolMetadata/gateway.d.ts +0 -7
@@ -1,4 +1,4 @@
1
- import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
1
+ import type { AuthInfo } from '@modelcontextprotocol/server';
2
2
  import type { ProviderResponse, FileContentQuery, FileContentResult } from '../types.js';
3
3
  import type { GitHubFileContentApiData } from '../../tools/github_fetch_content/types.js';
4
4
  export { parseGitHubProjectId } from './utils.js';
@@ -1,4 +1,4 @@
1
- import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
1
+ import type { AuthInfo } from '@modelcontextprotocol/server';
2
2
  import type { ProviderResponse, PullRequestQuery, PullRequestSearchResult } from '../types.js';
3
3
  import type { GitHubPullRequestsSearchParams } from '../../github/githubAPI.js';
4
4
  import type { GitHubPullRequestSearchApiData } from '../../tools/github_search_pull_requests/types.js';
@@ -1,4 +1,4 @@
1
- import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
1
+ import type { AuthInfo } from '@modelcontextprotocol/server';
2
2
  import type { ProviderResponse, CodeSearchQuery, CodeSearchResult, RepoSearchQuery, RepoSearchResult } from '../types.js';
3
3
  import type { GitHubSearchRepositoriesData } from '@octocodeai/octocode-core/extra-types';
4
4
  import type { OptimizedCodeSearchResult } from '../../github/githubAPI.js';
@@ -1,4 +1,4 @@
1
- import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
1
+ import type { AuthInfo } from '@modelcontextprotocol/server';
2
2
  import type { ProviderResponse, RepoStructureQuery, RepoStructureResult } from '../types.js';
3
3
  import type { GitHubRepositoryStructureResult } from '../../tools/github_view_repo_structure/types.js';
4
4
  export { parseGitHubProjectId } from './utils.js';
@@ -1,13 +1,12 @@
1
1
  import type { PaginationInfo } from '../../types/toolResults.js';
2
2
  /**
3
3
  * Agent-facing count-honesty fields for search/PR pagination envelopes.
4
- * `totalMatches` (set on the base pagination) is the single count; here we add
5
- * only `totalMatchesCapped` true when GitHub reported more than the reachable
6
- * 1000-result page window. The internal `reportedTotalMatches`/
7
- * `reachableTotalMatches`/`totalMatchesKind` drive that flag but are redundant
8
- * to emit (they duplicate `totalMatches` in the common uncapped case).
4
+ * `totalMatches` (set on the base pagination) is the count. Certainty is not
5
+ * redundant when that count is only a lower bound, so expose that exceptional
6
+ * kind along with the cap flag used for GitHub's 1000-result search window.
9
7
  */
10
8
  export declare function countPaginationMetadata(pagination: PaginationInfo | undefined): {
9
+ totalMatchesKind?: 'exact' | 'reported' | 'lowerBound';
11
10
  totalMatchesCapped?: boolean;
12
11
  uniqueFileCount?: number;
13
12
  };
@@ -2,8 +2,7 @@ type ProviderType = 'github';
2
2
  interface BaseProviderQuery {
3
3
  provider?: ProviderType;
4
4
  id?: string;
5
- mainResearchGoal?: string;
6
- researchGoal?: string;
5
+ goal?: string;
7
6
  reasoning?: string;
8
7
  }
9
8
  export interface CodeSearchQuery extends BaseProviderQuery {
@@ -96,7 +95,6 @@ export interface PullRequestQuery extends BaseProviderQuery {
96
95
  teamMentions?: string;
97
96
  archived?: boolean;
98
97
  content?: unknown;
99
- reviewMode?: 'summary' | 'full';
100
98
  filePage?: number;
101
99
  commentPage?: number;
102
100
  commitPage?: number;
@@ -178,7 +178,11 @@ export interface RepoStructureResult {
178
178
  totalFiles: number;
179
179
  totalFolders: number;
180
180
  truncated: boolean;
181
+ incompleteTree?: boolean;
181
182
  };
182
183
  pagination?: PaginationInfo;
183
184
  hints?: string[];
185
+ isPartial?: boolean;
186
+ terminalLimit?: boolean;
187
+ partialReasons?: Array<'providerTreeTruncated' | 'partialTreeFailures'>;
184
188
  }
@@ -1,4 +1,4 @@
1
- import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
1
+ import type { AuthInfo } from '@modelcontextprotocol/server';
2
2
  export type { CodeSearchQuery, FileContentQuery, RepoSearchQuery, PullRequestQuery, RepoStructureQuery, } from './providerQueries.js';
3
3
  export type { UnifiedRepository, CodeSearchItem, CodeSearchResult, FileContentResult, RepoSearchResult, PullRequestItem, PullRequestSearchResult, RepoStructureResult, } from './providerResults.js';
4
4
  import type { CodeSearchQuery, FileContentQuery, RepoSearchQuery, PullRequestQuery, RepoStructureQuery } from './providerQueries.js';
@@ -1,4 +1,4 @@
1
- import { CallToolResult } from '@modelcontextprotocol/sdk/types';
1
+ import { CallToolResult } from '@modelcontextprotocol/server';
2
2
  import type { BulkToolResponse } from './types/bulk.js';
3
3
  import type { StructuredToolResponse } from './types/toolResults.js';
4
4
  export type CallToolResultOutputMode = 'text' | 'json';
package/dist/schema.d.ts CHANGED
@@ -9,4 +9,6 @@
9
9
  * For execution, import `executeDirectTool` from `@octocodeai/octocode-tools-core/direct`.
10
10
  */
11
11
  export * from './tools/directToolCatalog.meta.js';
12
+ export * from './toolContract/runtime.js';
12
13
  export { loadToolContent } from './tools/toolMetadata/state.js';
14
+ export { STATIC_TOOL_NAMES } from './tools/toolNames.js';
package/dist/schema.js CHANGED
@@ -5,4 +5,16 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- import{completeMetadata as Et}from"@octocodeai/octocode-core";var s=Et.toolNames,S=s.LSP_GET_SEMANTIC_CONTENT;function q(e=process.env){let t=e.ENABLE_RELEASES;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}function I(e=process.env){let t=e.ENABLE_DISCUSSIONS;return t===void 0?!1:["1","true","yes","on"].includes(t.trim().toLowerCase())}var Dr=new Set([s.LOCAL_RIPGREP,s.LOCAL_FETCH_CONTENT,s.LOCAL_FIND_FILES,s.LOCAL_VIEW_STRUCTURE,S]);var De=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];import{CloneRepoQuerySchema as Pt}from"@octocodeai/octocode-core/schemas";import{z as F}from"zod";function i(e,t){return F.preprocess(r=>typeof r=="number"&&Number.isFinite(r)?Math.min(Math.max(r,e),t):r,F.number().int().min(e).max(t))}var u=i(1,1e3).optional().default(1),_=i(0,100).optional(),E=i(1,1e9).optional(),Ot={responseCharOffset:i(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:i(1,5e4).optional().describe("Full-response char window.")};function l(e,t={}){let{maxQueries:r=5}=t;return F.object({queries:F.array(e).min(1).max(r).describe("Parallel queries."),...Ot}).superRefine((n,a)=>{let o=new Set;n.queries.forEach((c,d)=>{c&&typeof c=="object"&&"id"in c&&typeof c.id=="string"&&(o.has(c.id)&&a.addIssue({code:"custom",message:`Duplicate query id "${c.id}" at index ${d}`,path:["queries",d,"id"]}),o.add(c.id))})})}import{z as Pe}from"zod";function At(e,t){return e?.description&&!t.description?t.describe(e.description):t}function we(e,t){let r={};for(let[n,a]of Object.entries(t))r[n]=At(e.shape[n],a);return r}function Dt(e,t){let r=e;return r.safeExtend?r.safeExtend(t):e.extend(t)}function Ie(e,t){if(!t?.length)return e;let r=new Set(t);return Pe.object(Object.fromEntries(Object.entries(e.shape).filter(([n])=>!r.has(n))))}function m(e,t={},r={}){let n=Ie(e,r.omit),a=Dt(n,we(n,t));return r.strict?a.strict():a}function p(e,t={},r={}){let n=Ie(e,r.omit),a=Pe.object({...n.shape,...we(n,t)});return r.strict?a.strict():a}var Q=m(Pt),z=l(Q);import{z as wt}from"zod";import{FileContentQuerySchema as Fe}from"@octocodeai/octocode-core/schemas";var It=wt.enum(["none","standard","symbols"]).optional(),Qe={startLine:E,endLine:E,contextLines:_,charOffset:i(0,1e8).optional(),charLength:i(1,5e4).optional(),minify:It},Ft=p(Fe,Qe),V=m(Fe,Qe),$=l(Ft);import{z as Qt}from"zod";import{GitHubCodeSearchQuerySchema as Ge}from"@octocodeai/octocode-core/schemas";var He={limit:i(1,100).optional(),page:u.default(1),match:Qt.enum(["file","path"]).default("file").describe('"file" searches file contents and returns snippets with matchIndices. "path" searches only file paths/names \u2014 no snippets, far cheaper; use it to confirm a file exists before reading it. (Unlike ghSearchRepos/ghSearchPullRequests, where `match` instead selects which text FIELDS to search \u2014 a different concept sharing this name.)')},X=m(Ge,He),W=l(p(Ge,He));import{z as Z}from"zod";import{GitHubPullRequestSearchQuerySchema as Ne}from"@octocodeai/octocode-core/schemas";var Be={type:Z.enum(["prs","commits","releases","issues"]).optional().describe('Research mode: "prs" (default) searches pull requests; "commits" walks commit history for a repo or path; "releases" lists the repository releases (tagName, publishedAt, prerelease flag) and surfaces the latest stable release; "issues" searches or reads GitHub issues (body/discussion comments \u2014 not PRs).'),prNumber:i(1,1e9).optional(),issueNumber:i(1,1e9).optional().describe('Issue number for type:"issues" detail mode \u2014 reads that specific issue (body/discussion comments). Requires owner+repo. Falls back to prNumber if omitted.'),limit:i(1,100).optional().default(30),match:Z.array(Z.enum(["title","body","comments"])).optional().describe('Fields to match keywords against: "title", "body", "comments". Default searches all three. Use ["title"] for the most precise and fastest match. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)'),page:u.default(1),filePage:u.optional(),commentPage:u.optional(),commitPage:u.optional(),itemsPerPage:i(1,100).optional().default(20),charOffset:i(0,1e8).optional(),commentBodyOffset:i(0,1e8).optional(),charLength:i(1,5e4).optional()},Gt=p(Ne,Be),Ht=m(Ne,Be),Nt=l(Gt);import{SearchPullRequestsQuerySchema as Me,SearchIssuesQuerySchema as ve,SearchCommitsQuerySchema as Ue,ListReleasesQuerySchema as qe}from"@octocodeai/octocode-core/schemas";var je={limit:i(1,100).optional().default(30),page:u.default(1),itemsPerPage:i(1,100).optional().default(20)},ze={...je,filePage:u.optional(),commentPage:u.optional(),commitPage:u.optional(),charOffset:i(0,1e8).optional(),commentBodyOffset:i(0,1e8).optional(),charLength:i(1,1e5).optional()},K=m(Me,ze),Y=l(p(Me,ze)),Ve={...je,commentPage:u.optional(),charOffset:i(0,1e8).optional(),commentBodyOffset:i(0,1e8).optional(),charLength:i(1,1e5).optional()},ee=m(ve,Ve),te=l(p(ve,Ve)),$e={page:u.default(1),limit:i(1,100).optional().describe("Commits per page \u2014 alias of itemsPerPage (preferred when both are set)."),filePage:u.optional(),charOffset:i(0,1e8).optional(),charLength:i(1,1e5).optional()},re=m(Ue,$e),ne=l(p(Ue,$e)),Xe={page:u.default(1),limit:i(1,100).optional().describe("Releases per page \u2014 alias of itemsPerPage (preferred when both are set).")},G=m(qe,Xe),H=l(p(qe,Xe));import{SearchDiscussionsQuerySchema as We}from"@octocodeai/octocode-core/schemas";var Ze={itemsPerPage:i(1,100).optional().default(20),limit:i(1,100).optional()},N=m(We,Ze),B=l(p(We,Ze));import{z as Je}from"zod";import{GitHubReposSearchSingleQuerySchema as Ke}from"@octocodeai/octocode-core/schemas";var Ye={limit:i(1,100).optional(),page:u.default(1),match:Je.array(Je.enum(["name","description","readme"])).optional().describe("Which text fields to search: name, description, and/or readme. Defaults to name+description; add 'readme' for broader, slower full-text search. (Unlike ghSearchCode, where `match` instead selects file-contents vs file-paths \u2014 a different concept sharing this name.)")},oe=m(Ke,Ye),ie=l(p(Ke,Ye));import{GitHubViewRepoStructureQuerySchema as et}from"@octocodeai/octocode-core/schemas";var tt={maxDepth:i(0,20).optional(),page:u.default(1),itemsPerPage:i(1,200).optional()},ae=m(et,tt),se=l(p(et,tt));import{z as M}from"zod";import{NpmPackageQuerySchema as rt}from"@octocodeai/octocode-core/schemas";var nt={page:u,keywords:M.union([M.string(),M.array(M.string())]).optional().describe("Registry keyword query (string; an array of terms is accepted and joined with spaces).")},ce=m(rt,nt),ue=l(p(rt,nt,{strict:!0}),{maxQueries:5});import{z as Mt}from"zod";import{FetchContentQuerySchema as ot}from"@octocodeai/octocode-core/schemas";var vt=Mt.enum(["none","standard","symbols"]).optional(),it={startLine:E,endLine:E,contextLines:_.default(5),charOffset:i(0,1e8).optional(),charLength:i(1,5e4).optional(),minify:vt},Ut=p(ot,it),le=m(ot,it),me=l(Ut,{maxQueries:5});import{z as pe}from"zod";import{FindFilesQuerySchema as qt}from"@octocodeai/octocode-core/schemas";var at={maxDepth:i(0,100).optional(),minDepth:i(0,100).optional(),limit:i(1,1e4).optional().describe("Discovery cap applied after sort, before pagination \u2014 total results are capped here; itemsPerPage/page page within that cap."),page:u.default(1),itemsPerPage:i(1,50).optional(),excludeDir:pe.array(pe.string()).optional().describe("Directory names to prune from the walk. Common generated/vendor dirs are pruned by default (node_modules, .git, dist, build, out, coverage, target, .next, .cache); pass [] to prune nothing, or pass an explicit list to choose pruned dirs.")},st=pe.object(Object.fromEntries(Object.entries(qt.shape).filter(([e])=>e!=="regexType")));function jt(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 zt=p(st,at),he=m(st,at).superRefine(jt),ge=l(zt,{maxQueries:5});import{FindDeadCodeQuerySchema as ct}from"@octocodeai/octocode-core/schemas";var ut={maxFiles:i(1,5e4).optional(),limit:i(1,5e3).optional(),page:u.default(1),itemsPerPage:i(1,50).optional()},Vt=p(ct,ut),ye=m(ct,ut),fe=l(Vt,{maxQueries:5});import{z as T}from"zod";import{RipgrepQuerySchema as lt}from"@octocodeai/octocode-core/schemas";var $t=["paginated","discovery","detailed","structural"],Xt=["semanticRanking"],mt={mode:T.enum($t).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters. (Unrelated to ghSearchPullRequests\'s `content.patches.mode` \u2014 different concepts sharing this name.)'),searchText:T.string().optional().describe('The search pattern. regex:"fixed" for a literal match, "perl" for advanced features (lookaheads, backreferences), else "smart". (Unlike ghSearchCode/ghSearchRepos, where `keywords` is an array of ANDed terms \u2014 this is a single string.)'),output:T.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content").describe('"content" (default) matches with line text; "files"/"filesWithout" return matching/non-matching paths; "countLines"/"countMatches" return per-file counts; "matchOnly" returns just the matched substring (required for unique/matchWindow). ("files" is unlike localViewStructure\'s `filesOnly`, which filters a directory listing to file entries.)'),pattern:T.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Modifiers are part of the node \u2014 `function $NAME` does not match `async function` or `export function`; include the modifiers or use a YAML `kind` rule for modifier-agnostic matches. Use this to find syntax shape, then use lspGetSemantics for semantic proof."),maxDepth:i(0,20).optional().describe("Keep files at most this many directory levels below the search root (0 = files directly in the root). Structural mode pushes this into the native walker; text/regex mode applies it after the native search and emits a warning when it filters deeper matches."),rule:T.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),captureText:T.boolean().optional().describe("Structural only: return full verbatim capture text for `$$$` list metavars (bodies, arg lists). Default false \u2014 list-capture text is omitted from `metavars`, and `metavarRanges` entries are comment-pruned and truncated to keep results lean; ranges always remain as line anchors."),contextLines:_,matchContentLength:i(1,1e5).optional().default(500),maxMatchesPerFile:i(1,1e5).optional(),maxFiles:i(1,1e5).optional(),matchPage:u.optional(),itemsPerPage:i(1,1e3).optional(),page:u.default(1),unique:T.enum(["off","list","count"]).optional().default("off").describe('Needs output:"matchOnly". "list" returns each matched value once per file; "count" adds its frequency.')},Wt={...mt,semanticRanking:T.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},Zt=p(lt,Wt),Jt=m(lt,mt,{strict:!0,omit:Xt}),be=Jt.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let r=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(r){let n=r[0].slice(2);t.addIssue({code:"custom",message:`\`${r[0]}\` is not a metavariable and matches nothing \u2014 use \`$${n}\` for one node or \`$$$${n}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),Le=l(Zt,{maxQueries:5});import{z as pt}from"zod";import{ViewStructureQuerySchema as dt}from"@octocodeai/octocode-core/schemas";var ht={excludeDir:pt.array(pt.string()).optional().describe("Directory names to prune from recursive walks (default: common generated/vendor dirs such as node_modules, dist, build, out, coverage, target). Pass [] to inspect everything."),maxDepth:i(0,20).optional(),limit:i(1,1e4).optional(),page:u.default(1),itemsPerPage:i(1,50).optional()},Kt=p(dt,ht),Te=m(dt,ht),Ce=l(Kt,{maxQueries:5});import{z as v}from"zod";import{LspGetSemanticsQuerySchema as gt}from"@octocodeai/octocode-core/schemas";var Yt=i(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),er=i(0,1e5).optional(),tr=["structured","compact"],yt={type:v.enum(De).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:v.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:Yt.optional(),orderHint:er,depth:i(0,20).optional().describe("Traversal depth for call-hierarchy / type-hierarchy queries (0 = direct only)."),includeDeclaration:v.boolean().optional().default(!0),page:u.describe("Result page for paginated reference/symbol lists (advance while pagination.hasMore)."),itemsPerPage:i(1,100).optional().describe("References/symbols returned per page (with page)."),contextLines:i(0,100).optional().describe("Lines of surrounding source shown around each result location."),format:v.enum(tr).optional().default("structured")},rr=p(gt,yt),xe=m(gt,yt);var Re=l(rr,{maxQueries:5});var ft=["GitHub","Local Code","Package","Other"],St=new Map([s.GITHUB_SEARCH_CODE,s.GITHUB_SEARCH_REPOSITORIES,s.GITHUB_PULL_REQUESTS,s.GITHUB_ISSUES,s.GITHUB_COMMITS,s.GITHUB_FETCH_CONTENT,s.GITHUB_VIEW_REPO_STRUCTURE,s.GITHUB_CLONE_REPO,s.LOCAL_RIPGREP,s.LOCAL_FIND_FILES,s.LOCAL_FIND_DEAD_CODE,s.LOCAL_FETCH_CONTENT,s.LOCAL_VIEW_STRUCTURE,S,s.PACKAGE_SEARCH,...I()?[s.GITHUB_DISCUSSIONS]:[]].map((e,t)=>[e,t])),f=class extends Error{constructor(r,n=[]){super(r);this.details=n;this.name="DirectToolInputError"}details},nr=["id","mainResearchGoal","researchGoal","reasoning"],w=new Set([...nr]),or=[{name:s.GITHUB_SEARCH_CODE,schema:X,inputSchema:W},{name:s.GITHUB_FETCH_CONTENT,schema:V,inputSchema:$},{name:s.GITHUB_VIEW_REPO_STRUCTURE,schema:ae,inputSchema:se},{name:s.GITHUB_SEARCH_REPOSITORIES,schema:oe,inputSchema:ie},{name:s.GITHUB_PULL_REQUESTS,schema:K,inputSchema:Y},{name:s.GITHUB_ISSUES,schema:ee,inputSchema:te},{name:s.GITHUB_COMMITS,schema:re,inputSchema:ne},...q()?[{name:s.GITHUB_RELEASES,schema:G,inputSchema:H}]:[],...I()?[{name:s.GITHUB_DISCUSSIONS,schema:N,inputSchema:B}]:[],{name:s.PACKAGE_SEARCH,schema:ce,inputSchema:ue},{name:s.GITHUB_CLONE_REPO,schema:Q,inputSchema:z},{name:s.LOCAL_RIPGREP,schema:be,inputSchema:Le},{name:s.LOCAL_VIEW_STRUCTURE,schema:Te,inputSchema:Ce},{name:s.LOCAL_FIND_FILES,schema:he,inputSchema:ge},{name:s.LOCAL_FIND_DEAD_CODE,schema:ye,inputSchema:fe},{name:s.LOCAL_FETCH_CONTENT,schema:le,inputSchema:me},{name:S,schema:xe,inputSchema:Re}],ir=[...q()?[]:[{name:s.GITHUB_RELEASES,schema:G,inputSchema:H,disabled:{envVar:"ENABLE_RELEASES"}}],...I()?[]:[{name:s.GITHUB_DISCUSSIONS,schema:N,inputSchema:B,disabled:{envVar:"ENABLE_DISCUSSIONS"}}]];function C(e){return or.find(t=>t.name===e)??ir.find(t=>t.name===e)}function k(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===s.PACKAGE_SEARCH?"Package":"Other"}function No(e){return[...e].sort((t,r)=>{let n=ft.indexOf(k(t)),a=ft.indexOf(k(r));if(n!==a)return n-a;let o=St.get(t)??Number.MAX_SAFE_INTEGER,c=St.get(r)??Number.MAX_SAFE_INTEGER;return o!==c?o-c:t.localeCompare(r)})}import{z as bt}from"zod";var ar=["id","researchGoal","reasoning"];function Uo(e){let t=C(e);if(!t)return"{}";try{return JSON.stringify(bt.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(bt.toJSONSchema(t.schema,{io:"input"}),null,2)}}function qo(e){return JSON.stringify(e??{},null,2)}function jo(e){let t=k(e),r=[...ar];return(t==="GitHub"||t==="Package")&&r.splice(1,0,"mainResearchGoal"),r}function zo(e,t){return t?.tools?.[e]?.description??e}import{z as sr}from"zod";function U(e){let t=C(e);if(!t)return[];let r=sr.toJSONSchema(t.schema,{io:"input"});if(!O(r))return[];let n=b(r.properties)?r.properties:{},a=new Set(Array.isArray(r.required)?r.required.filter(o=>!w.has(o)&&!ke(n[o])):[]);return Ee(n,a)}function cr(e){let t=[],r=typeof e.minimum=="number"?e.minimum:void 0,n=typeof e.maximum=="number"?e.maximum:void 0;return r!==void 0&&n!==void 0?t.push(`${r}-${n}`):r!==void 0?t.push(`>=${r}`):n!==void 0&&t.push(`<=${n}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function _e(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let r=O(e.items)?e.items:void 0;return`array<${r?_e(r):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let r=t.filter(O).map(_e).filter(n=>n!=="value");if(r.length>0)return[...new Set(r)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Ee(e,t,r=""){let n=[];for(let[a,o]of Object.entries(e)){if(!r&&w.has(a))continue;let c=O(o)?o:{},d=r?`${r}.${a}`:a;if(n.push({name:d,required:t.has(a),type:_e(c),constraints:cr(c),description:typeof c.description=="string"?c.description:void 0}),b(c.properties)){let g=new Set(Array.isArray(c.required)?c.required.filter(y=>typeof y=="string"?!ke(c.properties?.[y]):!1):[]);n.push(...Ee(c.properties,g,d))}let h=c.type==="array"&&O(c.items)?c.items:void 0;if(h&&b(h.properties)){let g=new Set(Array.isArray(h.required)?h.required.filter(y=>typeof y=="string"?!ke(h.properties?.[y]):!1):[]);n.push(...Ee(h.properties,g,d))}}return n}function Tt(e,t){if(t.startsWith("array<")){let r=t.slice(6,-1);return[Lt(e,r)]}return Lt(e,t)}function Lt(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return e}}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O(e){return b(e)}function ke(e){return O(e)&&"default"in e}function Ct(e){return e===s.GITHUB_PULL_REQUESTS?[{label:"PR search (list)",query:{owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"PR detail (diffs + reviews)",query:{owner:"sindresorhus",repo:"slugify",prNumber:1,content:{comments:{discussion:!0},reviews:!0,patches:{mode:"all"}}}}]:e===s.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:e===s.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:e===s.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===s.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===s.LOCAL_RIPGREP?[{label:"text search",query:{path:"packages/octocode-tools-core/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural code search",query:{path:"packages/octocode-tools-core/src/tools",mode:"structural",pattern:"eval($X)"}}]:e===s.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===s.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:"packages/octocode-tools-core",names:["scheme.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/tools/**",entryType:"f",itemsPerPage:20}},{label:"prune build dirs",query:{path:"packages/octocode-tools-core",names:["*.js"],entryType:"f",excludeDir:["node_modules","dist","coverage","out"],itemsPerPage:20}}]:e===s.LOCAL_FIND_DEAD_CODE?[{label:"default entrypoints (package.json + tests)",query:{path:"packages/octocode-tools-core",itemsPerPage:20}},{label:"explicit entrypoints",query:{path:"packages/octocode-tools-core",entrypoints:["src/index.ts","src/direct.ts"],includeTests:!1}}]:e===s.LOCAL_VIEW_STRUCTURE?[{label:"shallow tree",query:{path:"packages/octocode-tools-core/src/tools",maxDepth:2,itemsPerPage:50}},{label:"files only at depth 1",query:{path:"packages/octocode-engine/src",maxDepth:1,entryType:"f",itemsPerPage:100}}]:e===s.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===s.GITHUB_COMMITS?[{label:"file history (bounded window)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",since:"6m",itemsPerPage:10}},{label:"compare two refs (base...head)",query:{owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===s.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{packageName:"schema validation",page:1}}]:e===S?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function xt(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function ur(e){let t=Ct(e);if(t.length>0)return t.map(n=>({...n,command:xt(e,n.query)}));let r=lr(e);return Object.keys(r).length===0?[]:[{label:"schema-derived",query:r,command:xt(e,r)}]}function ri(e){return ur(e)[0]?.query??{}}function lr(e){if(!C(e))return{};let t=U(e),r=t.filter(o=>!o.name.includes(".")),n=mr(r),a={};for(let o of n)a[o.name]=Tt(o.name,o.type);return e.startsWith("lsp")&&t.some(o=>o.name==="uri")&&(a.uri??="uri"),e===S&&(a.type??="definition",a.symbolName??="symbolName",a.lineHint??=1),a}var Rt=4,Oe=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),_t=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function mr(e){let t=e.filter(o=>o.required),r=new Map;for(let o of t)r.set(o.name,o);let n=e.filter(o=>!o.required&&pr(o)).sort(dr),a=Math.max(Rt,t.length);for(let o of n){if(r.size>=a)break;r.set(o.name,o)}return r.size>0?[...r.values()]:e.filter(o=>!_t.has(o.name)).filter(o=>o.type!=="boolean").slice(0,Rt)}function pr(e){return _t.has(e.name)||e.type==="boolean"?!1:hr(e)?Oe.has(e.name):!0}function dr(e,t){let r=Oe.get(e.name)??Number.MAX_SAFE_INTEGER,n=Oe.get(t.name)??Number.MAX_SAFE_INTEGER;return r!==n?r-n:e.name.localeCompare(t.name)}function hr(e){return e.constraints?.includes("default ")===!0}function ai(e,t,r={}){if(typeof t!="string")return null;let n;try{n=JSON.parse(t)}catch{throw new f("Tool input must be valid JSON.")}return gr(e,n,r)}function gr(e,t,r={}){let n=fr(e,t,r),a=C(e);if(!a)throw new f(`Unknown tool: ${e}`);let o=a.inputSchema.safeParse(n);if(!o.success)throw new f("Tool input does not match the expected schema.",yr(o.error));return o.data}function yr(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function fr(e,t,r){let n=[];if(Array.isArray(t))n=t;else if(b(t)&&Array.isArray(t.queries))n=t.queries;else if(b(t))n=[t];else throw new f('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(n.length===0)throw new f("At least one query is required.");let a=b(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},o=n.map((c,d)=>Sr(e,d,_r(e,c,d,r),{sourceLabel:r.sourceLabel}));return{...a,queries:o}}function Sr(e,t,r,n){let a={...r},o=k(e),c=n.sourceLabel??"direct tool execution",d=br(e,c);return(typeof a.id!="string"||a.id.trim().length===0)&&(a.id=`${e}-${t+1}`),(o==="GitHub"||o==="Package")&&(typeof a.mainResearchGoal!="string"||a.mainResearchGoal.trim().length===0)&&(a.mainResearchGoal=d),(typeof a.researchGoal!="string"||a.researchGoal.trim().length===0)&&(a.researchGoal=d),(typeof a.reasoning!="string"||a.reasoning.trim().length===0)&&(a.reasoning=`Executed via ${c} tool command`),a}function br(e,t){return`Execute ${e} via ${t}`}function Lr(e,t){let r=e.length+1,n=t.length+1,a=Array.from({length:r*n},()=>0);for(let o=0;o<r;o++)a[o*n]=o;for(let o=0;o<n;o++)a[o]=o;for(let o=1;o<r;o++)for(let c=1;c<n;c++){let d=e[o-1]===t[c-1]?0:1;a[o*n+c]=Math.min(a[(o-1)*n+c]+1,a[o*n+c-1]+1,a[(o-1)*n+c-1]+d)}return a[r*n-1]}function Tr(e,t){let r=e.toLowerCase(),n,a=Number.POSITIVE_INFINITY,o,c=Number.POSITIVE_INFINITY;for(let d of t){let h=d.toLowerCase(),g=Lr(r,h);if(h.includes(r)||r.includes(h)){g<a&&(n=d,a=g);continue}if(r.length<3)continue;let y=Math.max(2,Math.floor(d.length/3));g<=y&&g<c&&(o=d,c=g)}return n??o}var Cr=new Set(["none","standard","symbols"]),xr={ghSearchCode:{keywordsToSearch:"keywords"},ghSearchRepos:{keywordsToSearch:"keywords"},npmSearch:{name:"packageName"},ghViewRepoStructure:{depth:"maxDepth"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri"},localGetFileContent:{filePath:"path"},localSearchCode:{keywordsToSearch:"searchText",keywords:"searchText",language:"langType"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:{field:"minify",map:e=>{if(e===!0)return"standard";if(e===!1)return"none";if(typeof e=="string"&&Cr.has(e))return e}}},ghSearchPullRequests:{merged:{field:"state",map:e=>e===!0?"merged":void 0}},ghSearchCommits:{filePath:"path"},localFindFiles:{maxResults:"limit"}};function Rr(e,t){let r=xr[e];if(!r)return t;let n;for(let[a,o]of Object.entries(r)){if(!(a in t))continue;let c=typeof o=="string"?o:o.field;if(c in t){n??={...t},delete n[a];continue}let d=typeof o=="string"?t[a]:o.map(t[a]);d!==void 0&&(n??={...t},n[c]=d,delete n[a])}return n??t}function _r(e,t,r,n={}){if(!b(t))throw new f("Tool input must be a JSON object or an array of objects.");let a=Rr(e,t),o=new Set([...U(e).filter(h=>!h.name.includes(".")).map(h=>h.name),...w]),c={},d=[];for(let[h,g]of Object.entries(a)){if(o.has(h)){c[h]=g;continue}d.push(h)}if(d.length>0&&o.size>0&&(n.onUnknownFields?.(d,r),n.rejectUnknownFields===!0)){let h=d.map(g=>{let y=Tr(g,o);return y?`'${g}' \u2192 did you mean '${y}'?`:""}).filter(Boolean);throw new f(`Unknown field(s): ${d.join(", ")}`,[...h,`Remove unknown field(s) from query ${r+1}: ${d.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return c}import{completeMetadata as Er}from"@octocodeai/octocode-core";var Ae=null;function kr(){return Ae||(Ae=Er),Ae}async function Or(){return kr()}export{w as DIRECT_TOOL_AUTO_FILLED_FIELDS,ft as DIRECT_TOOL_CATEGORIES,or as DIRECT_TOOL_DEFINITIONS,f as DirectToolInputError,ur as buildDirectToolCommandPatterns,ri as buildDirectToolExampleQuery,Tt as buildExampleValue,Lt as buildScalarExampleValue,Ee as collectDisplayFields,cr as describeSchemaConstraints,_e as describeSchemaType,C as findDirectToolDefinition,xt as formatDirectToolCommandPattern,qo as formatDirectToolMetadataSchemaText,Uo as formatDirectToolSchemaText,yr as formatDirectToolValidationIssues,jo as getDirectToolAutoFilledFields,k as getDirectToolCategory,zo as getDirectToolDescription,U as getDirectToolDisplayFields,ke as hasSchemaDefault,O as isJsonSchemaObject,b as isRecord,Or as loadToolContent,gr as prepareDirectToolInput,ai as prepareDirectToolInputFromJsonText,No as sortDirectToolNames};
8
+ import{z as Et}from"zod";var G={GITHUB_SEARCH:"ghSearch",GITHUB_FETCH_CONTENT:"ghGetFileContent",GITHUB_SEARCH_HISTORY:"ghSearchHistory",GITHUB_GET_HISTORY_ITEM:"ghGetHistoryItem",PACKAGE_SEARCH:"npmSearch",GITHUB_CLONE_REPO:"ghCloneRepo",LOCAL_SEARCH:"localSearch",LOCAL_ANALYZE_GRAPH:"localAnalyzeGraph",LOCAL_FETCH_CONTENT:"localGetFileContent",LSP_GET_SEMANTIC_CONTENT:"lspGetSemantics"},We=Et.object({goal:Et.string().optional().describe("What this query should accomplish."),reasoning:Et.string().optional().describe("Why this query advances the goal.")}),Be=Object.fromEntries(Object.entries(We.shape).map(([e,t])=>[e,t.description??""]));var jr={ghSearch:["Use only fields listed for the selected operation.","match: code=file|path; repositories=name|description|readme.","code cannot select branch; it searches GitHub's indexed default branch."],localSearch:["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."],localAnalyzeGraph:["dependencies | dependents -> requires file; depth applies.","path -> requires file + target.","deadCode/reachability use entrypoints and includeTests as roots."],localGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString."],lspGetSemantics:["workspaceSymbol needs symbolName and may use workspaceRoot.","documentSymbols/diagnostic need uri.","definition | references | hover | callers | callees | callHierarchy | implementation | typeDefinition | supertypes | subtypes -> requires uri + symbolName + lineHint."],ghGetFileContent:["Choose fullContent, a line range, or matchString.","A line range needs startLine and endLine.","matchString options apply with matchString.",'type:"directory" materializes; extraction fields read files.'],npmSearch:["Set exactly one of packageName or keywords."]};function Ye(e){return[...jr[e]??[]]}var Ur={ghSearch:[{name:"code",when:"Search code contents or file paths",requires:["operation"],excludes:["branch"],fields:["keywords","owner","repo","extension","filename","path","language","match","pageSize","page","concise"],example:{operation:"code",keywords:["toolSchemas"],owner:"bgauryy",repo:"octocode"}},{name:"repositories",when:"Discover repositories",requires:["operation"],fields:["keywords","topics","language","owner","stars","forks","goodFirstIssues","updated","created","size","match","sort","pageSize","page","archived","visibility","license","concise"],example:{operation:"repositories",keywords:["octocode"]}},{name:"tree",when:"Browse a known repository tree",requires:["operation","owner","repo"],fields:["owner","repo","branch","path","maxDepth","page","pageSize","include"],example:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}],localSearch:[{name:"text",when:"Search lexical text or regular expressions",requires:["operation","path","searchText"],example:{operation:"text",path:".",searchText:"toolSchemas"}},{name:"structural",when:"Match AST structure",requires:["operation","path","pattern"],example:{operation:"structural",path:".",pattern:"console.log($A)",langType:"typescript"}},{name:"files",when:"Discover paths by name or metadata",requires:["operation","path"],example:{operation:"files",path:".",names:["*.ts"]}},{name:"tree",when:"Browse a directory tree",requires:["operation","path"],example:{operation:"tree",path:".",maxDepth:5}}],localAnalyzeGraph:[{name:"dependencies",when:"Find files imported by a file",requires:["path","operation","file"],example:{path:".",operation:"dependencies",file:"src/index.ts"}},{name:"dependents",when:"Find files importing a file",requires:["path","operation","file"],example:{path:".",operation:"dependents",file:"src/index.ts"}},{name:"path",when:"Find a shortest dependency path",requires:["path","operation","file","target"],example:{path:".",operation:"path",file:"src/a.ts",target:"src/b.ts"}},{name:"cycles",when:"Find dependency cycles",requires:["path","operation"],example:{path:".",operation:"cycles"}},{name:"deadCode",when:"Find unreachable file candidates",requires:["path","operation"],example:{path:".",operation:"deadCode"}},{name:"reachability",when:"Find files unreachable from selected roots",requires:["path","operation","entrypoints"],example:{path:".",operation:"reachability",entrypoints:["src/index.ts"]}}],lspGetSemantics:[{name:"anchored",when:"Query a named symbol near a source line",requires:["uri","type","symbolName","lineHint"],example:{uri:"src/index.ts",type:"definition",symbolName:"main",lineHint:1}},{name:"document",when:"Query a whole document",requires:["uri","type"],example:{uri:"src/index.ts",type:"documentSymbols"}},{name:"workspace",when:"Search symbols across the workspace",requires:["workspaceRoot","type","symbolName"],example:{workspaceRoot:".",type:"workspaceSymbol",symbolName:"Schema"}}]};function Ot(e){return Ur[e]??[]}import{z as Je}from"zod";var xe=100,ze=1e3,ko=1e8,Ho=5e4,P=1e9,It=1e5,je=20,Ke=100,Ue=1e4,ce=50,U=100,q=30,Pt=200,kt=100;var Ht=1e5,Ft=500,et=1e5,Dt=1e3,Nt=20,Mt=100,Gt=20;function b(e){return{...e,description:e.instructions}}function l(e,t){return Je.number().int().min(e).max(t)}var L=Je.array(Je.string()).optional();function _(){return l(1,ze).default(1)}function O(){return l(1,ze).optional()}function tt(){return l(0,xe).optional()}function Re(){return l(1,P).optional()}function k(){return l(0,ko).optional()}function B(){return l(1,Ho).optional()}var h=We.shape,qr=new Set(Object.keys(h)),Xr={owner:"Repository owner (user or org).",repo:"Repository name, without the owner.",branch:"Branch, tag, or commit SHA; omit for the default branch.",path:"Target path. GitHub tools: repo-relative, exact case, no leading slash. Local tools: absolute path.",page:"Result page, 1-based. Advance only while pagination.hasMore.",itemsPerPage:"Items per result page.",limit:"Total result cap applied before pagination.",pageSize:"Results returned in one page.",contextLines:"Extra source lines around each match/anchor.",charLength:"Content-window length; continue with the returned offset when partial.",charOffset:"Content-window start; copy the returned offset. A partial window cannot prove absence."};function u(e,t,o=""){let r={};for(let n of Object.keys(t)){let i=t[n],a=o?`${o}.${n}`:n,f=o===""&&qr.has(n)?Be[a]:e[a]??(i.description?void 0:Xr[n]);r[n]=f?i.describe(f):i}return Je.object(r).strict()}function ot(e,t){let o=e.fullContent===!0,r=e.matchString!==void 0,n=e.startLine!==void 0||e.endLine!==void 0;o&&r&&t.addIssue({code:"custom",message:"Choose fullContent or matchString.",path:["matchString"]}),o&&n&&t.addIssue({code:"custom",message:"Choose fullContent or startLine/endLine.",path:["startLine"]}),r&&n&&t.addIssue({code:"custom",message:"Choose matchString or startLine/endLine.",path:["startLine"]}),e.startLine===void 0!=(e.endLine===void 0)&&t.addIssue({code:"custom",message:"Set startLine and endLine together.",path:[e.startLine===void 0?"startLine":"endLine"]}),e.startLine!==void 0&&e.endLine!==void 0&&e.endLine<e.startLine&&t.addIssue({code:"custom",message:"Set endLine greater than or equal to startLine.",path:["endLine"]})}import{z as rt}from"zod";import{z as te}from"zod";var Zr={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",path:"Repo path prefix, not a full file path.",match:'For ghSearch operation:"code": "file" returns snippets and character matchIndices; "path" returns paths only. Operation:"repositories" uses text-field names.',extension:'File extension filter, e.g. "ts" (no dot).',filename:"Exact filename filter.",language:'GitHub language filter, e.g. "typescript".',concise:'Flat "owner/repo:path" rows.',limit:"Results per page (paginate with page)."},oe=u(Zr,{...h,keywords:L,owner:te.string().optional(),repo:te.string().optional(),extension:te.string().optional(),filename:te.string().optional(),path:te.string().optional(),language:te.string().optional(),match:te.enum(["file","path"]).default("file"),limit:l(1,U).default(q),page:_(),concise:te.boolean().optional()});import{z as H}from"zod";var Vr={keywords:"ANDed; keep a phrase as one item; alternatives need separate queries.",topicsToSearch:"ANDed topic filters; metadata can be sparse.",match:'For ghSearch operation:"repositories": text fields to search are name, description, and readme; readme is broader and slower. Operation:"code" uses "file" or "path".',sort:"stars, forks, updated, help-wanted-issues, best-match.",language:'Primary language filter, e.g. "rust".',stars:'Star range: ">100", "10..50".',forks:'Fork range: ">50", "10..100".',goodFirstIssues:'Good-first-issue count range, e.g. ">5".',updated:'Last push date: ">2024-01-01" or "a..b".',created:'Creation date: ">2023-01-01" or "a..b".',size:'Repo size in KB: ">1000", "50..500".',license:'SPDX id, e.g. "mit".',archived:"true = archived only; default excludes archived.",visibility:'"public" or "private" (private needs token scope).',concise:'Flat "owner/repo" rows for triage.',limit:"Results per page (paginate with page)."},ee=u(Vr,{...h,keywords:L,topicsToSearch:L,language:H.string().optional(),owner:H.string().optional(),stars:H.string().optional(),forks:H.string().optional(),goodFirstIssues:H.string().optional(),updated:H.string().optional(),created:H.string().optional(),size:H.string().optional(),match:H.array(H.enum(["name","description","readme"])).optional(),sort:H.enum(["stars","forks","help-wanted-issues","updated","best-match"]).default("best-match"),limit:l(1,U).default(q),page:_(),archived:H.boolean().optional(),visibility:H.enum(["public","private"]).optional(),license:H.string().optional(),concise:H.boolean().optional()});import{z as Le}from"zod";var $r={path:'Repo-relative directory; ""/"." for root.',branch:"Ref; fallback warning means default branch was used.",maxDepth:"Tree recursion depth.",page:"Advance only on hasMore.",include:"Optional sizes, languages, contributors, branches, or tags; each adds an API call."},le=u($r,{...h,owner:Le.string(),repo:Le.string(),branch:Le.string().optional(),path:Le.string().optional(),maxDepth:l(0,Gt).optional(),page:_(),itemsPerPage:l(1,Pt).default(kt),include:Le.array(Le.enum(["sizes","languages","contributors","branches","tags"])).optional()});var Pa=b({name:"ghSearch",type:"Github",shortDescription:"Search GitHub code or repositories, or browse a repository tree.",instructions:`Choose operation:"code" for code contents or file paths, "repositories" to discover repositories, or "tree" to browse a known repository.
9
+ Each operation has a strict input branch; fields from other operations are rejected. Use ghGetFileContent only after a path is known. Empty GitHub search results do not prove absence.`,schema:{operation:'Required: "code", "repositories", or "tree".'}}),Wr=oe.omit({limit:!0}).extend({match:oe.shape.match.describe('For operation:"code": "file" returns snippets; "path" returns paths only.'),pageSize:oe.shape.limit.describe("Results returned per page."),operation:rt.literal("code").describe("Search code contents or file paths.")}).strict(),Yr=ee.omit({topicsToSearch:!0,limit:!0}).extend({topics:ee.shape.topicsToSearch.describe("Repository topics; all must match."),pageSize:ee.shape.limit.describe("Results returned per page."),match:ee.shape.match.describe('For operation:"repositories": fields to search: name, description, or readme.'),operation:rt.literal("repositories").describe("Discover repositories by keywords and repository filters.")}).strict(),Jr=le.omit({itemsPerPage:!0}).extend({operation:rt.literal("tree").describe("Browse the tree of a known repository."),pageSize:le.shape.itemsPerPage.describe("Tree entries returned per page.")}).strict(),vt=rt.discriminatedUnion("operation",[Wr,Yr,Jr]);import{z as X}from"zod";var Kr=b({name:"ghGetFileContent",type:"Github",shortDescription:"Read a file or a specific region from a GitHub repository.",instructions:`Read a known GitHub path after search or structure discovery; a complete search snippet needs no reread. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
10
+ Choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; continue with the returned charOffset. matchedLines are LSP anchors; match ranges and offsets are not. type:"directory" returns localPath when local access is enabled; otherwise use ghSearch operation:"tree".`,schema:{startLine:"Requires endLine; exclusive with fullContent/matchString.",endLine:"Requires startLine; must be >= startLine.",fullContent:"Whole small file; exclusive with range/match.",matchString:"Anchor returning padded matchRanges and exact matchedLines.",matchStringIsRegex:"Makes matchString a regex.",matchStringCaseSensitive:"Case-sensitive matchString.",type:'"file" reads; "directory" materializes localPath when clone/local access is enabled\u2014otherwise use ghSearch operation:"tree".',forceRefresh:"Bypass the 24h fetch cache and re-read from GitHub.",charOffset:"Copy pagination.nextCharOffset.",minify:'"symbols" outline, "standard" compact, "none" exact.'}}),nt=u(Kr.schema,{...h,owner:X.string(),repo:X.string(),branch:X.string().optional(),path:X.string(),startLine:Re(),endLine:Re(),fullContent:X.boolean().optional(),matchString:X.string().optional(),matchStringIsRegex:X.boolean().optional(),matchStringCaseSensitive:X.boolean().optional(),forceRefresh:X.boolean().optional(),type:X.enum(["file","directory"]).default("file"),contextLines:l(0,xe).default(5),charOffset:k(),charLength:B(),minify:X.enum(["none","standard","symbols"]).default("standard")}).superRefine(ot);import{z as s}from"zod";var en=b({name:"githubHistory",type:"Github",shortDescription:"Search and read GitHub pull requests and commit history.",instructions:`Use for PR/commit archaeology \u2014 not current code (ghSearch operation:"code"/ghGetFileContent). type:"prs" lists/reads PRs; type:"commits" walks history.
11
+ Param relations: list mode uses filters+sort/page; detail mode needs owner+repo+prNumber and content selectors. patches.mode:"selected" requires files or ranges. Body/patch/comment windows continue via returned charOffset/commentBodyOffset; file/comment/commit lists use their page fields. For code identity, clone and use local/LSP.`,schema:{type:'"prs" for pull requests; "commits" for commit history.',keywords:"PR search terms; ignored in commits mode.",match:'PR text fields searched by keywords; ghSearch operation:"code" instead uses match to select file content or paths.',prNumber:"Switches to PR detail mode; needs owner+repo.",issueNumber:"Switches to issue detail mode; needs owner+repo.",concise:"PR list triage; ignored with prNumber.",path:"Commit-mode file/dir prefix; trailing / scopes subtree.",includeDiff:"Commit-mode diffs; costly.",order:"asc+created helps archaeology.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',interactions:'Combined comment+reaction count range (">20").',project:'Project board: "owner/number".',"team-mentions":'Team mention: "org/team-slug".',filePage:"Changed-files page from contentPagination.",commentPage:"Comments page from contentPagination.",commitPage:"PR commits page from contentPagination.",reviewMode:'"full" fetches all PR detail surfaces.',content:"Detail selector for prNumber.","content.body":"Full PR description; windowed by charOffset.","content.changedFiles":"File list with status and +/- counts.","content.patches.mode":'"none", "selected" (cheapest; needs files or ranges), or "all".',"content.patches.ranges":"Line ranges for selected patch hunks.","content.comments.reviewInline":"Inline review comments; in_reply_to_id marks threads.","content.comments.includeBots":"Include bot/CI comments.","content.reviews":"Review verdicts per reviewer.","content.commits":"PR-bound commits selector.",matchString:"Substring filter for body/patch/comment windows.",charOffset:"Body/patch continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" compact patches; "none" exact diff; "symbols" not available.'}}),_e=en.schema,it=u(_e,{...h,type:s.enum(["prs","commits"]).default("prs"),since:s.string().optional(),until:s.string().optional(),path:s.string().optional(),branch:s.string().optional(),includeDiff:s.boolean().optional().default(!1),includeAssets:s.boolean().optional(),keywords:s.array(s.string()).optional(),prNumber:l(1,P).optional(),issueNumber:l(1,P).optional(),owner:s.string().optional(),repo:s.string().optional(),concise:s.boolean().optional(),state:s.enum(["open","closed","merged"]).optional(),assignee:s.string().optional(),author:s.string().optional(),committer:s.string().optional(),commenter:s.string().optional(),mentions:s.string().optional(),"review-requested":s.string().optional(),"reviewed-by":s.string().optional(),label:s.union([s.string(),s.array(s.string())]).optional(),checks:s.enum(["success","failure","pending"]).optional(),review:s.enum(["approved","changes_requested","required","none"]).optional(),head:s.string().optional(),base:s.string().optional(),created:s.string().optional(),updated:s.string().optional(),closed:s.string().optional(),"merged-at":s.string().optional(),comments:s.string().optional(),reactions:s.string().optional(),draft:s.boolean().optional(),match:s.array(s.enum(["title","body","comments"])).optional(),sort:s.enum(["created","updated","best-match","comments","reactions"]).optional(),order:s.enum(["asc","desc"]).optional(),limit:l(1,U).default(q),page:_(),archived:s.boolean().optional(),filePage:O(),commentPage:O(),commitPage:O(),reviewMode:s.literal("full").optional(),content:u(_e,{metadata:s.boolean().optional(),body:s.boolean().optional(),changedFiles:s.boolean().optional(),patches:u(_e,{mode:s.enum(["none","selected","all"]).default("none"),files:L,ranges:s.array(u(_e,{file:s.string(),additions:s.array(l(1,P)).optional(),deletions:s.array(l(1,P)).optional()},"content.patches.ranges")).optional()},"content.patches").optional(),comments:u(_e,{discussion:s.boolean().optional(),reviewInline:s.boolean().optional(),includeBots:s.boolean().default(!1),file:s.string().optional()},"content.comments").optional(),reviews:s.boolean().optional(),commits:u(_e,{list:s.boolean().optional(),includeFiles:s.boolean().optional()},"content.commits").optional()},"content").optional(),matchString:s.string().optional(),commentBodyOffset:k(),charOffset:k(),charLength:B(),minify:s.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let o=e.content?.patches;if(!o)return;let r=(o.files?.length??0)>0,n=(o.ranges?.length??0)>0,i=r||n;o.mode==="selected"&&!i&&t.addIssue({code:"custom",message:'content.patches.mode="selected" requires non-empty files or ranges.',path:["content","patches","files"]}),o.mode!=="selected"&&i&&t.addIssue({code:"custom",message:'content.patches.files and content.patches.ranges require mode="selected".',path:["content","patches","mode"]})});import{z as p}from"zod";var tn=b({name:"ghSearchHistory",type:"Github",shortDescription:"Search GitHub pull requests, or read one PR's files, diffs, and reviews.",instructions:`Use for PR history, diffs, and review context; use code tools for current bytes, commits for history, and issues for issue threads. Conversation is context: prove landed behavior from selected patches or the merge SHA.
12
+ List mode uses search filters; detail mode needs owner, repo, prNumber, and explicit content selectors. Selected patches need files or ranges. Continue windows and lists with returned offsets/pages. Use local/LSP for symbol identity.`,schema:{keywords:"PR search terms.",match:'PR text fields searched by keywords: title, body, comments. ghSearch operation:"code" instead uses match to select file content or paths.',prNumber:"PR detail mode; requires owner+repo.",concise:"PR list triage; list mode only.",state:"open, closed, or merged.",assignee:"Assigned GitHub login.",author:"PR author login.",commenter:"Commenter login.",mentions:"Mentioned login.","review-requested":"Requested reviewer login.","reviewed-by":"Reviewer login.",checks:"success, failure, or pending.",review:"approved, changes_requested, required, or none.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',created:'Created date/range, e.g. ">2024-01-01" or "a..b".',updated:"Updated-date filter (same format as created).",closed:"Closed-date filter (same format as created).","merged-at":"Merged-date filter (same format as created).",head:"Head branch name filter.",base:"Base branch name filter.",label:"Label name(s); multiple are ANDed.",draft:"true = only drafts; false = exclude drafts.",archived:"Include PRs from archived repos.",sort:"created, updated, comments, reactions, best-match.",order:"asc/desc; asc+created helps archaeology.",filePage:"Changed-files page from contentPagination.",commentPage:"Comments page from contentPagination.",commitPage:"PR commits page from contentPagination.",content:"Detail selector for prNumber.","content.body":"Include the PR description body.","content.changedFiles":"Include changed files and +/- counts.","content.patches":"Patch selector for changed files.","content.patches.mode":'"selected" or "all"; selected is cheapest.',"content.patches.files":'Restrict selected patches to these files (mode:"selected").',"content.patches.ranges":"Line ranges for selected patch hunks.","content.patches.ranges.file":"File the line range applies to.","content.patches.ranges.additions":"Added-side line numbers to include.","content.patches.ranges.deletions":"Deleted-side line numbers to include.","content.comments":"Conversation and inline-review selectors.","content.comments.discussion":"Include the PR conversation timeline.","content.comments.reviewInline":"Include inline review threads.","content.comments.includeBots":"Include bot/CI comments.","content.comments.file":"Filter comments to one file path.","content.reviews":"Include review verdicts per reviewer.","content.commits":"PR-bound commits selector.","content.commits.includeFiles":"Attach per-commit file changes.",matchString:"Substring filter for body/patch/comment windows.",charOffset:"Body/patch continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" compact patches; "none" exact diff; "symbols" not available.',pageSize:"PRs or detail-list items returned per page."}}),Ce=tn.schema,pe=u(Ce,{...h,keywords:p.array(p.string()).optional(),prNumber:l(1,P).optional(),owner:p.string().optional(),repo:p.string().optional(),concise:p.boolean().optional(),state:p.enum(["open","closed","merged"]).optional(),assignee:p.string().optional(),author:p.string().optional(),commenter:p.string().optional(),mentions:p.string().optional(),"review-requested":p.string().optional(),"reviewed-by":p.string().optional(),label:p.array(p.string()).optional(),checks:p.enum(["success","failure","pending"]).optional(),review:p.enum(["approved","changes_requested","required","none"]).optional(),head:p.string().optional(),base:p.string().optional(),created:p.string().optional(),updated:p.string().optional(),closed:p.string().optional(),"merged-at":p.string().optional(),comments:p.string().optional(),reactions:p.string().optional(),draft:p.boolean().optional(),match:p.array(p.enum(["title","body","comments"])).optional(),sort:p.enum(["created","updated","best-match","comments","reactions"]).optional(),order:p.enum(["asc","desc"]).optional(),pageSize:l(1,U).default(q),page:O(),archived:p.boolean().optional(),filePage:O(),commentPage:O(),commitPage:O(),content:u(Ce,{body:p.literal(!0).optional(),changedFiles:p.literal(!0).optional(),patches:u(Ce,{mode:p.enum(["selected","all"]),files:L,ranges:p.array(u(Ce,{file:p.string(),additions:p.array(l(1,P)).optional(),deletions:p.array(l(1,P)).optional()},"content.patches.ranges")).optional()},"content.patches").optional(),comments:u(Ce,{discussion:p.literal(!0).optional(),reviewInline:p.literal(!0).optional(),includeBots:p.literal(!0).optional(),file:p.string().optional()},"content.comments").optional(),reviews:p.literal(!0).optional(),commits:u(Ce,{includeFiles:p.literal(!0).optional()},"content.commits").optional()},"content").optional(),matchString:p.string().optional(),commentBodyOffset:k(),charOffset:k(),charLength:B(),minify:p.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let o=["content","filePage","commentPage","commitPage","matchString","commentBodyOffset","charOffset","charLength"],r=["keywords","concise","state","assignee","author","commenter","mentions","review-requested","reviewed-by","label","checks","review","head","base","created","updated","closed","merged-at","comments","reactions","draft","match","sort","order","page","archived"];if(e.prNumber===void 0)for(let f of o)e[f]!==void 0&&t.addIssue({code:"custom",message:`${f} requires prNumber detail mode.`,path:[f]});else{e.owner?.trim()||t.addIssue({code:"custom",message:"owner is required with prNumber.",path:["owner"]}),e.repo?.trim()||t.addIssue({code:"custom",message:"repo is required with prNumber.",path:["repo"]});for(let f of r)e[f]!==void 0&&t.addIssue({code:"custom",message:`${f} is only available in list mode.`,path:[f]})}e.content&&Object.keys(e.content).length===0&&t.addIssue({code:"custom",message:"content needs at least one selector.",path:["content"]});let n=e.content?.patches;if(!n)return;let i=(n.files?.length??0)>0,a=(n.ranges?.length??0)>0,m=i||a;n.mode==="selected"&&!m&&t.addIssue({code:"custom",message:'content.patches.mode="selected" requires non-empty files or ranges.',path:["content","patches","files"]}),n.mode!=="selected"&&m&&t.addIssue({code:"custom",message:'content.patches.files and content.patches.ranges require mode="selected".',path:["content","patches","mode"]})});import{z as y}from"zod";var on=b({name:"ghSearchHistory",type:"Github",shortDescription:"Search GitHub issues, or read one issue's body and comments.",instructions:`Use for bug reports and feature threads; use PR or code tools for those surfaces. List mode uses search filters. Detail mode needs owner, repo, issueNumber, and content selectors; continue bodies/comments with returned offsets and pages.
13
+ GitHub issue search also finds PRs, which are filtered out. totalCount is present only for a complete page; an empty page with hasMore still has a nextPage.`,schema:{keywords:"Issue search terms.",match:"Keyword fields: title, body, comments.",issueNumber:"Issue detail mode; requires owner+repo.",concise:"Issue list triage; list mode only.",state:"open or closed.",assignee:"Assigned GitHub login.",author:"Issue author login.",commenter:"Commenter login.",mentions:"Mentioned login.",archived:"Include issues from archived repos.",comments:'Comment-count range filter (">5"); not comment content.',reactions:'Reaction-count range filter (">10").',created:'Created date/range, e.g. ">2024-01-01" or "a..b".',updated:"Updated-date filter (same format as created).",closed:"Closed-date filter (same format as created).",label:"Label name(s); multiple are ANDed.",sort:"created, updated, comments, reactions, best-match.",order:"asc/desc; asc+created helps archaeology.",commentPage:"Comments page from contentPagination.",content:"Detail selector for issueNumber.","content.body":"Include the issue description body.","content.comments":"Comment-thread selector.","content.comments.discussion":"Include the comment thread.","content.comments.includeBots":"Include bot/CI comments.",matchString:"Substring filter for body/comment windows.",charOffset:"Body continuation offset from nextQuery.",commentBodyOffset:"Comment-body continuation offset from nextQuery.",minify:'"standard" (default) compacts body/comment text; "none" keeps it exact.',pageSize:"Issues or detail comments returned per page."}}),Qt=on.schema,ue=u(Qt,{...h,owner:y.string(),repo:y.string(),keywords:y.array(y.string()).optional(),issueNumber:l(1,P).optional(),concise:y.boolean().optional(),state:y.enum(["open","closed"]).optional(),assignee:y.string().optional(),author:y.string().optional(),commenter:y.string().optional(),mentions:y.string().optional(),label:y.array(y.string()).optional(),created:y.string().optional(),updated:y.string().optional(),closed:y.string().optional(),comments:y.string().optional(),reactions:y.string().optional(),match:y.array(y.enum(["title","body","comments"])).optional(),sort:y.enum(["created","updated","best-match","comments","reactions"]).optional(),order:y.enum(["asc","desc"]).optional(),pageSize:l(1,U).default(q),page:O(),archived:y.boolean().optional(),commentPage:O(),content:u(Qt,{body:y.literal(!0).optional(),comments:u(Qt,{discussion:y.literal(!0).optional(),includeBots:y.literal(!0).optional()},"content.comments").optional()},"content").optional(),matchString:y.string().optional(),commentBodyOffset:k(),charOffset:k(),charLength:B(),minify:y.enum(["none","standard"]).default("standard")}).superRefine((e,t)=>{let o=["content","commentPage","matchString","commentBodyOffset","charOffset","charLength"],r=["keywords","concise","state","assignee","author","commenter","mentions","label","created","updated","closed","comments","reactions","match","sort","order","page","archived"];if(e.issueNumber===void 0)for(let n of o)e[n]!==void 0&&t.addIssue({code:"custom",message:`${n} requires issueNumber detail mode.`,path:[n]});else{e.owner?.trim()||t.addIssue({code:"custom",message:"owner is required with issueNumber.",path:["owner"]}),e.repo?.trim()||t.addIssue({code:"custom",message:"repo is required with issueNumber.",path:["repo"]});for(let n of r)e[n]!==void 0&&t.addIssue({code:"custom",message:`${n} is only available in list mode.`,path:[n]})}e.content&&Object.keys(e.content).length===0&&t.addIssue({code:"custom",message:"content needs at least one selector.",path:["content"]})});import{z as Z}from"zod";var rn=b({name:"ghSearchHistory",type:"Github",shortDescription:"Walk a GitHub repository's commit history for a path or range.",instructions:`Trace when or why code changed; use code tools for current bytes and PR search for review context. History mode filters by path/date/ref/author; compare mode needs base+head. This tool does not search commit messages.
14
+ For one commit's changes, compare base:"SHA^" to head:"SHA" with includeDiff. Scope diffs to one commit or a tight window. Use a clone and LSP for symbol identity.`,schema:{pageSize:"Commits returned per page (walk with page).",owner:"Repository owner.",repo:"Repository name.",path:"File/dir prefix; trailing / scopes the subtree.",since:'Lower date bound: ISO date or relative window such as "30d".',until:"Upper date bound; same formats as since.",branch:"Ref to walk; defaults to the default branch.",includeDiff:"Attach diffs; prefer one commit or a tight window.",author:"Author login or email.",committer:"Committer login or email.",base:"Compare-mode base ref; set with head.",head:"Compare-mode head ref; set with base.",filePage:"Changed-file page from pagination.nextFilePage.",charOffset:"Patch offset from patchPagination.nextCharOffset.",charLength:"Patch-window length."}}),at=u(rn.schema,{...h,owner:Z.string(),repo:Z.string(),path:Z.string().optional(),since:Z.string().optional(),until:Z.string().optional(),branch:Z.string().optional(),author:Z.string().optional(),committer:Z.string().optional(),base:Z.string().optional(),head:Z.string().optional(),pageSize:l(1,100).optional().default(30),includeDiff:Z.boolean().optional().default(!1),page:_(),filePage:O(),charOffset:k(),charLength:B()}).superRefine((e,t)=>{(e.base&&!e.head||e.head&&!e.base)&&t.addIssue({code:"custom",path:[e.base?"head":"base"],message:"Set base and head together for compare mode."})});import{z as Bt}from"zod";var nn=b({name:"npmSearch",type:"NPM",shortDescription:"Look up npm packages and find their source repositories.",instructions:"Resolve npm packages to source repositories. Set exactly one of packageName for exact lookup or keywords for discovery. Follow the repository into GitHub tools.",schema:{keywords:"Discovery terms joined with spaces. Mutually exclusive with packageName.",packageName:"Exact package name; include scope for scoped packages.",page:"Keyword-result page only."}}),st=u(nn.schema,{...h,packageName:Bt.string().optional(),keywords:Bt.array(Bt.string()).optional(),page:_()}).superRefine((e,t)=>{let o=e.keywords?.join(" ").trim();!e.packageName?.trim()&&!o&&t.addIssue({code:"custom",path:["packageName"],message:"Set packageName or keywords."}),e.packageName?.trim()&&o&&t.addIssue({code:"custom",path:["keywords"],message:"Set packageName or keywords, not both."})});import{z as qe}from"zod";var an=b({name:"ghCloneRepo",type:"Github",shortDescription:"Clone a GitHub repo or subtree locally for repeated reads, search, or LSP.",instructions:"Best for repeated reads, local AST/regex, or LSP; use ghGetFileContent for one read. Discover a bounded sparsePath first. branch selects the ref and forceRefresh bypasses the cached clone. Pass results[].data.location.localPath to local tools.",schema:{sparsePath:"Bound checkout to a repo-relative file/dir.",forceRefresh:"Bypass cached clone."}}),zt=u(an.schema,{...h,owner:qe.string(),repo:qe.string(),branch:qe.string().optional(),sparsePath:qe.string().optional(),forceRefresh:qe.boolean().optional()});import{z}from"zod";import{z as C}from"zod";var jt={searchText:'Single lexical pattern. regex:"fixed" is literal and "perl" enables advanced syntax.',mode:'Search mode: "discovery" paths; "paginated" snippets; "detailed" context; "structural" AST.',pattern:"Structural code pattern: $X matches one node; $$$ARGS matches a list. Include modifiers or use a kind rule.",rule:"Structural YAML ast-grep rule for relational matches.",regex:'"smart" (default), "fixed" (literal), or "perl" (advanced).',caseMode:'"smart" (default), "sensitive", or "insensitive".',wholeWord:"Match whole words only (text/regex modes).",invertMatch:"Return non-matching lines (text/regex modes).",multiline:'"off" (default), "on", or "dotall" (. spans newlines).',include:"Glob(s) of files to include.",exclude:"Glob(s) of files to exclude.",excludeDir:"Directory names to prune from the walk.",noIgnore:"Also search .gitignored files.",hidden:"Include dot-files.",matchContentLength:"Matched-line characters kept per hit; longer lines are truncated.",maxFiles:"Text: page ceiling. Structural: scan cap; stats report truncation.",maxDepth:"Maximum levels below the search root; 0 means root files.",output:'"content" lines; "files"/"filesWithout" paths; count modes totals; "matchOnly" substrings.',unique:'With output:"matchOnly", deduplicate values or count frequency.',sort:'"relevance" (default), "matchCount", "path", "modified", "accessed", or "created".',sortReverse:"Reverse the sort order.",rankingProfile:'Language tuning for sort:"relevance"; "auto" detects.',langType:'Language/file type, e.g. "ts"; structural mode maps it to include globs.',captureText:"Structural: include verbatim $$$ list captures; ranges remain available when omitted.",maxMatchesPerFile:"Pairs with matchPage.",matchWindow:'Requires output:"matchOnly".',matchPage:"Per-file match page."},v=u(jt,{...h,searchText:C.string().optional(),path:C.string(),mode:C.enum(["paginated","discovery","detailed","structural"]).default("paginated"),pattern:C.string().optional(),rule:C.string().optional(),regex:C.enum(["smart","fixed","perl"]).default("smart"),caseMode:C.enum(["smart","sensitive","insensitive"]).default("smart"),wholeWord:C.boolean().optional(),invertMatch:C.boolean().optional(),include:L,exclude:L,excludeDir:L,noIgnore:C.boolean().optional(),hidden:C.boolean().optional(),contextLines:tt(),matchContentLength:l(1,Ht).default(Ft),maxMatchesPerFile:l(1,et).optional(),maxFiles:l(1,et).optional(),maxDepth:l(0,je).optional(),multiline:C.enum(["off","on","dotall"]).default("off"),sort:C.enum(["relevance","matchCount","path","modified","accessed","created"]).default("relevance"),sortReverse:C.boolean().optional(),rankingProfile:C.enum(["auto","typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"]).default("auto"),langType:C.string().optional(),captureText:C.boolean().optional(),output:C.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).default("content"),unique:C.enum(["off","list","count"]).default("off"),matchWindow:l(0,200).optional(),matchPage:O(),itemsPerPage:l(1,Dt).optional(),page:_()}).superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:"Set pattern or rule for structural mode.",path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"Choose pattern or rule, not both.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:"Remove wholeWord in structural mode.",path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:"Remove invertMatch in structural mode.",path:["invertMatch"]});for(let r of["regex","caseMode","multiline"]){let n=r==="multiline"?"off":"smart";e[r]!==n&&t.addIssue({code:"custom",message:`Remove ${r} in structural mode.`,path:[r]})}e.output!=="content"&&t.addIssue({code:"custom",message:"Remove output in structural mode.",path:["output"]}),e.unique!=="off"&&t.addIssue({code:"custom",message:"Remove unique in structural mode.",path:["unique"]})}else(e.pattern||e.rule)&&t.addIssue({code:"custom",message:"Use structural mode with pattern or rule.",path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:"Set searchText for text modes.",path:["searchText"]});e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'Use output:"matchOnly" with matchWindow.',path:["matchWindow"]}),e.unique!=="off"&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'Use output:"matchOnly" with unique.',path:["unique"]})});import{z as N}from"zod";var qt={maxDepth:"Maximum levels below path; 0 is direct entries.",minDepth:"Requires <= maxDepth when both set.",names:"Basename globs; ORed.",pathPattern:"Full-path glob.",regex:"Basename Rust regex.",empty:"Match only empty files/dirs.",time:"Time filters using d/h/w/m durations.","time.modifiedWithin":"Modified within this duration, e.g. 2d or 6h.","time.modifiedBefore":"Modified before this duration ago, e.g. 30d.","time.accessedWithin":"Accessed within this duration, e.g. 1w.",size:"Size range, e.g. 100k or 1m.","size.greater":"Minimum file size, e.g. 100k or 1m.","size.less":"Maximum file size, e.g. 500b or 2m.",extensions:'Extensions without dots, e.g. ["ts","tsx"].',excludeDir:"Directory names; generated/vendor dirs are pruned by default. Pass [] to prune nothing.",entryType:'"f" files, "d" dirs.',permissions:"Exact permission filter.",access:'"executable", "readable", or "writable" filter.',detail:'"basic" (default), "modified" (+mtime), or "full" (all metadata).',sortBy:'"modified" (default), "name", "path", or "size".',limit:"Post-sort result cap; pagination stays within it."},Ut=qt,W=u(Ut,{...h,path:N.string(),maxDepth:l(0,Ke).optional(),minDepth:l(0,Ke).optional(),names:L,pathPattern:N.string().optional(),regex:N.string().optional(),empty:N.boolean().optional(),time:u(Ut,{modifiedWithin:N.string().optional(),modifiedBefore:N.string().optional(),accessedWithin:N.string().optional()},"time").optional(),size:u(Ut,{greater:N.string().optional(),less:N.string().optional()},"size").optional(),permissions:N.string().optional(),access:N.enum(["executable","readable","writable"]).optional(),extensions:L,excludeDir:L,limit:l(1,Ue).optional(),detail:N.enum(["basic","modified","full"]).default("basic"),sortBy:N.enum(["modified","name","path","size"]).default("modified"),entryType:N.enum(["f","d"]).optional(),page:_(),itemsPerPage:l(1,ce).optional()}).superRefine((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"]})});import{z as re}from"zod";var Xt={pattern:"Name glob or substring; use the files operation for regex.",entryType:'"f" files only, "d" dirs only; omit for both.',detail:'"basic" (default), "modified" (+mtime), or "full" (size/perms).',hidden:"Include dot-files/dirs.",recursive:"true enables the default recursive depth; omit with maxDepth for immediate children.",maxDepth:"Recursion depth. Omitted: immediate children, or 5 if recursive:true; maxDepth alone enables recursion, so recursive:true is not required. 0 uses those defaults.",extensions:"Allowlist without dots.",excludeDir:"Directories to prune; [] includes generated/vendor directories.",sortBy:'"name" (default), "size", "time", or "extension".',reverse:"Reverse the sort order.",limit:"Discovery cap before pagination."},Y=u(Xt,{...h,path:re.string(),detail:re.enum(["basic","modified","full"]).default("basic"),hidden:re.boolean().optional(),sortBy:re.enum(["name","size","time","extension"]).default("name"),reverse:re.boolean().optional(),pattern:re.string().optional(),entryType:re.enum(["f","d"]).optional(),recursive:re.boolean().optional(),extensions:L,excludeDir:L,maxDepth:l(0,je).optional(),limit:l(1,Ue).optional(),page:_(),itemsPerPage:l(1,ce).optional()});var Xe={...jt};delete Xe.mode;delete Xe.output;delete Xe.itemsPerPage;delete Xe.sortReverse;var Do={...Xt};delete Do.recursive;var hs=b({name:"localSearch",type:"Local",shortDescription:"Search local text, syntax, paths, or directory trees through one operation.",instructions:'Choose operation:"text" for lexical anchors, "structural" for AST matches, "files" for path or metadata discovery, and "tree" for directory orientation. Each operation has a strict branch, so do not mix fields across operations. Files/tree prune common generated and vendor directories by default; pass excludeDir:[] to prune nothing. Read exact hits with localGetFileContent and prove symbol identity with lspGetSemantics.',schema:{...qt,...Do,...Xe,operation:'Required branch: "text", "structural", "files", or "tree".',resultView:'Text/structural result shape. Text also supports "paginated", "discovery", and "detailed".',pattern:"Structural AST pattern.",namePattern:"Tree entry name glob or substring.",pathRegex:"Files operation: basename Rust regex.",limit:"Files/tree discovery cap before pagination.",pageSize:"Results returned per page.",sort:"Operation-specific sort order.",reverse:"Reverse the selected sort order."}}),No=z.object(v.shape),sn=z.object(W.shape),cn=z.enum(["paginated","discovery","detailed","content","files","filesWithout","countLines","countMatches","matchOnly"]),ln=z.enum(["content","files","countLines","countMatches","matchOnly"]),pn=No.omit({pattern:!0,rule:!0,captureText:!0,mode:!0,output:!0,itemsPerPage:!0,sortReverse:!0}).extend({operation:z.literal("text").describe('Use "text" for lexical search.'),searchText:z.string().describe("Single lexical pattern."),resultView:cn.optional().default("paginated").describe("Text result shape; paginated is the default."),pageSize:v.shape.itemsPerPage.describe("Matches returned per page."),reverse:v.shape.sortReverse.describe("Reverse the selected sort order."),unique:v.shape.unique.describe('With resultView:"matchOnly", deduplicate values or count frequency.'),matchWindow:v.shape.matchWindow.describe('Requires resultView:"matchOnly".')}).strict(),Mo=No.omit({searchText:!0,pattern:!0,rule:!0,mode:!0,regex:!0,caseMode:!0,wholeWord:!0,invertMatch:!0,multiline:!0,unique:!0,matchWindow:!0,output:!0,itemsPerPage:!0,sortReverse:!0}).extend({operation:z.literal("structural").describe('Use "structural" for AST matching.'),resultView:ln.optional().default("content").describe("Structural result shape; content is the default."),pageSize:v.shape.itemsPerPage.describe("Matches returned per page."),reverse:v.shape.sortReverse.describe("Reverse the selected sort order.")}).strict(),un=Mo.extend({pattern:z.string().describe("Structural AST pattern.")}).strict(),mn=Mo.extend({rule:z.string().describe("Structural YAML ast-grep rule.")}).strict(),dn=sn.omit({regex:!0,limit:!0,sortBy:!0,itemsPerPage:!0}).extend({operation:z.literal("files").describe('Use "files" for path and metadata discovery.'),pathRegex:W.shape.regex.describe("Basename Rust regex."),limit:W.shape.limit.describe("Post-sort discovery cap."),sort:W.shape.sortBy.describe("File sort order."),pageSize:W.shape.itemsPerPage.describe("Files returned per page.")}).strict(),hn=Y.omit({pattern:!0,recursive:!0,limit:!0,sortBy:!0,itemsPerPage:!0}).extend({operation:z.literal("tree").describe('Use "tree" for directory orientation.'),namePattern:Y.shape.pattern.describe("Entry name glob or substring."),limit:Y.shape.limit.describe("Discovery cap before pagination."),sort:Y.shape.sortBy.describe("Tree sort order."),pageSize:Y.shape.itemsPerPage.describe("Entries returned per page.")}).strict();function Fo(e,t){if("error"in e)for(let o of e.error.issues)o.code==="custom"&&t.addIssue({code:"custom",message:o.message,path:o.path})}var Zt=z.union([pn,un,mn,dn,hn]).superRefine((e,t)=>{if(e.operation==="text"){let o=e.resultView,r={...e,itemsPerPage:e.pageSize,sortReverse:e.reverse};delete r.operation,delete r.resultView,delete r.pageSize,delete r.reverse;let n=["paginated","discovery","detailed"].includes(o)?{...r,mode:o}:{...r,mode:"paginated",output:o};Fo(v.safeParse(n),t);return}if(e.operation!=="structural"&&e.operation==="files"){let o={...e,regex:e.pathRegex,limit:e.limit,sortBy:e.sort,itemsPerPage:e.pageSize};delete o.operation,delete o.pathRegex,delete o.pageSize,delete o.sort,Fo(W.safeParse(o),t)}});import{z as w}from"zod";var fn="localAnalyzeGraph",Ss=b({name:fn,type:"Local",shortDescription:"Analyze a repository file graph through one bounded operation.",instructions:"Map file topology, not symbol identity. dependencies/dependents need file; path needs file+target; deadCode/reachability accept roots; cycles needs no selector. Import edges and dead-code results are candidates\u2014verify changes and deletions with exact reads plus LSP.",schema:{path:"Absolute repository or package root to scan.",operation:"One bounded operation: deadCode, cycles, dependencies, dependents, path, or reachability.",file:"Repository-relative source file for dependencies, dependents, or path.",target:"Repository-relative destination file for path.",depth:"Traversal depth for dependencies or dependents.",entrypoints:"Repository-relative roots for deadCode or reachability.",includeTests:"Treat test files as reachability roots.",excludeDir:"Directory names to prune from graph construction.",maxFiles:"Maximum source files scanned; truncation is reported.",limit:"Result cap applied before pagination.",page:"Result page, 1-based; advance only while pagination.hasMore.",pageSize:"Results returned per page."}}),Ze=(e,t)=>w.preprocess(o=>typeof o=="number"&&Number.isFinite(o)?Math.min(Math.max(o,e),t):o,w.number().int().min(e).max(t)),we=(e,t)=>w.literal(e).describe(t),Ae={...h,path:w.string().describe("Absolute repository or package root to scan."),excludeDir:w.array(w.string()).optional().describe("Directory names to prune from graph construction."),maxFiles:Ze(1,5e4).optional().describe("Maximum source files scanned; truncation is reported."),limit:Ze(1,5e3).optional().describe("Result cap applied before pagination."),page:Ze(1,ze).optional().default(1).describe("Result page, 1-based."),pageSize:Ze(1,ce).optional().describe("Results returned per page.")},Go={entrypoints:w.array(w.string()).optional().describe("Repo-relative reachability roots; omit to detect package.json main/exports/bin."),includeTests:w.boolean().optional().default(!0).describe("Treat tests as reachability roots (default true).")},vo={file:w.string().describe("Repo-relative source file."),depth:Ze(1,50).optional().default(1).describe("Maximum traversal depth (default 1).")},Ee=w.discriminatedUnion("operation",[w.object({...Ae,...Go,operation:we("deadCode","Find unreachable or unretained exported symbols and dead SCCs.")}).strict(),w.object({...Ae,operation:we("cycles","Find strongly connected file components.")}).strict(),w.object({...Ae,...vo,operation:we("dependencies","Traverse files imported or re-exported by the source file; results include edgeKinds and syntactic confidence.")}).strict(),w.object({...Ae,...vo,operation:we("dependents","Traverse files that import or re-export the source file; results include edgeKinds and syntactic confidence.")}).strict(),w.object({...Ae,file:w.string().describe("Repo-relative source file."),target:w.string().describe("Repo-relative destination file."),operation:we("path","Find the shortest directed import/re-export path with per-edge provenance.")}).strict(),w.object({...Ae,...Go,operation:we("reachability","Classify scanned files by reachability from entrypoints.")}).strict()]);import{z as Oe}from"zod";var gn=b({name:"localGetFileContent",type:"Local",shortDescription:"Read a local file or a specific region.",instructions:`Read a known local path after search, find, or structure discovery. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
15
+ Choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; continue with the returned charOffset. matchedLines are LSP anchors; match ranges and character offsets are not. Report fetched bytes only.`,schema:{fullContent:"Whole file; small files only; exclusive with range/match.",matchString:"Anchor returning padded matchRanges and exact matchedLines.",matchStringIsRegex:"Makes matchString a regex.",matchStringCaseSensitive:"Case-sensitive matchString.",startLine:"Requires endLine; exclusive with fullContent/matchString.",endLine:"Requires startLine; must be >= startLine.",charOffset:"Copy pagination.nextCharOffset.",minify:'"symbols" outline, "standard" compact, "none" exact.'}}),ct=u(gn.schema,{...h,path:Oe.string(),fullContent:Oe.boolean().optional(),matchString:Oe.string().optional(),matchStringIsRegex:Oe.boolean().optional(),matchStringCaseSensitive:Oe.boolean().optional(),startLine:Re(),endLine:Re(),contextLines:l(0,xe).default(5),charOffset:k(),charLength:B(),minify:Oe.enum(["none","standard","symbols"]).default("standard")}).superRefine(ot);import{z as me}from"zod";var yn=b({name:"lspGetSemantics",type:"Local",shortDescription:"Run LSP semantic queries \u2014 definitions, references, call hierarchy, symbols, type hierarchy, diagnostics.",instructions:`Use a real search/read line anchor for semantic proof. references finds usages; callers incoming calls; callees outgoing calls; callHierarchy both. Fall back to references if call hierarchy is unavailable.
16
+ documentSymbols/diagnostic need uri; workspaceSymbol needs symbolName; other operations need uri+symbolName+lineHint. orderHint resolves same-line names. format:"compact" saves tokens. Empty/unavailable results call for a new anchor or text search.`,schema:{pageSize:"References or symbols returned per page.",page:"Reference/symbol result page.",type:"Identity, usage, hierarchy, hover, symbol, or diagnostic operation.",uri:"Target file path/URI; required for every type except workspaceSymbol.",symbolName:"Bare anchored identifier, or fuzzy workspace symbol query.",lineHint:"Observed line containing symbolName.",orderHint:"Disambiguate repeated symbols on one line.",depth:"Call/type hierarchy depth; 0 is direct only.",includeDeclaration:"references: include the declaration; disable before unused analysis.",groupByFile:"references summary mode.",contextLines:"Lines of surrounding source shown around each result location.",format:'"compact" saves tokens; "structured" has typed locations.',workspaceRoot:"Use when auto-root is wrong."}}),lt=u(yn.schema,{...h,uri:me.string().optional(),type:me.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).default("definition"),symbolName:me.string().min(1).optional(),lineHint:l(1,P).optional(),orderHint:l(0,It).default(0),depth:l(0,Nt).optional(),includeDeclaration:me.boolean().default(!0),groupByFile:me.boolean().optional(),page:_(),pageSize:l(1,Mt).optional(),contextLines:tt(),format:me.enum(["structured","compact"]).default("structured"),workspaceRoot:me.string().optional()}).superRefine((e,t)=>{if(e.type==="workspaceSymbol"){e.symbolName||t.addIssue({code:"custom",path:["symbolName"],message:"Set symbolName for workspaceSymbol."});return}e.uri||t.addIssue({code:"custom",path:["uri"],message:"Set uri for file-scoped operations."}),!(e.type==="documentSymbols"||e.type==="diagnostic")&&(e.symbolName||t.addIssue({code:"custom",path:["symbolName"],message:"Set symbolName for anchored operations."}),Number.isInteger(e.lineHint)||t.addIssue({code:"custom",path:["lineHint"],message:"Set lineHint for anchored operations."}))});var de=G.LOCAL_ANALYZE_GRAPH,he="localSearch",Ie=G.GITHUB_SEARCH,fe="ghSearchHistory",ge="ghGetHistoryItem",A={GITHUB_SEARCH:G.GITHUB_SEARCH,GITHUB_FETCH_CONTENT:G.GITHUB_FETCH_CONTENT,PACKAGE_SEARCH:G.PACKAGE_SEARCH,GITHUB_CLONE_REPO:G.GITHUB_CLONE_REPO,LOCAL_FETCH_CONTENT:G.LOCAL_FETCH_CONTENT,LOCAL_ANALYZE_GRAPH:G.LOCAL_ANALYZE_GRAPH,LSP_GET_SEMANTIC_CONTENT:G.LSP_GET_SEMANTIC_CONTENT,GITHUB_SEARCH_HISTORY:fe,GITHUB_GET_HISTORY_ITEM:ge},J=A.LSP_GET_SEMANTIC_CONTENT,Js=new Set([he,A.LOCAL_FETCH_CONTENT,de,J]);var Qo=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];var V={ghSearch:`Choose operation:"code" for code contents or file paths, "repositories" to discover repositories, or "tree" to browse a known repository.
17
+ Each operation has a strict input branch; fields from other operations are rejected. Use ghGetFileContent only after a path is known. Empty GitHub search results do not prove absence.`,ghGetFileContent:`Read a known GitHub path after search or structure discovery; a complete search snippet needs no reread. A path-only call returns a bounded standard-minified view. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
18
+ Optionally choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; run the returned continuation. matchedLines are LSP anchors; match ranges and offsets are not. type:"directory" returns localPath when local access is enabled; otherwise use ghSearch operation:"tree".`,ghSearchHistory:'Search or list repository history. Choose operation:"pullRequests", "issues", or "commits"; fields from other operations are rejected. Pull-request search may be global, while issue and commit history require owner+repo. Search branches never accept detail identities, content selectors, or diff pagination. Follow a result with ghGetHistoryItem.',ghGetHistoryItem:'Retrieve exact GitHub history. Choose operation:"pullRequest" or "issue" with number, "commit" with ref, or "compare" with base+head. Every branch requires owner+repo and rejects fields from other branches. PR/issue content and commit/compare diffs keep their branch-specific page and character windows; copy returned continuations exactly.',npmSearch:"Resolve npm packages to source repositories. Set exactly one of packageName for exact lookup or keywords for discovery. Follow the repository into GitHub tools.",ghCloneRepo:"Best for repeated reads, local AST/regex, or LSP; use ghGetFileContent for one read. Discover a bounded sparsePath first; complete is relative to that requested scope. branch selects the ref and forceRefresh bypasses the cached clone. Pass results[].data.location.localPath to local tools.",localSearch:'Choose operation:"text" for lexical anchors, "structural" for AST matches, "files" for path or metadata discovery, and "tree" for directory orientation. Each operation has a strict branch, so do not mix fields across operations. Files/tree prune common generated and vendor directories by default; pass excludeDir:[] to prune nothing. Read exact hits with localGetFileContent and prove symbol identity with lspGetSemantics.',localAnalyzeGraph:"Map file topology, not symbol identity. dependencies/dependents need file; path needs file+target; deadCode/reachability accept roots; cycles needs no selector. Import edges and dead-code results are candidates\u2014verify changes and deletions with exact reads plus LSP.",localGetFileContent:`Read a known local path after search, find, or structure discovery. A path-only call returns a bounded standard-minified view. For large files, get a symbols outline, then an exact range or match. Read small config files whole with minify:"none".
19
+ Optionally choose fullContent, matchString, or startLine+endLine. Partial content cannot prove absence; run the returned continuation. matchedLines are LSP anchors; match ranges and character offsets are not. Report fetched bytes only.`,lspGetSemantics:`Use a real search/read line anchor for semantic proof. references finds usages; callers incoming calls; callees outgoing calls; callHierarchy both. Fall back to references if call hierarchy is unavailable.
20
+ documentSymbols/diagnostic need uri; workspaceSymbol needs symbolName; other operations need uri+symbolName+lineHint. orderHint resolves same-line names. format:"compact" saves tokens. Empty/unavailable results call for a new anchor or text search.`};import{z as Pe}from"zod";function c(e,t){return Pe.preprocess(o=>typeof o=="number"&&Number.isFinite(o)?Math.min(Math.max(o,e),t):o,Pe.number().int().min(e).max(t))}var T=c(1,1e3).optional().default(1),ke=c(0,100).optional(),He=c(1,1e9).optional(),M=Pe.preprocess(e=>typeof e=="number"&&Number.isFinite(e)?Math.max(e,0):e,Pe.number().nonnegative().refine(Number.isSafeInteger,"Expected a safe non-negative integer")),bn={responseCharOffset:M.optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:c(1,5e4).optional().describe("Full-response char window.")};function d(e,t={}){let{maxQueries:o=5}=t;return Pe.object({queries:Pe.array(e).min(1).max(o).describe("Parallel queries; response rows use matching zero-based indexes."),...bn}).strict()}import{z as Bo}from"zod";function Tn(e,t){return e?.description&&!t.description?t.describe(e.description):t}function zo(e,t){let o={};for(let[r,n]of Object.entries(t))o[r]=Tn(e.shape[r],n);return o}function xn(e,t){let o=e;return o.safeExtend?o.safeExtend(t):e.extend(t)}function jo(e,t){if(!t?.length)return e;let o=new Set(t);return Bo.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!o.has(r))))}function g(e,t={},o={}){let r=jo(e,o.omit);return xn(r,zo(r,t)).strict()}function S(e,t={},o={}){let r=jo(e,o.omit);return Bo.object({...r.shape,...zo(r,t)}).strict()}var pt=g(zt),$t=d(pt);import{z as Ln}from"zod";import{z as $}from"zod";var qo=["fullContent","matchString","matchStringIsRegex","matchStringCaseSensitive","startLine","endLine"],Rn=[...qo,"contextLines","charOffset","charLength","minify"];function Xo(e,t){let o=new Set(t);return Object.fromEntries(Object.entries(e).filter(([r])=>!o.has(r)))}function ut(e,t){return e.description?t.describe(e.description):t}function x(e,t){let o=e[t];if(!o)throw new TypeError(`Expected schema field: ${t}`);return o}function R(e,t){return x(e,t).nonoptional()}function Uo(e,t){let o=Xo(e.shape,[...qo,...t?["type"]:[]]),r=t?{type:t}:{},n=ut(x(e.shape,"fullContent"),$.literal(!1).optional()),i=ut(x(e.shape,"fullContent"),$.literal(!0)),a=$.object({...o,...r,fullContent:n}).strict(),m=$.object({...o,...r,fullContent:i}).strict(),f=$.object({...o,...r,fullContent:n,matchString:R(e.shape,"matchString"),matchStringIsRegex:x(e.shape,"matchStringIsRegex"),matchStringCaseSensitive:x(e.shape,"matchStringCaseSensitive")}).strict(),I=$.object({...o,...r,fullContent:n,startLine:R(e.shape,"startLine"),endLine:R(e.shape,"endLine")}).strict().superRefine((E,Io)=>{typeof E.startLine=="number"&&typeof E.endLine=="number"&&E.endLine<E.startLine&&Io.addIssue({code:"custom",path:["endLine"],message:"Set endLine greater than or equal to startLine."})});return[a,m,f,I]}function mt(e,t={}){if(!t.githubDirectoryMode)return $.union(Uo(e));let o=ut(x(e.shape,"type"),$.literal("file").optional()),r=ut(x(e.shape,"type"),$.literal("directory")),n=Xo(e.shape,[...Rn,"type"]),i=$.object({...n,type:r}).strict();return $.union([...Uo(e,o),i])}var _n=Ln.enum(["none","standard","symbols"]).optional(),Zo={startLine:He,endLine:He,contextLines:ke,charOffset:M.optional(),charLength:c(1,5e4).optional(),minify:_n},Cn=S(nt,Zo),Wt=g(nt,Zo),Yt=d(mt(Cn,{githubDirectoryMode:!0}));function Kt(e){return typeof e=="string"&&e.trim().length>0}function Jt(e){return Array.isArray(e)&&e.some(Kt)}function wn(e){return e.operation==="code"?Jt(e.keywords)||["owner","path","extension","filename","language"].some(t=>Kt(e[t])):e.operation==="repositories"?Jt(e.keywords)||Jt(e.topics)||["owner","language","stars","forks","goodFirstIssues","updated","created","size","visibility","license"].some(t=>Kt(e[t]))||typeof e.archived=="boolean":!0}var dt=vt.superRefine((e,t)=>{wn(e)||t.addIssue({code:"custom",path:["operation"],message:`${e.operation} needs at least one search term or scope filter`})}),eo=d(dt,{maxQueries:5});import{z as An}from"zod";var Vo={limit:c(1,100).optional(),page:T.default(1),match:An.enum(["file","path"]).default("file")},En=g(oe,Vo),On=d(S(oe,Vo));import{z as to}from"zod";var $o={type:to.enum(["prs","commits","issues"]).optional(),prNumber:c(1,1e9).optional(),issueNumber:c(1,1e9).optional(),pageSize:c(1,100).optional().default(30),match:to.array(to.enum(["title","body","comments"])).optional(),page:T.default(1),filePage:c(1,1e3).optional(),commentPage:c(1,1e3).optional(),commitPage:c(1,1e3).optional(),charOffset:M.optional(),commentBodyOffset:M.optional(),charLength:c(1,5e4).optional()},In=S(it,$o),Pn=g(it,$o),kn=d(In);import{z as St}from"zod";import{z as F}from"zod";function De(e,t,o){let r=e.safeParse(t);if(!r.success)for(let n of r.error.issues)o.addIssue({code:"custom",message:n.message,path:n.path})}function Wo(e){let t=e;for(;t instanceof F.ZodOptional||t instanceof F.ZodDefault;)t=t.unwrap();if(!(t instanceof F.ZodObject))throw new TypeError("Expected an object schema");return t}function Yo(e){let t=e;for(;t instanceof F.ZodOptional||t instanceof F.ZodDefault;)t=t.unwrap();if(!(t instanceof F.ZodArray))throw new TypeError("Expected an array schema");return t}function Ne(e,t){return e.description?t.describe(e.description):t}var Jo={pageSize:c(1,100).optional().default(30),page:c(1,1e3).optional()},Ko={...Jo,filePage:c(1,1e3).optional(),commentPage:c(1,1e3).optional(),commitPage:c(1,1e3).optional(),charOffset:M.optional(),commentBodyOffset:M.optional(),charLength:c(1,1e5).optional()},jc=g(pe,Ko).superRefine((e,t)=>De(pe,e,t)),Fe=S(pe,Ko),er=x(Fe.shape,"content"),tr=Wo(er),or=x(tr.shape,"patches"),ne=Wo(or),rr=Ne(x(ne.shape,"mode"),F.literal("selected")),Fn=Ne(x(ne.shape,"mode"),F.literal("all")),Dn=Ne(x(ne.shape,"files"),Yo(x(ne.shape,"files")).min(1)),Nn=Ne(x(ne.shape,"ranges"),Yo(x(ne.shape,"ranges")).min(1)),Mn=F.object({mode:rr,files:Dn,ranges:x(ne.shape,"ranges")}).strict(),Gn=F.object({mode:rr,files:x(ne.shape,"files"),ranges:Nn}).strict(),vn=F.object({mode:Fn}).strict(),Qn=tr.extend({patches:Ne(or,F.union([Mn,Gn,vn]).optional())}),ro=Fe.omit({prNumber:!0,filePage:!0,commentPage:!0,commitPage:!0,content:!0,matchString:!0,commentBodyOffset:!0,charOffset:!0,charLength:!0}),Bn=ro.superRefine((e,t)=>De(pe,e,t)),gt=Fe.omit({keywords:!0,concise:!0,state:!0,assignee:!0,author:!0,commenter:!0,mentions:!0,"review-requested":!0,"reviewed-by":!0,label:!0,checks:!0,review:!0,head:!0,base:!0,created:!0,updated:!0,closed:!0,"merged-at":!0,comments:!0,reactions:!0,draft:!0,match:!0,sort:!0,order:!0,page:!0,archived:!0}).extend({owner:R(Fe.shape,"owner"),repo:R(Fe.shape,"repo"),prNumber:R(Fe.shape,"prNumber"),content:Ne(er,Qn.optional())}),zn=gt.superRefine((e,t)=>De(pe,e,t)),Uc=d(F.union([Bn,zn])),nr={...Jo,commentPage:c(1,1e3).optional(),charOffset:M.optional(),commentBodyOffset:M.optional(),charLength:c(1,1e5).optional()},qc=g(ue,nr).superRefine((e,t)=>De(ue,e,t)),oo=S(ue,nr),$e=oo.omit({issueNumber:!0,commentPage:!0,content:!0,matchString:!0,commentBodyOffset:!0,charOffset:!0,charLength:!0}),jn=$e.superRefine((e,t)=>De(ue,e,t)),yt=oo.omit({keywords:!0,concise:!0,state:!0,assignee:!0,author:!0,commenter:!0,mentions:!0,label:!0,created:!0,updated:!0,closed:!0,comments:!0,reactions:!0,match:!0,sort:!0,order:!0,page:!0,archived:!0}).extend({issueNumber:R(oo.shape,"issueNumber")}),Un=yt.superRefine((e,t)=>De(ue,e,t)),Xc=d(F.union([jn,Un])),ir={page:T.default(1),pageSize:c(1,100).optional().default(30),filePage:T.optional(),charOffset:M.optional(),charLength:c(1,1e5).optional()};function qn(e,t){(e.base&&!e.head||e.head&&!e.base)&&t.addIssue({code:"custom",path:[e.base?"head":"base"],message:"compare mode requires base and head together"})}var Zc=g(at,ir).superRefine(qn),ft=S(at,ir),no=ft.omit({base:!0,head:!0}),Xn=no,Me=ft.omit({branch:!0,since:!0,until:!0,author:!0,committer:!0,page:!0}).extend({base:R(ft.shape,"base"),head:R(ft.shape,"head")}),Zn=Me,Vc=d(F.union([Xn,Zn]));var Se=e=>St.literal(e).describe("Required operation selector."),Ge=e=>R(e,"owner"),ve=e=>R(e,"repo"),Vn=ro.extend({operation:Se("pullRequests")}).strict(),$n=$e.extend({operation:Se("issues"),owner:Ge($e.shape),repo:ve($e.shape)}).strict(),io=no.omit({includeDiff:!0,filePage:!0,charOffset:!0,charLength:!0}),Wn=io.extend({operation:Se("commits"),owner:Ge(io.shape),repo:ve(io.shape)}).strict(),bt=St.discriminatedUnion("operation",[Vn,$n,Wn]).describe("Search or list GitHub pull requests, issues, or commits using one strict operation branch."),lo=d(bt),ao=gt.omit({prNumber:!0}),Yn=ao.extend({operation:Se("pullRequest"),owner:Ge(ao.shape),repo:ve(ao.shape),number:gt.shape.prNumber}).strict(),so=yt.omit({issueNumber:!0}),Jn=so.extend({operation:Se("issue"),owner:Ge(so.shape),repo:ve(so.shape),number:yt.shape.issueNumber}).strict(),co=Me.omit({base:!0,head:!0}),Kn=co.extend({operation:Se("commit"),owner:Ge(co.shape),repo:ve(co.shape),ref:St.string().min(1).describe("Commit SHA or ref to retrieve exactly.")}).strict(),ei=Me.extend({operation:Se("compare"),owner:Ge(Me.shape),repo:ve(Me.shape)}).strict(),Tt=St.discriminatedUnion("operation",[Yn,Jn,Kn,ei]).describe("Retrieve one GitHub pull request, issue, commit, or ref comparison using one strict operation branch."),po=d(Tt);import{z as ar}from"zod";var sr={limit:c(1,100).optional(),page:T.default(1),match:ar.array(ar.enum(["name","description","readme"])).optional()},ti=g(ee,sr),oi=d(S(ee,sr));var cr={maxDepth:c(0,20).optional(),page:T.default(1),itemsPerPage:c(1,200).optional()},ni=g(le,cr),ii=d(S(le,cr));import{z as Te}from"zod";var lr={page:T,pageSize:c(1,100).optional().describe("Packages returned per keyword-discovery page."),keywords:Te.array(Te.string()).optional()};function uo(e,t){let o=Array.isArray(e.keywords)?e.keywords.join(" ").trim():e.keywords?.trim();!e.packageName?.trim()&&!o&&t.addIssue({code:"custom",path:["packageName"],message:"provide packageName or keywords"}),e.packageName?.trim()&&o&&t.addIssue({code:"custom",path:["keywords"],message:"provide packageName or keywords, not both"}),e.packageName?.trim()&&e.pageSize!==void 0&&t.addIssue({code:"custom",path:["pageSize"],message:"pageSize is only available for keyword discovery"})}var mo=g(st,lr).superRefine(uo),xt=S(st,lr,{strict:!0}),pr=xt.omit({packageName:!0,keywords:!0,pageSize:!0}).shape,ai=Te.object({...pr,packageName:R(xt.shape,"packageName")}).strict().superRefine((e,t)=>uo(e,t)),si=Te.object({...pr,keywords:Te.array(Te.string()).min(1).describe(x(xt.shape,"keywords").description??""),pageSize:x(xt.shape,"pageSize")}).strict().superRefine((e,t)=>uo(e,t)),ho=d(Te.union([ai,si]),{maxQueries:5});import{z as ci}from"zod";var li=ci.enum(["none","standard","symbols"]).optional(),ur={startLine:He,endLine:He,contextLines:ke.default(5),charOffset:M.optional(),charLength:c(1,5e4).optional(),minify:li},pi=S(ct,ur),fo=g(ct,ur),go=d(mt(pi),{maxQueries:5});import{z as yo}from"zod";var mr={maxDepth:c(0,100).optional(),minDepth:c(0,100).optional(),limit:c(1,1e4).optional(),page:T.default(1),itemsPerPage:c(1,50).optional(),excludeDir:yo.array(yo.string()).optional()},dr=yo.object(Object.fromEntries(Object.entries(W.shape).filter(([e])=>e!=="regexType")));function ui(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 mi=S(dr,mr),di=g(dr,mr).superRefine(ui),hi=d(mi,{maxQueries:5});var To=d(Ee,{maxQueries:5});import{z as ie}from"zod";var fi=["paginated","discovery","detailed","structural"],gi=["semanticRanking"],hr={mode:ie.enum(fi).optional().default("paginated"),searchText:ie.string().optional(),output:ie.enum(["content","files","filesWithout","countLines","countMatches","matchOnly"]).optional().default("content"),pattern:ie.string().optional(),maxDepth:c(0,20).optional(),rule:ie.string().optional(),captureText:ie.boolean().optional(),contextLines:ke,matchContentLength:c(1,1e5).optional().default(500),maxMatchesPerFile:c(1,1e5).optional(),maxFiles:c(1,1e5).optional(),matchPage:T.optional(),itemsPerPage:c(1,1e3).optional(),page:T.default(1),unique:ie.enum(["off","list","count"]).optional().default("off")},yi={...hr,semanticRanking:ie.unknown().optional().superRefine((e,t)=>{e!==void 0&&t.addIssue({code:"custom",message:'semanticRanking is disabled in this build \u2014 sort:"relevance" already includes declaration/export/AST signals; remove this field.'})}).describe('DISABLED in this build \u2014 do not pass. sort:"relevance" already includes declaration/export/AST signals.')},Si=S(v,yi),bi=g(v,hr,{strict:!0,omit:gi}),Ti=bi.superRefine((e,t)=>{if(e.mode==="structural"){!e.pattern&&!e.rule&&t.addIssue({code:"custom",message:'mode:"structural" requires `pattern` or `rule`.',path:["pattern"]}),e.pattern&&e.rule&&t.addIssue({code:"custom",message:"`pattern` and `rule` are mutually exclusive.",path:["rule"]}),e.wholeWord&&t.addIssue({code:"custom",message:'`wholeWord` is not valid with mode:"structural".',path:["wholeWord"]}),e.invertMatch&&t.addIssue({code:"custom",message:'`invertMatch` is not valid with mode:"structural".',path:["invertMatch"]}),e.regex&&e.regex!=="smart"&&t.addIssue({code:"custom",message:'`regex` is not valid with mode:"structural".',path:["regex"]}),e.caseMode&&e.caseMode!=="smart"&&t.addIssue({code:"custom",message:'`caseMode` is not valid with mode:"structural".',path:["caseMode"]}),e.multiline&&e.multiline!=="off"&&t.addIssue({code:"custom",message:'`multiline` is not valid with mode:"structural".',path:["multiline"]}),e.output&&e.output!=="content"&&e.output!=="countMatches"&&e.output!=="files"&&t.addIssue({code:"custom",message:'With mode:"structural", `output` supports only "content" (default), "countMatches" (per-file counts, no match content \u2014 cheapest for counting), or "files" (paths only).',path:["output"]}),e.unique&&e.unique!=="off"&&t.addIssue({code:"custom",message:'`unique` is not valid with mode:"structural".',path:["unique"]});let o=e.pattern&&!["php","bash","sh","zsh"].includes(e.langType??"")?/(?<!\$)\$\$(?!\$)[A-Z_][A-Z0-9_]*/.exec(e.pattern):null;if(o){let r=o[0].slice(2);t.addIssue({code:"custom",message:`\`${o[0]}\` is not a metavariable and matches nothing \u2014 use \`$${r}\` for one node or \`$$$${r}\` for a list of nodes.`,path:["pattern"]})}return}(e.pattern||e.rule)&&t.addIssue({code:"custom",message:'`pattern`/`rule` require mode:"structural".',path:[e.pattern?"pattern":"rule"]}),e.searchText||t.addIssue({code:"custom",message:'`searchText` is required unless mode:"structural".',path:["searchText"]}),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'matchWindow requires output:"matchOnly".',path:["matchWindow"]}),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.addIssue({code:"custom",message:'unique requires output:"matchOnly".',path:["unique"]})}),xi=d(Si,{maxQueries:5});import{z as fr}from"zod";var gr={excludeDir:fr.array(fr.string()).optional(),maxDepth:c(0,20).optional(),limit:c(1,1e4).optional(),page:T.default(1),itemsPerPage:c(1,50).optional()},Ri=S(Y,gr),Li=g(Y,gr),_i=d(Ri,{maxQueries:5});import{z as Sr}from"zod";var[Ci,wi,Ai,Ei,Oi]=Zt.options,yr=Sr.enum(["content","files","countMatches"]).optional().default("content").describe("Structural result shape; content is the default."),Rt=Sr.union([Ci,wi.extend({resultView:yr}),Ai.extend({resultView:yr}),Ei,Oi]),Ro=d(Rt,{maxQueries:5});import{z as ae}from"zod";var Ii=c(1,1e9),Pi=c(0,1e5).optional(),ki=["structured","compact"],br={type:ae.enum(Qo).default("definition"),symbolName:ae.string().min(1).max(1024).optional(),lineHint:Ii.optional(),orderHint:Pi,depth:c(0,20).optional(),includeDeclaration:ae.boolean().optional().default(!0),page:T,pageSize:c(1,100).optional(),contextLines:c(0,100).optional(),format:ae.enum(ki).optional().default("structured")},se=S(lt,br),Hi=["definition","references","callers","callees","callHierarchy","hover","typeDefinition","implementation","supertypes","subtypes"],Fi=["documentSymbols","diagnostic"],Di=se.extend({type:ae.enum(Hi).optional(),uri:R(se.shape,"uri"),symbolName:R(se.shape,"symbolName"),lineHint:R(se.shape,"lineHint")}),Ni=se.extend({type:ae.enum(Fi),uri:R(se.shape,"uri")}),Mi=se.extend({type:ae.literal("workspaceSymbol"),symbolName:R(se.shape,"symbolName")}),Lo=g(lt,br),_o=d(ae.union([Di,Ni,Mi]),{maxQueries:5});var Tr=[{name:Ie,title:"GitHub Search",description:V.ghSearch,schema:dt,inputSchema:eo},{name:A.GITHUB_FETCH_CONTENT,title:"GitHub File Content Fetch",description:V.ghGetFileContent,schema:Wt,inputSchema:Yt},{name:fe,title:"GitHub History Search",description:V.ghSearchHistory,schema:bt,inputSchema:lo},{name:ge,title:"GitHub History Item",description:V.ghGetHistoryItem,schema:Tt,inputSchema:po},{name:A.PACKAGE_SEARCH,title:"Package Search",description:V.npmSearch,schema:mo,inputSchema:ho},{name:A.GITHUB_CLONE_REPO,title:"Clone / Fetch GitHub Repository Locally",description:V.ghCloneRepo,schema:pt,inputSchema:$t},{name:he,title:"Local Search",description:V.localSearch,schema:Rt,inputSchema:Ro},{name:de,title:"Local Analyze Graph",description:V.localAnalyzeGraph,schema:Ee,inputSchema:To},{name:A.LOCAL_FETCH_CONTENT,title:"Local Fetch Content",description:V.localGetFileContent,schema:fo,inputSchema:go},{name:J,title:"Get Semantic Content",description:V.lspGetSemantics,schema:Lo,inputSchema:_o}];var xr=["GitHub","Local Code","Package","Other"],Rr=new Map([Ie,fe,ge,A.GITHUB_FETCH_CONTENT,A.GITHUB_CLONE_REPO,he,de,A.LOCAL_FETCH_CONTENT,J,A.PACKAGE_SEARCH].map((e,t)=>[e,t])),K=class extends Error{constructor(o,r=[]){super(o);this.details=r;this.name="DirectToolInputError"}details},Gi=["goal","reasoning"],Qe=new Set([...Gi]);function vi(e){return{name:e.name,title:e.title,description:e.description,schema:e.schema,inputSchema:e.inputSchema}}var _r=Tr.map(e=>vi(e)),Cr=[..._r];function D(e){return _r.find(t=>t.name===e)}function Lr(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===A.PACKAGE_SEARCH?"Package":"Other"}function Ip(e){return[...e].sort((t,o)=>{let r=xr.indexOf(Lr(t)),n=xr.indexOf(Lr(o));if(r!==n)return r-n;let i=Rr.get(t)??Number.MAX_SAFE_INTEGER,a=Rr.get(o)??Number.MAX_SAFE_INTEGER;return i!==a?i-a:t.localeCompare(o)})}import{z as wr}from"zod";var Qi=["goal","reasoning"];function Fp(e){let t=D(e);if(!t)return"{}";try{return JSON.stringify(wr.toJSONSchema(t.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(wr.toJSONSchema(t.schema,{io:"input"}),null,2)}}function Dp(e){return JSON.stringify(e??{},null,2)}function Np(e){return D(e)?[...Qi]:[]}function Mp(e,t){return D(e)?.description??e}import{z as wo}from"zod";function Ct(e){let t=D(e);if(!t)return[];let o=wo.toJSONSchema(t.schema,{io:"input"});if(!j(o))return[];let r=wt(o),n=Or(r),i=Ir(r,n);return _t(n,i)}function Bp(e){let t=D(e);if(!t)return{};let o=wo.toJSONSchema(t.schema,{io:"input"});if(!j(o))return{};let r=new Map;for(let n of wt(o)){if(!Q(n.properties))continue;let i=n.properties.operation;if(!j(i)||typeof i.const!="string")continue;let a=r.get(i.const)??[];a.push(n),r.set(i.const,a)}return Object.fromEntries([...r].map(([n,i])=>{let a=Or(i),m=Ir(i,a);return[n,_t(a,m).filter(f=>!Qe.has(f.name)&&f.name!=="operation")]}))}function Er(e,t){let o=D(e);if(!o)return new Set;let r=wo.toJSONSchema(o.schema,{io:"input"});if(!j(r))return new Set;let n=wt(r),i=n.filter(m=>Bi(m,t)),a=i.length>0?i:n;return new Set(a.flatMap(m=>Q(m.properties)?Object.keys(m.properties):[]))}function Bi(e,t){if(!Q(e.properties))return!0;for(let[o,r]of Object.entries(t)){let n=e.properties[o];if(j(n)&&("const"in n&&r!==n.const||Array.isArray(n.enum)&&!n.enum.some(i=>i===r)))return!1}return!0}function zi(e){let t=[],o=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return o!==void 0&&r!==void 0?t.push(`${o}-${r}`):o!==void 0?t.push(`>=${o}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function Lt(e){if("const"in e)return`enum(${String(e.const)})`;if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let o=j(e.items)?e.items:void 0;return`array<${o?Lt(o):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let o=t.filter(j).map(Lt).filter(r=>r!=="value");if(o.length>0)return[...new Set(o)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function wt(e){return Q(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(j).flatMap(o=>wt(o))}function Or(e){let t=new Map;for(let o of e)if(Q(o.properties))for(let[r,n]of Object.entries(o.properties)){if(!j(n))continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return Object.fromEntries([...t].map(([o,r])=>{let n=r.filter(a=>"const"in a).map(a=>a.const);return n.length===r.length?[o,{enum:[...new Set(n)],description:o==="operation"?"Required operation selector.":r[0]?.description}]:new Set(r.map(Lt)).size>1?[o,{anyOf:r}]:[o,r[0]??{}]}))}function Ir(e,t){if(e.length===0)return new Set;let o=e.map(n=>new Set(Array.isArray(n.required)?n.required:[])),r=[...o[0]??new Set].filter(n=>o.every(i=>i.has(n)));return new Set(r.filter(n=>!Qe.has(n)&&!Co(t[n])))}function _t(e,t,o=""){let r=[];for(let[n,i]of Object.entries(e)){if(!o&&Qe.has(n))continue;let a=j(i)?i:{},m=o?`${o}.${n}`:n;if(r.push({name:m,required:t.has(n),type:Lt(a),constraints:zi(a),description:typeof a.description=="string"?a.description:void 0}),Q(a.properties)){let I=new Set(Array.isArray(a.required)?a.required.filter(E=>typeof E=="string"?!Co(a.properties?.[E]):!1):[]);r.push(..._t(a.properties,I,m))}let f=a.type==="array"&&j(a.items)?a.items:void 0;if(f&&Q(f.properties)){let I=new Set(Array.isArray(f.required)?f.required.filter(E=>typeof E=="string"?!Co(f.properties?.[E]):!1):[]);r.push(..._t(f.properties,I,m))}}return r}function Pr(e,t){if(t.startsWith("array<")){let o=t.slice(6,-1);return[Ar(e,o)]}return Ar(e,t)}function Ar(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return e}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function j(e){return Q(e)}function Co(e){return j(e)&&"default"in e}function kr(e){return e!==Ie?[]:[{label:"code search",query:{operation:"code",keywords:["localSearch"],owner:"bgauryy",repo:"octocode",pageSize:5}},{label:"repository search",query:{operation:"repositories",keywords:["code research"],language:"TypeScript",pageSize:5}},{label:"repository tree",query:{operation:"tree",owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2}}]}function Hr(e){let t=kr(e);return t.length>0?t:e===fe?[{label:"PR search (list)",query:{operation:"pullRequests",owner:"bgauryy",repo:"octocode",keywords:["localSearch"],concise:!0,pageSize:5}},{label:"issue search (list)",query:{operation:"issues",owner:"bgauryy",repo:"octocode",keywords:["schema"],state:"open",pageSize:5}},{label:"commit history",query:{operation:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"6m",pageSize:10}}]:e===A.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:e===he?[{label:"text anchors",query:{operation:"text",path:"/ABS/repo/src",searchText:"buildDirectToolCommandPatterns",maxFiles:20}},{label:"structural matches",query:{operation:"structural",path:"/ABS/repo/src",pattern:"eval($X)",langType:"typescript"}},{label:"file discovery",query:{operation:"files",path:"/ABS/repo",names:["package.json"],entryType:"f"}},{label:"tree orientation",query:{operation:"tree",path:"/ABS/repo/src",maxDepth:2}}]:e===A.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"/ABS/repo/packages/octocode-tools-core/package.json",startLine:1,endLine:30,minify:"none"}},{label:"matched slice",query:{path:"/ABS/repo/packages/octocode-tools-core/src/tools/directToolCatalog.meta.ts",matchString:"buildKnownDirectToolCommandPatternQueries",contextLines:8,minify:"standard"}}]:e===de?[{label:"dead code from detected entrypoints",query:{operation:"deadCode",path:"/ABS/repo",limit:20}},{label:"cycles",query:{operation:"cycles",path:"/ABS/repo",limit:20}},{label:"dependencies of one file",query:{operation:"dependencies",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"dependents of one file",query:{operation:"dependents",path:"/ABS/repo",file:"src/index.ts",depth:2}},{label:"shortest dependency path",query:{operation:"path",path:"/ABS/repo",file:"src/index.ts",target:"src/responses.ts"}},{label:"reachability from detected entrypoints",query:{operation:"reachability",path:"/ABS/repo",limit:20}}]:e===A.GITHUB_FETCH_CONTENT?[{label:"matched slice (cheap read of one function)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",matchString:"export function cleanJsonObject",contextLines:8}},{label:"symbols outline (unknown/large file)",query:{owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src/responses.ts",minify:"symbols"}}]:e===ge?[{label:"pull request detail",query:{operation:"pullRequest",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,patches:{mode:"all"}}}},{label:"issue detail",query:{operation:"issue",owner:"bgauryy",repo:"octocode",number:1,content:{body:!0,comments:{discussion:!0}}}},{label:"exact commit",query:{operation:"commit",owner:"bgauryy",repo:"octocode",ref:"main"}},{label:"compare two refs (base...head)",query:{operation:"compare",owner:"bgauryy",repo:"octocode",base:"main",head:"update-tools"}}]:e===A.PACKAGE_SEARCH?[{label:"exact package \u2192 source repo",query:{packageName:"zod"}},{label:"keyword discovery (paged candidates)",query:{keywords:["schema","validation"],page:1}}]:e===J?[{label:"symbol outline (absolute uri)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"documentSymbols"}},{label:"semantic definition (absolute uri + lineHint)",query:{uri:"/ABS/packages/octocode-tools-core/src/scheme/pagination.ts",type:"definition",symbolName:"buildNextPageContinuation",lineHint:72}}]:[]}function Fr(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function ji(e){let t=Hr(e);if(t.length>0)return t.map(r=>({...r,command:Fr(e,r.query)}));let o=Ui(e);return Object.keys(o).length===0?[]:[{label:"schema-derived",query:o,command:Fr(e,o)}]}function Jp(e){return ji(e)[0]?.query??{}}function Ui(e){if(!D(e))return{};let t=Ct(e),o=t.filter(i=>!i.name.includes(".")),r=qi(o),n={};for(let i of r)n[i.name]=Pr(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(n.uri??="uri"),e===J&&(n.type??="definition",n.symbolName??="symbolName",n.lineHint??=1),n}var Dr=4,Ao=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),Nr=new Set(["page","itemsPerPage","limit","pageSize","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function qi(e){let t=e.filter(i=>i.required),o=new Map;for(let i of t)o.set(i.name,i);let r=e.filter(i=>!i.required&&Xi(i)).sort(Zi),n=Math.max(Dr,t.length);for(let i of r){if(o.size>=n)break;o.set(i.name,i)}return o.size>0?[...o.values()]:e.filter(i=>!Nr.has(i.name)).filter(i=>i.type!=="boolean").slice(0,Dr)}function Xi(e){return Nr.has(e.name)||e.type==="boolean"?!1:Vi(e)?Ao.has(e.name):!0}function Zi(e,t){let o=Ao.get(e.name)??Number.MAX_SAFE_INTEGER,r=Ao.get(t.name)??Number.MAX_SAFE_INTEGER;return o!==r?o-r:e.name.localeCompare(t.name)}function Vi(e){return e.constraints?.includes("default ")===!0}import{z as vr}from"zod";import{z as $i}from"zod";function At(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mr(e){return At(e.properties)?[e]:(Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:[]).filter(At).flatMap(Mr)}function Wi(e){let t=D(e)?.schema;if(!t)return new Map;let o=$i.toJSONSchema(t),r=new Map;for(let n of Mr(o)){if(!At(n.properties))continue;let i=n.properties.operation;if(!At(i)||typeof i.const!="string")continue;let a=r.get(i.const)??new Set;for(let m of Object.keys(n.properties))["goal","reasoning","operation"].includes(m)||a.add(m);r.set(i.const,a)}return new Map([...r].map(([n,i])=>[n,[...i]]))}function Eo(e){if(e==="ghSearch"){let[t,...o]=Ye(e);return[...t?[t]:[],"code and repositories need at least one search term or scope filter.",...o]}return e==="localSearch"?["text needs searchText.","structural needs exactly one of pattern or rule.","Fields from different operations cannot be mixed."]:e==="ghSearchHistory"?["Choose pullRequests, issues, or commits; fields cannot cross operations.","issues and commits require owner+repo; pullRequests may search globally.","Search/list operations reject exact identities, content, and diff pagination."]:e==="ghGetHistoryItem"?["Every operation requires owner+repo.","pullRequest and issue need number; commit needs ref; compare needs base+head.","Fields and pagination axes cannot cross operations."]:Ye(e)}function Gr(e){let t=Wi(e);return(e==="ghSearchHistory"?[{name:"pullRequests",when:"Search or list pull requests",requires:["operation"],example:{operation:"pullRequests",keywords:["schema"]}},{name:"issues",when:"Search or list issues",requires:["operation","owner","repo"],example:{operation:"issues",owner:"o",repo:"r"}},{name:"commits",when:"List commit history",requires:["operation","owner","repo"],example:{operation:"commits",owner:"o",repo:"r"}}]:e==="ghGetHistoryItem"?[{name:"pullRequest",when:"Retrieve one pull request",requires:["operation","owner","repo","number"],example:{operation:"pullRequest",owner:"o",repo:"r",number:1}},{name:"issue",when:"Retrieve one issue",requires:["operation","owner","repo","number"],example:{operation:"issue",owner:"o",repo:"r",number:1}},{name:"commit",when:"Retrieve one commit",requires:["operation","owner","repo","ref"],example:{operation:"commit",owner:"o",repo:"r",ref:"main"}},{name:"compare",when:"Compare two refs",requires:["operation","owner","repo","base","head"],example:{operation:"compare",owner:"o",repo:"r",base:"main",head:"next"}}]:Ot(e)).map(r=>({...r,...e==="localSearch"&&r.name==="structural"?{requires:["operation","path"]}:{},...e==="lspGetSemantics"&&r.name==="workspace"?{requires:["type","symbolName"]}:{},...t.has(r.name)?{fields:t.get(r.name)}:{}}))}function cu(e,t,o={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new K("Tool input must be valid JSON.")}return Yi(e,r,o)}function Yi(e,t,o={}){let r=ea(e,t,o),n=D(e);if(!n)throw new K(`Unknown tool: ${e}`);let i=n.inputSchema.safeParse(r);if(!i.success)throw new K("Check the query fields.",[...Ji(e),...Ki(i.error)]);return i.data}function Ji(e){if(e==="npmSearch")return Eo(e).slice(0,1);if(e==="localSearch"){let t=Gr(e).map(o=>o.name);return t.length>0?[`operation must be one of ${t.map((o,r)=>r===t.length-1&&t.length>1?`or ${o}`:o).join(", ")}.`]:[]}if(e==="lspGetSemantics"){let t=Eo(e);return t.length>0?[t.join(" ")]:[]}return[]}function Ki(e){let t=o=>{let r=o.errors;if(o.code!=="invalid_union"||!Array.isArray(r))return[o];let n=r.filter(a=>Array.isArray(a));return n.length===0?[o]:n.reduce((a,m)=>m.length<a.length?m:a).map(a=>({...a,path:[...o.path,...a.path]}))};return e.issues.flatMap(t).map(o=>`${o.path.length>0?o.path.join("."):"input"}: ${o.message}`)}function ea(e,t,o){let r=[];if(Array.isArray(t))r=t;else if(Q(t)&&Array.isArray(t.queries))r=t.queries;else if(Q(t))r=[t];else throw new K('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new K("At least one query is required.");let n=Q(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([a])=>a!=="queries")):{},i=r.map((a,m)=>ta(e,aa(e,a,m,o),{sourceLabel:o.sourceLabel}));return{...n,queries:i}}function ta(e,t,o){let r={...t},n=o.sourceLabel??"direct tool execution",i=oa(e,n);return(typeof r.goal!="string"||r.goal.trim().length===0)&&(r.goal=i),(typeof r.reasoning!="string"||r.reasoning.trim().length===0)&&(r.reasoning=`Executed via ${n} tool command`),r}function oa(e,t){return`Execute ${e} via ${t}`}function ra(e,t){let o=e.length+1,r=t.length+1,n=Array.from({length:o*r},()=>0);for(let i=0;i<o;i++)n[i*r]=i;for(let i=0;i<r;i++)n[i]=i;for(let i=1;i<o;i++)for(let a=1;a<r;a++){let m=e[i-1]===t[a-1]?0:1;n[i*r+a]=Math.min(n[(i-1)*r+a]+1,n[i*r+a-1]+1,n[(i-1)*r+a-1]+m)}return n[o*r-1]}function na(e,t){let o=e.toLowerCase(),r,n=Number.POSITIVE_INFINITY,i,a=Number.POSITIVE_INFINITY;for(let m of t){let f=m.toLowerCase(),I=ra(o,f);if(f.includes(o)||o.includes(f)){I<n&&(r=m,n=I);continue}if(o.length<3)continue;let E=Math.max(2,Math.floor(m.length/3));I<=E&&I<a&&(i=m,a=I)}return r??i}var ia={npmSearch:{name:"packageName"},lspGetSemantics:{op:"type",line:"lineHint",path:"uri",itemsPerPage:"pageSize",limit:""},localGetFileContent:{filePath:"path"},localSearch:{itemsPerPage:"pageSize",maxResults:["maxFiles","limit","pageSize"],keywords:"searchText",language:"langType",regexType:"regex",sortBy:"sort",sortReverse:"reverse"},ghGetFileContent:{matchStringContextLines:"contextLines",minified:"minify"},ghSearch:{itemsPerPage:"pageSize",limit:"",topicsToSearch:"topics"},localAnalyzeGraph:{itemsPerPage:"pageSize",maxResults:"limit",maxDepth:"depth"}};function aa(e,t,o,r={}){if(!Q(t))throw new K("Tool input must be a JSON object or an array of objects.");let n=new Set([...Ct(e).filter(m=>!m.name.includes(".")).map(m=>m.name),...Qr(D(e)?.schema),...Qe]),i={},a=[];for(let[m,f]of Object.entries(t)){if(n.has(m)){i[m]=f;continue}a.push(m)}if(a.length>0&&n.size>0&&(r.onUnknownFields?.(a,o),r.rejectUnknownFields===!0)){let m=Er(e,t),f=a.map(I=>{let E=ia[e]?.[I],Po=(Array.isArray(E)?E:E===void 0?[]:[E]).find(zr=>m.has(zr))??na(I,m);return Po?`'${I}' \u2192 did you mean '${Po}'?`:""}).filter(Boolean);throw new K(`Unknown field(s): ${a.join(", ")}`,[...f,`Remove unknown field(s) from query ${o+1}: ${a.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`])}return i}function Qr(e){if(!e)return[];if(e instanceof vr.ZodObject)return Object.keys(e.shape);let t=e.options,o=e instanceof vr.ZodUnion?e.options:Array.isArray(t)?t:[];return o.length>0?[...new Set(o.flatMap(r=>Qr(r)))]:[]}function yu(e){let t=[],o=[];return!e||typeof e!="object"?(t.push("Query must be an object"),{isValid:!1,errors:t,warnings:o}):(e.mode!=="structural"&&(!e.searchText||typeof e.searchText!="string")&&t.push("`searchText` is required"),e.matchWindow!==void 0&&e.output!=="matchOnly"&&t.push('`matchWindow` requires output:"matchOnly"'),(e.unique==="list"||e.unique==="count")&&e.output!=="matchOnly"&&t.push('`unique` requires output:"matchOnly"'),{isValid:t.length===0,errors:t,warnings:o})}function Su(e){if(!e||typeof e!="object")return e;let t=e.mode;if(!t||typeof t!="string")return e;let o={...e};return t==="discovery"?o.output==="content"&&(o.output="files"):t==="detailed"&&o.contextLines===void 0&&(o.contextLines=3),o}import{SYSTEM_PROMPT as sa}from"@octocodeai/octocode-core";var Br={systemPrompt:sa,toolNames:G,baseSchema:Be,tools:Object.fromEntries(Cr.map(e=>[e.name,{description:e.description}]))};var Oo=null;function ca(){return Oo||(Oo=Br),Oo}async function la(){return ca()}export{Qe as DIRECT_TOOL_AUTO_FILLED_FIELDS,xr as DIRECT_TOOL_CATEGORIES,_r as DIRECT_TOOL_DEFINITIONS,Cr as DIRECT_TOOL_DISCOVERY_DEFINITIONS,K as DirectToolInputError,A as STATIC_TOOL_NAMES,Su as applyWorkflowMode,ji as buildDirectToolCommandPatterns,Jp as buildDirectToolExampleQuery,Pr as buildExampleValue,Ar as buildScalarExampleValue,_t as collectDisplayFields,zi as describeSchemaConstraints,Lt as describeSchemaType,D as findDirectToolDefinition,Fr as formatDirectToolCommandPattern,Dp as formatDirectToolMetadataSchemaText,Fp as formatDirectToolSchemaText,Ki as formatDirectToolValidationIssues,Er as getDirectToolAllowedFieldNames,Np as getDirectToolAutoFilledFields,Lr as getDirectToolCategory,Mp as getDirectToolDescription,Ct as getDirectToolDisplayFields,Eo as getDirectToolSchemaRelations,Gr as getDirectToolSchemaVariants,Bp as getDirectToolVariantDisplayFields,Co as hasSchemaDefault,j as isJsonSchemaObject,Q as isRecord,la as loadToolContent,Yi as prepareDirectToolInput,cu as prepareDirectToolInputFromJsonText,Ip as sortDirectToolNames,yu as validateRipgrepQuery};
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+ type AnyZodObject = z.ZodObject<z.ZodRawShape>;
3
+ export declare function getSchemaField(shape: z.ZodRawShape, name: string): z.ZodTypeAny;
4
+ export declare function getRequiredSchemaField(shape: z.ZodRawShape, name: string): z.ZodTypeAny;
5
+ /**
6
+ * Keep the public bulk root an object while making selector modes visible to
7
+ * JSON Schema consumers through a union at `queries.items`.
8
+ */
9
+ export declare function createContentSelectorQuerySchema(base: AnyZodObject, options?: {
10
+ githubDirectoryMode?: boolean;
11
+ }): z.ZodTypeAny;
12
+ export {};
@@ -4,10 +4,11 @@ export type MinifyMode = 'none' | 'standard' | 'symbols';
4
4
  export declare const relaxedPageNumberField: z.ZodDefault<z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>>;
5
5
  export declare const contextLinesField: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
6
6
  export declare const lineNumberField: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
7
+ export declare const offsetField: z.ZodPreprocess<z.ZodNumber>;
7
8
  export declare function createRelaxedBulkQuerySchema(querySchema: z.ZodTypeAny, options?: {
8
9
  maxQueries?: number;
9
10
  }): z.ZodObject<{
10
11
  responseCharOffset: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
11
12
  responseCharLength: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
12
13
  queries: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
13
- }, z.core.$strip>;
14
+ }, z.core.$strict>;
@@ -1,11 +1,8 @@
1
- import { type CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
- import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
1
+ import type { AuthInfo, CallToolResult, ServerContext } from '@modelcontextprotocol/server';
3
2
  import type { ToolSecurityContext } from '@octocodeai/octocode-engine/security';
4
- export declare function withSecurityValidation<T extends Record<string, unknown>>(toolName: string, toolHandler: (sanitizedArgs: T, context: ToolSecurityContext<AuthInfo>) => Promise<CallToolResult>): (args: unknown, extra: {
5
- authInfo?: AuthInfo;
6
- sessionId?: string;
7
- signal?: AbortSignal;
8
- }) => Promise<CallToolResult>;
9
- export declare function withBasicSecurityValidation<T extends object>(toolHandler: (sanitizedArgs: T, context: ToolSecurityContext<unknown>) => Promise<CallToolResult>, toolName?: string): (args: unknown, extra?: {
10
- signal?: AbortSignal;
11
- }) => Promise<CallToolResult>;
3
+ export declare function withSecurityValidation<T extends Record<string, unknown>>(toolName: string, toolHandler: (sanitizedArgs: T, context: ToolSecurityContext<AuthInfo>) => Promise<CallToolResult>, options?: {
4
+ timeoutMs?: number;
5
+ }): (args: unknown, context?: ServerContext) => Promise<CallToolResult>;
6
+ export declare function withBasicSecurityValidation<T extends object>(toolHandler: (sanitizedArgs: T, context: ToolSecurityContext<unknown>) => Promise<CallToolResult>, toolName?: string, options?: {
7
+ timeoutMs?: number;
8
+ }): (args: unknown, context?: ServerContext) => Promise<CallToolResult>;
@@ -5,5 +5,5 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- function u(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function f(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let r=new Date;return t.getTime()-r.getTime()<300*1e3}function S(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var y=new Map,ee=300*1e3;function te(e){let t=u(e),r=y.get(t);return!r||Date.now()-r.cachedAt>=ee?!1:r.credentials?!f(r.credentials):!0}function v(e){e?y.delete(u(e)):y.clear()}function G(e){let t=u(e);if(te(t))return y.get(t).credentials}function I(e,t){let r=u(e);y.set(r,{credentials:t,cachedAt:Date.now()})}import{existsSync as E,readFileSync as N,writeFileSync as z,unlinkSync as L,statSync as le,chmodSync as ue}from"node:fs";import{createCipheriv as de,createDecipheriv as fe,randomBytes as M}from"node:crypto";import{existsSync as re,mkdirSync as ne}from"node:fs";import{join as c}from"node:path";import{getOctocodeHome as oe}from"@octocodeai/config";var se=448;function ie(){return oe(process.env)}var a=ie(),k={home:a,config:c(a,".octocoderc"),credentials:c(a,"credentials.json"),key:c(a,".key"),session:c(a,"session.json"),stats:c(a,"stats.json"),tmp:c(a,"tmp"),clone:c(a,"tmp","clone"),tree:c(a,"tmp","tree"),repos:c(a,"tmp","clone"),cliConfig:c(a,"config.json"),lspConfig:c(a,"lsp-servers.json")};function W(){re(k.home)||ne(k.home,{recursive:!0,mode:se})}import{z as i}from"zod";var ae=i.object({token:i.string(),tokenType:i.literal("oauth"),scopes:i.array(i.string()).optional(),refreshToken:i.string().optional(),expiresAt:i.string().optional(),refreshTokenExpiresAt:i.string().optional()}),ce=i.object({hostname:i.string(),username:i.string(),token:ae,gitProtocol:i.enum(["ssh","https"]),createdAt:i.string(),updatedAt:i.string()}),j=i.object({version:i.number(),credentials:i.record(i.string(),ce)});var U=k.home,p=k.credentials,d=k.key,B="aes-256-gcm",pe=16;function R(){W()}function $(){if(R(),E(d))return le(d).mode&511&63&&ue(d,384),Buffer.from(N(d,"utf8"),"hex");let e=M(32);return z(d,e.toString("hex"),{mode:384}),e}function w(e){let t=$(),r=M(pe),n=de(B,t,r),o=n.update(e,"utf8","hex");o+=n.final("hex");let s=n.getAuthTag();return`${r.toString("hex")}:${s.toString("hex")}:${o}`}function b(e){let t=$(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error("Invalid encrypted data format");let s=Buffer.from(r,"hex"),l=Buffer.from(n,"hex"),m=fe(B,t,s);m.setAuthTag(l);let x=m.update(o,"hex","utf8");return x+=m.final("utf8"),x}function h(){if(R(),!E(p))return{version:1,credentials:{}};try{let e=N(p,"utf8"),t=b(e),r=JSON.parse(t),n=j.safeParse(r);return n.success?n.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function D(e){R();let t=w(JSON.stringify(e,null,2));z(p,t,{mode:384})}function K(){try{E(p)&&L(p),E(d)&&L(d)}catch{}}import{refreshToken as he}from"@octokit/oauth-methods";import{request as ge}from"@octokit/request";var T="178c6fc778ccc68e1d6a",g="github.com";function me(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 ke(e){return e==="github.com"||e===g?"https://api.github.com":`https://${e}/api/v3`}async function _(e,t=g,r=T){let n=await e.getCredentials(t);if(!n)return{success:!1,error:`Not logged in to ${t}`};if(!n.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(S(n))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await he({clientType:"github-app",clientId:r,clientSecret:"",refreshToken:n.token.refreshToken,request:ge.defaults({baseUrl:ke(t)})}),s={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,s),{success:!0,username:n.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?me(o.message):"Token refresh failed"}}}async function Y(e,t=g,r=T){let n=await e.getCredentials(t);if(!n||!n.token)return{token:null,source:"none"};if(!f(n))return{token:n.token.token,source:"stored",username:n.username};if(n.token.refreshToken){let o=await _(e,t,r);if(o.success){let s=await e.getCredentials(t);if(s?.token.token)return{token:s.token.token,source:"refreshed",username:s.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as xe}from"@octocodeai/config";import{execFile as Te}from"child_process";var Ce=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function P(e){return new Promise(t=>{let r=["auth","token"];e&&r.push("--hostname",e);let n=process.env.PATH??"",o=new Set(n.split(":")),s=Ce.filter(m=>!o.has(m)),l=s.length?`${s.join(":")}:${n}`:n;Te("gh",r,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:l}},(m,x)=>{if(m||!x){t(null);return}t(x.trim()||null)})})}var A=null;function q(e){A=e}function J(){A=null}function ye(){if(!A)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return A}async function O(e){let t=e?.hostname??g,r=e?.clientId??T,n=e?.getGhCliToken??P,o=xe();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let s=await ye().getTokenWithRefresh(t,r);if(s.token)return{token:s.token,source:"octocode-storage",wasRefreshed:s.source==="refreshed",username:s.username};try{let l=await Promise.resolve(n(t));if(l?.trim())return{token:l.trim(),source:"gh-cli",wasRefreshed:!1}}catch(l){process.stderr.write(`[octocode] gh auth token failed: ${l instanceof Error?l.message:String(l)}
9
- `)}return null}async function V(e=g){let t=await O({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Z(e=g,t=T){let r=await O({hostname:e,clientId:t,getGhCliToken:()=>null});return r?{token:r.token,source:r.source,wasRefreshed:r.wasRefreshed,username:r.username}:null}async function Q(e){let t=u(e.hostname),r={...e,hostname:t,updatedAt:new Date().toISOString()};try{let n=h();return n.credentials[t]=r,D(n),v(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function C(e="github.com",t){let r=u(e);if(!t?.bypassCache){let s=G(r);if(s!==void 0)return s}let o=h().credentials[r]||null;return I(r,o),o}function F(e="github.com"){let t=u(e);return h().credentials[t]||null}async function Re(e="github.com"){let t=u(e),r=!1,n=h();return n.credentials[t]&&(delete n.credentials[t],Object.keys(n.credentials).length===0?K():D(n),r=!0),v(t),{success:r,deletedFromFile:r}}async function Se(){let e=h();return Object.keys(e.credentials)}function ve(){let e=h();return Object.keys(e.credentials)}async function Ee(e="github.com"){return await C(e)!==null}function Ae(e="github.com"){return F(e)!==null}async function H(e,t){let r=await C(e);return r?(r.token=t,r.updatedAt=new Date().toISOString(),await Q(r),!0):!1}function Oe(){return p}async function we(e="github.com"){let t=await C(e);return!t||!t.token||f(t)?null:t.token.token}function be(e="github.com"){let t=F(e);return!t||!t.token||f(t)?null:t.token.token}async function De(e,t){return _({getCredentials:C,updateToken:H},e,t)}async function X(e,t){return Y({getCredentials:C,updateToken:H},e,t)}q({getTokenWithRefresh:X});export{p as CREDENTIALS_FILE,d as KEY_FILE,U as OCTOCODE_DIR,b as decrypt,Re as deleteCredentials,w as encrypt,R as ensureOctocodeDir,C as getCredentials,Oe as getCredentialsFilePath,F as getCredentialsSync,P as getGhCliToken,we as getToken,be as getTokenSync,X as getTokenWithRefresh,Ee as hasCredentials,Ae as hasCredentialsSync,v as invalidateCredentialsCache,S as isRefreshTokenExpired,f as isTokenExpired,Se as listStoredHosts,ve as listStoredHostsSync,h as readCredentialsStore,De as refreshAuthToken,J as resetTokenResolution,V as resolveToken,O as resolveTokenFull,Z as resolveTokenWithRefresh,Q as storeCredentials,H as updateToken};
8
+ function u(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function f(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let r=new Date;return t.getTime()-r.getTime()<300*1e3}function S(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var y=new Map,ee=300*1e3;function te(e){let t=u(e),r=y.get(t);return!r||Date.now()-r.cachedAt>=ee?!1:r.credentials?!f(r.credentials):!0}function v(e){e?y.delete(u(e)):y.clear()}function G(e){let t=u(e);if(te(t))return y.get(t).credentials}function I(e,t){let r=u(e);y.set(r,{credentials:t,cachedAt:Date.now()})}import{existsSync as E,readFileSync as N,writeFileSync as z,unlinkSync as L,statSync as le,chmodSync as ue}from"node:fs";import{createCipheriv as de,createDecipheriv as fe,randomBytes as M}from"node:crypto";import{existsSync as re,mkdirSync as ne}from"node:fs";import{join as c}from"node:path";import{getOctocodeHome as oe}from"@octocodeai/config";var se=448;function ie(){return oe(process.env)}var a=ie(),k={home:a,config:c(a,".octocoderc"),credentials:c(a,"credentials.json"),key:c(a,".key"),session:c(a,"session.json"),stats:c(a,"stats.json"),tmp:c(a,"tmp"),clone:c(a,"tmp","clone"),tree:c(a,"tmp","tree"),response:c(a,"tmp","response"),repos:c(a,"tmp","clone"),cliConfig:c(a,"config.json"),lspConfig:c(a,"lsp-servers.json")};function W(){re(k.home)||ne(k.home,{recursive:!0,mode:se})}import{z as i}from"zod";var ae=i.object({token:i.string(),tokenType:i.literal("oauth"),scopes:i.array(i.string()).optional(),refreshToken:i.string().optional(),expiresAt:i.string().optional(),refreshTokenExpiresAt:i.string().optional()}),ce=i.object({hostname:i.string(),username:i.string(),token:ae,gitProtocol:i.enum(["ssh","https"]),createdAt:i.string(),updatedAt:i.string()}),j=i.object({version:i.number(),credentials:i.record(i.string(),ce)});var U=k.home,p=k.credentials,d=k.key,B="aes-256-gcm",pe=16;function R(){W()}function $(){if(R(),E(d))return le(d).mode&511&63&&ue(d,384),Buffer.from(N(d,"utf8"),"hex");let e=M(32);return z(d,e.toString("hex"),{mode:384}),e}function w(e){let t=$(),r=M(pe),n=de(B,t,r),o=n.update(e,"utf8","hex");o+=n.final("hex");let s=n.getAuthTag();return`${r.toString("hex")}:${s.toString("hex")}:${o}`}function b(e){let t=$(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error("Invalid encrypted data format");let s=Buffer.from(r,"hex"),l=Buffer.from(n,"hex"),g=fe(B,t,s);g.setAuthTag(l);let x=g.update(o,"hex","utf8");return x+=g.final("utf8"),x}function h(){if(R(),!E(p))return{version:1,credentials:{}};try{let e=N(p,"utf8"),t=b(e),r=JSON.parse(t),n=j.safeParse(r);return n.success?n.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function D(e){R();let t=w(JSON.stringify(e,null,2));z(p,t,{mode:384})}function K(){try{E(p)&&L(p),E(d)&&L(d)}catch{}}import{refreshToken as he}from"@octokit/oauth-methods";import{request as me}from"@octokit/request";var T="178c6fc778ccc68e1d6a",m="github.com";function ge(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 ke(e){return e==="github.com"||e===m?"https://api.github.com":`https://${e}/api/v3`}async function _(e,t=m,r=T){let n=await e.getCredentials(t);if(!n)return{success:!1,error:`Not logged in to ${t}`};if(!n.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(S(n))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await he({clientType:"github-app",clientId:r,clientSecret:"",refreshToken:n.token.refreshToken,request:me.defaults({baseUrl:ke(t)})}),s={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,s),{success:!0,username:n.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?ge(o.message):"Token refresh failed"}}}async function Y(e,t=m,r=T){let n=await e.getCredentials(t);if(!n||!n.token)return{token:null,source:"none"};if(!f(n))return{token:n.token.token,source:"stored",username:n.username};if(n.token.refreshToken){let o=await _(e,t,r);if(o.success){let s=await e.getCredentials(t);if(s?.token.token)return{token:s.token.token,source:"refreshed",username:s.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}import{resolveEnvToken as xe}from"@octocodeai/config";import{execFile as Te}from"child_process";var Ce=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function P(e){return new Promise(t=>{let r=["auth","token"];e&&r.push("--hostname",e);let n=process.env.PATH??"",o=new Set(n.split(":")),s=Ce.filter(g=>!o.has(g)),l=s.length?`${s.join(":")}:${n}`:n;Te("gh",r,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:l}},(g,x)=>{if(g||!x){t(null);return}t(x.trim()||null)})})}var A=null;function q(e){A=e}function J(){A=null}function ye(){if(!A)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return A}async function O(e){let t=e?.hostname??m,r=e?.clientId??T,n=e?.getGhCliToken??P,o=xe();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let s=await ye().getTokenWithRefresh(t,r);if(s.token)return{token:s.token,source:"octocode-storage",wasRefreshed:s.source==="refreshed",username:s.username};try{let l=await Promise.resolve(n(t));if(l?.trim())return{token:l.trim(),source:"gh-cli",wasRefreshed:!1}}catch(l){process.stderr.write(`[octocode] gh auth token failed: ${l instanceof Error?l.message:String(l)}
9
+ `)}return null}async function V(e=m){let t=await O({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Z(e=m,t=T){let r=await O({hostname:e,clientId:t,getGhCliToken:()=>null});return r?{token:r.token,source:r.source,wasRefreshed:r.wasRefreshed,username:r.username}:null}async function Q(e){let t=u(e.hostname),r={...e,hostname:t,updatedAt:new Date().toISOString()};try{let n=h();return n.credentials[t]=r,D(n),v(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function C(e="github.com",t){let r=u(e);if(!t?.bypassCache){let s=G(r);if(s!==void 0)return s}let o=h().credentials[r]||null;return I(r,o),o}function F(e="github.com"){let t=u(e);return h().credentials[t]||null}async function Re(e="github.com"){let t=u(e),r=!1,n=h();return n.credentials[t]&&(delete n.credentials[t],Object.keys(n.credentials).length===0?K():D(n),r=!0),v(t),{success:r,deletedFromFile:r}}async function Se(){let e=h();return Object.keys(e.credentials)}function ve(){let e=h();return Object.keys(e.credentials)}async function Ee(e="github.com"){return await C(e)!==null}function Ae(e="github.com"){return F(e)!==null}async function H(e,t){let r=await C(e);return r?(r.token=t,r.updatedAt=new Date().toISOString(),await Q(r),!0):!1}function Oe(){return p}async function we(e="github.com"){let t=await C(e);return!t||!t.token||f(t)?null:t.token.token}function be(e="github.com"){let t=F(e);return!t||!t.token||f(t)?null:t.token.token}async function De(e,t){return _({getCredentials:C,updateToken:H},e,t)}async function X(e,t){return Y({getCredentials:C,updateToken:H},e,t)}q({getTokenWithRefresh:X});export{p as CREDENTIALS_FILE,d as KEY_FILE,U as OCTOCODE_DIR,b as decrypt,Re as deleteCredentials,w as encrypt,R as ensureOctocodeDir,C as getCredentials,Oe as getCredentialsFilePath,F as getCredentialsSync,P as getGhCliToken,we as getToken,be as getTokenSync,X as getTokenWithRefresh,Ee as hasCredentials,Ae as hasCredentialsSync,v as invalidateCredentialsCache,S as isRefreshTokenExpired,f as isTokenExpired,Se as listStoredHosts,ve as listStoredHostsSync,h as readCredentialsStore,De as refreshAuthToken,J as resetTokenResolution,V as resolveToken,O as resolveTokenFull,Z as resolveTokenWithRefresh,Q as storeCredentials,H as updateToken};
@@ -18,6 +18,7 @@ export declare const paths: {
18
18
  readonly tmp: string;
19
19
  readonly clone: string;
20
20
  readonly tree: string;
21
+ readonly response: string;
21
22
  readonly repos: string;
22
23
  readonly cliConfig: string;
23
24
  readonly lspConfig: string;
@@ -5,4 +5,4 @@ import { dirname as __dirname_fn } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __dirname_fn(__filename);
8
- import{existsSync as r,mkdirSync as n}from"node:fs";import{join as o}from"node:path";import{getOctocodeHome as c}from"@octocodeai/config";var s=448;function p(){return c(process.env)}function v(){return e}var e=p(),t={home:e,config:o(e,".octocoderc"),credentials:o(e,"credentials.json"),key:o(e,".key"),session:o(e,"session.json"),stats:o(e,"stats.json"),tmp:o(e,"tmp"),clone:o(e,"tmp","clone"),tree:o(e,"tmp","tree"),repos:o(e,"tmp","clone"),cliConfig:o(e,"config.json"),lspConfig:o(e,"lsp-servers.json")};function m(){r(t.home)||n(t.home,{recursive:!0,mode:s})}function x(){u()}function i(){m(),r(t.tmp)||n(t.tmp,{recursive:!0,mode:s})}function u(){i(),r(t.clone)||n(t.clone,{recursive:!0,mode:s})}function g(){i(),r(t.tree)||n(t.tree,{recursive:!0,mode:s})}export{e as OCTOCODE_HOME,u as ensureClone,m as ensureHome,x as ensureRepos,i as ensureTmp,g as ensureTree,p as getDefaultOctocodeHome,v as getOctocodeDir,t as paths};
8
+ import{existsSync as r,mkdirSync as n}from"node:fs";import{join as o}from"node:path";import{getOctocodeHome as c}from"@octocodeai/config";var s=448;function p(){return c(process.env)}function v(){return e}var e=p(),t={home:e,config:o(e,".octocoderc"),credentials:o(e,"credentials.json"),key:o(e,".key"),session:o(e,"session.json"),stats:o(e,"stats.json"),tmp:o(e,"tmp"),clone:o(e,"tmp","clone"),tree:o(e,"tmp","tree"),response:o(e,"tmp","response"),repos:o(e,"tmp","clone"),cliConfig:o(e,"config.json"),lspConfig:o(e,"lsp-servers.json")};function m(){r(t.home)||n(t.home,{recursive:!0,mode:s})}function x(){u()}function i(){m(),r(t.tmp)||n(t.tmp,{recursive:!0,mode:s})}function u(){i(),r(t.clone)||n(t.clone,{recursive:!0,mode:s})}function g(){i(),r(t.tree)||n(t.tree,{recursive:!0,mode:s})}export{e as OCTOCODE_HOME,u as ensureClone,m as ensureHome,x as ensureRepos,i as ensureTmp,g as ensureTree,p as getDefaultOctocodeHome,v as getOctocodeDir,t as paths};