@octocodeai/octocode-tools-core 16.6.2 → 16.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -9
- package/dist/direct.js +37 -34
- package/dist/github/pullRequestSearch.d.ts +1 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.js +39 -43
- package/dist/oql/adapters/graphProof.d.ts +6 -0
- package/dist/oql/adapters/graphView.d.ts +28 -0
- package/dist/oql/adapters/resultMap.d.ts +7 -0
- package/dist/oql/adapters/runner.d.ts +7 -0
- package/dist/oql/index.js +37 -34
- package/dist/oql/schema.d.ts +24 -8
- package/dist/oql/schemeText.d.ts +12 -11
- package/dist/oql/transformers/github/common.d.ts +7 -1
- package/dist/oql/types.d.ts +12 -2
- package/dist/responses.d.ts +4 -35
- package/dist/schema.js +2 -2
- package/dist/scheme/pagination.d.ts +51 -0
- package/dist/scheme/responseEnvelope.d.ts +67 -1
- package/dist/shared/config/index.d.ts +1 -8
- package/dist/shared/config/index.js +1 -2
- package/dist/shared/credentials/index.d.ts +1 -1
- package/dist/shared/credentials/index.js +2 -1
- package/dist/shared/credentials/storage.d.ts +0 -2
- package/dist/shared/credentials/testing.js +1 -1
- package/dist/shared/paths.d.ts +4 -0
- package/dist/shared/paths.js +1 -1
- package/dist/shared/session/index.js +1 -1
- package/dist/tools/directToolCatalog.exec.d.ts +5 -0
- package/dist/tools/github_clone_repo/scheme.d.ts +0 -1
- package/dist/tools/github_fetch_content/scheme.d.ts +6 -7
- package/dist/tools/github_search_code/scheme.d.ts +4 -6
- package/dist/tools/github_search_pull_requests/scheme.d.ts +0 -1
- package/dist/tools/github_search_repos/execution.d.ts +58 -0
- package/dist/tools/github_search_repos/scheme.d.ts +3 -6
- package/dist/tools/github_view_repo_structure/scheme.d.ts +0 -1
- package/dist/tools/local_binary_inspect/scheme.d.ts +97 -0
- package/dist/tools/local_fetch_content/scheme.d.ts +66 -0
- package/dist/tools/local_find_files/scheme.d.ts +49 -0
- package/dist/tools/local_ripgrep/scheme.d.ts +75 -0
- package/dist/tools/local_view_structure/scheme.d.ts +52 -0
- package/dist/tools/lsp/semantic_content/scheme.d.ts +8 -8
- package/dist/tools/lsp/shared/readiness.d.ts +17 -0
- package/dist/tools/package_search/scheme.d.ts +2 -4
- package/dist/tools/toolNames.d.ts +1 -0
- package/dist/utils/response/bulk.d.ts +1 -0
- package/dist/utils/response/groupedFinalizer.d.ts +7 -2
- package/package.json +4 -3
- package/dist/oql/adapters/v2.d.ts +0 -32
- package/dist/oql/v2params.d.ts +0 -22
- package/dist/shared/config/defaults.d.ts +0 -14
- package/dist/shared/config/loader.d.ts +0 -7
- package/dist/shared/config/resolver.d.ts +0 -2
- package/dist/shared/config/resolverCache.d.ts +0 -12
- package/dist/shared/config/resolverSections.d.ts +0 -10
- package/dist/shared/config/runtimeSurface.d.ts +0 -22
- package/dist/shared/config/types.d.ts +0 -92
- package/dist/shared/config/validator.d.ts +0 -2
- package/dist/shared/credentials/envTokens.d.ts +0 -9
package/dist/schema.js
CHANGED
|
@@ -5,5 +5,5 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
import{z as te}from"zod";import{completeMetadata as It}from"@octocodeai/octocode-core";var m=It.toolNames,T=m.LSP_GET_SEMANTIC_CONTENT,N="oqlSearch",Sr=new Set([m.LOCAL_RIPGREP,m.LOCAL_FETCH_CONTENT,m.LOCAL_FIND_FILES,m.LOCAL_VIEW_STRUCTURE,m.LOCAL_BINARY_INSPECT,T]);var ce=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];import{CloneRepoQuerySchema as Ht}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as jt}from"@octocodeai/octocode-core/schemas/outputs";import{z as H}from"zod";function p(t,r){return H.preprocess(o=>typeof o=="number"&&Number.isFinite(o)?Math.min(Math.max(o,t),r):o,H.number().int().min(t).max(r))}var y=p(1,1e3).optional().default(1),C=p(0,100).optional(),E=p(1,1e9).optional(),Qt={responseCharOffset:p(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:p(1,5e4).optional().describe("Full-response char window.")};function f(t,r={}){let{maxQueries:o=5}=r;return H.object({queries:H.array(t).min(1).max(o).describe("Parallel queries."),...Qt}).superRefine((i,c)=>{let s=new Set;i.queries.forEach((u,g)=>{u&&typeof u=="object"&&"id"in u&&typeof u.id=="string"&&(s.has(u.id)&&c.addIssue({code:"custom",message:`Duplicate query id "${u.id}" at index ${g}`,path:["queries",g,"id"]}),s.add(u.id))})})}import{z as le}from"zod";function Gt(t,r){return t?.description&&!r.description?r.describe(t.description):r}function ue(t,r){let o={};for(let[i,c]of Object.entries(r))o[i]=Gt(t.shape[i],c);return o}function Mt(t,r){let o=t;return o.safeExtend?o.safeExtend(r):t.extend(r)}function pe(t,r){if(!r?.length)return t;let o=new Set(r);return le.object(Object.fromEntries(Object.entries(t.shape).filter(([i])=>!o.has(i))))}function b(t,r={},o={}){let i=pe(t,o.omit),c=Mt(i,ue(i,r));return o.strict?c.strict():c}function S(t,r={},o={}){let i=pe(t,o.omit),c=le.object({...i.shape,...ue(i,r)});return o.strict?c.strict():c}import{z as x}from"zod";var Nt=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(),R={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:Nt};var W=b(Ht),me=f(W),Dr=jt.extend(R);import{z as a}from"zod";import{FileContentQuerySchema as de}from"@octocodeai/octocode-core/schemas";var Bt=a.enum(["none","standard","symbols"]).optional().default("standard"),zt=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()}),Ut=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:zt.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()}),$t=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()}),he={startLine:E,endLine:E,contextLines:C,charOffset:p(0,1e8).optional(),charLength:p(1,5e4).optional(),minify:Bt},Vt=S(de,he),ge=b(de,he),fe=f(Vt),zr=a.object({base:a.string().optional(),shared:a.record(a.string(),a.union([a.string(),a.number(),a.boolean()])).optional(),responsePagination:R.responsePagination,results:a.array(a.object({id:a.string(),data:a.object({owner:a.string(),repo:a.string(),files:a.array(Ut).optional(),directories:a.array($t).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 l}from"zod";import{GitHubCodeSearchQuerySchema as ye}from"@octocodeai/octocode-core/schemas";var be={limit:p(1,100).optional(),page:y.default(1)},Se=b(ye,be),xe=f(S(ye,be)),Kr=l.object({base:l.string().optional(),shared:l.record(l.string(),l.union([l.string(),l.number(),l.boolean()])).optional(),responsePagination:R.responsePagination,results:l.array(l.object({id:l.string(),data:l.object({files:l.array(l.object({owner:l.string(),repo:l.string(),path:l.string(),queryId:l.string().optional(),matches:l.array(l.object({value:l.string().optional(),pathOnly:l.boolean().optional(),matchIndices:l.array(l.object({start:l.number(),end:l.number(),lineOffset:l.number()})).optional(),url:l.string().optional()}))})),pagination:l.object({currentPage:l.number(),totalPages:l.number(),perPage:l.number(),totalMatches:l.number(),reportedTotalMatches:l.number().optional(),reachableTotalMatches:l.number().optional(),totalMatchesKind:l.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:l.boolean().optional(),hasMore:l.boolean(),nextPage:l.number().optional(),uniqueFileCount:l.number().optional()}).optional()})})),emptyQueries:l.array(l.object({id:l.string(),nonExistentScope:l.literal(!0).optional(),incompleteResults:l.literal(!0).optional()})).optional(),warnings:l.array(l.string()).optional(),errors:l.array(l.object({id:l.string(),error:l.string()})).optional()});import{z as P}from"zod";import{GitHubPullRequestSearchQuerySchema as Re}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Jt}from"@octocodeai/octocode-core/schemas/outputs";var Oe={perPage:p(1,100).optional().default(30),prNumber:p(1,1e9).optional(),limit:p(1,100).optional().default(30),page:y.default(1),filePage:y.optional(),commentPage:y.optional(),commitPage:y.optional(),itemsPerPage:p(1,100).optional().default(20),charOffset:p(0,1e8).optional(),commentBodyOffset:p(0,1e8).optional(),charLength:p(1,5e4).optional()},Kt=S(Re,Oe),we=b(Re,Oe),ke=f(Kt),so=Jt.extend({results:P.array(P.object({id:P.string().optional(),status:P.string().optional(),data:P.object({pull_requests:P.array(P.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...R});import{z as d}from"zod";import{GitHubReposSearchSingleQuerySchema as Te}from"@octocodeai/octocode-core/schemas";var Pe={limit:p(1,100).optional(),page:y.default(1)},Le=b(Te,Pe),Ce=f(S(Te,Pe)),Yt=d.object({owner:d.string(),repo:d.string(),stars:d.number().optional(),forks:d.number().optional(),openIssuesCount:d.number().optional(),language:d.string().optional(),license:d.string().optional(),description:d.string().optional(),homepage:d.string().optional(),pushedAt:d.string().optional(),createdAt:d.string().optional(),defaultBranch:d.string().optional(),topics:d.array(d.string()).optional(),visibility:d.string().optional(),url:d.string().optional(),updatedAt:d.string().optional()}),en=d.object({currentPage:d.number(),totalPages:d.number(),hasMore:d.boolean(),perPage:d.number().optional(),totalMatches:d.number().optional(),reportedTotalMatches:d.number().optional(),reachableTotalMatches:d.number().optional(),totalMatchesKind:d.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:d.boolean().optional(),nextPage:d.number().optional()}).optional(),tn=d.object({repositories:d.array(d.union([d.string(),Yt])).optional(),pagination:en}).passthrough(),fo=d.object({results:d.array(d.object({id:d.string().optional(),status:d.string().optional(),data:tn.optional()}).passthrough()).optional()}).extend(R);import{GitHubViewRepoStructureQuerySchema as Ee}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as rn}from"@octocodeai/octocode-core/schemas/outputs";var _e={maxDepth:p(0,20).optional(),page:y.default(1),itemsPerPage:p(1,200).optional()},qe=b(Ee,_e),Ae=f(S(Ee,_e)),To=rn.extend(R);import{z as h}from"zod";import{NpmPackageQuerySchema as ve}from"@octocodeai/octocode-core/schemas";var Fe={page:y,mode:h.enum(["lean","full"]).optional()},Ie=b(ve,Fe),De=f(S(ve,Fe,{strict:!0}),{maxQueries:5}),Ao=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(),repositoryId:h.string().optional(),next:h.record(h.string(),h.unknown()).optional()}).passthrough()).optional(),repositories:h.record(h.string(),h.object({repository:h.string(),owner:h.string(),repo:h.string(),repositoryDirectory:h.string().optional(),next:h.record(h.string(),h.unknown())}).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(R);import{z as on}from"zod";import{FetchContentQuerySchema as Qe}from"@octocodeai/octocode-core/schemas";var an=on.enum(["none","standard","symbols"]).optional().default("standard"),Ge={startLine:E,endLine:E,contextLines:C.default(5),charOffset:p(0,1e8).optional(),charLength:p(1,5e4).optional(),minify:an},sn=S(Qe,Ge),Me=b(Qe,Ge),Ne=f(sn,{maxQueries:5});import{z as cn}from"zod";import{FindFilesQuerySchema as ln}from"@octocodeai/octocode-core/schemas";var He={maxDepth:p(0,100).optional(),minDepth:p(0,100).optional(),limit:p(1,1e4).optional(),page:y.default(1),itemsPerPage:p(1,50).optional()},je=cn.object(Object.fromEntries(Object.entries(ln.shape).filter(([t])=>t!=="regexType")));function un(t,r){t.minDepth!==void 0&&t.maxDepth!==void 0&&t.minDepth>t.maxDepth&&r.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var pn=S(je,He),Be=b(je,He).superRefine(un),ze=f(pn,{maxQueries:5});import{z as _}from"zod";import{RipgrepQuerySchema as Ue}from"@octocodeai/octocode-core/schemas";var mn=["paginated","discovery","detailed","structural"],dn=["semanticRanking"],$e={mode:_.enum(mn).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:_.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:_.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:C,matchContentLength:p(1,1e5).optional().default(500),maxMatchesPerFile:p(1,1e5).optional(),maxFiles:p(1,1e5).optional(),matchPage:y.optional(),itemsPerPage:p(1,1e3).optional(),page:y.default(1),unique:_.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:_.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},hn={...$e,semanticRanking:_.never().optional()},gn=S(Ue,hn),fn=b(Ue,$e,{strict:!0,omit:dn}),Ve=fn.superRefine((t,r)=>{let o=t;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"]})}),Xe=f(gn,{maxQueries:5});import{ViewStructureQuerySchema as We}from"@octocodeai/octocode-core/schemas";var Ze={maxDepth:p(0,20).optional(),limit:p(1,1e4).optional(),page:y.default(1),itemsPerPage:p(1,50).optional()},yn=S(We,Ze),Je=b(We,Ze),Ke=f(yn,{maxQueries:5});import{z as n}from"zod";import{LspGetSemanticsQuerySchema as tt}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as bn}from"@octocodeai/octocode-core/schemas/outputs";var Sn=p(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),xn=p(0,1e5).optional(),Rn=["structured","compact"],nt={type:n.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:n.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:Sn.optional(),orderHint:xn,depth:p(0,20).optional(),includeDeclaration:n.boolean().optional().default(!0),page:y,itemsPerPage:p(1,100).optional(),contextLines:p(0,100).optional(),format:n.enum(Rn).optional().default("structured")},On=S(tt,nt),rt=b(tt,nt);var ot=f(On,{maxQueries:5}),Ye=n.object({line:n.number(),character:n.number()}),wn=n.object({start:Ye,end:Ye}),kn=n.object({startLine:n.number(),endLine:n.number()}),j=n.object({uri:n.string(),content:n.string().optional(),displayRange:kn.optional(),isDefinition:n.boolean().optional()}),B=n.string(),Tn=n.object({name:n.string(),uri:n.string(),foundAtLine:n.number(),orderHint:n.number().optional()}),Pn=n.object({serverAvailable:n.boolean().optional(),provider:n.string().optional(),source:n.string().optional()}),at=n.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),q=n.object({category:at,reason:n.string()}),Ln=n.object({currentPage:n.number(),totalPages:n.number(),totalResults:n.number(),hasMore:n.boolean(),itemsPerPage:n.number(),nextPage:n.number().optional()}),Cn=n.object({name:n.string(),kind:n.string(),line:n.number(),character:n.number(),endLine:n.number(),childCount:n.number(),containerName:n.string().optional()}),En=n.string(),it=n.object({name:n.string(),kind:n.string(),uri:n.string(),line:n.number(),endLine:n.number(),selectionLine:n.number().optional()}),_n=n.string(),qn=n.object({direction:n.enum(["incoming","outgoing"]),item:it,ranges:n.array(n.object({line:n.number(),character:n.number()})),rangeCount:n.number(),rangeSampleCount:n.number(),contentPreview:n.string().optional()}),An=n.string(),vn=n.object({complete:n.boolean(),truncatedByDepth:n.boolean(),cycleCount:n.number(),failedRequestCount:n.number(),dynamicCallsExcluded:n.literal(!0),stdlibCallsExcluded:n.number().optional()}),Fn=n.object({uri:n.string(),count:n.number(),firstLine:n.number(),firstCharacter:n.number(),lines:n.array(n.number()),hasDefinition:n.boolean().optional()}),In=n.string(),Dn=n.discriminatedUnion("kind",[n.object({kind:n.literal("definition"),locations:n.array(n.union([j,B]))}),n.object({kind:n.literal("typeDefinition"),locations:n.array(n.union([j,B]))}),n.object({kind:n.literal("implementation"),locations:n.array(n.union([j,B]))}),n.object({kind:n.literal("references"),locations:n.array(n.union([j,B])).optional(),byFile:n.array(n.union([Fn,In])).optional(),totalReferences:n.number(),totalFiles:n.number(),empty:q.optional()}),...["callers","callees","callHierarchy"].map(t=>n.object({kind:n.literal(t),root:n.union([it,_n]).optional(),direction:n.enum(["incoming","outgoing","both"]),calls:n.array(n.union([qn,An])),incomingCalls:n.number(),outgoingCalls:n.number(),completeness:vn,empty:q.optional()})),n.object({kind:n.literal("hover"),markdown:n.string().optional(),text:n.string().optional(),range:wn.optional()}),n.object({kind:n.literal("documentSymbols"),symbols:n.array(n.union([Cn,En])),totalSymbols:n.number().optional(),topLevelSymbols:n.number().optional(),empty:q.optional()}),n.object({kind:n.literal("workspaceSymbol"),query:n.string(),symbols:n.array(n.unknown()),totalSymbols:n.number(),empty:q.optional()}),n.object({kind:n.literal("typeHierarchy"),direction:n.enum(["supertypes","subtypes"]),root:n.unknown().optional(),items:n.array(n.unknown()),totalItems:n.number(),empty:q.optional()}),n.object({kind:n.literal("diagnostic"),diagnostics:n.array(n.unknown()),totalDiagnostics:n.number(),errorCount:n.number(),warningCount:n.number(),empty:q.optional()}),n.object({kind:n.literal("empty"),category:at,reason:n.string()})]),et=n.object({type:n.string(),uri:n.string(),format:n.enum(["structured","compact"]).optional(),resolvedSymbol:Tn.optional(),lsp:Pn,payload:Dn,pagination:Ln.optional(),summary:n.record(n.string(),n.unknown()).optional(),warnings:n.array(n.string()).optional()}),ua=n.object({base:n.string().optional(),shared:n.record(n.string(),n.union([n.string(),n.number(),n.boolean()])).optional(),results:n.array(n.union([n.object({id:n.string().min(1),status:n.literal("empty"),data:et}),n.object({id:n.string().min(1),status:n.literal("error"),data:bn}),n.object({id:n.string().min(1),data:et})]))});import{z as st}from"zod";import{LocalBinaryInspectQuerySchema as Qn}from"@octocodeai/octocode-core/schemas";var Gn={entryPageNumber:y.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:p(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:p(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:y.default(1).describe("1-based page for paginated entry/content listings."),detailed:st.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},ct=st.object({...Qn.shape,...Gn}),lt=ct.strict().superRefine((t,r)=>{t.mode==="extract"&&!t.archiveFile&&r.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),t.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"];t.mode==="decompress"&&o.some(i=>t.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".'})}),ut=f(ct,{maxQueries:5});import{z as e}from"zod";var L=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],z=["fixes","dataflow"];var ee=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:ee.optional()}),e.strictObject({kind:e.literal("npm")})])),Y=e.union([e.string(),e.array(e.string()).max(100)]),Mn=e.strictObject({path:Y.optional(),language:Y.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(),pt=e.enum(["smart","sensitive","insensitive"]),mt=e.string().max(1e4),Nn=e.strictObject({id:e.string().optional(),kind:e.literal("text"),value:mt,case:pt.optional(),wholeWord:e.boolean().optional()}),Hn=e.strictObject({id:e.string().optional(),kind:e.literal("regex"),value:mt,dialect:e.enum(["rust","pcre2","provider"]).optional(),case:pt.optional(),wholeWord:e.boolean().optional(),multiline:e.boolean().optional(),dotAll:e.boolean().optional()}),A=e.lazy(()=>e.strictObject({pattern:e.string().optional(),kind:e.string().optional(),inside:A.optional(),has:A.optional(),not:A.optional(),all:e.array(A).optional(),any:e.array(A).optional(),stopBy:e.literal("end").optional()})),dt=e.union([A,e.string().min(1)]),jn=e.strictObject({id:e.string().optional(),kind:e.literal("structural"),lang:e.string().min(1),pattern:e.string().optional(),rule:dt.optional()}),Bn=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()}),M=e.lazy(()=>e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all"),id:e.string().optional(),of:e.array(M).min(1)}),e.strictObject({kind:e.literal("any"),id:e.string().optional(),of:e.array(M).min(1)}),e.strictObject({kind:e.literal("not"),id:e.string().optional(),predicate:M}),Nn,Hn,jn,Bn])),ht=e.strictObject({mode:e.enum(["never","auto","required"]),strategy:e.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:e.boolean().optional(),forceRefresh:e.boolean().optional()}),gt=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()}),ft=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()}),yt=e.enum(["discovery","paginated","detailed"]),bt=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),target:e.enum(L),from:ee.optional(),scope:Mn,where:M.optional(),materialize:ht.optional(),fetch:gt.optional(),select:e.array(e.string()).optional(),view:yt.optional(),controls:ft.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()}),zn=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),queries:e.array(bt).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()}),Sa=e.union([bt,zn]),Un=L,$n=[...L,...z],St={schema:e.literal("oql").optional(),id:e.string().optional(),mainResearchGoal:e.string().optional(),researchGoal:e.string().optional(),reasoning:e.string().optional()},xt={...St,target:e.enum($n).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:ee.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:M.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([ht,e.enum(["never","auto","required"])]).optional(),fetch:gt.optional(),select:e.array(e.string()).optional(),view:yt.optional(),controls:ft.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:Y.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:dt.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()},Rt={...xt,target:e.enum(Un).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.")},Ot=e.object(Rt).catchall(e.unknown()),xa=e.object(xt).catchall(e.unknown()),Ra=e.object({...St,queries:e.array(e.unknown()).min(1)}).catchall(e.unknown()),wt=e.object({...Rt,queries:e.array(e.unknown()).min(1).max(5).optional(),combine:e.enum(["independent","merge"]).optional()}).catchall(e.unknown());var kt=["GitHub","Local Code","Package","Other"],Tt=new Map([m.GITHUB_SEARCH_CODE,m.GITHUB_SEARCH_REPOSITORIES,m.GITHUB_SEARCH_PULL_REQUESTS,m.GITHUB_FETCH_CONTENT,m.GITHUB_VIEW_REPO_STRUCTURE,m.GITHUB_CLONE_REPO,m.LOCAL_RIPGREP,m.LOCAL_FIND_FILES,m.LOCAL_FETCH_CONTENT,m.LOCAL_VIEW_STRUCTURE,T,m.PACKAGE_SEARCH,N].map((t,r)=>[t,r])),O=class extends Error{constructor(o,i=[]){super(o);this.details=i;this.name="DirectToolInputError"}details},Vn=["id","mainResearchGoal","researchGoal","reasoning"],ie=new Set([...Vn]),Xn=["id","researchGoal","reasoning"],Et=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],Wn=[{name:m.GITHUB_SEARCH_CODE,schema:Se,inputSchema:xe},{name:m.GITHUB_FETCH_CONTENT,schema:ge,inputSchema:fe},{name:m.GITHUB_VIEW_REPO_STRUCTURE,schema:qe,inputSchema:Ae},{name:m.GITHUB_SEARCH_REPOSITORIES,schema:Le,inputSchema:Ce},{name:m.GITHUB_SEARCH_PULL_REQUESTS,schema:we,inputSchema:ke},{name:m.PACKAGE_SEARCH,schema:Ie,inputSchema:De},{name:m.GITHUB_CLONE_REPO,schema:W,inputSchema:me},{name:m.LOCAL_RIPGREP,schema:Ve,inputSchema:Xe},{name:m.LOCAL_VIEW_STRUCTURE,schema:Je,inputSchema:Ke},{name:m.LOCAL_FIND_FILES,schema:Be,inputSchema:ze},{name:m.LOCAL_FETCH_CONTENT,schema:Me,inputSchema:Ne},{name:T,schema:rt,inputSchema:ot},{name:m.LOCAL_BINARY_INSPECT,schema:lt,inputSchema:ut},{name:N,schema:Ot,inputSchema:wt}];function $(t){return Wn.find(r=>r.name===t)}function U(t){return t.startsWith("gh")?"GitHub":t.startsWith("local")||t.startsWith("lsp")?"Local Code":t===m.PACKAGE_SEARCH?"Package":"Other"}function Na(t){return[...t].sort((r,o)=>{let i=kt.indexOf(U(r)),c=kt.indexOf(U(o));if(i!==c)return i-c;let s=Tt.get(r)??Number.MAX_SAFE_INTEGER,u=Tt.get(o)??Number.MAX_SAFE_INTEGER;return s!==u?s-u:r.localeCompare(o)})}function Ha(t){let r=$(t);if(!r)return"{}";try{return JSON.stringify(te.toJSONSchema(r.inputSchema),null,2)}catch{return JSON.stringify(te.toJSONSchema(r.schema),null,2)}}function ja(t){return JSON.stringify(t??{},null,2)}function Ba(t){let r=U(t),o=[...Xn];return(r==="GitHub"||r==="Package")&&o.splice(1,0,"mainResearchGoal"),o}function za(){return Et.map(t=>({...t}))}function Ua(){return JSON.stringify(Object.fromEntries(Et.map(t=>[t.name,t.optional?`${t.type} (optional)`:t.type])),null,2)}function $a(t,r){return r?.tools?.[t]?.description??t}function _t(t){let r=$(t);if(!r)return[];let o=te.toJSONSchema(r.schema);if(!v(o))return[];let i=k(o.properties)?o.properties:{},c=new Set(Array.isArray(o.required)?o.required.filter(s=>!ie.has(s)&&!ae(i[s])):[]);return oe(i,c)}function Pt(t,r){return`tools ${t} --queries '${JSON.stringify(r)}'`}function Zn(t){let r=Kn(t);if(r.length>0)return r.map(i=>({...i,command:Pt(t,i.query)}));let o=Jn(t);return Object.keys(o).length===0?[]:[{label:"schema-derived",query:o,command:Pt(t,o)}]}function Va(t){return Zn(t)[0]?.query??{}}function Jn(t){if(!$(t))return{};let r=_t(t),o=r.filter(s=>!s.name.includes(".")),i=ir(o),c={};for(let s of i)c[s.name]=ur(s.name,s.type);return t.startsWith("lsp")&&r.some(s=>s.name==="uri")&&(c.uri??="uri"),t===T&&(c.type??="definition",c.symbolName??="symbolName",c.lineHint??=1),c}function Kn(t){return t===N?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:t===m.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}}]:t===m.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}}]:t===m.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}}]:t===m.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"facebook",repo:"react",path:"packages",maxDepth:2,itemsPerPage:50}}]:t===m.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"facebook",repo:"react",sparsePath:"packages/react"}}]:t===m.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:t===m.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"}}]:t===m.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}}]:t===m.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}}]:t===T?[{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 Xa(t,r,o={}){if(typeof r!="string")return null;let i;try{i=JSON.parse(r)}catch{throw new O("Tool input must be valid JSON.")}return Yn(t,i,o)}function Yn(t,r,o={}){let i=tr(t,r,o),c=$(t);if(!c)throw new O(`Unknown tool: ${t}`);let s=c.inputSchema.safeParse(i);if(!s.success)throw new O("Tool input does not match the expected schema.",er(s.error));return s.data}function er(t){return t.issues.map(r=>`${r.path.length>0?r.path.join("."):"input"}: ${r.message}`)}function tr(t,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 O('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(i.length===0)throw new O("At least one query is required.");let c=k(r)&&Array.isArray(r.queries)?Object.fromEntries(Object.entries(r).filter(([u])=>u!=="queries")):{},s=i.map((u,g)=>nr(t,g,or(t,u,g,o),{sourceLabel:o.sourceLabel}));return{...c,queries:s}}function nr(t,r,o,i){let c={...o},s=U(t),u=i.sourceLabel??"direct tool execution",g=rr(t,u);return(typeof c.id!="string"||c.id.trim().length===0)&&(c.id=`${t}-${r+1}`),(s==="GitHub"||s==="Package")&&(typeof c.mainResearchGoal!="string"||c.mainResearchGoal.trim().length===0)&&(c.mainResearchGoal=g),(typeof c.researchGoal!="string"||c.researchGoal.trim().length===0)&&(c.researchGoal=g),(typeof c.reasoning!="string"||c.reasoning.trim().length===0)&&(c.reasoning=`Executed via ${u} tool command`),c}function rr(t,r){return`Execute ${t} via ${r}`}function or(t,r,o,i={}){if(!k(r))throw new O("Tool input must be a JSON object or an array of objects.");let c=new Set([..._t(t).filter(g=>!g.name.includes(".")).map(g=>g.name),...ie]),s={},u=[];for(let[g,w]of Object.entries(r)){if(c.has(g)){s[g]=w;continue}u.push(g)}if(u.length>0&&c.size>0&&(i.onUnknownFields?.(u,o),i.rejectUnknownFields===!0))throw new O(`Unknown field(s): ${u.join(", ")}`,[`Remove unknown field(s) from query ${o+1}: ${u.join(", ")}`,`Run tools ${t} --scheme to see valid fields.`]);return s}function ar(t){let r=[],o=typeof t.minimum=="number"?t.minimum:void 0,i=typeof t.maximum=="number"?t.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 t&&r.push(`default ${JSON.stringify(t.default)}`),r.length>0?r.join(", "):void 0}function ne(t){if(Array.isArray(t.enum)&&t.enum.length>0)return`enum(${t.enum.map(String).join(", ")})`;if(t.type==="array"){let o=v(t.items)?t.items:void 0;return`array<${o?ne(o):"value"}>`}let r=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:void 0;if(r){let o=r.filter(v).map(ne).filter(i=>i!=="value");if(o.length>0)return[...new Set(o)].join(" | ")}return Array.isArray(t.type)?t.type.join(" | "):typeof t.type=="string"?t.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]]),qt=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function ir(t){let r=t.filter(s=>s.required),o=new Map;for(let s of r)o.set(s.name,s);let i=t.filter(s=>!s.required&&sr(s)).sort(cr),c=Math.max(Lt,r.length);for(let s of i){if(o.size>=c)break;o.set(s.name,s)}return o.size>0?[...o.values()]:t.filter(s=>!qt.has(s.name)).filter(s=>s.type!=="boolean").slice(0,Lt)}function sr(t){return qt.has(t.name)||t.type==="boolean"?!1:lr(t)?re.has(t.name):!0}function cr(t,r){let o=re.get(t.name)??Number.MAX_SAFE_INTEGER,i=re.get(r.name)??Number.MAX_SAFE_INTEGER;return o!==i?o-i:t.name.localeCompare(r.name)}function lr(t){return t.constraints?.includes("default ")===!0}function oe(t,r,o=""){let i=[];for(let[c,s]of Object.entries(t)){if(!o&&ie.has(c))continue;let u=v(s)?s:{},g=o?`${o}.${c}`:c;if(i.push({name:g,required:r.has(c),type:ne(u),constraints:ar(u),description:typeof u.description=="string"?u.description:void 0}),k(u.properties)){let V=new Set(Array.isArray(u.required)?u.required.filter(I=>typeof I=="string"?!ae(u.properties?.[I]):!1):[]);i.push(...oe(u.properties,V,g))}let w=u.type==="array"&&v(u.items)?u.items:void 0;if(w&&k(w.properties)){let V=new Set(Array.isArray(w.required)?w.required.filter(I=>typeof I=="string"?!ae(w.properties?.[I]):!1):[]);i.push(...oe(w.properties,V,g))}}return i}function ur(t,r){if(r.startsWith("array<")){let o=r.slice(6,-1);return[Ct(t,o)]}return Ct(t,r)}function Ct(t,r){if(r.startsWith("enum("))return/^enum\(([^,)]+)/.exec(r)?.[1]??t;if(r==="integer"||r==="number")return t==="lineHint"?42:5;if(r==="boolean")return!0;switch(t){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 t}}function k(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function v(t){return k(t)}function ae(t){return v(t)&&"default"in t}var At={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 F={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:L,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","read a remote file (exact)":"search facebook/react/README.md --content-view exact","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","artifact inspect/list":"search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect","PR diff (GitHub)":"search facebook/react#123 --target diff | search facebook/react --target diff --pr 123","two-ref / two-file diff":"search src/a.ts src/b.ts --target diff | search owner/repo --target diff --base-ref <sha> --head-ref <sha> --path <file>","structural AST (local \u2014 needs full node shape)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" ./src --lang ts',"structural AST (GitHub \u2014 clones bounded subtree)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" facebook/react/packages --lang js --materialize auto',"GitHub index miss recovery":"search useState packages/react/src --repo facebook/react --materialize required | clone facebook/react/packages/react/src | cache fetch facebook/react packages/react/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},semanticsGuide:{documentSymbols:"list a file's symbols to get line anchors first (run before references/callers/hover)",references:"all usages of a symbol across the workspace (often includes its declaration)",callers:"incoming calls to a function/method (call sites only) \u2014 narrower than references",hover:"type, signature, and docs at a symbol"},query:{schema:'"oql" (inserted by normalization)',target:L.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:At};function pr(){return JSON.stringify(F,null,2)}function vt(t){let r="shorthand: ",o=t.indexOf(r);if(o===-1)return null;let i=t.slice(o+r.length).trim(),c=i.length,s=i.indexOf(",");s!==-1&&(c=Math.min(c,s));let u=i.search(/\.\s/);return u!==-1&&(c=Math.min(c,u)),i.slice(0,c).trim().replace(/\.$/,"")||null}function Ft(){let t=[],r=new Set;for(let[o,i]of Object.entries(F.targetDecisionTree))for(let c of i.matchAll(/target:"?(\w+)"?/g)){let s=c[1];!s||r.has(s)||(r.add(s),t.push({target:s,task:o}))}for(let o of F.activeTargets)r.has(o)||(r.add(o),t.push({target:o,task:"advanced target; see full schema"}));return t}function mr(){let t=F,r=["local","github","npm","materialized"],o=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],i=t.quickStart,c=t.agentBestPractices.find(s=>/snippet/i.test(s));return{schema:"oql",kind:"octocode.search.compactScheme",description:t.description,sources:Object.fromEntries(r.map(s=>[s,vt(t.sourceGuide[s])??"a prior clone / cache fetch / materialize localPath"])),targets:Ft(),recipes:Object.fromEntries(o.map(s=>[s,i[s]]).filter(s=>typeof s[1]=="string")),semantics:t.semanticsGuide,proof:{snippets:c,providerUnindexed:t.evidenceSemantics.providerUnindexed},commands:{explain:"search --explain --query '{...}'",fullSchema:"search --scheme"}}}function dr(){return JSON.stringify(mr(),null,2)}function hr(){let t=F,r=["octocode search \u2014 compact agent guide (full reference: search --scheme)","","SOURCE \u2014 where to look (choose one):"],o=["local","github","npm","materialized"];for(let u of o){let g=vt(t.sourceGuide[u]);r.push(` ${u.padEnd(13)}${g??"a prior clone / cache fetch / materialize localPath"}`)}r.push("","TARGET \u2014 answer type (--target, or inferred from the args):");for(let{target:u,task:g}of Ft())r.push(` ${u.padEnd(13)}${g}`);r.push("","COMMON RECIPES:");let i=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],c=t.quickStart;for(let u of i){let g=c[u];g&&r.push(` ${g}`)}r.push("","LSP SEMANTICS (run documentSymbols first, then narrow):");for(let[u,g]of Object.entries(t.semanticsGuide))r.push(` ${u.padEnd(16)}${g}`);r.push("","PROOF \u2014 snippets are discovery, not proof:");let s=t.agentBestPractices.find(u=>/snippet/i.test(u));return s&&r.push(` ${s}`),r.push(` ${t.evidenceSemantics.providerUnindexed}`),r.push("","Routing debug: search --explain --query '{...}'","Full schema: search --scheme"),r.join(`
|
|
9
|
-
`)}import{completeMetadata as
|
|
8
|
+
import{z as pe}from"zod";import{completeMetadata as Vt}from"@octocodeai/octocode-core";var d=Vt.toolNames,A=d.LSP_GET_SEMANTIC_CONTENT,X="oqlSearch";function oe(t=process.env){let o=t.ENABLE_OQL;return o===void 0?!1:["1","true","yes","on"].includes(o.trim().toLowerCase())}var $o=new Set([d.LOCAL_RIPGREP,d.LOCAL_FETCH_CONTENT,d.LOCAL_FIND_FILES,d.LOCAL_VIEW_STRUCTURE,d.LOCAL_BINARY_INSPECT,A]);var be=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];import{CloneRepoQuerySchema as Yt}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as en}from"@octocodeai/octocode-core/schemas/outputs";import{z as W}from"zod";function p(t,o){return W.preprocess(r=>typeof r=="number"&&Number.isFinite(r)?Math.min(Math.max(r,t),o):r,W.number().int().min(t).max(o))}var w=p(1,1e3).optional().default(1),I=p(0,100).optional(),D=p(1,1e9).optional(),Wt={responseCharOffset:p(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:p(1,5e4).optional().describe("Full-response char window.")};function R(t,o={}){let{maxQueries:r=5}=o;return W.object({queries:W.array(t).min(1).max(r).describe("Parallel queries."),...Wt}).superRefine((i,l)=>{let s=new Set;i.queries.forEach((u,y)=>{u&&typeof u=="object"&&"id"in u&&typeof u.id=="string"&&(s.has(u.id)&&l.addIssue({code:"custom",message:`Duplicate query id "${u.id}" at index ${y}`,path:["queries",y,"id"]}),s.add(u.id))})})}import{z as Se}from"zod";function Zt(t,o){return t?.description&&!o.description?o.describe(t.description):o}function xe(t,o){let r={};for(let[i,l]of Object.entries(o))r[i]=Zt(t.shape[i],l);return r}function Jt(t,o){let r=t;return r.safeExtend?r.safeExtend(o):t.extend(o)}function Oe(t,o){if(!o?.length)return t;let r=new Set(o);return Se.object(Object.fromEntries(Object.entries(t.shape).filter(([i])=>!r.has(i))))}function k(t,o={},r={}){let i=Oe(t,r.omit),l=Jt(i,xe(i,o));return r.strict?l.strict():l}function T(t,o={},r={}){let i=Oe(t,r.omit),l=Se.object({...i.shape,...xe(i,o)});return r.strict?l.strict():l}import{z as g}from"zod";import{z as x}from"zod";var L=x.object({currentPage:x.number(),totalPages:x.number(),hasMore:x.boolean(),nextPage:x.number().optional(),pageSize:x.number().optional(),totalItems:x.number().optional()}),Z=x.object({charOffset:x.number(),charLength:x.number(),totalChars:x.number(),hasMore:x.boolean(),nextCharOffset:x.number().optional(),currentPage:x.number().optional(),totalPages:x.number().optional(),chunkMode:x.enum(["semantic","char-limit"]).optional()}),z=x.object({tool:x.string(),query:x.record(x.string(),x.unknown()),why:x.string().optional(),confidence:x.enum(["exact","heuristic"]).optional()}),Re=x.object({level:x.enum(["info","warning","error"]),message:x.string(),field:x.string().optional(),code:x.string().optional()});var we=g.object({currentPage:g.number(),totalPages:g.number(),hasMore:g.boolean(),charOffset:g.number(),charLength:g.number(),totalChars:g.number(),nextCharOffset:g.number().optional()}).optional(),C={base:g.string().optional(),shared:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional(),responsePagination:we};function Kt(t){return g.object({id:g.string(),status:g.enum(["empty","error"]).optional(),data:t,diagnostics:g.array(Re).optional(),next:g.record(g.string(),z).optional()})}var ir=Kt(g.record(g.string(),g.unknown()).optional()),E={base:g.string().optional(),shared:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional(),responsePagination:we};var ae=k(Yt),ke=R(ae),dr=en.extend(C);import{z as a}from"zod";import{FileContentQuerySchema as Te}from"@octocodeai/octocode-core/schemas";var tn=a.enum(["none","standard","symbols"]).optional().default("standard"),nn=a.object({currentPage:a.number(),totalPages:a.number(),hasMore:a.boolean(),nextPage:a.number().optional(),charOffset:a.number().optional(),charLength:a.number().optional(),totalChars:a.number().optional(),nextCharOffset:a.number().optional()}),on=a.object({continueChars:a.object({tool:a.literal("ghGetFileContent"),query:a.record(a.string(),a.unknown())}).optional()}),rn=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:nn.optional(),next:on.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()}),an=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()}),Pe={startLine:D,endLine:D,contextLines:I,charOffset:p(0,1e8).optional(),charLength:p(1,5e4).optional(),minify:tn},sn=T(Te,Pe),Le=k(Te,Pe),Ce=R(sn),Or=a.object({base:a.string().optional(),shared:a.record(a.string(),a.union([a.string(),a.number(),a.boolean()])).optional(),responsePagination:C.responsePagination,results:a.array(a.object({id:a.string(),data:a.object({owner:a.string(),repo:a.string(),files:a.array(rn).optional(),directories:a.array(an).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 m}from"zod";import{GitHubCodeSearchQuerySchema as Ee}from"@octocodeai/octocode-core/schemas";var qe={limit:p(1,100).optional(),page:w.default(1)},_e=k(Ee,qe),ve=R(T(Ee,qe)),cn=L.extend({totalMatchesKind:m.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:m.boolean().optional(),uniqueFileCount:m.number().optional()}),qr=m.object({base:m.string().optional(),shared:m.record(m.string(),m.union([m.string(),m.number(),m.boolean()])).optional(),responsePagination:C.responsePagination,results:m.array(m.object({id:m.string(),data:m.object({files:m.array(m.object({owner:m.string(),repo:m.string(),path:m.string(),queryId:m.string().optional(),matches:m.array(m.object({value:m.string().optional(),pathOnly:m.boolean().optional(),matchIndices:m.array(m.object({start:m.number(),end:m.number(),lineOffset:m.number()})).optional(),url:m.string().optional()}))})),pagination:cn.optional()})})),emptyQueries:m.array(m.object({id:m.string(),nonExistentScope:m.literal(!0).optional(),incompleteResults:m.literal(!0).optional()})).optional(),warnings:m.array(m.string()).optional(),errors:m.array(m.object({id:m.string(),error:m.string()})).optional()});import{z as F}from"zod";import{GitHubPullRequestSearchQuerySchema as Ae}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as mn}from"@octocodeai/octocode-core/schemas/outputs";var Fe={perPage:p(1,100).optional().default(30),prNumber:p(1,1e9).optional(),limit:p(1,100).optional().default(30),page:w.default(1),filePage:w.optional(),commentPage:w.optional(),commitPage:w.optional(),itemsPerPage:p(1,100).optional().default(20),charOffset:p(0,1e8).optional(),commentBodyOffset:p(0,1e8).optional(),charLength:p(1,5e4).optional()},dn=T(Ae,Fe),Ie=k(Ae,Fe),De=R(dn),Gr=mn.extend({results:F.array(F.object({id:F.string().optional(),status:F.string().optional(),data:F.object({pull_requests:F.array(F.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...C});import{z as S}from"zod";import{GitHubReposSearchSingleQuerySchema as Qe}from"@octocodeai/octocode-core/schemas";var je={limit:p(1,100).optional(),page:w.default(1)},Ge=k(Qe,je),Me=R(T(Qe,je)),hn=S.object({owner:S.string(),repo:S.string(),stars:S.number().optional(),forks:S.number().optional(),openIssuesCount:S.number().optional(),language:S.string().optional(),license:S.string().optional(),description:S.string().optional(),homepage:S.string().optional(),pushedAt:S.string().optional(),createdAt:S.string().optional(),defaultBranch:S.string().optional(),topics:S.array(S.string()).optional(),visibility:S.string().optional(),url:S.string().optional(),updatedAt:S.string().optional()}),gn=L.extend({totalMatchesKind:S.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:S.boolean().optional()}).optional(),fn=S.object({repositories:S.array(S.union([S.string(),hn])).optional(),pagination:gn}).passthrough(),Xr=S.object({results:S.array(S.object({id:S.string().optional(),status:S.string().optional(),data:fn.optional()}).passthrough()).optional()}).extend(C);import{GitHubViewRepoStructureQuerySchema as Ne}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as bn}from"@octocodeai/octocode-core/schemas/outputs";var He={maxDepth:p(0,20).optional(),page:w.default(1),itemsPerPage:p(1,200).optional()},ze=k(Ne,He),Be=R(T(Ne,He)),oa=bn.extend(C);import{z as b}from"zod";import{NpmPackageQuerySchema as Ue}from"@octocodeai/octocode-core/schemas";var $e={page:w,mode:b.enum(["lean","full"]).optional()},Ve=k(Ue,$e),Xe=R(T(Ue,$e,{strict:!0}),{maxQueries:5}),pa=b.object({results:b.array(b.looseObject({id:b.string(),data:b.looseObject({packages:b.array(b.object({name:b.string(),version:b.string().optional(),description:b.string().optional(),license:b.string().optional(),downloads:b.number().optional(),repository:b.string().optional(),repositoryDirectory:b.string().optional(),repositoryId:b.string().optional(),next:b.record(b.string(),b.unknown()).optional()}).passthrough()).optional(),repositories:b.record(b.string(),b.object({repository:b.string(),owner:b.string(),repo:b.string(),repositoryDirectory:b.string().optional(),next:b.record(b.string(),b.unknown())}).passthrough()).optional(),pagination:L.optional()}).optional(),status:b.string().optional()})).optional()}).extend(C);import{z as O}from"zod";import{FetchContentQuerySchema as We}from"@octocodeai/octocode-core/schemas";var Sn=O.enum(["none","standard","symbols"]).optional().default("standard"),Ze={startLine:D,endLine:D,contextLines:I.default(5),charOffset:p(0,1e8).optional(),charLength:p(1,5e4).optional(),minify:Sn},xn=T(We,Ze),Je=k(We,Ze),Ke=R(xn,{maxQueries:5}),On=O.object({start:O.number(),end:O.number()}),Rn=O.object({path:O.string().optional(),content:O.string().optional(),contentView:O.enum(["none","standard","symbols"]).optional(),isSkeleton:O.boolean().optional(),totalLines:O.number().optional(),sourceChars:O.number().optional(),startLine:O.number().optional(),endLine:O.number().optional(),isPartial:O.boolean().optional(),matchRanges:O.array(On).optional(),pagination:O.union([Z,L]).optional(),modified:O.string().optional(),lastModified:O.string().optional(),lastModifiedBy:O.string().optional(),warnings:O.array(O.string()).optional(),matchNotFound:O.boolean().optional(),searchedFor:O.string().optional()}),xa=O.object({results:O.array(O.object({id:O.string(),status:O.enum(["empty","error"]).optional(),data:Rn}))}).extend(E);import{z as P}from"zod";import{FindFilesQuerySchema as wn}from"@octocodeai/octocode-core/schemas";var Ye={maxDepth:p(0,100).optional(),minDepth:p(0,100).optional(),limit:p(1,1e4).optional(),page:w.default(1),itemsPerPage:p(1,50).optional()},et=P.object(Object.fromEntries(Object.entries(wn.shape).filter(([t])=>t!=="regexType")));function kn(t,o){t.minDepth!==void 0&&t.maxDepth!==void 0&&t.minDepth>t.maxDepth&&o.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var Tn=T(et,Ye),tt=k(et,Ye).superRefine(kn),nt=R(Tn,{maxQueries:5}),Pn=P.object({name:P.string().optional(),path:P.string().optional(),type:P.enum(["file","dir","directory","link","symlink"]).optional(),size:P.union([P.number(),P.string()]).optional(),modified:P.string().optional(),accessed:P.string().optional(),created:P.string().optional(),permissions:P.string().optional()}),Ln=P.object({files:P.array(Pn).optional(),summary:P.string().optional(),pagination:L.optional(),warnings:P.array(P.string()).optional()}),Ea=P.object({results:P.array(P.object({id:P.string(),status:P.enum(["empty","error"]).optional(),data:Ln}))}).extend(E);import{z as h}from"zod";import{RipgrepQuerySchema as ot}from"@octocodeai/octocode-core/schemas";var Cn=["paginated","discovery","detailed","structural"],En=["semanticRanking"],rt={mode:h.enum(Cn).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:h.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:h.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:I,matchContentLength:p(1,1e5).optional().default(500),maxMatchesPerFile:p(1,1e5).optional(),maxFiles:p(1,1e5).optional(),matchPage:w.optional(),itemsPerPage:p(1,1e3).optional(),page:w.default(1),unique:h.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:h.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},qn={...rt,semanticRanking:h.never().optional()},_n=T(ot,qn),vn=k(ot,rt,{strict:!0,omit:En}),at=vn.superRefine((t,o)=>{let r=t;if(r.caseSensitive&&r.caseInsensitive&&o.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),r.fixedString&&r.perlRegex&&o.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),r.filesOnly&&r.filesWithoutMatch&&o.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),r.countLinesPerFile&&r.countMatchesPerFile&&o.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),r.multilineDotall&&!r.multiline&&o.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),r.mode==="structural"){for(let i of["unique","countUnique"])r[i]&&o.addIssue({code:"custom",message:`\`${i}\` is not valid with mode:"structural".`,path:[i]});return}r.unique&&!r.onlyMatching&&o.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),r.countUnique&&!r.onlyMatching&&o.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),it=R(_n,{maxQueries:5}),An=h.object({line:h.number(),endLine:h.number().optional(),value:h.string().optional(),column:h.number().optional(),count:h.number().optional(),metavars:h.record(h.string(),h.array(h.string())).optional()}),Fn=h.object({path:h.string(),matches:h.array(An).optional(),totalOccurrences:h.number().optional(),totalMatchedLines:h.number().optional(),totalMatchRows:h.number().optional(),returnedMatchRows:h.number().optional(),matchPagination:L.optional(),next:h.record(h.string(),z).optional()}),In=h.object({files:h.array(Fn).optional(),summary:h.string().optional(),searchEngine:h.string().optional(),pagination:L.optional(),next:h.record(h.string(),z).optional(),warnings:h.array(h.string()).optional()}),ja=h.object({results:h.array(h.object({id:h.string(),status:h.enum(["empty","error"]).optional(),data:In}))}).extend(E);import{z as f}from"zod";import{ViewStructureQuerySchema as st}from"@octocodeai/octocode-core/schemas";var ct={maxDepth:p(0,20).optional(),limit:p(1,1e4).optional(),page:w.default(1),itemsPerPage:p(1,50).optional()},Dn=T(st,ct),lt=k(st,ct),ut=R(Dn,{maxQueries:5}),Qn=f.object({name:f.string().optional(),type:f.enum(["file","dir","directory","link","symlink"]),path:f.string().optional(),depth:f.number().optional(),size:f.union([f.number(),f.string()]).optional(),modified:f.string().optional(),permissions:f.string().optional()}),jn=f.object({path:f.string().optional(),entries:f.array(Qn).optional(),files:f.array(f.string()).optional(),folders:f.array(f.string()).optional(),links:f.array(f.string()).optional(),summary:f.union([f.string(),f.record(f.string(),f.unknown())]).optional(),pagination:L.optional(),warnings:f.array(f.string()).optional()}),Va=f.object({results:f.array(f.object({id:f.string(),status:f.enum(["empty","error"]).optional(),data:jn}))}).extend(E);import{z as n}from"zod";import{LspGetSemanticsQuerySchema as dt}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as Gn}from"@octocodeai/octocode-core/schemas/outputs";var Mn=p(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),Nn=p(0,1e5).optional(),Hn=["structured","compact"],ht={type:n.enum(be).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:n.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:Mn.optional(),orderHint:Nn,depth:p(0,20).optional(),includeDeclaration:n.boolean().optional().default(!0),page:w,itemsPerPage:p(1,100).optional(),contextLines:p(0,100).optional(),format:n.enum(Hn).optional().default("structured")},zn=T(dt,ht),gt=k(dt,ht);var ft=R(zn,{maxQueries:5}),pt=n.object({line:n.number(),character:n.number()}),Bn=n.object({start:pt,end:pt}),Un=n.object({startLine:n.number(),endLine:n.number()}),J=n.object({uri:n.string(),content:n.string().optional(),displayRange:Un.optional(),isDefinition:n.boolean().optional()}),K=n.string(),$n=n.object({name:n.string(),uri:n.string(),foundAtLine:n.number(),orderHint:n.number().optional()}),Vn=n.object({serverAvailable:n.boolean().optional(),provider:n.string().optional(),source:n.string().optional()}),yt=n.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),Q=n.object({category:yt,reason:n.string()}),Xn=L,Wn=n.object({name:n.string(),kind:n.string(),line:n.number(),character:n.number(),endLine:n.number(),childCount:n.number(),containerName:n.string().optional()}),Zn=n.string(),bt=n.object({name:n.string(),kind:n.string(),uri:n.string(),line:n.number(),endLine:n.number(),selectionLine:n.number().optional()}),Jn=n.string(),Kn=n.object({direction:n.enum(["incoming","outgoing"]),item:bt,ranges:n.array(n.object({line:n.number(),character:n.number()})),rangeCount:n.number(),rangeSampleCount:n.number(),contentPreview:n.string().optional()}),Yn=n.string(),eo=n.object({complete:n.boolean(),truncatedByDepth:n.boolean(),cycleCount:n.number(),failedRequestCount:n.number(),dynamicCallsExcluded:n.literal(!0),stdlibCallsExcluded:n.number().optional()}),to=n.object({uri:n.string(),count:n.number(),firstLine:n.number(),firstCharacter:n.number(),lines:n.array(n.number()),hasDefinition:n.boolean().optional()}),no=n.string(),oo=n.discriminatedUnion("kind",[n.object({kind:n.literal("definition"),locations:n.array(n.union([J,K]))}),n.object({kind:n.literal("typeDefinition"),locations:n.array(n.union([J,K]))}),n.object({kind:n.literal("implementation"),locations:n.array(n.union([J,K]))}),n.object({kind:n.literal("references"),locations:n.array(n.union([J,K])).optional(),byFile:n.array(n.union([to,no])).optional(),totalReferences:n.number(),totalFiles:n.number(),empty:Q.optional()}),...["callers","callees","callHierarchy"].map(t=>n.object({kind:n.literal(t),root:n.union([bt,Jn]).optional(),direction:n.enum(["incoming","outgoing","both"]),calls:n.array(n.union([Kn,Yn])),incomingCalls:n.number(),outgoingCalls:n.number(),completeness:eo,empty:Q.optional()})),n.object({kind:n.literal("hover"),markdown:n.string().optional(),text:n.string().optional(),range:Bn.optional()}),n.object({kind:n.literal("documentSymbols"),symbols:n.array(n.union([Wn,Zn])),totalSymbols:n.number().optional(),topLevelSymbols:n.number().optional(),empty:Q.optional()}),n.object({kind:n.literal("workspaceSymbol"),query:n.string(),symbols:n.array(n.unknown()),totalSymbols:n.number(),empty:Q.optional()}),n.object({kind:n.literal("typeHierarchy"),direction:n.enum(["supertypes","subtypes"]),root:n.unknown().optional(),items:n.array(n.unknown()),totalItems:n.number(),empty:Q.optional()}),n.object({kind:n.literal("diagnostic"),diagnostics:n.array(n.unknown()),totalDiagnostics:n.number(),errorCount:n.number(),warningCount:n.number(),empty:Q.optional()}),n.object({kind:n.literal("empty"),category:yt,reason:n.string()})]),mt=n.object({type:n.string(),uri:n.string(),format:n.enum(["structured","compact"]).optional(),resolvedSymbol:$n.optional(),lsp:Vn.optional(),payload:oo,pagination:Xn.optional(),summary:n.record(n.string(),n.unknown()).optional(),warnings:n.array(n.string()).optional()}),oi=n.object({base:n.string().optional(),shared:n.record(n.string(),n.union([n.string(),n.number(),n.boolean()])).optional(),results:n.array(n.union([n.object({id:n.string().min(1),status:n.literal("empty"),data:mt}),n.object({id:n.string().min(1),status:n.literal("error"),data:Gn}),n.object({id:n.string().min(1),data:mt})]))});import{z as c}from"zod";import{LocalBinaryInspectQuerySchema as ro}from"@octocodeai/octocode-core/schemas";var ao={entryPageNumber:w.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:p(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:p(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:w.default(1).describe("1-based page for paginated entry/content listings."),detailed:c.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},St=c.object({...ro.shape,...ao}),xt=St.strict().superRefine((t,o)=>{t.mode==="extract"&&!t.archiveFile&&o.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),t.archiveFile?.startsWith("-")&&o.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let r=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];t.mode==="decompress"&&r.some(i=>t.path.toLowerCase().endsWith(i))&&o.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".'})}),Ot=R(St,{maxQueries:5}),io=c.object({path:c.string(),mode:c.literal("inspect"),format:c.string().optional(),size:c.number().optional(),isText:c.boolean().optional(),encoding:c.string().optional(),symbols:c.array(c.string()).optional(),imports:c.array(c.string()).optional(),exports:c.array(c.string()).optional(),sections:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()}),so=c.object({name:c.string(),size:c.number().optional(),compressedSize:c.number().optional(),isDir:c.boolean().optional(),modified:c.string().optional()}),co=c.object({path:c.string(),mode:c.literal("list"),entries:c.array(so).optional(),pagination:L.optional(),warnings:c.array(c.string()).optional()}),lo=c.object({path:c.string(),mode:c.enum(["extract","decompress"]),archiveFile:c.string().optional(),content:c.string().optional(),isPartial:c.boolean().optional(),pagination:Z.optional(),warnings:c.array(c.string()).optional()}),uo=c.object({path:c.string(),mode:c.literal("strings"),strings:c.array(c.object({value:c.string(),offset:c.number().optional()})).optional(),content:c.string().optional(),totalStrings:c.number().optional(),scanOffset:c.number().optional(),nextScanOffset:c.number().optional(),hasMore:c.boolean().optional(),warnings:c.array(c.string()).optional()}),po=c.object({path:c.string(),mode:c.literal("unpack"),localPath:c.string().optional(),fileCount:c.number().optional(),totalSize:c.number().optional(),warnings:c.array(c.string()).optional()}),mo=c.union([io,co,lo,uo,po]),ui=c.object({results:c.array(c.object({id:c.string(),status:c.enum(["empty","error","success"]).optional(),data:mo}))}).extend(E);import{z as e}from"zod";var j=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],Y=["fixes","dataflow"];var ue=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:ue.optional()}),e.strictObject({kind:e.literal("npm")})])),le=e.union([e.string(),e.array(e.string()).max(100)]),ho=e.strictObject({path:le.optional(),language:le.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(),Rt=e.enum(["smart","sensitive","insensitive"]),wt=e.string().max(1e4),go=e.strictObject({id:e.string().optional(),kind:e.literal("text"),value:wt,case:Rt.optional(),wholeWord:e.boolean().optional()}),fo=e.strictObject({id:e.string().optional(),kind:e.literal("regex"),value:wt,dialect:e.enum(["rust","pcre2","provider"]).optional(),case:Rt.optional(),wholeWord:e.boolean().optional(),multiline:e.boolean().optional(),dotAll:e.boolean().optional()}),G=e.lazy(()=>e.strictObject({pattern:e.string().optional(),kind:e.string().optional(),inside:G.optional(),has:G.optional(),not:G.optional(),all:e.array(G).optional(),any:e.array(G).optional(),stopBy:e.literal("end").optional()})),kt=e.union([G,e.string().min(1)]),yo=e.strictObject({id:e.string().optional(),kind:e.literal("structural"),lang:e.string().min(1),pattern:e.string().optional(),rule:kt.optional()}),bo=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()}),V=e.lazy(()=>e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all"),id:e.string().optional(),of:e.array(V).min(1)}),e.strictObject({kind:e.literal("any"),id:e.string().optional(),of:e.array(V).min(1)}),e.strictObject({kind:e.literal("not"),id:e.string().optional(),predicate:V}),go,fo,yo,bo])),Tt=e.strictObject({mode:e.enum(["never","auto","required"]),strategy:e.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:e.boolean().optional(),forceRefresh:e.boolean().optional()}),Pt=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()}),Lt=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","size","name"]).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()}),Ct=e.enum(["discovery","paginated","detailed"]),Et=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),target:e.enum(j),from:ue.optional(),scope:ho,where:V.optional(),materialize:Tt.optional(),fetch:Pt.optional(),select:e.array(e.string()).optional(),view:Ct.optional(),controls:Lt.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()}),So=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),queries:e.array(Et).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()}),gi=e.union([Et,So]),qt=[...j,...Y],_t={schema:e.literal("oql").optional(),id:e.string().optional(),mainResearchGoal:e.string().optional(),researchGoal:e.string().optional(),reasoning:e.string().optional()},vt={..._t,target:e.enum(qt).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:ue.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:V.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([Tt,e.enum(["never","auto","required"])]).optional(),fetch:Pt.optional(),select:e.array(e.string()).optional(),view:Ct.optional(),controls:Lt.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:le.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:kt.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()},At={...vt,target:e.enum(qt).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes. Reserved targets are accepted so the normalizer can return an unsupported-target diagnostic instead of a schema rejection.")},Ft=e.object(At).catchall(e.unknown()),fi=e.object(vt).catchall(e.unknown()),yi=e.object({..._t,queries:e.array(e.unknown()).min(1)}).catchall(e.unknown()),It=e.object({...At,queries:e.array(e.unknown()).min(1).max(5).optional(),combine:e.enum(["independent","merge"]).optional()}).catchall(e.unknown());var Dt=["GitHub","Local Code","Package","Other"],Qt=new Map([d.GITHUB_SEARCH_CODE,d.GITHUB_SEARCH_REPOSITORIES,d.GITHUB_SEARCH_PULL_REQUESTS,d.GITHUB_FETCH_CONTENT,d.GITHUB_VIEW_REPO_STRUCTURE,d.GITHUB_CLONE_REPO,d.LOCAL_RIPGREP,d.LOCAL_FIND_FILES,d.LOCAL_FETCH_CONTENT,d.LOCAL_VIEW_STRUCTURE,A,d.PACKAGE_SEARCH,...oe()?[X]:[]].map((t,o)=>[t,o])),q=class extends Error{constructor(r,i=[]){super(r);this.details=i;this.name="DirectToolInputError"}details},xo=["id","mainResearchGoal","researchGoal","reasoning"],fe=new Set([...xo]),Oo=["id","researchGoal","reasoning"],Nt=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],Ro=[{name:d.GITHUB_SEARCH_CODE,schema:_e,inputSchema:ve},{name:d.GITHUB_FETCH_CONTENT,schema:Le,inputSchema:Ce},{name:d.GITHUB_VIEW_REPO_STRUCTURE,schema:ze,inputSchema:Be},{name:d.GITHUB_SEARCH_REPOSITORIES,schema:Ge,inputSchema:Me},{name:d.GITHUB_SEARCH_PULL_REQUESTS,schema:Ie,inputSchema:De},{name:d.PACKAGE_SEARCH,schema:Ve,inputSchema:Xe},{name:d.GITHUB_CLONE_REPO,schema:ae,inputSchema:ke},{name:d.LOCAL_RIPGREP,schema:at,inputSchema:it},{name:d.LOCAL_VIEW_STRUCTURE,schema:lt,inputSchema:ut},{name:d.LOCAL_FIND_FILES,schema:tt,inputSchema:nt},{name:d.LOCAL_FETCH_CONTENT,schema:Je,inputSchema:Ke},{name:A,schema:gt,inputSchema:ft},{name:d.LOCAL_BINARY_INSPECT,schema:xt,inputSchema:Ot},...oe()?[{name:X,schema:Ft,inputSchema:It}]:[]];function te(t){return Ro.find(o=>o.name===t)}function ee(t){return t.startsWith("gh")?"GitHub":t.startsWith("local")||t.startsWith("lsp")?"Local Code":t===d.PACKAGE_SEARCH?"Package":"Other"}function Di(t){return[...t].sort((o,r)=>{let i=Dt.indexOf(ee(o)),l=Dt.indexOf(ee(r));if(i!==l)return i-l;let s=Qt.get(o)??Number.MAX_SAFE_INTEGER,u=Qt.get(r)??Number.MAX_SAFE_INTEGER;return s!==u?s-u:o.localeCompare(r)})}function Qi(t){let o=te(t);if(!o)return"{}";try{return JSON.stringify(pe.toJSONSchema(o.inputSchema,{io:"input"}),null,2)}catch{return JSON.stringify(pe.toJSONSchema(o.schema,{io:"input"}),null,2)}}function ji(t){return JSON.stringify(t??{},null,2)}function Gi(t){let o=ee(t),r=[...Oo];return(o==="GitHub"||o==="Package")&&r.splice(1,0,"mainResearchGoal"),r}function Mi(){return Nt.map(t=>({...t}))}function Ni(){return JSON.stringify(Object.fromEntries(Nt.map(t=>[t.name,t.optional?`${t.type} (optional)`:t.type])),null,2)}function Hi(t,o){return o?.tools?.[t]?.description??t}function Ht(t){let o=te(t);if(!o)return[];let r=pe.toJSONSchema(o.schema,{io:"input"});if(!M(r))return[];let i=v(r.properties)?r.properties:{},l=new Set(Array.isArray(r.required)?r.required.filter(s=>!fe.has(s)&&!ge(i[s])):[]);return he(i,l)}function jt(t,o){return`tools ${t} --queries '${JSON.stringify(o)}'`}function wo(t){let o=To(t);if(o.length>0)return o.map(i=>({...i,command:jt(t,i.query)}));let r=ko(t);return Object.keys(r).length===0?[]:[{label:"schema-derived",query:r,command:jt(t,r)}]}function zi(t){return wo(t)[0]?.query??{}}function ko(t){if(!te(t))return{};let o=Ht(t),r=o.filter(s=>!s.name.includes(".")),i=Ao(r),l={};for(let s of i)l[s.name]=Qo(s.name,s.type);return t.startsWith("lsp")&&o.some(s=>s.name==="uri")&&(l.uri??="uri"),t===A&&(l.type??="definition",l.symbolName??="symbolName",l.lineHint??=1),l}function To(t){return t===X?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:t===d.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"bgauryy",repo:"octocode",keywordsToSearch:["localSearchCode"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"bgauryy",repo:"octocode",path:"packages/octocode-tools-core/src",since:"2024-01-01T00:00:00Z",perPage:5}}]:t===d.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"bgauryy",repo:"octocode",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["localSearchCode"],owner:"bgauryy",repo:"octocode",extension:"ts",limit:5}}]:t===d.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"bgauryy",concise:!0,limit:5}}]:t===d.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"bgauryy",repo:"octocode",path:"packages",maxDepth:2,itemsPerPage:50}}]:t===d.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"bgauryy",repo:"octocode",sparsePath:"packages/octocode-tools-core"}}]:t===d.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:t===d.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"}}]:t===d.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}}]:t===d.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}}]:t===A?[{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 Bi(t,o,r={}){if(typeof o!="string")return null;let i;try{i=JSON.parse(o)}catch{throw new q("Tool input must be valid JSON.")}return Po(t,i,r)}function Po(t,o,r={}){let i=Co(t,o,r),l=te(t);if(!l)throw new q(`Unknown tool: ${t}`);let s=l.inputSchema.safeParse(i);if(!s.success)throw new q("Tool input does not match the expected schema.",Lo(s.error));return s.data}function Lo(t){return t.issues.map(o=>`${o.path.length>0?o.path.join("."):"input"}: ${o.message}`)}function Co(t,o,r){let i=[];if(Array.isArray(o))i=o;else if(v(o)&&Array.isArray(o.queries))i=o.queries;else if(v(o))i=[o];else throw new q('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(i.length===0)throw new q("At least one query is required.");let l=v(o)&&Array.isArray(o.queries)?Object.fromEntries(Object.entries(o).filter(([u])=>u!=="queries")):{},s=i.map((u,y)=>Eo(t,y,_o(t,u,y,r),{sourceLabel:r.sourceLabel}));return{...l,queries:s}}function Eo(t,o,r,i){let l={...r},s=ee(t),u=i.sourceLabel??"direct tool execution",y=qo(t,u);return(typeof l.id!="string"||l.id.trim().length===0)&&(l.id=`${t}-${o+1}`),(s==="GitHub"||s==="Package")&&(typeof l.mainResearchGoal!="string"||l.mainResearchGoal.trim().length===0)&&(l.mainResearchGoal=y),(typeof l.researchGoal!="string"||l.researchGoal.trim().length===0)&&(l.researchGoal=y),(typeof l.reasoning!="string"||l.reasoning.trim().length===0)&&(l.reasoning=`Executed via ${u} tool command`),l}function qo(t,o){return`Execute ${t} via ${o}`}function _o(t,o,r,i={}){if(!v(o))throw new q("Tool input must be a JSON object or an array of objects.");let l=new Set([...Ht(t).filter(y=>!y.name.includes(".")).map(y=>y.name),...fe]),s={},u=[];for(let[y,_]of Object.entries(o)){if(l.has(y)){s[y]=_;continue}u.push(y)}if(u.length>0&&l.size>0&&(i.onUnknownFields?.(u,r),i.rejectUnknownFields===!0))throw new q(`Unknown field(s): ${u.join(", ")}`,[`Remove unknown field(s) from query ${r+1}: ${u.join(", ")}`,`Run tools ${t} --scheme to see valid fields.`]);return s}function vo(t){let o=[],r=typeof t.minimum=="number"?t.minimum:void 0,i=typeof t.maximum=="number"?t.maximum:void 0;return r!==void 0&&i!==void 0?o.push(`${r}-${i}`):r!==void 0?o.push(`>=${r}`):i!==void 0&&o.push(`<=${i}`),"default"in t&&o.push(`default ${JSON.stringify(t.default)}`),o.length>0?o.join(", "):void 0}function me(t){if(Array.isArray(t.enum)&&t.enum.length>0)return`enum(${t.enum.map(String).join(", ")})`;if(t.type==="array"){let r=M(t.items)?t.items:void 0;return`array<${r?me(r):"value"}>`}let o=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:void 0;if(o){let r=o.filter(M).map(me).filter(i=>i!=="value");if(r.length>0)return[...new Set(r)].join(" | ")}return Array.isArray(t.type)?t.type.join(" | "):typeof t.type=="string"?t.type:"value"}var Gt=4,de=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]]),zt=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function Ao(t){let o=t.filter(s=>s.required),r=new Map;for(let s of o)r.set(s.name,s);let i=t.filter(s=>!s.required&&Fo(s)).sort(Io),l=Math.max(Gt,o.length);for(let s of i){if(r.size>=l)break;r.set(s.name,s)}return r.size>0?[...r.values()]:t.filter(s=>!zt.has(s.name)).filter(s=>s.type!=="boolean").slice(0,Gt)}function Fo(t){return zt.has(t.name)||t.type==="boolean"?!1:Do(t)?de.has(t.name):!0}function Io(t,o){let r=de.get(t.name)??Number.MAX_SAFE_INTEGER,i=de.get(o.name)??Number.MAX_SAFE_INTEGER;return r!==i?r-i:t.name.localeCompare(o.name)}function Do(t){return t.constraints?.includes("default ")===!0}function he(t,o,r=""){let i=[];for(let[l,s]of Object.entries(t)){if(!r&&fe.has(l))continue;let u=M(s)?s:{},y=r?`${r}.${l}`:l;if(i.push({name:y,required:o.has(l),type:me(u),constraints:vo(u),description:typeof u.description=="string"?u.description:void 0}),v(u.properties)){let ne=new Set(Array.isArray(u.required)?u.required.filter(H=>typeof H=="string"?!ge(u.properties?.[H]):!1):[]);i.push(...he(u.properties,ne,y))}let _=u.type==="array"&&M(u.items)?u.items:void 0;if(_&&v(_.properties)){let ne=new Set(Array.isArray(_.required)?_.required.filter(H=>typeof H=="string"?!ge(_.properties?.[H]):!1):[]);i.push(...he(_.properties,ne,y))}}return i}function Qo(t,o){if(o.startsWith("array<")){let r=o.slice(6,-1);return[Mt(t,r)]}return Mt(t,o)}function Mt(t,o){if(o.startsWith("enum("))return/^enum\(([^,)]+)/.exec(o)?.[1]??t;if(o==="integer"||o==="number")return t==="lineHint"?42:5;if(o==="boolean")return!0;switch(t){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"bgauryy";case"repo":return"octocode";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"zod";default:return t}}function v(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function M(t){return v(t)}function ge(t){return M(t)&&"default"in t}var Bt={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 N={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:j,reservedTargets:Y,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" vercel/next.js',"package lookup (npm)":"search zod --target packages","PR deep read (GitHub)":"search vercel/next.js#1 --target pullRequests --comments --patches","commit history (GitHub)":"search vercel/next.js/packages/next/src --target commits --since 2024-01-01T00:00:00Z","browse a tree (local dir or owner/repo)":"search ./src --tree | search vercel/next.js --tree","read a file (local or owner/repo/path)":"search ./src/index.ts | search vercel/next.js/packages/next/src/server/config.ts","read a remote file (exact)":"search vercel/next.js/README.md --content-view exact","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","artifact inspect/list":"search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect","PR diff (GitHub)":"search vercel/next.js#123 --target diff | search vercel/next.js --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 }" vercel/next.js/packages/next/src --lang ts --materialize auto',"GitHub index miss recovery":"search useState packages/next/src --repo vercel/next.js --materialize required | clone vercel/next.js/packages/next/src | cache fetch vercel/next.js packages/next/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},semanticsGuide:{documentSymbols:"list a file's symbols to get line anchors first (run before references/callers/hover)",references:"all usages of a symbol across the workspace (often includes its declaration)",callers:"incoming calls to a function/method (call sites only) \u2014 narrower than references",hover:"type, signature, and docs at a symbol"},query:{schema:'"oql" (inserted by normalization)',target:j.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?:"relevance"|"matchCount"|"path"|"modified"|"accessed"|"created"|"size"|"name", sortReverse?, rankingProfile?, debugRanking? }, budget?: { maxFiles?, maxCandidates?, maxBytes?, maxMaterializedBytes?, maxPlanNodes?, maxBooleanExpansion?, timeoutMs? } } \u2014 output/cost controls; sort values "size"/"name" apply to target:"files" only (lowered to localFindFiles sortBy), the rest are code-search sorts',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:"=") SCOPE: field predicates evaluate file attributes, so they run on target:"files" (and mixed into files-lane booleans); target:"code" rejects a bare field predicate with unsupportedPredicate \u2014 use text/regex/structural for code content, or target:"files" for file discovery.',boolean:'{ kind:"all"|"any", of: Predicate[] } | { kind:"not", predicate }',booleanSugar:"Top-level sugar keys lower to canonical booleans at normalize time: and:[...]\u2192all, or:[...]\u2192any, noneOf:[...]\u2192not(any), xor:[a,b]\u2192any(all(a,not b),all(not a,b)), oneOf:[...]\u2192exactly-one expansion (bounded by controls.budget.maxBooleanExpansion), invert:true\u2192not(where). Prefer canonical all/any/not in programmatic queries; sugar is for terse hand-written ones."},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:Bt};function jo(){return JSON.stringify(N,null,2)}function Ut(t){let o="shorthand: ",r=t.indexOf(o);if(r===-1)return null;let i=t.slice(r+o.length).trim(),l=i.length,s=i.indexOf(",");s!==-1&&(l=Math.min(l,s));let u=i.search(/\.\s/);return u!==-1&&(l=Math.min(l,u)),i.slice(0,l).trim().replace(/\.$/,"")||null}function $t(){let t=[],o=new Set;for(let[r,i]of Object.entries(N.targetDecisionTree))for(let l of i.matchAll(/target:"?(\w+)"?/g)){let s=l[1];!s||o.has(s)||(o.add(s),t.push({target:s,task:r}))}for(let r of N.activeTargets)o.has(r)||(o.add(r),t.push({target:r,task:"advanced target; see full schema"}));return t}function Go(){let t=N,o=["local","github","npm","materialized"],r=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],i=t.quickStart,l=t.agentBestPractices.find(s=>/snippet/i.test(s));return{schema:"oql",kind:"octocode.search.compactScheme",description:t.description,sources:Object.fromEntries(o.map(s=>[s,Ut(t.sourceGuide[s])??"a prior clone / cache fetch / materialize localPath"])),targets:$t(),recipes:Object.fromEntries(r.map(s=>[s,i[s]]).filter(s=>typeof s[1]=="string")),semantics:t.semanticsGuide,proof:{snippets:l,providerUnindexed:t.evidenceSemantics.providerUnindexed},commands:{explain:"search --explain --query '{...}'",fullSchema:"search --scheme"}}}function Mo(){return JSON.stringify(Go(),null,2)}function No(){let t=N,o=["octocode search \u2014 compact agent guide (full reference: search --scheme)","","SOURCE \u2014 where to look (choose one):"],r=["local","github","npm","materialized"];for(let u of r){let y=Ut(t.sourceGuide[u]);o.push(` ${u.padEnd(13)}${y??"a prior clone / cache fetch / materialize localPath"}`)}o.push("","TARGET \u2014 answer type (--target, or inferred from the args):");for(let{target:u,task:y}of $t())o.push(` ${u.padEnd(13)}${y}`);o.push("","COMMON RECIPES:");let i=["text search (local)","text search (GitHub)","read a remote file (exact)","package lookup (npm)","semantics (local/materialized)"],l=t.quickStart;for(let u of i){let y=l[u];y&&o.push(` ${y}`)}o.push("","LSP SEMANTICS (run documentSymbols first, then narrow):");for(let[u,y]of Object.entries(t.semanticsGuide))o.push(` ${u.padEnd(16)}${y}`);o.push("","PROOF \u2014 snippets are discovery, not proof:");let s=t.agentBestPractices.find(u=>/snippet/i.test(u));return s&&o.push(` ${s}`),o.push(` ${t.evidenceSemantics.providerUnindexed}`),o.push("","Routing debug: search --explain --query '{...}'","Full schema: search --scheme"),o.join(`
|
|
9
|
+
`)}import{completeMetadata as Ho}from"@octocodeai/octocode-core";var ye=null;function zo(){return ye||(ye=Ho),ye}async function Bo(){return zo()}export{Dt as DIRECT_TOOL_CATEGORIES,Ro as DIRECT_TOOL_DEFINITIONS,q as DirectToolInputError,N as OQL_SCHEMA_DOC,wo as buildDirectToolCommandPatterns,zi as buildDirectToolExampleQuery,te as findDirectToolDefinition,jt as formatDirectToolCommandPattern,ji as formatDirectToolMetadataSchemaText,Ni as formatDirectToolOutputSchemaText,Qi as formatDirectToolSchemaText,Lo as formatDirectToolValidationIssues,Gi as getDirectToolAutoFilledFields,ee as getDirectToolCategory,Hi as getDirectToolDescription,Ht as getDirectToolDisplayFields,Mi as getDirectToolOutputFields,Bo as loadToolContent,Mo as oqlCompactSchemeJson,No as oqlCompactSchemeText,jo as oqlSchemaText,Po as prepareDirectToolInput,Bi as prepareDirectToolInputFromJsonText,Di as sortDirectToolNames};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical pagination schemas for all direct tools.
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth — every tool output schema composes from these.
|
|
5
|
+
* No compatibility aliases: each concept has exactly one name.
|
|
6
|
+
*/
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
export declare const ItemPaginationSchema: z.ZodObject<{
|
|
9
|
+
currentPage: z.ZodNumber;
|
|
10
|
+
totalPages: z.ZodNumber;
|
|
11
|
+
hasMore: z.ZodBoolean;
|
|
12
|
+
nextPage: z.ZodOptional<z.ZodNumber>;
|
|
13
|
+
pageSize: z.ZodOptional<z.ZodNumber>;
|
|
14
|
+
totalItems: z.ZodOptional<z.ZodNumber>;
|
|
15
|
+
}, z.core.$strip>;
|
|
16
|
+
export type ItemPagination = z.infer<typeof ItemPaginationSchema>;
|
|
17
|
+
export declare const CharPaginationSchema: z.ZodObject<{
|
|
18
|
+
charOffset: z.ZodNumber;
|
|
19
|
+
charLength: z.ZodNumber;
|
|
20
|
+
totalChars: z.ZodNumber;
|
|
21
|
+
hasMore: z.ZodBoolean;
|
|
22
|
+
nextCharOffset: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
currentPage: z.ZodOptional<z.ZodNumber>;
|
|
24
|
+
totalPages: z.ZodOptional<z.ZodNumber>;
|
|
25
|
+
chunkMode: z.ZodOptional<z.ZodEnum<{
|
|
26
|
+
semantic: "semantic";
|
|
27
|
+
"char-limit": "char-limit";
|
|
28
|
+
}>>;
|
|
29
|
+
}, z.core.$strip>;
|
|
30
|
+
export type CharPagination = z.infer<typeof CharPaginationSchema>;
|
|
31
|
+
export declare const ToolContinuationSchema: z.ZodObject<{
|
|
32
|
+
tool: z.ZodString;
|
|
33
|
+
query: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
34
|
+
why: z.ZodOptional<z.ZodString>;
|
|
35
|
+
confidence: z.ZodOptional<z.ZodEnum<{
|
|
36
|
+
exact: "exact";
|
|
37
|
+
heuristic: "heuristic";
|
|
38
|
+
}>>;
|
|
39
|
+
}, z.core.$strip>;
|
|
40
|
+
export type ToolContinuation = z.infer<typeof ToolContinuationSchema>;
|
|
41
|
+
export declare const ToolDiagnosticSchema: z.ZodObject<{
|
|
42
|
+
level: z.ZodEnum<{
|
|
43
|
+
error: "error";
|
|
44
|
+
info: "info";
|
|
45
|
+
warning: "warning";
|
|
46
|
+
}>;
|
|
47
|
+
message: z.ZodString;
|
|
48
|
+
field: z.ZodOptional<z.ZodString>;
|
|
49
|
+
code: z.ZodOptional<z.ZodString>;
|
|
50
|
+
}, z.core.$strip>;
|
|
51
|
+
export type ToolDiagnostic = z.infer<typeof ToolDiagnosticSchema>;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
export declare const responseEnvelopeFields: {
|
|
3
|
-
readonly hints: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
4
3
|
readonly base: z.ZodOptional<z.ZodString>;
|
|
5
4
|
readonly shared: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>>;
|
|
6
5
|
readonly responsePagination: z.ZodOptional<z.ZodObject<{
|
|
@@ -14,3 +13,70 @@ export declare const responseEnvelopeFields: {
|
|
|
14
13
|
}, z.core.$strip>>;
|
|
15
14
|
};
|
|
16
15
|
export declare function withResponseEnvelope<S extends z.ZodObject>(schema: S): S;
|
|
16
|
+
export declare function makeToolResultRowSchema<TData extends z.ZodTypeAny>(dataSchema: TData): z.ZodObject<{
|
|
17
|
+
id: z.ZodString;
|
|
18
|
+
status: z.ZodOptional<z.ZodEnum<{
|
|
19
|
+
empty: "empty";
|
|
20
|
+
error: "error";
|
|
21
|
+
}>>;
|
|
22
|
+
data: TData;
|
|
23
|
+
diagnostics: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
24
|
+
level: z.ZodEnum<{
|
|
25
|
+
error: "error";
|
|
26
|
+
info: "info";
|
|
27
|
+
warning: "warning";
|
|
28
|
+
}>;
|
|
29
|
+
message: z.ZodString;
|
|
30
|
+
field: z.ZodOptional<z.ZodString>;
|
|
31
|
+
code: z.ZodOptional<z.ZodString>;
|
|
32
|
+
}, z.core.$strip>>>;
|
|
33
|
+
next: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
34
|
+
tool: z.ZodString;
|
|
35
|
+
query: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
36
|
+
why: z.ZodOptional<z.ZodString>;
|
|
37
|
+
confidence: z.ZodOptional<z.ZodEnum<{
|
|
38
|
+
exact: "exact";
|
|
39
|
+
heuristic: "heuristic";
|
|
40
|
+
}>>;
|
|
41
|
+
}, z.core.$strip>>>;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
export declare const GenericToolResultRowSchema: z.ZodObject<{
|
|
44
|
+
id: z.ZodString;
|
|
45
|
+
status: z.ZodOptional<z.ZodEnum<{
|
|
46
|
+
empty: "empty";
|
|
47
|
+
error: "error";
|
|
48
|
+
}>>;
|
|
49
|
+
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
50
|
+
diagnostics: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
51
|
+
level: z.ZodEnum<{
|
|
52
|
+
error: "error";
|
|
53
|
+
info: "info";
|
|
54
|
+
warning: "warning";
|
|
55
|
+
}>;
|
|
56
|
+
message: z.ZodString;
|
|
57
|
+
field: z.ZodOptional<z.ZodString>;
|
|
58
|
+
code: z.ZodOptional<z.ZodString>;
|
|
59
|
+
}, z.core.$strip>>>;
|
|
60
|
+
next: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
61
|
+
tool: z.ZodString;
|
|
62
|
+
query: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
63
|
+
why: z.ZodOptional<z.ZodString>;
|
|
64
|
+
confidence: z.ZodOptional<z.ZodEnum<{
|
|
65
|
+
exact: "exact";
|
|
66
|
+
heuristic: "heuristic";
|
|
67
|
+
}>>;
|
|
68
|
+
}, z.core.$strip>>>;
|
|
69
|
+
}, z.core.$strip>;
|
|
70
|
+
export declare const bulkOutputEnvelopeFields: {
|
|
71
|
+
readonly base: z.ZodOptional<z.ZodString>;
|
|
72
|
+
readonly shared: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>>;
|
|
73
|
+
readonly responsePagination: z.ZodOptional<z.ZodObject<{
|
|
74
|
+
currentPage: z.ZodNumber;
|
|
75
|
+
totalPages: z.ZodNumber;
|
|
76
|
+
hasMore: z.ZodBoolean;
|
|
77
|
+
charOffset: z.ZodNumber;
|
|
78
|
+
charLength: z.ZodNumber;
|
|
79
|
+
totalChars: z.ZodNumber;
|
|
80
|
+
nextCharOffset: z.ZodOptional<z.ZodNumber>;
|
|
81
|
+
}, z.core.$strip>>;
|
|
82
|
+
};
|
|
@@ -1,9 +1,2 @@
|
|
|
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
1
|
export { OctocodeConfigSchema } from './schemas.js';
|
|
2
|
+
export { setRuntimeSurface, invalidateConfigCache } from '@octocodeai/config';
|
|
@@ -5,5 +5,4 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
|
|
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 Oe(e){let n=me(e);return JSON.parse(n)}function he(){return z(y)}async function Re(){return U()}function U(){let e=y;if(!z(e))return{success:!1,error:"Config file does not exist",path:e};try{let n=Ce(e,"utf-8");if(!n.trim())return{success:!0,config:{},path:e};let o=Oe(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 Te(){return y}function _e(){return F.home}function Ee(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 J(e,n){return e==null?null:typeof e!="boolean"?`${n}: Must be a boolean`:null}function Q(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:Q(e,n)}function Y(e,n){return e==null?null:typeof e!="string"?`${n}: Must be a string`:null}function Le(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("github: Must be an object");return}let t=Ee(e.apiUrl,"github.apiUrl");t&&n.push(t)}function Ae(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=J(o.enabled,"local.enabled");t&&n.push(t);let r=J(o.enableClone,"local.enableClone");r&&n.push(r);let i=Q(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=Y(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 ve(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 we(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 xe(e,n){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){n.push("lsp: Must be an object");return}let t=Y(e.configPath,"lsp.configPath");t&&n.push(t)}function ye(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}`)),Le(t.github,n),Ae(t.local,n),ve(t.tools,n),we(t.network,n),xe(t.lsp,n),ye(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 Ue(e){globalThis[j]=e}function $(){return globalThis[j]??"mcp"}function Ne(){delete globalThis[j]}function Z(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 ee(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||A.apiUrl}}function ne(e){let n=$()==="cli",o=Z(process.env.ENABLE_LOCAL),t=Z(process.env.ENABLE_CLONE),r=N(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled: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 oe(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 te(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 re(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??v.configPath}}var Se=new Set(["yaml","json"]);function ie(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:Se.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:ee(e?.github),local:ne(e?.local),tools:oe(e?.tools),network:te(e?.network),lsp:re(e?.lsp),output:ie(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 se(){return S()}var c=null,E=0,ke=6e4;function b(){let e=Date.now();return c&&e-E<ke||(c=S(),E=e),c}async function X(){return b()}async function ue(){return V(),X()}function V(){c=null,E=0}function ae(){c=null,E=0}function fe(){return{cached:c!==null,timestamp:E}}function Ie(e){let n=b(),o=e.split("."),t=n;for(let r of o){if(t==null||typeof t!="object")return;t=t[r]}return t}export{le 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,fe as _getCacheState,ae as _resetConfigCache,Ne as _resetRuntimeSurface,he as configExists,X as getConfig,Te as getConfigPath,b as getConfigSync,Ie as getConfigValue,_e as getOctocodeDir,$ as getRuntimeSurface,V as invalidateConfigCache,Re as loadConfig,U as loadConfigSync,ue as reloadConfig,se as resolveConfig,S as resolveConfigSync,Ue as setRuntimeSurface,q as validateConfig};
|
|
8
|
+
import{z as t}from"zod";var n=t.looseObject({$schema:t.string().optional(),version:t.number().int().optional(),github:t.record(t.string(),t.unknown()).optional(),local:t.record(t.string(),t.unknown()).optional(),tools:t.record(t.string(),t.unknown()).optional(),network:t.record(t.string(),t.unknown()).optional(),lsp:t.record(t.string(),t.unknown()).optional(),output:t.record(t.string(),t.unknown()).optional()});import f from"node:fs";import d from"node:path";import h from"node:os";import O from"node:path";import{existsSync as m,readFileSync as T}from"node:fs";import _ from"node:path";var o="__octocodeRuntimeSurface__";function r(e){globalThis[o]=e}var i=null,s=0;function a(){i=null,s=0}export{n as OctocodeConfigSchema,a as invalidateConfigCache,r as setRuntimeSurface};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
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,
|
|
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, } from './storage.js';
|
|
3
3
|
export { getGhCliToken } from './ghCli.js';
|