@octocodeai/octocode-tools-core 16.3.0 → 16.6.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.
- package/README.md +564 -0
- package/dist/config.d.ts +7 -0
- package/dist/direct.js +39 -41
- package/dist/errors/pathUtils.d.ts +1 -1
- package/dist/github/directoryFetch.d.ts +2 -1
- package/dist/github/githubAPI.d.ts +32 -1
- package/dist/github/history.d.ts +3 -0
- package/dist/github/prTransformation.d.ts +1 -1
- package/dist/github/repoStructureRecursive.d.ts +6 -0
- package/dist/index.d.ts +16 -30
- package/dist/index.js +44 -46
- package/dist/oql/adapters/compile.d.ts +25 -0
- package/dist/oql/adapters/github.d.ts +3 -0
- package/dist/oql/adapters/local.d.ts +7 -0
- package/dist/oql/adapters/materialize.d.ts +11 -0
- package/dist/oql/adapters/pagination.d.ts +21 -0
- package/dist/oql/adapters/researchTargets.d.ts +50 -0
- package/dist/oql/adapters/resultMap.d.ts +20 -0
- package/dist/oql/adapters/ruleYaml.d.ts +11 -0
- package/dist/oql/adapters/runner.d.ts +14 -0
- package/dist/oql/adapters/v2.d.ts +32 -0
- package/dist/oql/capabilities.d.ts +31 -0
- package/dist/oql/defaults.d.ts +26 -0
- package/dist/oql/diagnostics.d.ts +25 -0
- package/dist/oql/diffLanes.d.ts +29 -0
- package/dist/oql/envelope.d.ts +19 -0
- package/dist/oql/features.d.ts +7 -0
- package/dist/oql/index.d.ts +26 -0
- package/dist/oql/index.js +49 -0
- package/dist/oql/normalize.d.ts +5 -0
- package/dist/oql/planner.d.ts +7 -0
- package/dist/oql/research/analyze.d.ts +134 -0
- package/dist/oql/research/packets.d.ts +80 -0
- package/dist/oql/run.d.ts +32 -0
- package/dist/oql/schema.d.ts +1018 -0
- package/dist/oql/schemeText.d.ts +138 -0
- package/dist/oql/shorthand.d.ts +177 -0
- package/dist/oql/targetParams.d.ts +20 -0
- package/dist/oql/transformers/contract.d.ts +19 -0
- package/dist/oql/transformers/github/code.d.ts +17 -0
- package/dist/oql/transformers/github/common.d.ts +8 -0
- package/dist/oql/transformers/language.d.ts +1 -0
- package/dist/oql/transformers/registry.d.ts +16 -0
- package/dist/oql/transformers/types.d.ts +11 -0
- package/dist/oql/types.d.ts +633 -0
- package/dist/oql/v2params.d.ts +22 -0
- package/dist/providers/providerQueries.d.ts +9 -0
- package/dist/providers/providerResults.d.ts +2 -0
- package/dist/providers/types.d.ts +1 -1
- package/dist/schema.d.ts +13 -0
- package/dist/schema.js +8 -0
- package/dist/scheme/coreSchemas.d.ts +5 -5
- package/dist/scheme/fields.d.ts +6 -6
- package/dist/serverConfig.d.ts +1 -2
- package/dist/session.d.ts +2 -24
- package/dist/shared/config/defaults.d.ts +14 -0
- package/dist/shared/config/index.d.ts +9 -0
- package/dist/shared/config/index.js +9 -0
- package/dist/shared/config/loader.d.ts +7 -0
- package/dist/shared/config/resolver.d.ts +2 -0
- package/dist/shared/config/resolverCache.d.ts +12 -0
- package/dist/shared/config/resolverSections.d.ts +10 -0
- package/dist/shared/config/runtimeSurface.d.ts +21 -0
- package/dist/shared/config/schemas.d.ts +11 -0
- package/dist/shared/config/types.d.ts +92 -0
- package/dist/shared/config/validator.d.ts +2 -0
- package/dist/shared/credentials/constants.d.ts +2 -0
- package/dist/shared/credentials/credentialCache.d.ts +13 -0
- package/dist/shared/credentials/credentialEncryption.d.ts +10 -0
- package/dist/shared/credentials/credentialUtils.d.ts +4 -0
- package/dist/shared/credentials/envTokens.d.ts +9 -0
- package/dist/shared/credentials/ghCli.d.ts +1 -0
- package/dist/shared/credentials/index.d.ts +3 -0
- package/dist/shared/credentials/index.js +8 -0
- package/dist/shared/credentials/schemas.d.ts +22 -0
- package/dist/shared/credentials/storage.d.ts +30 -0
- package/dist/shared/credentials/testing.d.ts +2 -0
- package/dist/shared/credentials/testing.js +8 -0
- package/dist/shared/credentials/tokenRefresh.d.ts +24 -0
- package/dist/shared/credentials/tokenResolution.d.ts +30 -0
- package/dist/shared/credentials/types.d.ts +28 -0
- package/dist/shared/fs-utils.d.ts +2 -0
- package/dist/shared/fs-utils.js +8 -0
- package/dist/shared/index.d.ts +6 -0
- package/dist/shared/languageSelectors.d.ts +23 -0
- package/dist/shared/paths.d.ts +31 -0
- package/dist/shared/paths.js +8 -0
- package/dist/shared/platform/index.d.ts +1 -0
- package/dist/shared/platform/index.js +8 -0
- package/dist/shared/platform/platform.d.ts +8 -0
- package/dist/shared/session/index.d.ts +5 -0
- package/dist/shared/session/index.js +8 -0
- package/dist/shared/session/schemas.d.ts +103 -0
- package/dist/shared/session/sessionCache.d.ts +9 -0
- package/dist/shared/session/sessionDiskIO.d.ts +6 -0
- package/dist/shared/session/statsDefaults.d.ts +4 -0
- package/dist/shared/session/storage.d.ts +20 -0
- package/dist/shared/session/types.d.ts +53 -0
- package/dist/tools/directToolCatalog.d.ts +15 -56
- package/dist/tools/directToolCatalog.exec.d.ts +11 -0
- package/dist/tools/directToolCatalog.meta.d.ts +82 -0
- package/dist/tools/github_clone_repo/cache.d.ts +5 -1
- package/dist/tools/github_clone_repo/scheme.d.ts +56 -9
- package/dist/tools/github_clone_repo/types.d.ts +3 -1
- package/dist/tools/github_fetch_content/scheme.d.ts +112 -4
- package/dist/tools/github_fetch_content/types.d.ts +39 -0
- package/dist/tools/github_search_code/scheme.d.ts +6 -6
- package/dist/tools/github_search_pull_requests/contentResponse.d.ts +0 -1
- package/dist/tools/github_search_pull_requests/execution.d.ts +1 -11
- package/dist/tools/github_search_pull_requests/scheme.d.ts +6 -2
- package/dist/tools/github_search_repos/scheme.d.ts +7 -6
- package/dist/tools/github_view_repo_structure/execution.d.ts +0 -9
- package/dist/tools/github_view_repo_structure/scheme.d.ts +10 -6
- package/dist/tools/local_binary_inspect/archiveOps.d.ts +2 -0
- package/dist/tools/local_binary_inspect/binaryInspector.d.ts +48 -7
- package/dist/tools/local_binary_inspect/binaryOps.d.ts +16 -7
- package/dist/tools/local_binary_inspect/scheme.d.ts +10 -7
- package/dist/tools/local_fetch_content/scheme.d.ts +2 -2
- package/dist/tools/local_find_files/scheme.d.ts +2 -2
- package/dist/tools/local_ripgrep/lspBoost.d.ts +54 -0
- package/dist/tools/local_ripgrep/rankingProfile.d.ts +113 -0
- package/dist/tools/local_ripgrep/ripgrepResultBuilder.d.ts +10 -1
- package/dist/tools/local_ripgrep/scheme.d.ts +29 -4
- package/dist/tools/local_ripgrep/structuralSearch.d.ts +3 -4
- package/dist/tools/local_view_structure/scheme.d.ts +2 -2
- package/dist/tools/local_view_structure/structureFilters.d.ts +1 -3
- package/dist/tools/local_view_structure/structureResponse.d.ts +1 -0
- package/dist/tools/lsp/semantic_content/scheme.d.ts +174 -10
- package/dist/tools/lsp/shared/callHierarchyTraversal.d.ts +2 -2
- package/dist/tools/lsp/shared/resolveSymbolAnchor.d.ts +2 -2
- package/dist/tools/lsp/shared/semanticTypes.d.ts +36 -6
- package/dist/tools/oql_search/execution.d.ts +7 -0
- package/dist/tools/package_search/execution.d.ts +10 -0
- package/dist/tools/package_search/scheme.d.ts +9 -7
- package/dist/tools/providerMappers.d.ts +24 -5
- package/dist/tools/toolConfig.d.ts +1 -0
- package/dist/tools/toolMetadata/proxies.d.ts +0 -6
- package/dist/tools/toolNames.d.ts +2 -0
- package/dist/tools/utils.d.ts +3 -7
- package/dist/types/bulk.d.ts +0 -2
- package/dist/types/execution.d.ts +1 -2
- package/dist/types/server.d.ts +0 -1
- package/dist/types/session.d.ts +0 -19
- package/dist/types/toolResults.d.ts +2 -3
- package/dist/utils/contextUtils.d.ts +49 -2
- package/dist/utils/core/lines.d.ts +16 -0
- package/dist/utils/core/types.d.ts +12 -1
- package/dist/utils/file/filters.d.ts +2 -11
- package/dist/utils/markdownOutline.d.ts +10 -0
- package/dist/utils/parsers/diff.d.ts +18 -0
- package/dist/utils/response/error.d.ts +38 -4
- package/dist/utils/response/groupedFinalizer.d.ts +0 -25
- package/package.json +51 -14
- package/dist/commands/BaseCommandBuilder.d.ts +0 -14
- package/dist/commands/FindCommandBuilder.d.ts +0 -23
- package/dist/commands/LsCommandBuilder.d.ts +0 -15
- package/dist/commands/RipgrepCommandBuilder.d.ts +0 -27
- package/dist/hints/dynamic.d.ts +0 -6
- package/dist/hints/index.d.ts +0 -2
- package/dist/hints/types.d.ts +0 -1
- package/dist/tools/github_clone_repo/hints.d.ts +0 -2
- package/dist/tools/github_fetch_content/hints.d.ts +0 -2
- package/dist/tools/github_search_code/hints.d.ts +0 -2
- package/dist/tools/github_search_pull_requests/hints.d.ts +0 -2
- package/dist/tools/github_search_repos/hints.d.ts +0 -2
- package/dist/tools/github_view_repo_structure/hints.d.ts +0 -2
- package/dist/tools/local_fetch_content/hints.d.ts +0 -2
- package/dist/tools/local_find_files/hints.d.ts +0 -2
- package/dist/tools/local_ripgrep/grepFallbackExecutor.d.ts +0 -3
- package/dist/tools/local_ripgrep/hints.d.ts +0 -2
- package/dist/tools/local_ripgrep/ripgrepParser.d.ts +0 -9
- package/dist/tools/local_view_structure/hints.d.ts +0 -2
- package/dist/tools/local_view_structure/structureParser.d.ts +0 -3
- package/dist/tools/local_view_structure/structureWalker.d.ts +0 -24
- package/dist/tools/lsp/semantic_content/hints.d.ts +0 -4
- package/dist/tools/package_search/hints.d.ts +0 -2
- package/dist/types/metadata.d.ts +0 -69
- package/dist/utils/exec/commandAvailability.d.ts +0 -19
- package/dist/utils/exec/ripgrepBinary.d.ts +0 -3
- package/dist/utils/pagination/outputSizeLimit.d.ts +0 -16
- package/dist/utils/response/structuredPagination.d.ts +0 -9
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@octocodeai/octocode-tools-core/schema` — the engine-FREE direct-tool schema
|
|
3
|
+
* surface (P3). Re-exports only the metadata/schema-text/display/input-prep API
|
|
4
|
+
* from `directToolCatalog.meta.ts`, with NO transitive `@octocodeai/octocode-engine`
|
|
5
|
+
* import. Importing this never loads the native `.node` addon, so consumers that
|
|
6
|
+
* only need `--scheme` / help / `context` (e.g. the CLI on engine-less runtimes
|
|
7
|
+
* like Codex.app Node) can read schemas without the engine.
|
|
8
|
+
*
|
|
9
|
+
* For execution, import `executeDirectTool` from `@octocodeai/octocode-tools-core/direct`.
|
|
10
|
+
*/
|
|
11
|
+
export * from './tools/directToolCatalog.meta.js';
|
|
12
|
+
export { oqlSchemaText, OQL_SCHEMA_DOC } from './oql/schemeText.js';
|
|
13
|
+
export { loadToolContent } from './tools/toolMetadata/state.js';
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __createRequire } from 'module';
|
|
3
|
+
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
4
|
+
import { dirname as __dirname_fn } from 'path';
|
|
5
|
+
const require = __createRequire(import.meta.url);
|
|
6
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
7
|
+
const __dirname = __dirname_fn(__filename);
|
|
8
|
+
import{z as te}from"zod";import{completeMetadata as Ft}from"@octocodeai/octocode-core";var p=Ft.toolNames,P=p.LSP_GET_SEMANTIC_CONTENT,N="oqlSearch",dr=new Set([p.LOCAL_RIPGREP,p.LOCAL_FETCH_CONTENT,p.LOCAL_FIND_FILES,p.LOCAL_VIEW_STRUCTURE,p.LOCAL_BINARY_INSPECT,P]);var ce=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];import{CloneRepoQuerySchema as Nt}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as Ht}from"@octocodeai/octocode-core/schemas/outputs";import{z as H}from"zod";function l(n,r){return H.preprocess(o=>typeof o=="number"&&Number.isFinite(o)?Math.min(Math.max(o,n),r):o,H.number().int().min(n).max(r))}var f=l(1,1e3).optional().default(1),E=l(0,100).optional(),_=l(1,1e9).optional(),Dt={responseCharOffset:l(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:l(1,5e4).optional().describe("Full-response char window.")};function g(n,r={}){let{maxQueries:o=5}=r;return H.object({queries:H.array(n).min(1).max(o).describe("Parallel queries."),...Dt}).superRefine((i,c)=>{let u=new Set;i.queries.forEach((d,S)=>{d&&typeof d=="object"&&"id"in d&&typeof d.id=="string"&&(u.has(d.id)&&c.addIssue({code:"custom",message:`Duplicate query id "${d.id}" at index ${S}`,path:["queries",S,"id"]}),u.add(d.id))})})}import{z as le}from"zod";function Qt(n,r){return n?.description&&!r.description?r.describe(n.description):r}function ue(n,r){let o={};for(let[i,c]of Object.entries(r))o[i]=Qt(n.shape[i],c);return o}function Mt(n,r){let o=n;return o.safeExtend?o.safeExtend(r):n.extend(r)}function pe(n,r){if(!r?.length)return n;let o=new Set(r);return le.object(Object.fromEntries(Object.entries(n.shape).filter(([i])=>!o.has(i))))}function y(n,r={},o={}){let i=pe(n,o.omit),c=Mt(i,ue(i,r));return o.strict?c.strict():c}function b(n,r={},o={}){let i=pe(n,o.omit),c=le.object({...i.shape,...ue(i,r)});return o.strict?c.strict():c}import{z as x}from"zod";var Gt=x.object({currentPage:x.number(),totalPages:x.number(),hasMore:x.boolean(),charOffset:x.number(),charLength:x.number(),totalChars:x.number(),nextCharOffset:x.number().optional()}).optional(),O={hints:x.array(x.string()).optional(),base:x.string().optional(),shared:x.record(x.string(),x.union([x.string(),x.number(),x.boolean()])).optional(),responsePagination:Gt};var X=y(Nt),me=g(X),_r=Ht.extend(O);import{z as a}from"zod";import{FileContentQuerySchema as ge}from"@octocodeai/octocode-core/schemas";var jt=a.enum(["none","standard","symbols"]).optional().default("standard"),Bt=a.object({currentPage:a.number(),totalPages:a.number(),hasMore:a.boolean(),nextPage:a.number().optional(),nextMatchPage:a.number().optional(),charOffset:a.number().optional(),charLength:a.number().optional(),totalChars:a.number().optional(),nextCharOffset:a.number().optional(),filesPerPage:a.number().optional(),totalFiles:a.number().optional(),entriesPerPage:a.number().optional(),totalEntries:a.number().optional(),matchesPerPage:a.number().optional(),totalMatches:a.number().optional()}),de=a.object({path:a.string(),content:a.string(),localPath:a.string().optional(),repoRoot:a.string().optional(),contentView:a.enum(["none","standard","symbols"]).optional(),isSkeleton:a.boolean().optional(),totalLines:a.number().optional(),sourceChars:a.number().optional(),sourceBytes:a.number().optional(),resolvedBranch:a.string().optional(),pagination:Bt.optional(),isPartial:a.boolean().optional(),startLine:a.number().optional(),endLine:a.number().optional(),matchRanges:a.array(a.object({start:a.number(),end:a.number()})).optional(),lastModified:a.string().optional(),lastModifiedBy:a.string().optional(),warnings:a.array(a.string()).optional(),matchNotFound:a.boolean().optional(),searchedFor:a.string().optional(),cached:a.boolean().optional()}),he=a.object({path:a.string(),localPath:a.string(),repoRoot:a.string().optional(),fileCount:a.number(),totalSize:a.number(),complete:a.boolean().optional(),directoryEntryCount:a.number().optional(),eligibleFileCount:a.number().optional(),savedFileCount:a.number().optional(),skipped:a.object({nonFile:a.number(),missingDownloadUrl:a.number(),oversized:a.number(),binary:a.number(),fileLimit:a.number(),fetchFailed:a.number(),totalSizeLimit:a.number(),pathTraversal:a.number()}).optional(),limits:a.object({maxDirectoryFiles:a.number(),maxTotalSize:a.number(),maxFileSize:a.number()}).optional(),warnings:a.array(a.string()).optional(),files:a.array(a.object({path:a.string(),size:a.number(),type:a.string()})).optional(),cached:a.boolean().optional(),resolvedBranch:a.string().optional()}),fe={startLine:_,endLine:_,contextLines:E,charOffset:l(0,1e8).optional(),charLength:l(1,5e4).optional(),minify:jt},zt=b(ge,fe),ye=y(ge,fe),be=g(zt),Mr=a.object({base:a.string().optional(),shared:a.record(a.string(),a.union([a.string(),a.number(),a.boolean()])).optional(),responsePagination:O.responsePagination,results:a.array(a.object({id:a.string(),owner:a.string(),repo:a.string(),files:a.array(de).optional(),directories:a.array(he).optional(),data:a.object({owner:a.string(),repo:a.string(),files:a.array(de).optional(),directories:a.array(he).optional()}).optional()})),errors:a.array(a.object({id:a.string(),owner:a.string().optional(),repo:a.string().optional(),path:a.string().optional(),error:a.string()})).optional()});import{z as s}from"zod";import{GitHubCodeSearchQuerySchema as Se}from"@octocodeai/octocode-core/schemas";var xe={limit:l(1,100).optional(),page:f.default(1)},Re=y(Se,xe),Oe=g(b(Se,xe)),$r=s.object({base:s.string().optional(),shared:s.record(s.string(),s.union([s.string(),s.number(),s.boolean()])).optional(),responsePagination:O.responsePagination,results:s.array(s.object({id:s.string(),data:s.object({files:s.array(s.object({owner:s.string(),repo:s.string(),path:s.string(),queryId:s.string().optional(),matches:s.array(s.object({value:s.string().optional(),pathOnly:s.boolean().optional(),matchIndices:s.array(s.object({start:s.number(),end:s.number(),lineOffset:s.number()})).optional(),url:s.string().optional()}))})),pagination:s.object({currentPage:s.number(),totalPages:s.number(),perPage:s.number(),totalMatches:s.number(),reportedTotalMatches:s.number().optional(),reachableTotalMatches:s.number().optional(),totalMatchesKind:s.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:s.boolean().optional(),hasMore:s.boolean(),nextPage:s.number().optional(),uniqueFileCount:s.number().optional()}).optional()})})),emptyQueries:s.array(s.object({id:s.string(),nonExistentScope:s.literal(!0).optional(),incompleteResults:s.literal(!0).optional()})).optional(),warnings:s.array(s.string()).optional(),errors:s.array(s.object({id:s.string(),error:s.string()})).optional()});import{z as L}from"zod";import{GitHubPullRequestSearchQuerySchema as we}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Xt}from"@octocodeai/octocode-core/schemas/outputs";var Te={perPage:l(1,100).optional().default(30),prNumber:l(1,1e9).optional(),limit:l(1,100).optional().default(30),page:f.default(1),filePage:f.optional(),commentPage:f.optional(),commitPage:f.optional(),itemsPerPage:l(1,100).optional().default(20),charOffset:l(0,1e8).optional(),commentBodyOffset:l(0,1e8).optional(),charLength:l(1,5e4).optional()},Wt=b(we,Te),ke=y(we,Te),Pe=g(Wt),to=Xt.extend({results:L.array(L.object({id:L.string().optional(),status:L.string().optional(),data:L.object({pull_requests:L.array(L.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...O});import{z as m}from"zod";import{GitHubReposSearchSingleQuerySchema as Le}from"@octocodeai/octocode-core/schemas";var Ce={limit:l(1,100).optional(),page:f.default(1)},Ee=y(Le,Ce),_e=g(b(Le,Ce)),Zt=m.object({owner:m.string(),repo:m.string(),stars:m.number().optional(),forks:m.number().optional(),openIssuesCount:m.number().optional(),language:m.string().optional(),license:m.string().optional(),description:m.string().optional(),homepage:m.string().optional(),pushedAt:m.string().optional(),createdAt:m.string().optional(),defaultBranch:m.string().optional(),topics:m.array(m.string()).optional(),visibility:m.string().optional(),url:m.string().optional(),updatedAt:m.string().optional()}),Jt=m.object({currentPage:m.number(),totalPages:m.number(),hasMore:m.boolean(),perPage:m.number().optional(),totalMatches:m.number().optional(),reportedTotalMatches:m.number().optional(),reachableTotalMatches:m.number().optional(),totalMatchesKind:m.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:m.boolean().optional(),nextPage:m.number().optional()}).optional(),Kt=m.object({repositories:m.array(m.union([m.string(),Zt])).optional(),pagination:Jt}).passthrough(),lo=m.object({results:m.array(m.object({id:m.string().optional(),status:m.string().optional(),data:Kt.optional()}).passthrough()).optional()}).extend(O);import{GitHubViewRepoStructureQuerySchema as Ae}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as en}from"@octocodeai/octocode-core/schemas/outputs";var qe={maxDepth:l(0,20).optional(),page:f.default(1),itemsPerPage:l(1,200).optional()},ve=y(Ae,qe),Fe=g(b(Ae,qe)),So=en.extend(O);import{z as h}from"zod";import{NpmPackageQuerySchema as Ie}from"@octocodeai/octocode-core/schemas";var De={page:f,mode:h.enum(["lean","full"]).optional()},Qe=y(Ie,De),Me=g(b(Ie,De,{strict:!0}),{maxQueries:5}),Po=h.object({results:h.array(h.looseObject({id:h.string(),data:h.looseObject({packages:h.array(h.object({name:h.string(),version:h.string().optional(),description:h.string().optional(),license:h.string().optional(),downloads:h.number().optional(),repository:h.string().optional(),repositoryDirectory:h.string().optional(),next:h.record(h.string(),h.unknown()).optional()}).passthrough()).optional(),pagination:h.object({currentPage:h.number(),totalPages:h.number(),perPage:h.number(),totalFound:h.number(),returned:h.number(),hasMore:h.boolean(),nextPage:h.number().optional()}).optional()}).optional(),status:h.string().optional()})).optional()}).extend(O);import{z as tn}from"zod";import{FetchContentQuerySchema as Ge}from"@octocodeai/octocode-core/schemas";var nn=tn.enum(["none","standard","symbols"]).optional().default("standard"),Ne={startLine:_,endLine:_,contextLines:E.default(5),charOffset:l(0,1e8).optional(),charLength:l(1,5e4).optional(),minify:nn},rn=b(Ge,Ne),He=y(Ge,Ne),je=g(rn,{maxQueries:5});import{z as on}from"zod";import{FindFilesQuerySchema as an}from"@octocodeai/octocode-core/schemas";var Be={maxDepth:l(0,100).optional(),minDepth:l(0,100).optional(),limit:l(1,1e4).optional(),page:f.default(1),itemsPerPage:l(1,50).optional()},ze=on.object(Object.fromEntries(Object.entries(an.shape).filter(([n])=>n!=="regexType")));function sn(n,r){n.minDepth!==void 0&&n.maxDepth!==void 0&&n.minDepth>n.maxDepth&&r.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var cn=b(ze,Be),Ue=y(ze,Be).superRefine(sn),$e=g(cn,{maxQueries:5});import{z as A}from"zod";import{RipgrepQuerySchema as Ve}from"@octocodeai/octocode-core/schemas";var ln=["paginated","discovery","detailed","structural"],un=["semanticRanking"],Xe={mode:A.enum(ln).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters.'),pattern:A.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:A.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:E,matchContentLength:l(1,1e5).optional().default(500),maxMatchesPerFile:l(1,1e5).optional(),maxFiles:l(1,1e5).optional(),matchPage:f.optional(),itemsPerPage:l(1,1e3).optional(),page:f.default(1),unique:A.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:A.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},pn={...Xe,semanticRanking:A.never().optional()},mn=b(Ve,pn),dn=y(Ve,Xe,{strict:!0,omit:un}),We=dn.superRefine((n,r)=>{let o=n;if(o.caseSensitive&&o.caseInsensitive&&r.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),o.fixedString&&o.perlRegex&&r.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),o.filesOnly&&o.filesWithoutMatch&&r.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),o.countLinesPerFile&&o.countMatchesPerFile&&r.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),o.multilineDotall&&!o.multiline&&r.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),o.mode==="structural"){for(let i of["unique","countUnique"])o[i]&&r.addIssue({code:"custom",message:`\`${i}\` is not valid with mode:"structural".`,path:[i]});return}o.unique&&!o.onlyMatching&&r.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),o.countUnique&&!o.onlyMatching&&r.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),Ze=g(mn,{maxQueries:5});import{ViewStructureQuerySchema as Je}from"@octocodeai/octocode-core/schemas";var Ke={maxDepth:l(0,20).optional(),limit:l(1,1e4).optional(),page:f.default(1),itemsPerPage:l(1,50).optional()},hn=b(Je,Ke),Ye=y(Je,Ke),et=g(hn,{maxQueries:5});import{z as t}from"zod";import{LspGetSemanticsQuerySchema as rt}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as gn}from"@octocodeai/octocode-core/schemas/outputs";var fn=l(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),yn=l(0,1e5).optional(),bn=["structured","compact"],ot={type:t.enum(ce).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:t.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:fn.optional(),orderHint:yn,depth:l(0,20).optional(),includeDeclaration:t.boolean().optional().default(!0),page:f,itemsPerPage:l(1,100).optional(),contextLines:l(0,100).optional(),format:t.enum(bn).optional().default("structured")},Sn=b(rt,ot),at=y(rt,ot);var it=g(Sn,{maxQueries:5}),tt=t.object({line:t.number(),character:t.number()}),xn=t.object({start:tt,end:tt}),Rn=t.object({startLine:t.number(),endLine:t.number()}),j=t.object({uri:t.string(),content:t.string().optional(),displayRange:Rn.optional(),isDefinition:t.boolean().optional()}),B=t.string(),On=t.object({name:t.string(),uri:t.string(),foundAtLine:t.number(),orderHint:t.number().optional()}),wn=t.object({serverAvailable:t.boolean().optional(),provider:t.string().optional(),source:t.string().optional()}),st=t.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),q=t.object({category:st,reason:t.string()}),Tn=t.object({currentPage:t.number(),totalPages:t.number(),totalResults:t.number(),hasMore:t.boolean(),itemsPerPage:t.number(),nextPage:t.number().optional()}),kn=t.object({name:t.string(),kind:t.string(),line:t.number(),character:t.number(),endLine:t.number(),childCount:t.number(),containerName:t.string().optional()}),Pn=t.string(),ct=t.object({name:t.string(),kind:t.string(),uri:t.string(),line:t.number(),endLine:t.number(),selectionLine:t.number().optional()}),Ln=t.string(),Cn=t.object({direction:t.enum(["incoming","outgoing"]),item:ct,ranges:t.array(t.object({line:t.number(),character:t.number()})),rangeCount:t.number(),rangeSampleCount:t.number(),contentPreview:t.string().optional()}),En=t.string(),_n=t.object({complete:t.boolean(),truncatedByDepth:t.boolean(),cycleCount:t.number(),failedRequestCount:t.number(),dynamicCallsExcluded:t.literal(!0),stdlibCallsExcluded:t.number().optional()}),An=t.object({uri:t.string(),count:t.number(),firstLine:t.number(),firstCharacter:t.number(),lines:t.array(t.number()),hasDefinition:t.boolean().optional()}),qn=t.string(),vn=t.discriminatedUnion("kind",[t.object({kind:t.literal("definition"),locations:t.array(t.union([j,B]))}),t.object({kind:t.literal("typeDefinition"),locations:t.array(t.union([j,B]))}),t.object({kind:t.literal("implementation"),locations:t.array(t.union([j,B]))}),t.object({kind:t.literal("references"),locations:t.array(t.union([j,B])).optional(),byFile:t.array(t.union([An,qn])).optional(),totalReferences:t.number(),totalFiles:t.number(),empty:q.optional()}),...["callers","callees","callHierarchy"].map(n=>t.object({kind:t.literal(n),root:t.union([ct,Ln]).optional(),direction:t.enum(["incoming","outgoing","both"]),calls:t.array(t.union([Cn,En])),incomingCalls:t.number(),outgoingCalls:t.number(),completeness:_n,empty:q.optional()})),t.object({kind:t.literal("hover"),markdown:t.string().optional(),text:t.string().optional(),range:xn.optional()}),t.object({kind:t.literal("documentSymbols"),symbols:t.array(t.union([kn,Pn])),totalSymbols:t.number().optional(),topLevelSymbols:t.number().optional(),empty:q.optional()}),t.object({kind:t.literal("workspaceSymbol"),query:t.string(),symbols:t.array(t.unknown()),totalSymbols:t.number(),empty:q.optional()}),t.object({kind:t.literal("typeHierarchy"),direction:t.enum(["supertypes","subtypes"]),root:t.unknown().optional(),items:t.array(t.unknown()),totalItems:t.number(),empty:q.optional()}),t.object({kind:t.literal("diagnostic"),diagnostics:t.array(t.unknown()),totalDiagnostics:t.number(),errorCount:t.number(),warningCount:t.number(),empty:q.optional()}),t.object({kind:t.literal("empty"),category:st,reason:t.string()})]),nt=t.object({type:t.string(),uri:t.string(),format:t.enum(["structured","compact"]).optional(),resolvedSymbol:On.optional(),lsp:wn,payload:vn,pagination:Tn.optional(),summary:t.record(t.string(),t.unknown()).optional(),warnings:t.array(t.string()).optional()}),oa=t.object({base:t.string().optional(),shared:t.record(t.string(),t.union([t.string(),t.number(),t.boolean()])).optional(),results:t.array(t.union([t.object({id:t.string().min(1),status:t.literal("empty"),data:nt}),t.object({id:t.string().min(1),status:t.literal("error"),data:gn}),t.object({id:t.string().min(1),data:nt})]))});import{z as lt}from"zod";import{LocalBinaryInspectQuerySchema as Fn}from"@octocodeai/octocode-core/schemas";var In={entryPageNumber:f.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:l(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:l(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:f.default(1).describe("1-based page for paginated entry/content listings."),detailed:lt.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},ut=lt.object({...Fn.shape,...In}),pt=ut.strict().superRefine((n,r)=>{n.mode==="extract"&&!n.archiveFile&&r.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),n.archiveFile?.startsWith("-")&&r.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let o=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];n.mode==="decompress"&&o.some(i=>n.path.toLowerCase().endsWith(i))&&r.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),mt=g(ut,{maxQueries:5});import{z as e}from"zod";var C=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],z=["fixes","dataflow"];var Y=e.lazy(()=>e.union([e.strictObject({kind:e.literal("local"),path:e.string().min(1)}),e.strictObject({kind:e.literal("github"),repo:e.string().min(1).optional(),owner:e.string().min(1).optional(),ref:e.string().min(1).optional()}),e.strictObject({kind:e.literal("materialized"),localPath:e.string().min(1),source:Y.optional()}),e.strictObject({kind:e.literal("npm")})])),K=e.union([e.string(),e.array(e.string()).max(100)]),Dn=e.strictObject({path:K.optional(),language:K.optional(),include:e.array(e.string()).max(100).optional(),exclude:e.array(e.string()).max(100).optional(),excludeDir:e.array(e.string()).max(100).optional(),hidden:e.boolean().optional(),noIgnore:e.boolean().optional(),minDepth:e.number().int().min(0).max(64).optional(),maxDepth:e.number().int().min(0).max(64).optional()}).optional(),dt=e.enum(["smart","sensitive","insensitive"]),ht=e.string().max(1e4),Qn=e.strictObject({id:e.string().optional(),kind:e.literal("text"),value:ht,case:dt.optional(),wholeWord:e.boolean().optional()}),Mn=e.strictObject({id:e.string().optional(),kind:e.literal("regex"),value:ht,dialect:e.enum(["rust","pcre2","provider"]).optional(),case:dt.optional(),wholeWord:e.boolean().optional(),multiline:e.boolean().optional(),dotAll:e.boolean().optional()}),v=e.lazy(()=>e.strictObject({pattern:e.string().optional(),kind:e.string().optional(),inside:v.optional(),has:v.optional(),not:v.optional(),all:e.array(v).optional(),any:e.array(v).optional(),stopBy:e.literal("end").optional()})),gt=e.union([v,e.string().min(1)]),Gn=e.strictObject({id:e.string().optional(),kind:e.literal("structural"),lang:e.string().min(1),pattern:e.string().optional(),rule:gt.optional()}),Nn=e.strictObject({id:e.string().optional(),kind:e.literal("field"),field:e.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:e.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:e.unknown().optional()}),G=e.lazy(()=>e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all"),id:e.string().optional(),of:e.array(G).min(1)}),e.strictObject({kind:e.literal("any"),id:e.string().optional(),of:e.array(G).min(1)}),e.strictObject({kind:e.literal("not"),id:e.string().optional(),predicate:G}),Qn,Mn,Gn,Nn])),ft=e.strictObject({mode:e.enum(["never","auto","required"]),strategy:e.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:e.boolean().optional(),forceRefresh:e.boolean().optional()}),yt=e.strictObject({content:e.strictObject({range:e.strictObject({startLine:e.number().int().min(1).optional(),endLine:e.number().int().min(1).optional(),contextLines:e.number().int().min(0).max(100).optional()}).optional(),match:e.strictObject({text:e.string(),regex:e.boolean().optional(),caseSensitive:e.boolean().optional()}).optional(),contentView:e.enum(["exact","compact","symbols"]).optional(),charOffset:e.number().int().min(0).max(1e8).optional(),charLength:e.number().int().min(1).max(5e4).optional(),fullContent:e.boolean().optional()}).optional(),tree:e.strictObject({maxDepth:e.number().int().min(0).max(64).optional(),pattern:e.string().optional(),includeSizes:e.boolean().optional(),extensions:e.array(e.string()).optional(),filesOnly:e.boolean().optional(),directoriesOnly:e.boolean().optional(),sortBy:e.enum(["name","size","time","extension"]).optional(),reverse:e.boolean().optional()}).optional()}),bt=e.strictObject({search:e.strictObject({countLinesPerFile:e.boolean().optional(),countMatchesPerFile:e.boolean().optional(),onlyMatching:e.boolean().optional(),unique:e.boolean().optional(),countUnique:e.boolean().optional(),contextLines:e.number().int().min(0).max(100).optional(),invertMatch:e.boolean().optional(),matchWindow:e.number().int().min(0).optional(),matchContentLength:e.number().int().min(1).optional(),maxMatchesPerFile:e.number().int().min(1).optional(),matchPage:e.number().int().min(1).optional(),sort:e.enum(["relevance","matchCount","path","modified","accessed","created"]).optional(),sortReverse:e.boolean().optional(),rankingProfile:e.string().optional(),debugRanking:e.boolean().optional()}).optional(),budget:e.strictObject({maxFiles:e.number().int().min(1).optional(),maxCandidates:e.number().int().min(1).optional(),maxBytes:e.number().int().min(1).optional(),maxMaterializedBytes:e.number().int().min(1).optional(),maxPlanNodes:e.number().int().min(1).optional(),maxBooleanExpansion:e.number().int().min(1).optional(),timeoutMs:e.number().int().min(1).optional()}).optional()}),St=e.enum(["discovery","paginated","detailed"]),xt=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),target:e.enum(C),from:Y.optional(),scope:Dn,where:G.optional(),materialize:ft.optional(),fetch:yt.optional(),select:e.array(e.string()).optional(),view:St.optional(),controls:bt.optional(),limit:e.number().int().min(1).optional(),page:e.number().int().min(1).optional(),itemsPerPage:e.number().int().min(1).optional(),params:e.record(e.string(),e.unknown()).optional(),explain:e.boolean().optional()}),Hn=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),queries:e.array(xt).min(1).max(5),combine:e.enum(["independent","merge"]).optional(),limit:e.number().int().min(1).optional(),page:e.number().int().min(1).optional(),itemsPerPage:e.number().int().min(1).optional(),explain:e.boolean().optional()}),da=e.union([xt,Hn]),jn=C,Bn=[...C,...z],Rt={schema:e.literal("oql").optional(),id:e.string().optional(),mainResearchGoal:e.string().optional(),researchGoal:e.string().optional(),reasoning:e.string().optional()},ee={...Rt,target:e.enum(Bn).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Y.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:G.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:e.union([ft,e.enum(["never","auto","required"])]).optional(),fetch:yt.optional(),select:e.array(e.string()).optional(),view:St.optional(),controls:bt.optional(),limit:e.number().int().min(1).optional(),page:e.number().int().min(1).optional(),itemsPerPage:e.number().int().min(1).optional(),params:e.record(e.string(),e.unknown()).optional(),explain:e.boolean().optional(),repo:e.string().optional(),owner:e.string().optional(),ref:e.string().optional(),path:K.optional(),text:e.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:e.string().optional(),pattern:e.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:gt.optional(),lang:e.string().optional(),and:e.array(e.unknown()).optional(),or:e.array(e.unknown()).optional(),xor:e.array(e.unknown()).optional(),noneOf:e.array(e.unknown()).optional(),oneOf:e.array(e.unknown()).optional(),invert:e.unknown().optional(),filesOnly:e.boolean().optional(),filesWithoutMatch:e.boolean().optional(),verbose:e.boolean().optional()},Ot=e.object({...ee,target:e.enum(jn).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes.")}).catchall(e.unknown()),ha=e.object(ee).catchall(e.unknown()),ga=e.object({...Rt,queries:e.array(e.unknown()).min(1)}).catchall(e.unknown()),wt=e.object({...ee,queries:e.array(e.unknown()).min(1).max(5).optional(),combine:e.enum(["independent","merge"]).optional()}).catchall(e.unknown());var Tt=["GitHub","Local Code","Package","Other"],kt=new Map([p.GITHUB_SEARCH_CODE,p.GITHUB_SEARCH_REPOSITORIES,p.GITHUB_SEARCH_PULL_REQUESTS,p.GITHUB_FETCH_CONTENT,p.GITHUB_VIEW_REPO_STRUCTURE,p.GITHUB_CLONE_REPO,p.LOCAL_RIPGREP,p.LOCAL_FIND_FILES,p.LOCAL_FETCH_CONTENT,p.LOCAL_VIEW_STRUCTURE,P,p.PACKAGE_SEARCH,N].map((n,r)=>[n,r])),w=class extends Error{constructor(o,i=[]){super(o);this.details=i;this.name="DirectToolInputError"}details},zn=["id","mainResearchGoal","researchGoal","reasoning"],ie=new Set([...zn]),Un=["id","researchGoal","reasoning"],Et=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],$n=[{name:p.GITHUB_SEARCH_CODE,schema:Re,inputSchema:Oe},{name:p.GITHUB_FETCH_CONTENT,schema:ye,inputSchema:be},{name:p.GITHUB_VIEW_REPO_STRUCTURE,schema:ve,inputSchema:Fe},{name:p.GITHUB_SEARCH_REPOSITORIES,schema:Ee,inputSchema:_e},{name:p.GITHUB_SEARCH_PULL_REQUESTS,schema:ke,inputSchema:Pe},{name:p.PACKAGE_SEARCH,schema:Qe,inputSchema:Me},{name:p.GITHUB_CLONE_REPO,schema:X,inputSchema:me},{name:p.LOCAL_RIPGREP,schema:We,inputSchema:Ze},{name:p.LOCAL_VIEW_STRUCTURE,schema:Ye,inputSchema:et},{name:p.LOCAL_FIND_FILES,schema:Ue,inputSchema:$e},{name:p.LOCAL_FETCH_CONTENT,schema:He,inputSchema:je},{name:P,schema:at,inputSchema:it},{name:p.LOCAL_BINARY_INSPECT,schema:pt,inputSchema:mt},{name:N,schema:Ot,inputSchema:wt}];function $(n){return $n.find(r=>r.name===n)}function U(n){return n.startsWith("gh")?"GitHub":n.startsWith("local")||n.startsWith("lsp")?"Local Code":n===p.PACKAGE_SEARCH?"Package":"Other"}function Fa(n){return[...n].sort((r,o)=>{let i=Tt.indexOf(U(r)),c=Tt.indexOf(U(o));if(i!==c)return i-c;let u=kt.get(r)??Number.MAX_SAFE_INTEGER,d=kt.get(o)??Number.MAX_SAFE_INTEGER;return u!==d?u-d:r.localeCompare(o)})}function Ia(n){let r=$(n);if(!r)return"{}";try{return JSON.stringify(te.toJSONSchema(r.inputSchema),null,2)}catch{return JSON.stringify(te.toJSONSchema(r.schema),null,2)}}function Da(n){return JSON.stringify(n??{},null,2)}function Qa(n){let r=U(n),o=[...Un];return(r==="GitHub"||r==="Package")&&o.splice(1,0,"mainResearchGoal"),o}function Ma(){return Et.map(n=>({...n}))}function Ga(){return JSON.stringify(Object.fromEntries(Et.map(n=>[n.name,n.optional?`${n.type} (optional)`:n.type])),null,2)}function Na(n,r){return r?.tools?.[n]?.description??n}function _t(n){let r=$(n);if(!r)return[];let o=te.toJSONSchema(r.schema);if(!F(o))return[];let i=k(o.properties)?o.properties:{},c=new Set(Array.isArray(o.required)?o.required.filter(u=>!ie.has(u)&&!ae(i[u])):[]);return oe(i,c)}function Pt(n,r){return`tools ${n} --queries '${JSON.stringify(r)}'`}function Vn(n){let r=Wn(n);if(r.length>0)return r.map(i=>({...i,command:Pt(n,i.query)}));let o=Xn(n);return Object.keys(o).length===0?[]:[{label:"schema-derived",query:o,command:Pt(n,o)}]}function Ha(n){return Vn(n)[0]?.query??{}}function Xn(n){if(!$(n))return{};let r=_t(n),o=r.filter(u=>!u.name.includes(".")),i=rr(o),c={};for(let u of i)c[u.name]=sr(u.name,u.type);return n.startsWith("lsp")&&r.some(u=>u.name==="uri")&&(c.uri??="uri"),n===P&&(c.type??="definition",c.symbolName??="symbolName",c.lineHint??=1),c}function Wn(n){return n===N?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:n===p.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"facebook",repo:"react",keywordsToSearch:["useState"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"facebook",repo:"react",path:"packages/react/src",since:"2024-01-01T00:00:00Z",perPage:5}}]:n===p.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"facebook",repo:"react",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["useState"],owner:"facebook",repo:"react",extension:"js",limit:5}}]:n===p.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"facebook",concise:!0,limit:5}}]:n===p.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"facebook",repo:"react",path:"packages",maxDepth:2,itemsPerPage:50}}]:n===p.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"facebook",repo:"react",sparsePath:"packages/react"}}]:n===p.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:n===p.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"src/index.ts",startLine:1,endLine:40,minify:"none"}},{label:"matched slice",query:{path:"src/index.ts",matchString:"registerTool",contextLines:8,minify:"standard"}}]:n===p.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:".",names:["*.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/**",entryType:"f",itemsPerPage:20}}]:n===p.LOCAL_BINARY_INSPECT?[{label:"archive listing",query:{path:"archive.zip",mode:"list",entriesPerPage:50}},{label:"binary strings",query:{path:"dist/app.node",mode:"strings",minLength:8,charLength:2e3}}]:n===P?[{label:"semantic definition",query:{uri:"/path/to/file.ts",type:"definition",symbolName:"myFunction",lineHint:42}},{label:"symbol outline",query:{uri:"/path/to/file.ts",type:"documentSymbols"}}]:[]}function ja(n,r,o={}){if(typeof r!="string")return null;let i;try{i=JSON.parse(r)}catch{throw new w("Tool input must be valid JSON.")}return Zn(n,i,o)}function Zn(n,r,o={}){let i=Kn(n,r,o),c=$(n);if(!c)throw new w(`Unknown tool: ${n}`);let u=c.inputSchema.safeParse(i);if(!u.success)throw new w("Tool input does not match the expected schema.",Jn(u.error));return u.data}function Jn(n){return n.issues.map(r=>`${r.path.length>0?r.path.join("."):"input"}: ${r.message}`)}function Kn(n,r,o){let i=[];if(Array.isArray(r))i=r;else if(k(r)&&Array.isArray(r.queries))i=r.queries;else if(k(r))i=[r];else throw new w('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(i.length===0)throw new w("At least one query is required.");let c=k(r)&&Array.isArray(r.queries)?Object.fromEntries(Object.entries(r).filter(([R])=>R!=="queries")):{},u=!1,d={...o,onUnknownFields:(R,T)=>{u=!0,o.onUnknownFields?.(R,T)}},S=i.map((R,T)=>Yn(n,T,tr(n,R,T,d),{sourceLabel:o.sourceLabel}));if(u&&o.onUnknownFields!==void 0)throw new w("Tool input contains unknown fields. See warnings above for details.");return{...c,queries:S}}function Yn(n,r,o,i){let c={...o},u=U(n),d=i.sourceLabel??"direct tool execution",S=er(n,d);return(typeof c.id!="string"||c.id.trim().length===0)&&(c.id=`${n}-${r+1}`),(u==="GitHub"||u==="Package")&&(typeof c.mainResearchGoal!="string"||c.mainResearchGoal.trim().length===0)&&(c.mainResearchGoal=S),(typeof c.researchGoal!="string"||c.researchGoal.trim().length===0)&&(c.researchGoal=S),(typeof c.reasoning!="string"||c.reasoning.trim().length===0)&&(c.reasoning=`Executed via ${d} tool command`),c}function er(n,r){return`Execute ${n} via ${r}`}function tr(n,r,o,i={}){if(!k(r))throw new w("Tool input must be a JSON object or an array of objects.");let c=new Set([..._t(n).filter(S=>!S.name.includes(".")).map(S=>S.name),...ie]),u={},d=[];for(let[S,R]of Object.entries(r)){if(c.has(S)){u[S]=R;continue}d.push(S)}return d.length>0&&c.size>0&&i.onUnknownFields?.(d,o),u}function nr(n){let r=[],o=typeof n.minimum=="number"?n.minimum:void 0,i=typeof n.maximum=="number"?n.maximum:void 0;return o!==void 0&&i!==void 0?r.push(`${o}-${i}`):o!==void 0?r.push(`>=${o}`):i!==void 0&&r.push(`<=${i}`),"default"in n&&r.push(`default ${JSON.stringify(n.default)}`),r.length>0?r.join(", "):void 0}function ne(n){if(Array.isArray(n.enum)&&n.enum.length>0)return`enum(${n.enum.map(String).join(", ")})`;if(n.type==="array"){let o=F(n.items)?n.items:void 0;return`array<${o?ne(o):"value"}>`}let r=Array.isArray(n.anyOf)?n.anyOf:Array.isArray(n.oneOf)?n.oneOf:void 0;if(r){let o=r.filter(F).map(ne).filter(i=>i!=="value");if(o.length>0)return[...new Set(o)].join(" | ")}return Array.isArray(n.type)?n.type.join(" | "):typeof n.type=="string"?n.type:"value"}var Lt=4,re=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]]),At=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function rr(n){let r=n.filter(u=>u.required),o=new Map;for(let u of r)o.set(u.name,u);let i=n.filter(u=>!u.required&&or(u)).sort(ar),c=Math.max(Lt,r.length);for(let u of i){if(o.size>=c)break;o.set(u.name,u)}return o.size>0?[...o.values()]:n.filter(u=>!At.has(u.name)).filter(u=>u.type!=="boolean").slice(0,Lt)}function or(n){return At.has(n.name)||n.type==="boolean"?!1:ir(n)?re.has(n.name):!0}function ar(n,r){let o=re.get(n.name)??Number.MAX_SAFE_INTEGER,i=re.get(r.name)??Number.MAX_SAFE_INTEGER;return o!==i?o-i:n.name.localeCompare(r.name)}function ir(n){return n.constraints?.includes("default ")===!0}function oe(n,r,o=""){let i=[];for(let[c,u]of Object.entries(n)){if(!o&&ie.has(c))continue;let d=F(u)?u:{},S=o?`${o}.${c}`:c;if(i.push({name:S,required:r.has(c),type:ne(d),constraints:nr(d),description:typeof d.description=="string"?d.description:void 0}),k(d.properties)){let T=new Set(Array.isArray(d.required)?d.required.filter(I=>typeof I=="string"?!ae(d.properties?.[I]):!1):[]);i.push(...oe(d.properties,T,S))}let R=d.type==="array"&&F(d.items)?d.items:void 0;if(R&&k(R.properties)){let T=new Set(Array.isArray(R.required)?R.required.filter(I=>typeof I=="string"?!ae(R.properties?.[I]):!1):[]);i.push(...oe(R.properties,T,S))}}return i}function sr(n,r){if(r.startsWith("array<")){let o=r.slice(6,-1);return[Ct(n,o)]}return Ct(n,r)}function Ct(n,r){if(r.startsWith("enum("))return/^enum\(([^,)]+)/.exec(r)?.[1]??n;if(r==="integer"||r==="number")return n==="lineHint"?42:5;if(r==="boolean")return!0;switch(n){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"facebook";case"repo":return"react";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"react";default:return n}}function k(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function F(n){return k(n)}function ae(n){return F(n)&&"default"in n}var qt={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"};var vt={schema:"oql",description:"octocode search \u2014 typed read-only queries over code, files, symbols, repos, packages, history, artifacts, diffs, and graph evidence. Think source + answer type + filters + read/output options; use --explain for routing; follow next.* for pages, exact reads, materialization, or proof.",activeTargets:C,reservedTargets:z,sourceGuide:{local:'from:{kind:"local",path:"./src"}; shorthand: search "term" ./src, search ./src --tree, search file.ts --op documentSymbols. Best for local code/content/files/tree/LSP/artifacts/diff.',github:'from:{kind:"github",repo:"owner/repo",ref?}; shorthand: search "term" owner/repo, search owner/repo --tree, search owner/repo#123 --target pullRequests. GitHub code is indexed/default-branch scoped; materialize for AST/LSP/local proof.',npm:'from:{kind:"npm"} with target:"packages"; shorthand: search zod --target packages. Use to resolve package metadata and source repo, then continue with GitHub or local/materialized proof.',materialized:'from:{kind:"materialized",localPath:"/abs/path"} after target:"materialize", clone, or cache fetch. Use when a remote repo/subtree must behave like local code.'},plainLanguage:{source:"`from` = where to look: local path, GitHub repo, npm, or a materialized checkout.",answerType:"`target` = what kind of answer you want: code matches, file content, tree, files, symbols, repos, packages, PRs, commits, artifacts, diffs, research packets, graph proof, or materialization.",filters:"`where` = match/filter conditions for code and file discovery only: text, regex, AST shape, file fields, and boolean combinations.",readOptions:"`fetch` = what to read once you know the file/tree: exact content, compact content, symbol outline, ranges, match slices, or tree depth.",targetOptions:"`params` = options that belong to one answer type, such as LSP operation, PR number, package name, artifact mode, research intent, or graph proof.",output:"`view`, `select`, and `controls` = response shape, projected fields, search tuning, and cost limits.",paging:"`page` + `itemsPerPage` page the target's primary result domain. For code search that may be matched files; per-file match paging uses `controls.search.matchPage` / `--match-page`."},targetDecisionTree:{"find a string/pattern in code":"target:code (shorthand default for text/regex/--pattern/--rule; needs a where filter)","read or slice a known file":"target:content (file positional + --content-view, --start-line/--end-line, or --match-string)","see the file/dir layout":"target:structure (--tree)","find files by name/glob/ext/size/mtime":"target:files (--search path, --name/--ext/--size-greater/--modified-within)","symbol defs/refs/callers/hover":"target:semantics (--op \u2026; local or materialized only)","search GitHub repos":"target:repositories (--stars/--lang/--topic)","resolve an npm package":"target:packages","PR list or deep-read":"target:pullRequests (owner/repo#N)","commit history":"target:commits (--since/--until)","a diff":"target:diff ({prNumber} for a PR patch, {baseRef,headRef,path} for two refs)","inspect a binary/archive":"target:artifacts (--inspect/--list/--strings/--extract)","dead-code / reachability sweep":'target:research, then upgrade with target:graph proof:"lsp"',"make a remote repo behave like local (AST/LSP/negation)":"target:materialize (or clone / cache fetch)"},agentBestPractices:["Start with cheap orientation: --tree, --search path, --view discovery, or --content-view symbols.","Then narrow and read exact evidence: --match-string, --start-line/--end-line, --char-offset/--char-length, or --content-view exact.","Use snippets as discovery only; make decisions from exact content, PR/commit metadata, or LSP/graph proof.","For semantics, run documentSymbols first to get line anchors, then references/callers/hover with symbolName + lineHint.","For GitHub zero rows / providerUnindexed, do NOT claim absence \u2014 follow evidenceSemantics.providerUnindexed (verify path with structure, then materialize a bounded path).","Read evidence.answerReady, evidence.complete, diagnostics, pagination, and next.* before concluding."],quickStart:{"text search (local)":'search "functionName" ./src',"text search (GitHub)":'search "functionName" facebook/react',"package lookup (npm)":"search zod --target packages","PR deep read (GitHub)":"search facebook/react#1 --target pullRequests --comments --patches","commit history (GitHub)":"search facebook/react/packages/react/src --target commits --since 2024-01-01T00:00:00Z","browse a tree (local dir or owner/repo)":"search ./src --tree | search facebook/react --tree","read a file (local or owner/repo/path)":"search ./src/index.ts | search facebook/react/packages/react/src/index.js","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","artifact inspect/list":"search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect","PR diff (GitHub)":"search facebook/react#123 --target diff | search facebook/react --target diff --pr 123","two-ref / two-file diff":"search src/a.ts src/b.ts --target diff | search owner/repo --target diff --base-ref <sha> --head-ref <sha> --path <file>","structural AST (local \u2014 needs full node shape)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" ./src --lang ts',"structural AST (GitHub \u2014 clones bounded subtree)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" facebook/react/packages --lang js --materialize auto',"GitHub index miss recovery":"search useState packages/react/src --repo facebook/react --materialize required | clone facebook/react/packages/react/src | cache fetch facebook/react packages/react/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},query:{schema:'"oql" (inserted by normalization)',target:C.join(" | "),from:'{ kind:"local", path } | { kind:"github", repo?, owner?, ref? } | { kind:"materialized", localPath, source? } | { kind:"npm" } \u2014 local row.path is relative to from.path; the pre-filled next.fetch carries the resolved ABSOLUTE path, so follow it directly rather than re-joining paths yourself',scope:"{ path?, language?, include?, exclude?, excludeDir?, hidden?, noIgnore?, minDepth?, maxDepth? } \u2014 minDepth/maxDepth bound directory recursion depth (0-64)",where:"filters for code/files only: text | regex | structural | field | all | any | not. To read a matched file slice, use fetch.content.match. For PR/commit/artifact text narrowing, use that target params hint.",materialize:'{ mode:"never"|"auto"|"required", strategy?:"file"|"tree"|"subtree"|"repo", allowFullRepo?, forceRefresh? }',fetch:'{ content?: { contentView:"exact"|"compact"|"symbols", fullContent?, match?:{text|regex,case?}, range?:{startLine?,endLine?,contextLines?}, charOffset?, charLength? }, tree?:{ maxDepth?, pattern?, includeSizes?, extensions?, filesOnly?, directoriesOnly?, sortBy?:"name"|"size"|"time"|"extension", reverse? } } \u2014 read options for known files/trees; fetch.content.fullContent:true returns the WHOLE file in one shot (lossless, no char-window paging); to read the region around a string, anchor with fetch.content.match (NOT a top-level where, which is code/files only)',params:"target options (validated by OQL for common fields and by the backing tool exhaustively) \u2014 see params hints below",select:"string[] projection of result/continuation fields",view:"discovery | paginated | detailed",controls:"{ search?: { countLinesPerFile?, countMatchesPerFile?, onlyMatching?, unique?, countUnique?, contextLines?, invertMatch?, matchWindow?, matchContentLength?, maxMatchesPerFile?, matchPage?, sort?, sortReverse?, rankingProfile?, debugRanking? }, budget?: { maxFiles?, maxCandidates?, maxBytes?, maxMaterializedBytes?, maxPlanNodes?, maxBooleanExpansion?, timeoutMs? } } \u2014 output/cost controls",limit:"number \u2014 total result cap where supported. Prefer itemsPerPage for paged research/graph/file-history continuations.",page:"number \u2014 top-level page number for OQL windowing/continuations",itemsPerPage:"number \u2014 page size for the target primary result domain. For code search this may be matched files, not individual matches; per-file match paging uses controls.search.matchPage. Per-target params expose backing-tool sub-pages only (filePage/commentPage/commitPage, entryPageNumber, scanOffset, etc.).",explain:"boolean"},params:{semantics:'{ type:"definition"|"references"|"callers"|"callees"|"callHierarchy"|"hover"|"documentSymbols"|"typeDefinition"|"implementation"|"workspaceSymbol"|"supertypes"|"subtypes"|"diagnostic", uri?, symbolName?, symbolKind?, lineHint?, orderHint?, depth?, contextLines?, includeDeclaration?, groupByFile?, workspaceRoot?, format? } \u2014 backing tool lspGetSemantics; contextLines adds call-flow snippets; symbolKind filters returned symbol rows after documentSymbols/workspaceSymbol',repositories:"{ keywords?: string[], topicsToSearch?: string[], language?, owner?, stars?, license?, sort?, archived?, limit?, page? } \u2014 backing tool ghSearchRepos; keywords/topicsToSearch are arrays even for one term",packages:'{ packageName?: string | keywords?: string[], mode?:"lean"|"full", page? } \u2014 backing tool npmSearch',pullRequests:'{ state?:"open"|"closed"|"merged", author?, label?, keywordsToSearch?, prNumber?, reviewMode?, filePage?, commentPage?, commitPage?, limit?, page?, matchString?, matchScope?:"body"|"title"|"comments"|"reviews"|"all", content? } \u2014 backing tool ghHistoryResearch; matchString filters fetched PR title/body/comments/reviews per matchScope (default body), not a search-index query \u2014 no match \u2192 zeroMatches',commits:'{ path?, branch?, since?, until?, includeDiff?, limit?, page?, filePage?, itemsPerPage?, matchString? } \u2014 backing tool ghHistoryResearch type:"commits"; matchString filters commit messages; repo/directory diffs page changed files per commit with filePage/itemsPerPage',artifacts:'{ mode:"inspect"|"list"|"extract"|"decompress"|"strings"|"unpack", minLength?, entryPageNumber?, scanOffset?, charOffset?, charLength?, matchString? } \u2014 localBinaryInspect. matchString filters text-producing modes (extract/decompress/strings) over the current fetched payload. For large strings dumps, follow next.search on data.localPath for lossless ripgrep paging; next.artifactContent (charOffset) = next inline text window; next.artifactStrings (scanOffset) = next binary scan window. extract/unpack/decompress \u2192 tree at data.localPath (next.structure/next.files).',diff:"{ prNumber, files? } (PR patch via ghHistoryResearch) | { baseRef, headRef, path } (direct two-ref file diff via ghGetFileContent + local line diff); neither shape -> invalidQuery repair",research:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:("symbols"|"files"|"dependencies"|"relations")[], mode?:"plan"|"analyze"|"prove", maxFiles? } \u2014 TWO-PHASE: page:1+itemsPerPage:1 \u2192 data.summary (full-scope counts) and may include a bounded first packet page; page:2+ \u2192 data.packets[] continuation pages (candidates w/ retainedBy edges + per-packet next.*). Always evidence:"candidate"/answerReady:false (normal). Follow the row's pre-filled next.graph (proof:"lsp", proofLimit-bounded) to upgrade a page to LSP-proven proofStatus.`,graph:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:(\u2026)[], mode?:"plan"|"analyze"|"prove", maxFiles?, subject?, subjectKind?, relation?, verdict?, direction?:"incoming"|"outgoing"|"both", proof?:"none"|"lsp", proofLimit?, includePackets?, includeFacts?, includeEdges? } \u2014 UPGRADE PATH: run a research row's pre-filled next.graph directly. proof:"lsp" sets per-row proofStatus: "confirmed-by-lsp" (refs=0 in bounded workspace; still inspect entrypoints/exports before deletion), "conflicting-evidence" (refs>0 \u2192 retained, check retainedBy), "needs-framework-graph" (maybe an entrypoint). answerReady:false is normal \u2014 follow next.* for more pages/proof.`,materialize:'(no params; no `where`) clone/cache a bounded corpus (from:{kind:"github",repo} + scope.path) and return a stable materialized checkpoint row (localPath/repoRoot/ref/cache/complete) with next.structure/next.files. Use after GitHub providerUnindexed; for CLI alternatives use clone owner/repo[/path] or cache fetch owner/repo [path] --depth file|tree|clone.'},predicates:{text:'{ kind:"text", value, case?, wholeWord? }',regex:'{ kind:"regex", value, dialect?:"rust"|"pcre2"|"provider", case?, wholeWord?, multiline?, dotAll? }',structural:'{ kind:"structural", lang, pattern? | rule? } (exactly one; rule is a JSON object or grep-compatible YAML rule string) \u2014 pattern must match the COMPLETE node, so include the parts the real node has: a fn WITH a return type only matches if the pattern has one too (`function $N($$$A): $R { $$$B }`); omitting it returns 0. Shapes: `function $N($$$A) { $$$B }` (no-return-type fn), `($$$A) => $$$B` (arrow, block+expression), `$F($$$A)` (call), `$O.$M($$$A)` (method). For "find symbol X" the ROBUST form is a rule, not a pattern: `{ kind:"function_declaration", has:{ pattern:"X" } }`. 0 matches + no parse error = pattern shape \u2260 real node (add `: $R`, or switch to a rule). Note: $$$-only patterns skip files with no literal anchor \u2192 low counts; add a literal name or use a regex where.',field:'{ kind:"field", field:"path"|"basename"|"extension"|"size"|"modified"|"accessed"|"empty"|"permissions"|"executable"|"readable"|"writable"|"entryType", op:"="|"!="|"in"|"exists"|"glob"|"regex"|">"|">="|"<"|"<="|"within"|"before", value? } (use symbolic ops like "="; aliases such as "eq" are invalid; there is no "contains" op \u2014 use op:"glob", value:"*term*" or op:"regex"; "within"/"before" compare modified/accessed times; empty/executable/readable/writable are boolean file attributes paired with op:"exists" or op:"=")',boolean:'{ kind:"all"|"any", of: Predicate[] } | { kind:"not", predicate }'},batch:{queries:"OqlQuery[] (1-5)",combine:"independent | merge"},explainRoutes:{PUSHDOWN:"Backend evaluates this predicate exactly \u2014 good. No residual work.",RESIDUAL:"Backend narrows candidates but OQL must finish evaluation locally.",ROUTE:"OQL must use a different lane, often materialization.",UNSUPPORTED:"OQL cannot execute this predicate safely on the chosen source."},defaults:qt};function cr(){return JSON.stringify(vt,null,2)}import{completeMetadata as lr}from"@octocodeai/octocode-core";var se=null;function ur(){return se||(se=lr),se}async function pr(){return ur()}export{Tt as DIRECT_TOOL_CATEGORIES,$n as DIRECT_TOOL_DEFINITIONS,w as DirectToolInputError,vt as OQL_SCHEMA_DOC,Vn as buildDirectToolCommandPatterns,Ha as buildDirectToolExampleQuery,$ as findDirectToolDefinition,Pt as formatDirectToolCommandPattern,Da as formatDirectToolMetadataSchemaText,Ga as formatDirectToolOutputSchemaText,Ia as formatDirectToolSchemaText,Jn as formatDirectToolValidationIssues,Qa as getDirectToolAutoFilledFields,U as getDirectToolCategory,Na as getDirectToolDescription,_t as getDirectToolDisplayFields,Ma as getDirectToolOutputFields,pr as loadToolContent,cr as oqlSchemaText,Zn as prepareDirectToolInput,ja as prepareDirectToolInputFromJsonText,Fa as sortDirectToolNames};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
type AnyZodObject = z.ZodObject<z.ZodRawShape>;
|
|
3
3
|
export type QueryShape = Record<string, z.ZodTypeAny>;
|
|
4
|
-
|
|
4
|
+
type QuerySchemaOptions = {
|
|
5
5
|
strict?: boolean;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
omit?: readonly string[];
|
|
7
|
+
};
|
|
8
|
+
export declare function describeQuerySchema<T extends AnyZodObject>(coreSchema: T, overrides?: QueryShape, options?: QuerySchemaOptions): T;
|
|
9
|
+
export declare function createQueryShapeSchema<T extends AnyZodObject>(coreSchema: T, overrides?: QueryShape, options?: QuerySchemaOptions): AnyZodObject;
|
|
10
10
|
export {};
|
package/dist/scheme/fields.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
export declare function clampedInt(min: number, max: number): z.
|
|
2
|
+
export declare function clampedInt(min: number, max: number): z.ZodPreprocess<z.ZodNumber>;
|
|
3
3
|
export type MinifyMode = 'none' | 'standard' | 'symbols';
|
|
4
|
-
export declare const relaxedPageNumberField: z.ZodDefault<z.ZodOptional<z.
|
|
5
|
-
export declare const contextLinesField: z.ZodOptional<z.
|
|
6
|
-
export declare const lineNumberField: z.ZodOptional<z.
|
|
4
|
+
export declare const relaxedPageNumberField: z.ZodDefault<z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>>;
|
|
5
|
+
export declare const contextLinesField: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
|
|
6
|
+
export declare const lineNumberField: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
|
|
7
7
|
export declare function createRelaxedBulkQuerySchema(querySchema: z.ZodTypeAny, options?: {
|
|
8
8
|
maxQueries?: number;
|
|
9
9
|
}): z.ZodObject<{
|
|
10
|
-
responseCharOffset: z.ZodOptional<z.
|
|
11
|
-
responseCharLength: z.ZodOptional<z.
|
|
10
|
+
responseCharOffset: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
|
|
11
|
+
responseCharLength: z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>;
|
|
12
12
|
queries: z.ZodArray<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
|
|
13
13
|
}, z.core.$strip>;
|
package/dist/serverConfig.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderType } from './providers/types.js';
|
|
2
|
-
import { resolveTokenFull } from '
|
|
2
|
+
import { resolveTokenFull } from './shared/index.js';
|
|
3
3
|
import type { ServerConfig, TokenSourceType } from './types/server.js';
|
|
4
4
|
type ResolveTokenFullFn = typeof resolveTokenFull;
|
|
5
5
|
export declare function _setTokenResolvers(resolvers: {
|
|
@@ -12,7 +12,6 @@ export declare function getServerConfig(): ServerConfig;
|
|
|
12
12
|
export declare function getGitHubToken(): Promise<string | null>;
|
|
13
13
|
export declare function isLocalEnabled(): boolean;
|
|
14
14
|
export declare function isCloneEnabled(): boolean;
|
|
15
|
-
export declare function isLoggingEnabled(): boolean;
|
|
16
15
|
export declare function getTokenSource(): Promise<TokenSourceType>;
|
|
17
16
|
export declare function getActiveProvider(): ProviderType;
|
|
18
17
|
export declare function getActiveProviderConfig(): {
|
package/dist/session.d.ts
CHANGED
|
@@ -1,25 +1,3 @@
|
|
|
1
|
-
import { type PersistedSession } from 'octocode-shared';
|
|
2
1
|
import type { RateLimitData } from './types/session.js';
|
|
3
|
-
declare
|
|
4
|
-
|
|
5
|
-
private readonly logEndpoint;
|
|
6
|
-
constructor();
|
|
7
|
-
getSessionId(): string;
|
|
8
|
-
getSession(): PersistedSession;
|
|
9
|
-
logInit(): Promise<void>;
|
|
10
|
-
logToolCall(toolName: string, repos: string[], _mainResearchGoal?: string, _researchGoal?: string, _reasoning?: string): Promise<void>;
|
|
11
|
-
logError(toolName: string, errorCode: string): Promise<void>;
|
|
12
|
-
logRateLimit(data: RateLimitData): Promise<void>;
|
|
13
|
-
logPackageRegistryFailure(registry: string): void;
|
|
14
|
-
private sendLog;
|
|
15
|
-
}
|
|
16
|
-
export declare function initializeSession(): SessionManager;
|
|
17
|
-
export declare function getSessionManager(): SessionManager | null;
|
|
18
|
-
export declare function logSessionInit(): Promise<void>;
|
|
19
|
-
export declare function logToolCall(toolName: string, repos: string[], mainResearchGoal?: string, researchGoal?: string, reasoning?: string): Promise<void>;
|
|
20
|
-
export declare function logPromptCall(promptName: string): Promise<void>;
|
|
21
|
-
export declare function logSessionError(toolName: string, errorCode: string): Promise<void>;
|
|
22
|
-
export declare function logRateLimit(data: RateLimitData): Promise<void>;
|
|
23
|
-
export declare function logPackageRegistryFailure(registry: string): void;
|
|
24
|
-
export declare function resetSessionManager(): void;
|
|
25
|
-
export {};
|
|
2
|
+
export declare function recordRateLimit(data: RateLimitData): void;
|
|
3
|
+
export declare function recordPackageRegistryFailure(registry: string): void;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { RequiredGitHubConfig, RequiredLocalConfig, RequiredToolsConfig, RequiredNetworkConfig, RequiredLspConfig, RequiredOutputConfig, ResolvedConfig } from './types.js';
|
|
2
|
+
export declare const DEFAULT_GITHUB_CONFIG: RequiredGitHubConfig;
|
|
3
|
+
export declare const DEFAULT_LOCAL_CONFIG: RequiredLocalConfig;
|
|
4
|
+
export declare const DEFAULT_TOOLS_CONFIG: RequiredToolsConfig;
|
|
5
|
+
export declare const DEFAULT_NETWORK_CONFIG: RequiredNetworkConfig;
|
|
6
|
+
export declare const DEFAULT_LSP_CONFIG: RequiredLspConfig;
|
|
7
|
+
export declare const DEFAULT_OUTPUT_CONFIG: RequiredOutputConfig;
|
|
8
|
+
export declare const DEFAULT_CONFIG: Omit<ResolvedConfig, 'source' | 'configPath'>;
|
|
9
|
+
export declare const MIN_TIMEOUT = 5000;
|
|
10
|
+
export declare const MAX_TIMEOUT = 300000;
|
|
11
|
+
export declare const MIN_RETRIES = 0;
|
|
12
|
+
export declare const MAX_RETRIES = 10;
|
|
13
|
+
export declare const MIN_OUTPUT_DEFAULT_CHAR_LENGTH = 1000;
|
|
14
|
+
export declare const MAX_OUTPUT_DEFAULT_CHAR_LENGTH = 50000;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type { OctocodeConfig, ResolvedConfig, ValidationResult, LoadConfigResult, GitHubConfigOptions, LocalConfigOptions, ToolsConfigOptions, NetworkConfigOptions, LspConfigOptions, OutputConfigOptions, OutputPaginationConfigOptions, RequiredGitHubConfig, RequiredLocalConfig, RequiredToolsConfig, RequiredNetworkConfig, RequiredLspConfig, RequiredOutputConfig, RequiredOutputPaginationConfig, MinifyMode, } from './types.js';
|
|
2
|
+
export { CONFIG_SCHEMA_VERSION, CONFIG_FILE_NAME } from './types.js';
|
|
3
|
+
export { DEFAULT_CONFIG, DEFAULT_GITHUB_CONFIG, DEFAULT_LOCAL_CONFIG, DEFAULT_TOOLS_CONFIG, DEFAULT_NETWORK_CONFIG, DEFAULT_LSP_CONFIG, DEFAULT_OUTPUT_CONFIG, MIN_TIMEOUT, MAX_TIMEOUT, MIN_RETRIES, MAX_RETRIES, MIN_OUTPUT_DEFAULT_CHAR_LENGTH, MAX_OUTPUT_DEFAULT_CHAR_LENGTH, } from './defaults.js';
|
|
4
|
+
export { CONFIG_FILE_PATH } from './loader.js';
|
|
5
|
+
export { loadConfig, loadConfigSync, configExists, getConfigPath, getOctocodeDir, } from './loader.js';
|
|
6
|
+
export { validateConfig } from './validator.js';
|
|
7
|
+
export { getConfig, getConfigSync, reloadConfig, resolveConfig, resolveConfigSync, invalidateConfigCache, getConfigValue, _resetConfigCache, _getCacheState, } from './resolver.js';
|
|
8
|
+
export { setRuntimeSurface, getRuntimeSurface, _resetRuntimeSurface, type RuntimeSurface, } from './runtimeSurface.js';
|
|
9
|
+
export { OctocodeConfigSchema } from './schemas.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __createRequire } from 'module';
|
|
3
|
+
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
4
|
+
import { dirname as __dirname_fn } from 'path';
|
|
5
|
+
const require = __createRequire(import.meta.url);
|
|
6
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
7
|
+
const __dirname = __dirname_fn(__filename);
|
|
8
|
+
var L=1,fe=".octocoderc";var A={apiUrl:"https://api.github.com"},l={enabled:!1,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},d={enabled:null,enableAdditional:null,disabled:null},C={timeout:3e4,maxRetries:3},v={configPath:void 0},p={format:"yaml",pagination:{defaultCharLength:2e4}},k={version:1,github:A,local:l,tools:d,network:C,lsp:v,output:p},m=5e3,O=3e5,h=0,R=10,T=1e3,_=5e4;import{existsSync as K,readFileSync as ge}from"node:fs";import{existsSync as We,mkdirSync as Xe}from"node:fs";import{join as u}from"node:path";import w from"node:os";import le from"node:path";var x=w.platform()==="win32",I=w.platform()==="darwin",ce=w.platform()==="linux",g=w.homedir();function M(){return x?process.env.APPDATA||le.join(g,"AppData","Roaming"):g}var P=".octocode";function de(e){let n=process.env[e];return n&&n.trim().length>0?n:void 0}function pe(){return x?u(M(),P):I?u(g,P):u(de("XDG_CONFIG_HOME")??u(g,".config"),P)}var a=pe(),F={home:a,config:u(a,".octocoderc"),credentials:u(a,"credentials.json"),key:u(a,".key"),session:u(a,"session.json"),stats:u(a,"stats.json"),tmp:u(a,"tmp"),clone:u(a,"tmp","clone"),tree:u(a,"tmp","tree"),binary:u(a,"tmp","binary"),repos:u(a,"tmp","clone"),unzip:u(a,"tmp","unzip"),cliConfig:u(a,"config.json"),lspConfig:u(a,"lsp-servers.json")};import{z as s}from"zod";var D=s.looseObject({$schema:s.string().optional(),version:s.number().int().optional(),github:s.record(s.string(),s.unknown()).optional(),local:s.record(s.string(),s.unknown()).optional(),tools:s.record(s.string(),s.unknown()).optional(),network:s.record(s.string(),s.unknown()).optional(),lsp:s.record(s.string(),s.unknown()).optional(),output:s.record(s.string(),s.unknown()).optional()});var y=F.config;function Ce(e){let n="",o=0,t=!1,r="";for(;o<e.length;){let i=e[o],f=e[o+1];if(!t&&(i==='"'||i==="'")){t=!0,r=i,n+=i,o++;continue}if(t){if(n+=i,i==="\\"&&o+1<e.length){n+=e[o+1],o+=2;continue}i===r&&(t=!1),o++;continue}if(i==="/"&&f==="/"){for(;o<e.length&&e[o]!==`
|
|
9
|
+
`;)o++;continue}if(i==="/"&&f==="*"){for(o+=2;o<e.length-1;){if(e[o]==="*"&&e[o+1]==="/"){o+=2;break}o++}continue}n+=i,o++}return n=n.replace(/,(\s*[}\]])/g,"$1"),n}function me(e){let n=Ce(e);return JSON.parse(n)}function Oe(){return K(y)}async function he(){return U()}function U(){let e=y;if(!K(e))return{success:!1,error:"Config file does not exist",path:e};try{let n=ge(e,"utf-8");if(!n.trim())return{success:!0,config:{},path:e};let o=me(n),t=D.safeParse(o);return t.success?{success:!0,config:t.data,path:e}:{success:!1,error:`Config file has invalid structure: ${t.error.issues[0]?.message??"unknown error"}`,path:e}}catch(n){return{success:!1,error:`Failed to parse config file: ${n instanceof Error?n.message:"Unknown error"}`,path:e}}}function Re(){return y}function Te(){return F.home}function _e(e,n){if(e==null)return null;if(typeof e!="string")return`${n}: Must be a string`;try{let o=new URL(e);return["http:","https:"].includes(o.protocol)?null:`${n}: Only http/https URLs allowed`}catch{return`${n}: Invalid URL format`}}function H(e,n,o,t){return e==null?null:typeof e!="number"||isNaN(e)?`${n}: Must be a number`:e<o||e>t?`${n}: Must be between ${o} and ${t}`:null}function z(e,n){return e==null?null:typeof e!="boolean"?`${n}: Must be a boolean`:null}function J(e,n){if(e==null)return null;if(!Array.isArray(e))return`${n}: Must be an array`;for(let o=0;o<e.length;o++)if(typeof e[o]!="string")return`${n}[${o}]: Must be a string`;return null}function be(e){let n=[];for(let o=0;o<e.length;o++){let t=e[o];typeof t=="string"&&(t.trim()===""?n.push(`local.allowedPaths[${o}]: empty or whitespace-only path`):!t.startsWith("/")&&!t.startsWith("~")?n.push(`local.allowedPaths[${o}]: must be absolute path or start with ~ (got "${t}")`):t.includes("..")&&n.push(`local.allowedPaths[${o}]: path traversal (..) not allowed (got "${t}")`))}return n}function G(e,n){return e===void 0||e===null?null:J(e,n)}function Q(e,n){return e==null?null:typeof e!="string"?`${n}: Must be a string`:null}function Ee(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("github: Must be an object");return}let t=_e(e.apiUrl,"github.apiUrl");t&&n.push(t)}function Le(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("local: Must be an object");return}let o=e,t=z(o.enabled,"local.enabled");t&&n.push(t);let r=z(o.enableClone,"local.enableClone");r&&n.push(r);let i=J(o.allowedPaths,"local.allowedPaths");if(i)n.push(i);else if(Array.isArray(o.allowedPaths)){let f=be(o.allowedPaths);n.push(...f)}if(o.workspaceRoot!==void 0&&o.workspaceRoot!==null){let f=Q(o.workspaceRoot,"local.workspaceRoot");f?n.push(f):typeof o.workspaceRoot=="string"&&!o.workspaceRoot.startsWith("/")&&!o.workspaceRoot.startsWith("~")?n.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+o.workspaceRoot+'")'):typeof o.workspaceRoot=="string"&&o.workspaceRoot.includes("..")&&n.push('local.workspaceRoot: path traversal (..) not allowed (got "'+o.workspaceRoot+'")')}}function Ae(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("tools: Must be an object");return}let o=e,t=G(o.enabled,"tools.enabled");t&&n.push(t);let r=G(o.enableAdditional,"tools.enableAdditional");r&&n.push(r);let i=G(o.disabled,"tools.disabled");i&&n.push(i)}function ve(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("network: Must be an object");return}let o=e,t=H(o.timeout,"network.timeout",m,O);t&&n.push(t);let r=H(o.maxRetries,"network.maxRetries",h,R);r&&n.push(r)}function we(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("lsp: Must be an object");return}let t=Q(e.configPath,"lsp.configPath");t&&n.push(t)}function xe(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("output: Must be an object");return}let o=e;if(o.format!==void 0&&(typeof o.format!="string"?n.push("output.format: Must be a string"):["yaml","json"].includes(o.format)||n.push("output.format: Must be one of: yaml, json")),o.pagination!==void 0&&o.pagination!==null)if(typeof o.pagination!="object"||Array.isArray(o.pagination))n.push("output.pagination: Must be an object");else{let t=o.pagination,r=H(t.defaultCharLength,"output.pagination.defaultCharLength",T,_);r&&n.push(r)}}function q(e){let n=[],o=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let t=e;t.version!==void 0&&(typeof t.version!="number"||!Number.isInteger(t.version)?n.push("version: Must be an integer"):t.version>1&&o.push(`version: Config version ${t.version} is newer than supported version ${1}`)),Ee(t.github,n),Le(t.local,n),Ae(t.tools,n),ve(t.network,n),we(t.lsp,n),xe(t.output,n);let r=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(t))r.has(i)||o.push(`Unknown configuration key: ${i}`);return{valid:n.length===0,errors:n,warnings:o,config:n.length===0?e:void 0}}var j="__octocodeRuntimeSurface__";function ye(e){globalThis[j]=e}function $(){return globalThis[j]??"mcp"}function Ue(){delete globalThis[j]}function Y(e){if(e==null)return;let n=e.trim().toLowerCase();if(n!==""){if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1}}function B(e){if(e==null)return;let n=e.trim();if(n==="")return;let o=parseInt(n,10);if(!isNaN(o))return o}function N(e){if(e==null)return;let n=e.trim();if(n!=="")return n.split(",").map(o=>o.trim()).filter(o=>o.length>0)}function Z(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||A.apiUrl}}function ee(e){let n=$()==="cli",o=Y(process.env.ENABLE_LOCAL),t=Y(process.env.ENABLE_CLONE),r=N(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n?!0:o??e?.enabled??l.enabled,enableClone:t??e?.enableClone??(n?!0:l.enableClone),allowedPaths:r??e?.allowedPaths??l.allowedPaths,workspaceRoot:i??e?.workspaceRoot??l.workspaceRoot}}function ne(e){let n=N(process.env.TOOLS_TO_RUN),o=N(process.env.ENABLE_TOOLS),t=N(process.env.DISABLE_TOOLS);return{enabled:n??e?.enabled??d.enabled,enableAdditional:o??e?.enableAdditional??d.enableAdditional,disabled:t??e?.disabled??d.disabled}}function oe(e){let n=B(process.env.REQUEST_TIMEOUT),o=B(process.env.MAX_RETRIES),t=n??e?.timeout??C.timeout;t=Math.max(m,Math.min(O,t));let r=o??e?.maxRetries??C.maxRetries;return r=Math.max(h,Math.min(R,r)),{timeout:t,maxRetries:r}}function te(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??v.configPath}}var Ne=new Set(["yaml","json"]);function re(e){let n=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),o=B(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),t=n||e?.format||p.format,r=o??e?.pagination?.defaultCharLength??p.pagination.defaultCharLength,i=Math.max(T,Math.min(_,r));return{format:Ne.has(t)?t:p.format,pagination:{defaultCharLength:i}}}function W(e,n){let o=e!==void 0,t=process.env.GITHUB_API_URL!==void 0||process.env.ENABLE_LOCAL!==void 0||process.env.ENABLE_CLONE!==void 0||process.env.ALLOWED_PATHS!==void 0||process.env.WORKSPACE_ROOT!==void 0||process.env.TOOLS_TO_RUN!==void 0||process.env.ENABLE_TOOLS!==void 0||process.env.DISABLE_TOOLS!==void 0||process.env.REQUEST_TIMEOUT!==void 0||process.env.MAX_RETRIES!==void 0||process.env.OCTOCODE_LSP_CONFIG!==void 0||process.env.OCTOCODE_OUTPUT_FORMAT!==void 0||process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH!==void 0,r;return o&&t?r="mixed":o?r="file":r="defaults",{version:e?.version??k.version,github:Z(e?.github),local:ee(e?.local),tools:ne(e?.tools),network:oe(e?.network),lsp:te(e?.lsp),output:re(e?.output),source:r,configPath:o?n:void 0}}function S(){let e=U();return e.success&&e.config&&q(e.config).valid?W(e.config,e.path):W(void 0)}async function ie(){return S()}var c=null,b=0,Se=6e4;function E(){let e=Date.now();return c&&e-b<Se||(c=S(),b=e),c}async function X(){return E()}async function se(){return V(),X()}function V(){c=null,b=0}function ue(){c=null,b=0}function ae(){return{cached:c!==null,timestamp:b}}function ke(e){let n=E(),o=e.split("."),t=n;for(let r of o){if(t==null||typeof t!="object")return;t=t[r]}return t}export{fe as CONFIG_FILE_NAME,y as CONFIG_FILE_PATH,L as CONFIG_SCHEMA_VERSION,k as DEFAULT_CONFIG,A as DEFAULT_GITHUB_CONFIG,l as DEFAULT_LOCAL_CONFIG,v as DEFAULT_LSP_CONFIG,C as DEFAULT_NETWORK_CONFIG,p as DEFAULT_OUTPUT_CONFIG,d as DEFAULT_TOOLS_CONFIG,_ as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,R as MAX_RETRIES,O as MAX_TIMEOUT,T as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,h as MIN_RETRIES,m as MIN_TIMEOUT,D as OctocodeConfigSchema,ae as _getCacheState,ue as _resetConfigCache,Ue as _resetRuntimeSurface,Oe as configExists,X as getConfig,Re as getConfigPath,E as getConfigSync,ke as getConfigValue,Te as getOctocodeDir,$ as getRuntimeSurface,V as invalidateConfigCache,he as loadConfig,U as loadConfigSync,se as reloadConfig,ie as resolveConfig,S as resolveConfigSync,ye as setRuntimeSurface,q as validateConfig};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { LoadConfigResult } from './types.js';
|
|
2
|
+
export declare const CONFIG_FILE_PATH: string;
|
|
3
|
+
export declare function configExists(): boolean;
|
|
4
|
+
export declare function loadConfig(): Promise<LoadConfigResult>;
|
|
5
|
+
export declare function loadConfigSync(): LoadConfigResult;
|
|
6
|
+
export declare function getConfigPath(): string;
|
|
7
|
+
export declare function getOctocodeDir(): string;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ResolvedConfig } from './types.js';
|
|
2
|
+
export declare function resolveConfigSync(): ResolvedConfig;
|
|
3
|
+
export declare function resolveConfig(): Promise<ResolvedConfig>;
|
|
4
|
+
export declare function getConfigSync(): ResolvedConfig;
|
|
5
|
+
export declare function getConfig(): Promise<ResolvedConfig>;
|
|
6
|
+
export declare function reloadConfig(): Promise<ResolvedConfig>;
|
|
7
|
+
export declare function invalidateConfigCache(): void;
|
|
8
|
+
export declare function _resetConfigCache(): void;
|
|
9
|
+
export declare function _getCacheState(): {
|
|
10
|
+
cached: boolean;
|
|
11
|
+
timestamp: number;
|
|
12
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { OctocodeConfig, RequiredGitHubConfig, RequiredLocalConfig, RequiredToolsConfig, RequiredNetworkConfig, RequiredLspConfig, RequiredOutputConfig } from './types.js';
|
|
2
|
+
export declare function parseBooleanEnv(value: string | undefined): boolean | undefined;
|
|
3
|
+
export declare function parseIntEnv(value: string | undefined): number | undefined;
|
|
4
|
+
export declare function parseStringArrayEnv(value: string | undefined): string[] | undefined;
|
|
5
|
+
export declare function resolveGitHub(fileConfig?: OctocodeConfig['github']): RequiredGitHubConfig;
|
|
6
|
+
export declare function resolveLocal(fileConfig?: OctocodeConfig['local']): RequiredLocalConfig;
|
|
7
|
+
export declare function resolveTools(fileConfig?: OctocodeConfig['tools']): RequiredToolsConfig;
|
|
8
|
+
export declare function resolveNetwork(fileConfig?: OctocodeConfig['network']): RequiredNetworkConfig;
|
|
9
|
+
export declare function resolveLsp(fileConfig?: OctocodeConfig['lsp']): RequiredLspConfig;
|
|
10
|
+
export declare function resolveOutput(fileConfig?: OctocodeConfig['output']): RequiredOutputConfig;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which interface is driving the shared tool core right now.
|
|
3
|
+
*
|
|
4
|
+
* Some config defaults differ by surface (see `resolveLocal`):
|
|
5
|
+
* - `cli`: `ENABLE_LOCAL` is IGNORED — local tools are always enabled (the CLI
|
|
6
|
+
* is a local-first interface); clone defaults to ENABLED.
|
|
7
|
+
* - `mcp`: `ENABLE_LOCAL` is honored and defaults to DISABLED; clone defaults
|
|
8
|
+
* to DISABLED.
|
|
9
|
+
*
|
|
10
|
+
* Defaults to `mcp`, the primary consumer. The CLI binary calls
|
|
11
|
+
* `setRuntimeSurface('cli')` at startup before any tool runs.
|
|
12
|
+
*
|
|
13
|
+
* State lives on `globalThis` (not a module-level variable) so a single shared
|
|
14
|
+
* value is seen even when bundlers (esbuild) inline this module more than once
|
|
15
|
+
* across different package subpath entry points (`/config`, `/direct`, …).
|
|
16
|
+
*/
|
|
17
|
+
export type RuntimeSurface = 'cli' | 'mcp';
|
|
18
|
+
export declare function setRuntimeSurface(surface: RuntimeSurface): void;
|
|
19
|
+
export declare function getRuntimeSurface(): RuntimeSurface;
|
|
20
|
+
/** Test helper: restore the default surface. */
|
|
21
|
+
export declare function _resetRuntimeSurface(): void;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const OctocodeConfigSchema: z.ZodObject<{
|
|
3
|
+
$schema: z.ZodOptional<z.ZodString>;
|
|
4
|
+
version: z.ZodOptional<z.ZodNumber>;
|
|
5
|
+
github: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
6
|
+
local: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
7
|
+
tools: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
8
|
+
network: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
9
|
+
lsp: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
10
|
+
output: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
11
|
+
}, z.core.$loose>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
export declare const CONFIG_SCHEMA_VERSION = 1;
|
|
2
|
+
export declare const CONFIG_FILE_NAME = ".octocoderc";
|
|
3
|
+
export interface GitHubConfigOptions {
|
|
4
|
+
apiUrl?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface LocalConfigOptions {
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
enableClone?: boolean;
|
|
9
|
+
allowedPaths?: string[];
|
|
10
|
+
workspaceRoot?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ToolsConfigOptions {
|
|
13
|
+
enabled?: string[] | null;
|
|
14
|
+
enableAdditional?: string[] | null;
|
|
15
|
+
disabled?: string[] | null;
|
|
16
|
+
}
|
|
17
|
+
export interface NetworkConfigOptions {
|
|
18
|
+
timeout?: number;
|
|
19
|
+
maxRetries?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface LspConfigOptions {
|
|
22
|
+
configPath?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface OutputPaginationConfigOptions {
|
|
25
|
+
defaultCharLength?: number;
|
|
26
|
+
}
|
|
27
|
+
export type MinifyMode = 'none' | 'standard' | 'symbols';
|
|
28
|
+
export interface OutputConfigOptions {
|
|
29
|
+
format?: 'yaml' | 'json';
|
|
30
|
+
pagination?: OutputPaginationConfigOptions;
|
|
31
|
+
}
|
|
32
|
+
export interface OctocodeConfig {
|
|
33
|
+
$schema?: string;
|
|
34
|
+
version?: number;
|
|
35
|
+
github?: GitHubConfigOptions;
|
|
36
|
+
local?: LocalConfigOptions;
|
|
37
|
+
tools?: ToolsConfigOptions;
|
|
38
|
+
network?: NetworkConfigOptions;
|
|
39
|
+
lsp?: LspConfigOptions;
|
|
40
|
+
output?: OutputConfigOptions;
|
|
41
|
+
}
|
|
42
|
+
export interface RequiredGitHubConfig {
|
|
43
|
+
apiUrl: string;
|
|
44
|
+
}
|
|
45
|
+
export interface RequiredLocalConfig {
|
|
46
|
+
enabled: boolean;
|
|
47
|
+
enableClone: boolean;
|
|
48
|
+
allowedPaths: string[];
|
|
49
|
+
workspaceRoot: string | undefined;
|
|
50
|
+
}
|
|
51
|
+
export interface RequiredToolsConfig {
|
|
52
|
+
enabled: string[] | null;
|
|
53
|
+
enableAdditional: string[] | null;
|
|
54
|
+
disabled: string[] | null;
|
|
55
|
+
}
|
|
56
|
+
export interface RequiredNetworkConfig {
|
|
57
|
+
timeout: number;
|
|
58
|
+
maxRetries: number;
|
|
59
|
+
}
|
|
60
|
+
export interface RequiredLspConfig {
|
|
61
|
+
configPath: string | undefined;
|
|
62
|
+
}
|
|
63
|
+
export interface RequiredOutputPaginationConfig {
|
|
64
|
+
defaultCharLength: number;
|
|
65
|
+
}
|
|
66
|
+
export interface RequiredOutputConfig {
|
|
67
|
+
format: 'yaml' | 'json';
|
|
68
|
+
pagination: RequiredOutputPaginationConfig;
|
|
69
|
+
}
|
|
70
|
+
export interface ResolvedConfig {
|
|
71
|
+
version: number;
|
|
72
|
+
github: RequiredGitHubConfig;
|
|
73
|
+
local: RequiredLocalConfig;
|
|
74
|
+
tools: RequiredToolsConfig;
|
|
75
|
+
network: RequiredNetworkConfig;
|
|
76
|
+
lsp: RequiredLspConfig;
|
|
77
|
+
output: RequiredOutputConfig;
|
|
78
|
+
source: 'file' | 'defaults' | 'mixed';
|
|
79
|
+
configPath?: string;
|
|
80
|
+
}
|
|
81
|
+
export interface ValidationResult {
|
|
82
|
+
valid: boolean;
|
|
83
|
+
errors: string[];
|
|
84
|
+
warnings: string[];
|
|
85
|
+
config?: OctocodeConfig;
|
|
86
|
+
}
|
|
87
|
+
export interface LoadConfigResult {
|
|
88
|
+
success: boolean;
|
|
89
|
+
config?: OctocodeConfig;
|
|
90
|
+
error?: string;
|
|
91
|
+
path: string;
|
|
92
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { StoredCredentials } from './types.js';
|
|
2
|
+
export declare function invalidateCredentialsCache(hostname?: string): void;
|
|
3
|
+
export declare function _getCacheStats(): {
|
|
4
|
+
size: number;
|
|
5
|
+
entries: Array<{
|
|
6
|
+
hostname: string;
|
|
7
|
+
age: number;
|
|
8
|
+
valid: boolean;
|
|
9
|
+
}>;
|
|
10
|
+
};
|
|
11
|
+
export declare function _resetCredentialsCache(): void;
|
|
12
|
+
export declare function getCachedCredentials(hostname: string): StoredCredentials | null | undefined;
|
|
13
|
+
export declare function setCachedCredentials(hostname: string, credentials: StoredCredentials | null): void;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CredentialsStore } from './types.js';
|
|
2
|
+
export declare const OCTOCODE_DIR: string;
|
|
3
|
+
export declare const CREDENTIALS_FILE: string;
|
|
4
|
+
export declare const KEY_FILE: string;
|
|
5
|
+
export declare function ensureOctocodeDir(): void;
|
|
6
|
+
export declare function encrypt(data: string): string;
|
|
7
|
+
export declare function decrypt(encryptedData: string): string;
|
|
8
|
+
export declare function readCredentialsStore(): CredentialsStore;
|
|
9
|
+
export declare function writeCredentialsStore(store: CredentialsStore): void;
|
|
10
|
+
export declare function cleanupKeyFile(): void;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { StoredCredentials } from './types.js';
|
|
2
|
+
export declare function normalizeHostname(hostname: string): string;
|
|
3
|
+
export declare function isTokenExpired(credentials: StoredCredentials): boolean;
|
|
4
|
+
export declare function isRefreshTokenExpired(credentials: StoredCredentials): boolean;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { TokenSource } from './types.js';
|
|
2
|
+
export declare const ENV_TOKEN_VARS: readonly ["OCTOCODE_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
|
3
|
+
export declare function getTokenFromEnv(): string | null;
|
|
4
|
+
export declare function getEnvTokenSource(): TokenSource;
|
|
5
|
+
export declare function hasEnvToken(): boolean;
|
|
6
|
+
export declare function resolveEnvToken(): {
|
|
7
|
+
token: string;
|
|
8
|
+
source: NonNullable<TokenSource>;
|
|
9
|
+
} | null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getGhCliToken(hostname?: string): Promise<string | null>;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export type { OAuthToken, StoredCredentials, StoreResult, DeleteResult, CredentialsStore, TokenSource, } from './types.js';
|
|
2
|
+
export { storeCredentials, getCredentials, type GetCredentialsOptions, getCredentialsSync, deleteCredentials, updateToken, invalidateCredentialsCache, getToken, getTokenSync, resolveToken, type ResolvedToken, getTokenWithRefresh, type TokenWithRefreshResult, resolveTokenWithRefresh, type ResolvedTokenWithRefresh, refreshAuthToken, type RefreshResult, resolveTokenFull, type FullTokenResolution, type GhCliTokenGetter, resetTokenResolution, listStoredHosts, listStoredHostsSync, hasCredentials, hasCredentialsSync, isTokenExpired, isRefreshTokenExpired, getCredentialsFilePath, readCredentialsStore, encrypt, decrypt, ensureOctocodeDir, OCTOCODE_DIR, CREDENTIALS_FILE, KEY_FILE, ENV_TOKEN_VARS, getTokenFromEnv, getEnvTokenSource, hasEnvToken, } from './storage.js';
|
|
3
|
+
export { getGhCliToken } from './ghCli.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __createRequire } from 'module';
|
|
3
|
+
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
4
|
+
import { dirname as __dirname_fn } from 'path';
|
|
5
|
+
const require = __createRequire(import.meta.url);
|
|
6
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
7
|
+
const __dirname = __dirname_fn(__filename);
|
|
8
|
+
function l(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 E(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var R=new Map,fe=300*1e3;function pe(e){let t=l(e),r=R.get(t);return!r||Date.now()-r.cachedAt>=fe?!1:r.credentials?!f(r.credentials):!0}function A(e){e?R.delete(l(e)):R.clear()}function K(e){let t=l(e);if(pe(t))return R.get(t).credentials}function U(e,t){let r=l(e);R.set(r,{credentials:t,cachedAt:Date.now()})}import{existsSync as D,readFileSync as Y,writeFileSync as q,unlinkSync as $,statSync as Re,chmodSync as Se}from"node:fs";import{createCipheriv as ve,createDecipheriv as Ee,randomBytes as J}from"node:crypto";import{existsSync as me,mkdirSync as ge}from"node:fs";import{join as a}from"node:path";import O from"node:os";import de from"node:path";var b=O.platform()==="win32",P=O.platform()==="darwin",he=O.platform()==="linux",k=O.homedir();function H(){return b?process.env.APPDATA||de.join(k,"AppData","Roaming"):k}var F=".octocode",ke=448;function Te(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function Ce(){return b?a(H(),F):P?a(k,F):a(Te("XDG_CONFIG_HOME")??a(k,".config"),F)}var c=Ce(),T={home:c,config:a(c,".octocoderc"),credentials:a(c,"credentials.json"),key:a(c,".key"),session:a(c,"session.json"),stats:a(c,"stats.json"),tmp:a(c,"tmp"),clone:a(c,"tmp","clone"),tree:a(c,"tmp","tree"),binary:a(c,"tmp","binary"),repos:a(c,"tmp","clone"),unzip:a(c,"tmp","unzip"),cliConfig:a(c,"config.json"),lspConfig:a(c,"lsp-servers.json")};function B(){me(T.home)||ge(T.home,{recursive:!0,mode:ke})}import{z as i}from"zod";var xe=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()}),ye=i.object({hostname:i.string(),username:i.string(),token:xe,gitProtocol:i.enum(["ssh","https"]),createdAt:i.string(),updatedAt:i.string()}),V=i.object({version:i.number(),credentials:i.record(i.string(),ye)});var Z=T.home,p=T.credentials,u=T.key,X="aes-256-gcm",Ae=16;function S(){B()}function Q(){if(S(),D(u))return Re(u).mode&511&63&&Se(u,384),Buffer.from(Y(u,"utf8"),"hex");let e=J(32);return q(u,e.toString("hex"),{mode:384}),e}function G(e){let t=Q(),r=J(Ae),n=ve(X,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 N(e){let t=Q(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error("Invalid encrypted data format");let s=Buffer.from(r,"hex"),g=Buffer.from(n,"hex"),m=Ee(X,t,s);m.setAuthTag(g);let y=m.update(o,"hex","utf8");return y+=m.final("utf8"),y}function d(){if(S(),!D(p))return{version:1,credentials:{}};try{let e=Y(p,"utf8"),t=N(e),r=JSON.parse(t),n=V.safeParse(r);return n.success?n.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function I(e){S();let t=G(JSON.stringify(e,null,2));q(p,t,{mode:384})}function ee(){try{D(p)&&$(p),D(u)&&$(u)}catch{}}import{refreshToken as Oe}from"@octokit/oauth-methods";import{request as be}from"@octokit/request";var C="178c6fc778ccc68e1d6a",h="github.com";function De(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 we(e){return e==="github.com"||e===h?"https://api.github.com":`https://${e}/api/v3`}async function L(e,t=h,r=C){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(E(n))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await Oe({clientType:"github-app",clientId:r,clientSecret:"",refreshToken:n.token.refreshToken,request:be.defaults({baseUrl:we(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?De(o.message):"Token refresh failed"}}}async function te(e,t=h,r=C){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 L(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"}}var v=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN"];function W(){for(let e of v){let t=process.env[e];if(t&&t.trim())return t.trim()}return null}function re(){for(let e of v){let t=process.env[e];if(t&&t.trim())return`env:${e}`}return null}function ne(){return W()!==null}function oe(){for(let e of v){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}import{execFile as _e}from"child_process";var Pe=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function j(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=Pe.filter(m=>!o.has(m)),g=s.length?`${s.join(":")}:${n}`:n;_e("gh",r,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:g}},(m,y)=>{if(m||!y){t(null);return}t(y.trim()||null)})})}var w=null;function se(e){w=e}function ie(){w=null}function He(){if(!w)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return w}async function _(e){let t=e?.hostname??h,r=e?.clientId??C,n=e?.getGhCliToken??j,o=oe();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let s=await He().getTokenWithRefresh(t,r);if(s.token)return{token:s.token,source:"octocode-storage",wasRefreshed:s.source==="refreshed",username:s.username};try{let g=await Promise.resolve(n(t));if(g?.trim())return{token:g.trim(),source:"gh-cli",wasRefreshed:!1}}catch{}return null}async function ae(e=h){let t=await _({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function ce(e=h,t=C){let r=await _({hostname:e,clientId:t,getGhCliToken:()=>null});return r?{token:r.token,source:r.source,wasRefreshed:r.wasRefreshed,username:r.username}:null}async function le(e){let t=l(e.hostname),r={...e,hostname:t,updatedAt:new Date().toISOString()};try{let n=d();return n.credentials[t]=r,I(n),A(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function x(e="github.com",t){let r=l(e);if(!t?.bypassCache){let s=K(r);if(s!==void 0)return s}let o=d().credentials[r]||null;return U(r,o),o}function M(e="github.com"){let t=l(e);return d().credentials[t]||null}async function Fe(e="github.com"){let t=l(e),r=!1,n=d();return n.credentials[t]&&(delete n.credentials[t],Object.keys(n.credentials).length===0?ee():I(n),r=!0),A(t),{success:r,deletedFromFile:r}}async function Ge(){let e=d();return Object.keys(e.credentials)}function Ne(){let e=d();return Object.keys(e.credentials)}async function Ie(e="github.com"){return await x(e)!==null}function Le(e="github.com"){return M(e)!==null}async function z(e,t){let r=await x(e);return r?(r.token=t,r.updatedAt=new Date().toISOString(),await le(r),!0):!1}function We(){return p}async function je(e="github.com"){let t=await x(e);return!t||!t.token||f(t)?null:t.token.token}function Me(e="github.com"){let t=M(e);return!t||!t.token||f(t)?null:t.token.token}async function ze(e,t){return L({getCredentials:x,updateToken:z},e,t)}async function ue(e,t){return te({getCredentials:x,updateToken:z},e,t)}se({getTokenWithRefresh:ue});export{p as CREDENTIALS_FILE,v as ENV_TOKEN_VARS,u as KEY_FILE,Z as OCTOCODE_DIR,N as decrypt,Fe as deleteCredentials,G as encrypt,S as ensureOctocodeDir,x as getCredentials,We as getCredentialsFilePath,M as getCredentialsSync,re as getEnvTokenSource,j as getGhCliToken,je as getToken,W as getTokenFromEnv,Me as getTokenSync,ue as getTokenWithRefresh,Ie as hasCredentials,Le as hasCredentialsSync,ne as hasEnvToken,A as invalidateCredentialsCache,E as isRefreshTokenExpired,f as isTokenExpired,Ge as listStoredHosts,Ne as listStoredHostsSync,d as readCredentialsStore,ze as refreshAuthToken,ie as resetTokenResolution,ae as resolveToken,_ as resolveTokenFull,ce as resolveTokenWithRefresh,le as storeCredentials,z as updateToken};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const CredentialsStoreSchema: z.ZodObject<{
|
|
3
|
+
version: z.ZodNumber;
|
|
4
|
+
credentials: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
5
|
+
hostname: z.ZodString;
|
|
6
|
+
username: z.ZodString;
|
|
7
|
+
token: z.ZodObject<{
|
|
8
|
+
token: z.ZodString;
|
|
9
|
+
tokenType: z.ZodLiteral<"oauth">;
|
|
10
|
+
scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
11
|
+
refreshToken: z.ZodOptional<z.ZodString>;
|
|
12
|
+
expiresAt: z.ZodOptional<z.ZodString>;
|
|
13
|
+
refreshTokenExpiresAt: z.ZodOptional<z.ZodString>;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
gitProtocol: z.ZodEnum<{
|
|
16
|
+
ssh: "ssh";
|
|
17
|
+
https: "https";
|
|
18
|
+
}>;
|
|
19
|
+
createdAt: z.ZodString;
|
|
20
|
+
updatedAt: z.ZodString;
|
|
21
|
+
}, z.core.$strip>>;
|
|
22
|
+
}, z.core.$strip>;
|