@octocodeai/octocode-tools-core 16.6.0 → 16.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +176 -248
- package/dist/direct.js +34 -35
- package/dist/errors/localToolErrors.d.ts +1 -0
- package/dist/index.js +39 -40
- package/dist/oql/adapters/local.d.ts +1 -0
- package/dist/oql/envelope.d.ts +2 -0
- package/dist/oql/index.d.ts +2 -1
- package/dist/oql/index.js +34 -34
- package/dist/oql/schemeText.d.ts +16 -0
- package/dist/oql/types.d.ts +7 -0
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +2 -1
- package/dist/shared/config/index.js +2 -2
- package/dist/shared/config/runtimeSurface.d.ts +5 -4
- package/dist/shared/credentials/envTokens.d.ts +1 -1
- package/dist/shared/credentials/index.js +1 -1
- package/dist/shared/credentials/types.d.ts +1 -1
- package/dist/shared/paths.d.ts +2 -1
- package/dist/shared/paths.js +1 -1
- package/dist/shared/session/index.js +1 -1
- package/dist/tools/directToolCatalog.meta.d.ts +1 -0
- package/dist/tools/github_fetch_content/scheme.d.ts +0 -82
- package/dist/tools/local_binary_inspect/binaryInspector.d.ts +0 -4
- package/dist/tools/lsp/semantic_content/scheme.d.ts +0 -14
- package/dist/tools/lsp/shared/semanticTypes.d.ts +2 -2
- package/dist/tools/package_search/execution.d.ts +23 -0
- package/dist/tools/package_search/scheme.d.ts +8 -0
- package/dist/tools/toolNames.d.ts +1 -1
- package/dist/types/server.d.ts +1 -1
- package/package.json +6 -3
package/dist/oql/schemeText.d.ts
CHANGED
|
@@ -42,6 +42,7 @@ export declare const OQL_SCHEMA_DOC: {
|
|
|
42
42
|
readonly 'commit history (GitHub)': "search facebook/react/packages/react/src --target commits --since 2024-01-01T00:00:00Z";
|
|
43
43
|
readonly 'browse a tree (local dir or owner/repo)': "search ./src --tree | search facebook/react --tree";
|
|
44
44
|
readonly 'read a file (local or owner/repo/path)': "search ./src/index.ts | search facebook/react/packages/react/src/index.js";
|
|
45
|
+
readonly 'read a remote file (exact)': "search facebook/react/README.md --content-view exact";
|
|
45
46
|
readonly 'semantics (local/materialized)': "search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42";
|
|
46
47
|
readonly 'artifact inspect/list': "search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect";
|
|
47
48
|
readonly 'PR diff (GitHub)': "search facebook/react#123 --target diff | search facebook/react --target diff --pr 123";
|
|
@@ -69,6 +70,12 @@ export declare const OQL_SCHEMA_DOC: {
|
|
|
69
70
|
readonly 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.";
|
|
70
71
|
readonly 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.";
|
|
71
72
|
};
|
|
73
|
+
readonly semanticsGuide: {
|
|
74
|
+
readonly documentSymbols: "list a file's symbols to get line anchors first (run before references/callers/hover)";
|
|
75
|
+
readonly references: "all usages of a symbol across the workspace (often includes its declaration)";
|
|
76
|
+
readonly callers: "incoming calls to a function/method (call sites only) — narrower than references";
|
|
77
|
+
readonly hover: "type, signature, and docs at a symbol";
|
|
78
|
+
};
|
|
72
79
|
readonly query: {
|
|
73
80
|
readonly schema: "\"oql\" (inserted by normalization)";
|
|
74
81
|
readonly target: string;
|
|
@@ -136,3 +143,12 @@ export declare const OQL_SCHEMA_DOC: {
|
|
|
136
143
|
};
|
|
137
144
|
};
|
|
138
145
|
export declare function oqlSchemaText(): string;
|
|
146
|
+
export declare function oqlCompactSchemeJson(): string;
|
|
147
|
+
/**
|
|
148
|
+
* Lean, agent-facing summary of the OQL contract, served by
|
|
149
|
+
* `octocode search --scheme --compact`. Every section is DERIVED from
|
|
150
|
+
* `OQL_SCHEMA_DOC` (sourceGuide, targetDecisionTree, quickStart, semanticsGuide,
|
|
151
|
+
* agentBestPractices, evidenceSemantics) so it can never drift from the full
|
|
152
|
+
* `--scheme`. Cold agents read this; advanced flows stay in the full schema.
|
|
153
|
+
*/
|
|
154
|
+
export declare function oqlCompactSchemeText(): string;
|
package/dist/oql/types.d.ts
CHANGED
|
@@ -410,6 +410,7 @@ export interface OqlPackageData {
|
|
|
410
410
|
description?: string;
|
|
411
411
|
downloads?: number;
|
|
412
412
|
repository?: string;
|
|
413
|
+
repositoryId?: string;
|
|
413
414
|
[k: string]: unknown;
|
|
414
415
|
}
|
|
415
416
|
export interface OqlPullRequestData {
|
|
@@ -596,6 +597,10 @@ export interface OqlContinuation {
|
|
|
596
597
|
query: OqlCanonicalInput;
|
|
597
598
|
baseQueryId?: string;
|
|
598
599
|
queryIndex?: number;
|
|
600
|
+
why?: string;
|
|
601
|
+
confidence?: 'exact' | 'heuristic';
|
|
602
|
+
}
|
|
603
|
+
export interface OqlContinuationHint {
|
|
599
604
|
why: string;
|
|
600
605
|
confidence: 'exact' | 'heuristic';
|
|
601
606
|
}
|
|
@@ -604,8 +609,10 @@ export interface OqlResultEnvelope {
|
|
|
604
609
|
queryId?: string;
|
|
605
610
|
queryIndex?: number;
|
|
606
611
|
results: OqlProofGradedResultRow[];
|
|
612
|
+
shared?: Record<string, unknown>;
|
|
607
613
|
pagination?: Pagination;
|
|
608
614
|
next?: Record<string, OqlContinuation>;
|
|
615
|
+
nextHints?: Record<string, OqlContinuationHint>;
|
|
609
616
|
diagnostics: OqlDiagnostic[];
|
|
610
617
|
provenance: OqlProvenance[];
|
|
611
618
|
evidence: {
|
package/dist/schema.d.ts
CHANGED
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
* For execution, import `executeDirectTool` from `@octocodeai/octocode-tools-core/direct`.
|
|
10
10
|
*/
|
|
11
11
|
export * from './tools/directToolCatalog.meta.js';
|
|
12
|
-
export { oqlSchemaText, OQL_SCHEMA_DOC } from './oql/schemeText.js';
|
|
12
|
+
export { oqlSchemaText, oqlCompactSchemeText, oqlCompactSchemeJson, OQL_SCHEMA_DOC, } from './oql/schemeText.js';
|
|
13
13
|
export { loadToolContent } from './tools/toolMetadata/state.js';
|
package/dist/schema.js
CHANGED
|
@@ -5,4 +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 Ft}from"@octocodeai/octocode-core";var p=Ft.toolNames,P=p.LSP_GET_SEMANTIC_CONTENT,N="oqlSearch",dr=new Set([p.LOCAL_RIPGREP,p.LOCAL_FETCH_CONTENT,p.LOCAL_FIND_FILES,p.LOCAL_VIEW_STRUCTURE,p.LOCAL_BINARY_INSPECT,P]);var ce=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"];import{CloneRepoQuerySchema as Nt}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as Ht}from"@octocodeai/octocode-core/schemas/outputs";import{z as H}from"zod";function l(n,r){return H.preprocess(o=>typeof o=="number"&&Number.isFinite(o)?Math.min(Math.max(o,n),r):o,H.number().int().min(n).max(r))}var f=l(1,1e3).optional().default(1),E=l(0,100).optional(),_=l(1,1e9).optional(),Dt={responseCharOffset:l(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:l(1,5e4).optional().describe("Full-response char window.")};function g(n,r={}){let{maxQueries:o=5}=r;return H.object({queries:H.array(n).min(1).max(o).describe("Parallel queries."),...Dt}).superRefine((i,c)=>{let u=new Set;i.queries.forEach((d,S)=>{d&&typeof d=="object"&&"id"in d&&typeof d.id=="string"&&(u.has(d.id)&&c.addIssue({code:"custom",message:`Duplicate query id "${d.id}" at index ${S}`,path:["queries",S,"id"]}),u.add(d.id))})})}import{z as le}from"zod";function Qt(n,r){return n?.description&&!r.description?r.describe(n.description):r}function ue(n,r){let o={};for(let[i,c]of Object.entries(r))o[i]=Qt(n.shape[i],c);return o}function Mt(n,r){let o=n;return o.safeExtend?o.safeExtend(r):n.extend(r)}function pe(n,r){if(!r?.length)return n;let o=new Set(r);return le.object(Object.fromEntries(Object.entries(n.shape).filter(([i])=>!o.has(i))))}function y(n,r={},o={}){let i=pe(n,o.omit),c=Mt(i,ue(i,r));return o.strict?c.strict():c}function b(n,r={},o={}){let i=pe(n,o.omit),c=le.object({...i.shape,...ue(i,r)});return o.strict?c.strict():c}import{z as x}from"zod";var Gt=x.object({currentPage:x.number(),totalPages:x.number(),hasMore:x.boolean(),charOffset:x.number(),charLength:x.number(),totalChars:x.number(),nextCharOffset:x.number().optional()}).optional(),O={hints:x.array(x.string()).optional(),base:x.string().optional(),shared:x.record(x.string(),x.union([x.string(),x.number(),x.boolean()])).optional(),responsePagination:Gt};var X=y(Nt),me=g(X),_r=Ht.extend(O);import{z as a}from"zod";import{FileContentQuerySchema as ge}from"@octocodeai/octocode-core/schemas";var jt=a.enum(["none","standard","symbols"]).optional().default("standard"),Bt=a.object({currentPage:a.number(),totalPages:a.number(),hasMore:a.boolean(),nextPage:a.number().optional(),nextMatchPage:a.number().optional(),charOffset:a.number().optional(),charLength:a.number().optional(),totalChars:a.number().optional(),nextCharOffset:a.number().optional(),filesPerPage:a.number().optional(),totalFiles:a.number().optional(),entriesPerPage:a.number().optional(),totalEntries:a.number().optional(),matchesPerPage:a.number().optional(),totalMatches:a.number().optional()}),de=a.object({path:a.string(),content:a.string(),localPath:a.string().optional(),repoRoot:a.string().optional(),contentView:a.enum(["none","standard","symbols"]).optional(),isSkeleton:a.boolean().optional(),totalLines:a.number().optional(),sourceChars:a.number().optional(),sourceBytes:a.number().optional(),resolvedBranch:a.string().optional(),pagination:Bt.optional(),isPartial:a.boolean().optional(),startLine:a.number().optional(),endLine:a.number().optional(),matchRanges:a.array(a.object({start:a.number(),end:a.number()})).optional(),lastModified:a.string().optional(),lastModifiedBy:a.string().optional(),warnings:a.array(a.string()).optional(),matchNotFound:a.boolean().optional(),searchedFor:a.string().optional(),cached:a.boolean().optional()}),he=a.object({path:a.string(),localPath:a.string(),repoRoot:a.string().optional(),fileCount:a.number(),totalSize:a.number(),complete:a.boolean().optional(),directoryEntryCount:a.number().optional(),eligibleFileCount:a.number().optional(),savedFileCount:a.number().optional(),skipped:a.object({nonFile:a.number(),missingDownloadUrl:a.number(),oversized:a.number(),binary:a.number(),fileLimit:a.number(),fetchFailed:a.number(),totalSizeLimit:a.number(),pathTraversal:a.number()}).optional(),limits:a.object({maxDirectoryFiles:a.number(),maxTotalSize:a.number(),maxFileSize:a.number()}).optional(),warnings:a.array(a.string()).optional(),files:a.array(a.object({path:a.string(),size:a.number(),type:a.string()})).optional(),cached:a.boolean().optional(),resolvedBranch:a.string().optional()}),fe={startLine:_,endLine:_,contextLines:E,charOffset:l(0,1e8).optional(),charLength:l(1,5e4).optional(),minify:jt},zt=b(ge,fe),ye=y(ge,fe),be=g(zt),Mr=a.object({base:a.string().optional(),shared:a.record(a.string(),a.union([a.string(),a.number(),a.boolean()])).optional(),responsePagination:O.responsePagination,results:a.array(a.object({id:a.string(),owner:a.string(),repo:a.string(),files:a.array(de).optional(),directories:a.array(he).optional(),data:a.object({owner:a.string(),repo:a.string(),files:a.array(de).optional(),directories:a.array(he).optional()}).optional()})),errors:a.array(a.object({id:a.string(),owner:a.string().optional(),repo:a.string().optional(),path:a.string().optional(),error:a.string()})).optional()});import{z as s}from"zod";import{GitHubCodeSearchQuerySchema as Se}from"@octocodeai/octocode-core/schemas";var xe={limit:l(1,100).optional(),page:f.default(1)},Re=y(Se,xe),Oe=g(b(Se,xe)),$r=s.object({base:s.string().optional(),shared:s.record(s.string(),s.union([s.string(),s.number(),s.boolean()])).optional(),responsePagination:O.responsePagination,results:s.array(s.object({id:s.string(),data:s.object({files:s.array(s.object({owner:s.string(),repo:s.string(),path:s.string(),queryId:s.string().optional(),matches:s.array(s.object({value:s.string().optional(),pathOnly:s.boolean().optional(),matchIndices:s.array(s.object({start:s.number(),end:s.number(),lineOffset:s.number()})).optional(),url:s.string().optional()}))})),pagination:s.object({currentPage:s.number(),totalPages:s.number(),perPage:s.number(),totalMatches:s.number(),reportedTotalMatches:s.number().optional(),reachableTotalMatches:s.number().optional(),totalMatchesKind:s.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:s.boolean().optional(),hasMore:s.boolean(),nextPage:s.number().optional(),uniqueFileCount:s.number().optional()}).optional()})})),emptyQueries:s.array(s.object({id:s.string(),nonExistentScope:s.literal(!0).optional(),incompleteResults:s.literal(!0).optional()})).optional(),warnings:s.array(s.string()).optional(),errors:s.array(s.object({id:s.string(),error:s.string()})).optional()});import{z as L}from"zod";import{GitHubPullRequestSearchQuerySchema as we}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as Xt}from"@octocodeai/octocode-core/schemas/outputs";var Te={perPage:l(1,100).optional().default(30),prNumber:l(1,1e9).optional(),limit:l(1,100).optional().default(30),page:f.default(1),filePage:f.optional(),commentPage:f.optional(),commitPage:f.optional(),itemsPerPage:l(1,100).optional().default(20),charOffset:l(0,1e8).optional(),commentBodyOffset:l(0,1e8).optional(),charLength:l(1,5e4).optional()},Wt=b(we,Te),ke=y(we,Te),Pe=g(Wt),to=Xt.extend({results:L.array(L.object({id:L.string().optional(),status:L.string().optional(),data:L.object({pull_requests:L.array(L.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...O});import{z as m}from"zod";import{GitHubReposSearchSingleQuerySchema as Le}from"@octocodeai/octocode-core/schemas";var Ce={limit:l(1,100).optional(),page:f.default(1)},Ee=y(Le,Ce),_e=g(b(Le,Ce)),Zt=m.object({owner:m.string(),repo:m.string(),stars:m.number().optional(),forks:m.number().optional(),openIssuesCount:m.number().optional(),language:m.string().optional(),license:m.string().optional(),description:m.string().optional(),homepage:m.string().optional(),pushedAt:m.string().optional(),createdAt:m.string().optional(),defaultBranch:m.string().optional(),topics:m.array(m.string()).optional(),visibility:m.string().optional(),url:m.string().optional(),updatedAt:m.string().optional()}),Jt=m.object({currentPage:m.number(),totalPages:m.number(),hasMore:m.boolean(),perPage:m.number().optional(),totalMatches:m.number().optional(),reportedTotalMatches:m.number().optional(),reachableTotalMatches:m.number().optional(),totalMatchesKind:m.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:m.boolean().optional(),nextPage:m.number().optional()}).optional(),Kt=m.object({repositories:m.array(m.union([m.string(),Zt])).optional(),pagination:Jt}).passthrough(),lo=m.object({results:m.array(m.object({id:m.string().optional(),status:m.string().optional(),data:Kt.optional()}).passthrough()).optional()}).extend(O);import{GitHubViewRepoStructureQuerySchema as Ae}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as en}from"@octocodeai/octocode-core/schemas/outputs";var qe={maxDepth:l(0,20).optional(),page:f.default(1),itemsPerPage:l(1,200).optional()},ve=y(Ae,qe),Fe=g(b(Ae,qe)),So=en.extend(O);import{z as h}from"zod";import{NpmPackageQuerySchema as Ie}from"@octocodeai/octocode-core/schemas";var De={page:f,mode:h.enum(["lean","full"]).optional()},Qe=y(Ie,De),Me=g(b(Ie,De,{strict:!0}),{maxQueries:5}),Po=h.object({results:h.array(h.looseObject({id:h.string(),data:h.looseObject({packages:h.array(h.object({name:h.string(),version:h.string().optional(),description:h.string().optional(),license:h.string().optional(),downloads:h.number().optional(),repository:h.string().optional(),repositoryDirectory:h.string().optional(),next:h.record(h.string(),h.unknown()).optional()}).passthrough()).optional(),pagination:h.object({currentPage:h.number(),totalPages:h.number(),perPage:h.number(),totalFound:h.number(),returned:h.number(),hasMore:h.boolean(),nextPage:h.number().optional()}).optional()}).optional(),status:h.string().optional()})).optional()}).extend(O);import{z as tn}from"zod";import{FetchContentQuerySchema as Ge}from"@octocodeai/octocode-core/schemas";var nn=tn.enum(["none","standard","symbols"]).optional().default("standard"),Ne={startLine:_,endLine:_,contextLines:E.default(5),charOffset:l(0,1e8).optional(),charLength:l(1,5e4).optional(),minify:nn},rn=b(Ge,Ne),He=y(Ge,Ne),je=g(rn,{maxQueries:5});import{z as on}from"zod";import{FindFilesQuerySchema as an}from"@octocodeai/octocode-core/schemas";var Be={maxDepth:l(0,100).optional(),minDepth:l(0,100).optional(),limit:l(1,1e4).optional(),page:f.default(1),itemsPerPage:l(1,50).optional()},ze=on.object(Object.fromEntries(Object.entries(an.shape).filter(([n])=>n!=="regexType")));function sn(n,r){n.minDepth!==void 0&&n.maxDepth!==void 0&&n.minDepth>n.maxDepth&&r.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var cn=b(ze,Be),Ue=y(ze,Be).superRefine(sn),$e=g(cn,{maxQueries:5});import{z as A}from"zod";import{RipgrepQuerySchema as Ve}from"@octocodeai/octocode-core/schemas";var ln=["paginated","discovery","detailed","structural"],un=["semanticRanking"],Xe={mode:A.enum(ln).optional().default("paginated").describe('"paginated" snippets; "discovery" paths only; "detailed" snippets plus context; "structural" AST/code-shape search with pattern or rule. Structural matches return line/capture anchors that can feed lspGetSemantics when symbol identity matters.'),pattern:A.string().optional().describe("Structural only: code-shaped AST pattern with $X (one node) or $$$ARGS (node list). Use this to find syntax shape, then use lspGetSemantics for semantic proof."),rule:A.string().optional().describe("Structural only: YAML ast-grep rule for not/inside/has/all/any. Use for partial or relational AST queries before escalating matched anchors to lspGetSemantics."),contextLines:E,matchContentLength:l(1,1e5).optional().default(500),maxMatchesPerFile:l(1,1e5).optional(),maxFiles:l(1,1e5).optional(),matchPage:f.optional(),itemsPerPage:l(1,1e3).optional(),page:f.default(1),unique:A.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:A.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},pn={...Xe,semanticRanking:A.never().optional()},mn=b(Ve,pn),dn=y(Ve,Xe,{strict:!0,omit:un}),We=dn.superRefine((n,r)=>{let o=n;if(o.caseSensitive&&o.caseInsensitive&&r.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),o.fixedString&&o.perlRegex&&r.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),o.filesOnly&&o.filesWithoutMatch&&r.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),o.countLinesPerFile&&o.countMatchesPerFile&&r.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),o.multilineDotall&&!o.multiline&&r.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),o.mode==="structural"){for(let i of["unique","countUnique"])o[i]&&r.addIssue({code:"custom",message:`\`${i}\` is not valid with mode:"structural".`,path:[i]});return}o.unique&&!o.onlyMatching&&r.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),o.countUnique&&!o.onlyMatching&&r.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),Ze=g(mn,{maxQueries:5});import{ViewStructureQuerySchema as Je}from"@octocodeai/octocode-core/schemas";var Ke={maxDepth:l(0,20).optional(),limit:l(1,1e4).optional(),page:f.default(1),itemsPerPage:l(1,50).optional()},hn=b(Je,Ke),Ye=y(Je,Ke),et=g(hn,{maxQueries:5});import{z as t}from"zod";import{LspGetSemanticsQuerySchema as rt}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as gn}from"@octocodeai/octocode-core/schemas/outputs";var fn=l(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),yn=l(0,1e5).optional(),bn=["structured","compact"],ot={type:t.enum(ce).default("definition").describe("Semantic operation for local code intelligence. Use after text or structural AST search when you need identity, references, call flow, type relations, hover, symbols, or diagnostics."),symbolName:t.string().min(1).max(1024).optional().describe("Exact bare identifier at the lineHint anchor for symbol operations; workspaceSymbol uses this as the fuzzy project-wide symbol query."),lineHint:fn.optional(),orderHint:yn,depth:l(0,20).optional(),includeDeclaration:t.boolean().optional().default(!0),page:f,itemsPerPage:l(1,100).optional(),contextLines:l(0,100).optional(),format:t.enum(bn).optional().default("structured")},Sn=b(rt,ot),at=y(rt,ot);var it=g(Sn,{maxQueries:5}),tt=t.object({line:t.number(),character:t.number()}),xn=t.object({start:tt,end:tt}),Rn=t.object({startLine:t.number(),endLine:t.number()}),j=t.object({uri:t.string(),content:t.string().optional(),displayRange:Rn.optional(),isDefinition:t.boolean().optional()}),B=t.string(),On=t.object({name:t.string(),uri:t.string(),foundAtLine:t.number(),orderHint:t.number().optional()}),wn=t.object({serverAvailable:t.boolean().optional(),provider:t.string().optional(),source:t.string().optional()}),st=t.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),q=t.object({category:st,reason:t.string()}),Tn=t.object({currentPage:t.number(),totalPages:t.number(),totalResults:t.number(),hasMore:t.boolean(),itemsPerPage:t.number(),nextPage:t.number().optional()}),kn=t.object({name:t.string(),kind:t.string(),line:t.number(),character:t.number(),endLine:t.number(),childCount:t.number(),containerName:t.string().optional()}),Pn=t.string(),ct=t.object({name:t.string(),kind:t.string(),uri:t.string(),line:t.number(),endLine:t.number(),selectionLine:t.number().optional()}),Ln=t.string(),Cn=t.object({direction:t.enum(["incoming","outgoing"]),item:ct,ranges:t.array(t.object({line:t.number(),character:t.number()})),rangeCount:t.number(),rangeSampleCount:t.number(),contentPreview:t.string().optional()}),En=t.string(),_n=t.object({complete:t.boolean(),truncatedByDepth:t.boolean(),cycleCount:t.number(),failedRequestCount:t.number(),dynamicCallsExcluded:t.literal(!0),stdlibCallsExcluded:t.number().optional()}),An=t.object({uri:t.string(),count:t.number(),firstLine:t.number(),firstCharacter:t.number(),lines:t.array(t.number()),hasDefinition:t.boolean().optional()}),qn=t.string(),vn=t.discriminatedUnion("kind",[t.object({kind:t.literal("definition"),locations:t.array(t.union([j,B]))}),t.object({kind:t.literal("typeDefinition"),locations:t.array(t.union([j,B]))}),t.object({kind:t.literal("implementation"),locations:t.array(t.union([j,B]))}),t.object({kind:t.literal("references"),locations:t.array(t.union([j,B])).optional(),byFile:t.array(t.union([An,qn])).optional(),totalReferences:t.number(),totalFiles:t.number(),empty:q.optional()}),...["callers","callees","callHierarchy"].map(n=>t.object({kind:t.literal(n),root:t.union([ct,Ln]).optional(),direction:t.enum(["incoming","outgoing","both"]),calls:t.array(t.union([Cn,En])),incomingCalls:t.number(),outgoingCalls:t.number(),completeness:_n,empty:q.optional()})),t.object({kind:t.literal("hover"),markdown:t.string().optional(),text:t.string().optional(),range:xn.optional()}),t.object({kind:t.literal("documentSymbols"),symbols:t.array(t.union([kn,Pn])),totalSymbols:t.number().optional(),topLevelSymbols:t.number().optional(),empty:q.optional()}),t.object({kind:t.literal("workspaceSymbol"),query:t.string(),symbols:t.array(t.unknown()),totalSymbols:t.number(),empty:q.optional()}),t.object({kind:t.literal("typeHierarchy"),direction:t.enum(["supertypes","subtypes"]),root:t.unknown().optional(),items:t.array(t.unknown()),totalItems:t.number(),empty:q.optional()}),t.object({kind:t.literal("diagnostic"),diagnostics:t.array(t.unknown()),totalDiagnostics:t.number(),errorCount:t.number(),warningCount:t.number(),empty:q.optional()}),t.object({kind:t.literal("empty"),category:st,reason:t.string()})]),nt=t.object({type:t.string(),uri:t.string(),format:t.enum(["structured","compact"]).optional(),resolvedSymbol:On.optional(),lsp:wn,payload:vn,pagination:Tn.optional(),summary:t.record(t.string(),t.unknown()).optional(),warnings:t.array(t.string()).optional()}),oa=t.object({base:t.string().optional(),shared:t.record(t.string(),t.union([t.string(),t.number(),t.boolean()])).optional(),results:t.array(t.union([t.object({id:t.string().min(1),status:t.literal("empty"),data:nt}),t.object({id:t.string().min(1),status:t.literal("error"),data:gn}),t.object({id:t.string().min(1),data:nt})]))});import{z as lt}from"zod";import{LocalBinaryInspectQuerySchema as Fn}from"@octocodeai/octocode-core/schemas";var In={entryPageNumber:f.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:l(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:l(1,5e4).optional().describe("Max chars of inline content for this window (paired with charOffset). Omit for the default window; follow pagination.next to page losslessly."),page:f.default(1).describe("1-based page for paginated entry/content listings."),detailed:lt.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},ut=lt.object({...Fn.shape,...In}),pt=ut.strict().superRefine((n,r)=>{n.mode==="extract"&&!n.archiveFile&&r.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),n.archiveFile?.startsWith("-")&&r.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let o=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];n.mode==="decompress"&&o.some(i=>n.path.toLowerCase().endsWith(i))&&r.addIssue({code:"custom",path:["mode"],message:'This path looks like a multi-entry archive \u2014 use mode="list" or mode="extract" instead of mode="decompress".'})}),mt=g(ut,{maxQueries:5});import{z as e}from"zod";var C=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],z=["fixes","dataflow"];var Y=e.lazy(()=>e.union([e.strictObject({kind:e.literal("local"),path:e.string().min(1)}),e.strictObject({kind:e.literal("github"),repo:e.string().min(1).optional(),owner:e.string().min(1).optional(),ref:e.string().min(1).optional()}),e.strictObject({kind:e.literal("materialized"),localPath:e.string().min(1),source:Y.optional()}),e.strictObject({kind:e.literal("npm")})])),K=e.union([e.string(),e.array(e.string()).max(100)]),Dn=e.strictObject({path:K.optional(),language:K.optional(),include:e.array(e.string()).max(100).optional(),exclude:e.array(e.string()).max(100).optional(),excludeDir:e.array(e.string()).max(100).optional(),hidden:e.boolean().optional(),noIgnore:e.boolean().optional(),minDepth:e.number().int().min(0).max(64).optional(),maxDepth:e.number().int().min(0).max(64).optional()}).optional(),dt=e.enum(["smart","sensitive","insensitive"]),ht=e.string().max(1e4),Qn=e.strictObject({id:e.string().optional(),kind:e.literal("text"),value:ht,case:dt.optional(),wholeWord:e.boolean().optional()}),Mn=e.strictObject({id:e.string().optional(),kind:e.literal("regex"),value:ht,dialect:e.enum(["rust","pcre2","provider"]).optional(),case:dt.optional(),wholeWord:e.boolean().optional(),multiline:e.boolean().optional(),dotAll:e.boolean().optional()}),v=e.lazy(()=>e.strictObject({pattern:e.string().optional(),kind:e.string().optional(),inside:v.optional(),has:v.optional(),not:v.optional(),all:e.array(v).optional(),any:e.array(v).optional(),stopBy:e.literal("end").optional()})),gt=e.union([v,e.string().min(1)]),Gn=e.strictObject({id:e.string().optional(),kind:e.literal("structural"),lang:e.string().min(1),pattern:e.string().optional(),rule:gt.optional()}),Nn=e.strictObject({id:e.string().optional(),kind:e.literal("field"),field:e.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:e.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:e.unknown().optional()}),G=e.lazy(()=>e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all"),id:e.string().optional(),of:e.array(G).min(1)}),e.strictObject({kind:e.literal("any"),id:e.string().optional(),of:e.array(G).min(1)}),e.strictObject({kind:e.literal("not"),id:e.string().optional(),predicate:G}),Qn,Mn,Gn,Nn])),ft=e.strictObject({mode:e.enum(["never","auto","required"]),strategy:e.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:e.boolean().optional(),forceRefresh:e.boolean().optional()}),yt=e.strictObject({content:e.strictObject({range:e.strictObject({startLine:e.number().int().min(1).optional(),endLine:e.number().int().min(1).optional(),contextLines:e.number().int().min(0).max(100).optional()}).optional(),match:e.strictObject({text:e.string(),regex:e.boolean().optional(),caseSensitive:e.boolean().optional()}).optional(),contentView:e.enum(["exact","compact","symbols"]).optional(),charOffset:e.number().int().min(0).max(1e8).optional(),charLength:e.number().int().min(1).max(5e4).optional(),fullContent:e.boolean().optional()}).optional(),tree:e.strictObject({maxDepth:e.number().int().min(0).max(64).optional(),pattern:e.string().optional(),includeSizes:e.boolean().optional(),extensions:e.array(e.string()).optional(),filesOnly:e.boolean().optional(),directoriesOnly:e.boolean().optional(),sortBy:e.enum(["name","size","time","extension"]).optional(),reverse:e.boolean().optional()}).optional()}),bt=e.strictObject({search:e.strictObject({countLinesPerFile:e.boolean().optional(),countMatchesPerFile:e.boolean().optional(),onlyMatching:e.boolean().optional(),unique:e.boolean().optional(),countUnique:e.boolean().optional(),contextLines:e.number().int().min(0).max(100).optional(),invertMatch:e.boolean().optional(),matchWindow:e.number().int().min(0).optional(),matchContentLength:e.number().int().min(1).optional(),maxMatchesPerFile:e.number().int().min(1).optional(),matchPage:e.number().int().min(1).optional(),sort:e.enum(["relevance","matchCount","path","modified","accessed","created"]).optional(),sortReverse:e.boolean().optional(),rankingProfile:e.string().optional(),debugRanking:e.boolean().optional()}).optional(),budget:e.strictObject({maxFiles:e.number().int().min(1).optional(),maxCandidates:e.number().int().min(1).optional(),maxBytes:e.number().int().min(1).optional(),maxMaterializedBytes:e.number().int().min(1).optional(),maxPlanNodes:e.number().int().min(1).optional(),maxBooleanExpansion:e.number().int().min(1).optional(),timeoutMs:e.number().int().min(1).optional()}).optional()}),St=e.enum(["discovery","paginated","detailed"]),xt=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),target:e.enum(C),from:Y.optional(),scope:Dn,where:G.optional(),materialize:ft.optional(),fetch:yt.optional(),select:e.array(e.string()).optional(),view:St.optional(),controls:bt.optional(),limit:e.number().int().min(1).optional(),page:e.number().int().min(1).optional(),itemsPerPage:e.number().int().min(1).optional(),params:e.record(e.string(),e.unknown()).optional(),explain:e.boolean().optional()}),Hn=e.strictObject({schema:e.literal("oql"),id:e.string().optional(),queries:e.array(xt).min(1).max(5),combine:e.enum(["independent","merge"]).optional(),limit:e.number().int().min(1).optional(),page:e.number().int().min(1).optional(),itemsPerPage:e.number().int().min(1).optional(),explain:e.boolean().optional()}),da=e.union([xt,Hn]),jn=C,Bn=[...C,...z],Rt={schema:e.literal("oql").optional(),id:e.string().optional(),mainResearchGoal:e.string().optional(),researchGoal:e.string().optional(),reasoning:e.string().optional()},ee={...Rt,target:e.enum(Bn).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes."),from:Y.optional().describe('Source. Defaults to local cwd when omitted; use {kind:"github",owner,repo} for remote or {kind:"materialized",localPath} after a fetch/clone.'),where:G.optional().describe("Canonical predicate tree (kind: text | regex | structural | field | all | any | not). Mutually exclusive with the flat shorthand fields (text/regex/pattern/and/or/...): use ONE shape, not both."),materialize:e.union([ft,e.enum(["never","auto","required"])]).optional(),fetch:yt.optional(),select:e.array(e.string()).optional(),view:St.optional(),controls:bt.optional(),limit:e.number().int().min(1).optional(),page:e.number().int().min(1).optional(),itemsPerPage:e.number().int().min(1).optional(),params:e.record(e.string(),e.unknown()).optional(),explain:e.boolean().optional(),repo:e.string().optional(),owner:e.string().optional(),ref:e.string().optional(),path:K.optional(),text:e.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:e.string().optional(),pattern:e.string().optional().describe("Shorthand AST/structural pattern (\u2192 structural where, target code). A function pattern must match a COMPLETE node \u2014 include return type (e.g. `function $N($$$A): $R { $$$B }`) or use a `rule` for partial/relational matches."),rule:gt.optional(),lang:e.string().optional(),and:e.array(e.unknown()).optional(),or:e.array(e.unknown()).optional(),xor:e.array(e.unknown()).optional(),noneOf:e.array(e.unknown()).optional(),oneOf:e.array(e.unknown()).optional(),invert:e.unknown().optional(),filesOnly:e.boolean().optional(),filesWithoutMatch:e.boolean().optional(),verbose:e.boolean().optional()},Ot=e.object({...ee,target:e.enum(jn).optional().describe("REQUIRED unless inferable from sugar (text/regex/pattern/rule/boolean \u2192 code, fetch.content \u2192 content, fetch.tree \u2192 structure). One of the active targets \u2014 run `search --scheme` for the full list and recipes.")}).catchall(e.unknown()),ha=e.object(ee).catchall(e.unknown()),ga=e.object({...Rt,queries:e.array(e.unknown()).min(1)}).catchall(e.unknown()),wt=e.object({...ee,queries:e.array(e.unknown()).min(1).max(5).optional(),combine:e.enum(["independent","merge"]).optional()}).catchall(e.unknown());var Tt=["GitHub","Local Code","Package","Other"],kt=new Map([p.GITHUB_SEARCH_CODE,p.GITHUB_SEARCH_REPOSITORIES,p.GITHUB_SEARCH_PULL_REQUESTS,p.GITHUB_FETCH_CONTENT,p.GITHUB_VIEW_REPO_STRUCTURE,p.GITHUB_CLONE_REPO,p.LOCAL_RIPGREP,p.LOCAL_FIND_FILES,p.LOCAL_FETCH_CONTENT,p.LOCAL_VIEW_STRUCTURE,P,p.PACKAGE_SEARCH,N].map((n,r)=>[n,r])),w=class extends Error{constructor(o,i=[]){super(o);this.details=i;this.name="DirectToolInputError"}details},zn=["id","mainResearchGoal","researchGoal","reasoning"],ie=new Set([...zn]),Un=["id","researchGoal","reasoning"],Et=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],$n=[{name:p.GITHUB_SEARCH_CODE,schema:Re,inputSchema:Oe},{name:p.GITHUB_FETCH_CONTENT,schema:ye,inputSchema:be},{name:p.GITHUB_VIEW_REPO_STRUCTURE,schema:ve,inputSchema:Fe},{name:p.GITHUB_SEARCH_REPOSITORIES,schema:Ee,inputSchema:_e},{name:p.GITHUB_SEARCH_PULL_REQUESTS,schema:ke,inputSchema:Pe},{name:p.PACKAGE_SEARCH,schema:Qe,inputSchema:Me},{name:p.GITHUB_CLONE_REPO,schema:X,inputSchema:me},{name:p.LOCAL_RIPGREP,schema:We,inputSchema:Ze},{name:p.LOCAL_VIEW_STRUCTURE,schema:Ye,inputSchema:et},{name:p.LOCAL_FIND_FILES,schema:Ue,inputSchema:$e},{name:p.LOCAL_FETCH_CONTENT,schema:He,inputSchema:je},{name:P,schema:at,inputSchema:it},{name:p.LOCAL_BINARY_INSPECT,schema:pt,inputSchema:mt},{name:N,schema:Ot,inputSchema:wt}];function $(n){return $n.find(r=>r.name===n)}function U(n){return n.startsWith("gh")?"GitHub":n.startsWith("local")||n.startsWith("lsp")?"Local Code":n===p.PACKAGE_SEARCH?"Package":"Other"}function Fa(n){return[...n].sort((r,o)=>{let i=Tt.indexOf(U(r)),c=Tt.indexOf(U(o));if(i!==c)return i-c;let u=kt.get(r)??Number.MAX_SAFE_INTEGER,d=kt.get(o)??Number.MAX_SAFE_INTEGER;return u!==d?u-d:r.localeCompare(o)})}function Ia(n){let r=$(n);if(!r)return"{}";try{return JSON.stringify(te.toJSONSchema(r.inputSchema),null,2)}catch{return JSON.stringify(te.toJSONSchema(r.schema),null,2)}}function Da(n){return JSON.stringify(n??{},null,2)}function Qa(n){let r=U(n),o=[...Un];return(r==="GitHub"||r==="Package")&&o.splice(1,0,"mainResearchGoal"),o}function Ma(){return Et.map(n=>({...n}))}function Ga(){return JSON.stringify(Object.fromEntries(Et.map(n=>[n.name,n.optional?`${n.type} (optional)`:n.type])),null,2)}function Na(n,r){return r?.tools?.[n]?.description??n}function _t(n){let r=$(n);if(!r)return[];let o=te.toJSONSchema(r.schema);if(!F(o))return[];let i=k(o.properties)?o.properties:{},c=new Set(Array.isArray(o.required)?o.required.filter(u=>!ie.has(u)&&!ae(i[u])):[]);return oe(i,c)}function Pt(n,r){return`tools ${n} --queries '${JSON.stringify(r)}'`}function Vn(n){let r=Wn(n);if(r.length>0)return r.map(i=>({...i,command:Pt(n,i.query)}));let o=Xn(n);return Object.keys(o).length===0?[]:[{label:"schema-derived",query:o,command:Pt(n,o)}]}function Ha(n){return Vn(n)[0]?.query??{}}function Xn(n){if(!$(n))return{};let r=_t(n),o=r.filter(u=>!u.name.includes(".")),i=rr(o),c={};for(let u of i)c[u.name]=sr(u.name,u.type);return n.startsWith("lsp")&&r.some(u=>u.name==="uri")&&(c.uri??="uri"),n===P&&(c.type??="definition",c.symbolName??="symbolName",c.lineHint??=1),c}function Wn(n){return n===N?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:n===p.GITHUB_SEARCH_PULL_REQUESTS?[{label:"PR search",query:{type:"prs",owner:"facebook",repo:"react",keywordsToSearch:["useState"],concise:!0,limit:5}},{label:"commit history",query:{type:"commits",owner:"facebook",repo:"react",path:"packages/react/src",since:"2024-01-01T00:00:00Z",perPage:5}}]:n===p.GITHUB_SEARCH_CODE?[{label:"path search",query:{keywords:["package.json"],owner:"facebook",repo:"react",match:"path",concise:!0,limit:5}},{label:"content search",query:{keywords:["useState"],owner:"facebook",repo:"react",extension:"js",limit:5}}]:n===p.GITHUB_SEARCH_REPOSITORIES?[{label:"repository search",query:{keywords:["react"],language:"TypeScript",stars:">1000",concise:!0,limit:5}},{label:"owner repositories",query:{owner:"facebook",concise:!0,limit:5}}]:n===p.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"facebook",repo:"react",path:"packages",maxDepth:2,itemsPerPage:50}}]:n===p.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"facebook",repo:"react",sparsePath:"packages/react"}}]:n===p.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:n===p.LOCAL_FETCH_CONTENT?[{label:"exact line range",query:{path:"src/index.ts",startLine:1,endLine:40,minify:"none"}},{label:"matched slice",query:{path:"src/index.ts",matchString:"registerTool",contextLines:8,minify:"standard"}}]:n===p.LOCAL_FIND_FILES?[{label:"basename globs",query:{path:".",names:["*.ts","package.json"],entryType:"f",itemsPerPage:20}},{label:"monorepo path glob",query:{path:".",pathPattern:"packages/*/src/**",entryType:"f",itemsPerPage:20}}]:n===p.LOCAL_BINARY_INSPECT?[{label:"archive listing",query:{path:"archive.zip",mode:"list",entriesPerPage:50}},{label:"binary strings",query:{path:"dist/app.node",mode:"strings",minLength:8,charLength:2e3}}]:n===P?[{label:"semantic definition",query:{uri:"/path/to/file.ts",type:"definition",symbolName:"myFunction",lineHint:42}},{label:"symbol outline",query:{uri:"/path/to/file.ts",type:"documentSymbols"}}]:[]}function ja(n,r,o={}){if(typeof r!="string")return null;let i;try{i=JSON.parse(r)}catch{throw new w("Tool input must be valid JSON.")}return Zn(n,i,o)}function Zn(n,r,o={}){let i=Kn(n,r,o),c=$(n);if(!c)throw new w(`Unknown tool: ${n}`);let u=c.inputSchema.safeParse(i);if(!u.success)throw new w("Tool input does not match the expected schema.",Jn(u.error));return u.data}function Jn(n){return n.issues.map(r=>`${r.path.length>0?r.path.join("."):"input"}: ${r.message}`)}function Kn(n,r,o){let i=[];if(Array.isArray(r))i=r;else if(k(r)&&Array.isArray(r.queries))i=r.queries;else if(k(r))i=[r];else throw new w('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(i.length===0)throw new w("At least one query is required.");let c=k(r)&&Array.isArray(r.queries)?Object.fromEntries(Object.entries(r).filter(([R])=>R!=="queries")):{},u=!1,d={...o,onUnknownFields:(R,T)=>{u=!0,o.onUnknownFields?.(R,T)}},S=i.map((R,T)=>Yn(n,T,tr(n,R,T,d),{sourceLabel:o.sourceLabel}));if(u&&o.onUnknownFields!==void 0)throw new w("Tool input contains unknown fields. See warnings above for details.");return{...c,queries:S}}function Yn(n,r,o,i){let c={...o},u=U(n),d=i.sourceLabel??"direct tool execution",S=er(n,d);return(typeof c.id!="string"||c.id.trim().length===0)&&(c.id=`${n}-${r+1}`),(u==="GitHub"||u==="Package")&&(typeof c.mainResearchGoal!="string"||c.mainResearchGoal.trim().length===0)&&(c.mainResearchGoal=S),(typeof c.researchGoal!="string"||c.researchGoal.trim().length===0)&&(c.researchGoal=S),(typeof c.reasoning!="string"||c.reasoning.trim().length===0)&&(c.reasoning=`Executed via ${d} tool command`),c}function er(n,r){return`Execute ${n} via ${r}`}function tr(n,r,o,i={}){if(!k(r))throw new w("Tool input must be a JSON object or an array of objects.");let c=new Set([..._t(n).filter(S=>!S.name.includes(".")).map(S=>S.name),...ie]),u={},d=[];for(let[S,R]of Object.entries(r)){if(c.has(S)){u[S]=R;continue}d.push(S)}return d.length>0&&c.size>0&&i.onUnknownFields?.(d,o),u}function nr(n){let r=[],o=typeof n.minimum=="number"?n.minimum:void 0,i=typeof n.maximum=="number"?n.maximum:void 0;return o!==void 0&&i!==void 0?r.push(`${o}-${i}`):o!==void 0?r.push(`>=${o}`):i!==void 0&&r.push(`<=${i}`),"default"in n&&r.push(`default ${JSON.stringify(n.default)}`),r.length>0?r.join(", "):void 0}function ne(n){if(Array.isArray(n.enum)&&n.enum.length>0)return`enum(${n.enum.map(String).join(", ")})`;if(n.type==="array"){let o=F(n.items)?n.items:void 0;return`array<${o?ne(o):"value"}>`}let r=Array.isArray(n.anyOf)?n.anyOf:Array.isArray(n.oneOf)?n.oneOf:void 0;if(r){let o=r.filter(F).map(ne).filter(i=>i!=="value");if(o.length>0)return[...new Set(o)].join(" | ")}return Array.isArray(n.type)?n.type.join(" | "):typeof n.type=="string"?n.type:"value"}var Lt=4,re=new Map([["keywords",10],["keywordsToSearch",11],["query",12],["text",13],["packageName",14],["name",15],["uri",20],["type",21],["owner",30],["repo",31],["extension",32],["filename",33],["language",34],["path",40],["target",50],["from",51],["scope",52],["pattern",60],["rule",61],["op",80],["operation",81],["minify",90]]),At=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"]);function rr(n){let r=n.filter(u=>u.required),o=new Map;for(let u of r)o.set(u.name,u);let i=n.filter(u=>!u.required&&or(u)).sort(ar),c=Math.max(Lt,r.length);for(let u of i){if(o.size>=c)break;o.set(u.name,u)}return o.size>0?[...o.values()]:n.filter(u=>!At.has(u.name)).filter(u=>u.type!=="boolean").slice(0,Lt)}function or(n){return At.has(n.name)||n.type==="boolean"?!1:ir(n)?re.has(n.name):!0}function ar(n,r){let o=re.get(n.name)??Number.MAX_SAFE_INTEGER,i=re.get(r.name)??Number.MAX_SAFE_INTEGER;return o!==i?o-i:n.name.localeCompare(r.name)}function ir(n){return n.constraints?.includes("default ")===!0}function oe(n,r,o=""){let i=[];for(let[c,u]of Object.entries(n)){if(!o&&ie.has(c))continue;let d=F(u)?u:{},S=o?`${o}.${c}`:c;if(i.push({name:S,required:r.has(c),type:ne(d),constraints:nr(d),description:typeof d.description=="string"?d.description:void 0}),k(d.properties)){let T=new Set(Array.isArray(d.required)?d.required.filter(I=>typeof I=="string"?!ae(d.properties?.[I]):!1):[]);i.push(...oe(d.properties,T,S))}let R=d.type==="array"&&F(d.items)?d.items:void 0;if(R&&k(R.properties)){let T=new Set(Array.isArray(R.required)?R.required.filter(I=>typeof I=="string"?!ae(R.properties?.[I]):!1):[]);i.push(...oe(R.properties,T,S))}}return i}function sr(n,r){if(r.startsWith("array<")){let o=r.slice(6,-1);return[Ct(n,o)]}return Ct(n,r)}function Ct(n,r){if(r.startsWith("enum("))return/^enum\(([^,)]+)/.exec(r)?.[1]??n;if(r==="integer"||r==="number")return n==="lineHint"?42:5;if(r==="boolean")return!0;switch(n){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"facebook";case"repo":return"react";case"extension":return"ts";case"filename":return"package.json";case"language":return"TypeScript";case"symbolName":return"myFunction";case"name":case"packageName":return"react";default:return n}}function k(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function F(n){return k(n)}function ae(n){return F(n)&&"default"in n}var qt={schema:"oql",view:"paginated",page:1,itemsPerPage:25,githubMaterializeMode:"never",textCase:"smart",regexDialectLocal:"rust",regexCase:"smart",contentView:"compact",contentCharLength:2e4,matchContentLength:500,maxPlanNodes:128,maxBooleanExpansion:64,normalCodeContext:2,detailedCodeContext:3,localSearchSort:"relevance",localRankingProfile:"auto"};var vt={schema:"oql",description:"octocode search \u2014 typed read-only queries over code, files, symbols, repos, packages, history, artifacts, diffs, and graph evidence. Think source + answer type + filters + read/output options; use --explain for routing; follow next.* for pages, exact reads, materialization, or proof.",activeTargets:C,reservedTargets:z,sourceGuide:{local:'from:{kind:"local",path:"./src"}; shorthand: search "term" ./src, search ./src --tree, search file.ts --op documentSymbols. Best for local code/content/files/tree/LSP/artifacts/diff.',github:'from:{kind:"github",repo:"owner/repo",ref?}; shorthand: search "term" owner/repo, search owner/repo --tree, search owner/repo#123 --target pullRequests. GitHub code is indexed/default-branch scoped; materialize for AST/LSP/local proof.',npm:'from:{kind:"npm"} with target:"packages"; shorthand: search zod --target packages. Use to resolve package metadata and source repo, then continue with GitHub or local/materialized proof.',materialized:'from:{kind:"materialized",localPath:"/abs/path"} after target:"materialize", clone, or cache fetch. Use when a remote repo/subtree must behave like local code.'},plainLanguage:{source:"`from` = where to look: local path, GitHub repo, npm, or a materialized checkout.",answerType:"`target` = what kind of answer you want: code matches, file content, tree, files, symbols, repos, packages, PRs, commits, artifacts, diffs, research packets, graph proof, or materialization.",filters:"`where` = match/filter conditions for code and file discovery only: text, regex, AST shape, file fields, and boolean combinations.",readOptions:"`fetch` = what to read once you know the file/tree: exact content, compact content, symbol outline, ranges, match slices, or tree depth.",targetOptions:"`params` = options that belong to one answer type, such as LSP operation, PR number, package name, artifact mode, research intent, or graph proof.",output:"`view`, `select`, and `controls` = response shape, projected fields, search tuning, and cost limits.",paging:"`page` + `itemsPerPage` page the target's primary result domain. For code search that may be matched files; per-file match paging uses `controls.search.matchPage` / `--match-page`."},targetDecisionTree:{"find a string/pattern in code":"target:code (shorthand default for text/regex/--pattern/--rule; needs a where filter)","read or slice a known file":"target:content (file positional + --content-view, --start-line/--end-line, or --match-string)","see the file/dir layout":"target:structure (--tree)","find files by name/glob/ext/size/mtime":"target:files (--search path, --name/--ext/--size-greater/--modified-within)","symbol defs/refs/callers/hover":"target:semantics (--op \u2026; local or materialized only)","search GitHub repos":"target:repositories (--stars/--lang/--topic)","resolve an npm package":"target:packages","PR list or deep-read":"target:pullRequests (owner/repo#N)","commit history":"target:commits (--since/--until)","a diff":"target:diff ({prNumber} for a PR patch, {baseRef,headRef,path} for two refs)","inspect a binary/archive":"target:artifacts (--inspect/--list/--strings/--extract)","dead-code / reachability sweep":'target:research, then upgrade with target:graph proof:"lsp"',"make a remote repo behave like local (AST/LSP/negation)":"target:materialize (or clone / cache fetch)"},agentBestPractices:["Start with cheap orientation: --tree, --search path, --view discovery, or --content-view symbols.","Then narrow and read exact evidence: --match-string, --start-line/--end-line, --char-offset/--char-length, or --content-view exact.","Use snippets as discovery only; make decisions from exact content, PR/commit metadata, or LSP/graph proof.","For semantics, run documentSymbols first to get line anchors, then references/callers/hover with symbolName + lineHint.","For GitHub zero rows / providerUnindexed, do NOT claim absence \u2014 follow evidenceSemantics.providerUnindexed (verify path with structure, then materialize a bounded path).","Read evidence.answerReady, evidence.complete, diagnostics, pagination, and next.* before concluding."],quickStart:{"text search (local)":'search "functionName" ./src',"text search (GitHub)":'search "functionName" facebook/react',"package lookup (npm)":"search zod --target packages","PR deep read (GitHub)":"search facebook/react#1 --target pullRequests --comments --patches","commit history (GitHub)":"search facebook/react/packages/react/src --target commits --since 2024-01-01T00:00:00Z","browse a tree (local dir or owner/repo)":"search ./src --tree | search facebook/react --tree","read a file (local or owner/repo/path)":"search ./src/index.ts | search facebook/react/packages/react/src/index.js","semantics (local/materialized)":"search ./src/index.ts --op documentSymbols | search ./src/index.ts --op references --symbol runCLI --line 42","artifact inspect/list":"search app.tgz --target artifacts --list | search dist/server.node --target artifacts --inspect","PR diff (GitHub)":"search facebook/react#123 --target diff | search facebook/react --target diff --pr 123","two-ref / two-file diff":"search src/a.ts src/b.ts --target diff | search owner/repo --target diff --base-ref <sha> --head-ref <sha> --path <file>","structural AST (local \u2014 needs full node shape)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" ./src --lang ts',"structural AST (GitHub \u2014 clones bounded subtree)":'search --pattern "function $NAME($$$ARGS) { $$$BODY }" facebook/react/packages --lang js --materialize auto',"GitHub index miss recovery":"search useState packages/react/src --repo facebook/react --materialize required | clone facebook/react/packages/react/src | cache fetch facebook/react packages/react/src --depth tree","dead-code triage (research)":`search --query '{"schema":"oql","target":"research","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols","files"]},"itemsPerPage":1,"page":1}'`,"LSP-proven dead symbols (graph)":`search --query '{"schema":"oql","target":"graph","from":{"kind":"local","path":"./src"},"params":{"intent":"reachability","facets":["symbols"],"proof":"lsp","proofLimit":5,"includePackets":true},"page":1,"itemsPerPage":10}'`,"OQL full-schema reference":"search --scheme","routing explanation before running":`search --explain --query '{"target":"code","from":{"kind":"local","path":"./src"},"where":{"kind":"text","value":"term"}}'`},evidenceSemantics:{"answerReady:true":"The envelope answers the query as asked. No required follow-up.","answerReady:false":"Normal, NOT a failure \u2014 the results above are valid; only answerReady:true means no follow-up is needed. Follow next.* for more pages, LSP proof, or content.","complete:false":"Pages/proof/slices may remain. Read diagnostics: non-blocking warnings can still leave usable rows, but deletion/absence claims need the requested scope plus the listed continuations.","kind:proof":"Backend evaluated the request exactly.","kind:partial":"Truncation, pagination, or residual checks remain.","kind:candidate":"Useful evidence, not proof. research/graph are always candidate \u2014 upgrade via next.semantic/search/fetch.","kind:unsupported":"OQL could not safely execute the requested semantics.","proofStatus:confirmed-by-lsp":"LSP refs=0 inside the bounded workspace. Inspect for deletion only after checking entrypoints, framework conventions, dynamic imports, package exports, and scripts.","proofStatus:conflicting-evidence":"LSP refs>0 \u2014 symbol IS retained; check retainedBy before acting.","proofStatus:needs-framework-graph":"Maybe an entrypoint (framework/export/dynamic import) \u2014 LSP alone can't prove reachability.","proofStatus:candidate":`Pre-proof state (no LSP run yet) \u2014 run the row's next.graph (proof:"lsp") to resolve it to confirmed-by-lsp / conflicting-evidence / needs-framework-graph.`,partialParse:"Non-fatal structural-search warning. Some files were not parsed, often because a literal prefilter had no anchor; add a literal/rule or broaden proof before claiming absence.",providerUnindexed:'GitHub provider returned zero rows. This is NOT absence. Verify the path with structure, then use bounded local proof: search "term" path --repo owner/repo --materialize required, clone owner/repo[/path], or cache fetch owner/repo [path] --depth file|tree|clone.'},query:{schema:'"oql" (inserted by normalization)',target:C.join(" | "),from:'{ kind:"local", path } | { kind:"github", repo?, owner?, ref? } | { kind:"materialized", localPath, source? } | { kind:"npm" } \u2014 local row.path is relative to from.path; the pre-filled next.fetch carries the resolved ABSOLUTE path, so follow it directly rather than re-joining paths yourself',scope:"{ path?, language?, include?, exclude?, excludeDir?, hidden?, noIgnore?, minDepth?, maxDepth? } \u2014 minDepth/maxDepth bound directory recursion depth (0-64)",where:"filters for code/files only: text | regex | structural | field | all | any | not. To read a matched file slice, use fetch.content.match. For PR/commit/artifact text narrowing, use that target params hint.",materialize:'{ mode:"never"|"auto"|"required", strategy?:"file"|"tree"|"subtree"|"repo", allowFullRepo?, forceRefresh? }',fetch:'{ content?: { contentView:"exact"|"compact"|"symbols", fullContent?, match?:{text|regex,case?}, range?:{startLine?,endLine?,contextLines?}, charOffset?, charLength? }, tree?:{ maxDepth?, pattern?, includeSizes?, extensions?, filesOnly?, directoriesOnly?, sortBy?:"name"|"size"|"time"|"extension", reverse? } } \u2014 read options for known files/trees; fetch.content.fullContent:true returns the WHOLE file in one shot (lossless, no char-window paging); to read the region around a string, anchor with fetch.content.match (NOT a top-level where, which is code/files only)',params:"target options (validated by OQL for common fields and by the backing tool exhaustively) \u2014 see params hints below",select:"string[] projection of result/continuation fields",view:"discovery | paginated | detailed",controls:"{ search?: { countLinesPerFile?, countMatchesPerFile?, onlyMatching?, unique?, countUnique?, contextLines?, invertMatch?, matchWindow?, matchContentLength?, maxMatchesPerFile?, matchPage?, sort?, sortReverse?, rankingProfile?, debugRanking? }, budget?: { maxFiles?, maxCandidates?, maxBytes?, maxMaterializedBytes?, maxPlanNodes?, maxBooleanExpansion?, timeoutMs? } } \u2014 output/cost controls",limit:"number \u2014 total result cap where supported. Prefer itemsPerPage for paged research/graph/file-history continuations.",page:"number \u2014 top-level page number for OQL windowing/continuations",itemsPerPage:"number \u2014 page size for the target primary result domain. For code search this may be matched files, not individual matches; per-file match paging uses controls.search.matchPage. Per-target params expose backing-tool sub-pages only (filePage/commentPage/commitPage, entryPageNumber, scanOffset, etc.).",explain:"boolean"},params:{semantics:'{ type:"definition"|"references"|"callers"|"callees"|"callHierarchy"|"hover"|"documentSymbols"|"typeDefinition"|"implementation"|"workspaceSymbol"|"supertypes"|"subtypes"|"diagnostic", uri?, symbolName?, symbolKind?, lineHint?, orderHint?, depth?, contextLines?, includeDeclaration?, groupByFile?, workspaceRoot?, format? } \u2014 backing tool lspGetSemantics; contextLines adds call-flow snippets; symbolKind filters returned symbol rows after documentSymbols/workspaceSymbol',repositories:"{ keywords?: string[], topicsToSearch?: string[], language?, owner?, stars?, license?, sort?, archived?, limit?, page? } \u2014 backing tool ghSearchRepos; keywords/topicsToSearch are arrays even for one term",packages:'{ packageName?: string | keywords?: string[], mode?:"lean"|"full", page? } \u2014 backing tool npmSearch',pullRequests:'{ state?:"open"|"closed"|"merged", author?, label?, keywordsToSearch?, prNumber?, reviewMode?, filePage?, commentPage?, commitPage?, limit?, page?, matchString?, matchScope?:"body"|"title"|"comments"|"reviews"|"all", content? } \u2014 backing tool ghHistoryResearch; matchString filters fetched PR title/body/comments/reviews per matchScope (default body), not a search-index query \u2014 no match \u2192 zeroMatches',commits:'{ path?, branch?, since?, until?, includeDiff?, limit?, page?, filePage?, itemsPerPage?, matchString? } \u2014 backing tool ghHistoryResearch type:"commits"; matchString filters commit messages; repo/directory diffs page changed files per commit with filePage/itemsPerPage',artifacts:'{ mode:"inspect"|"list"|"extract"|"decompress"|"strings"|"unpack", minLength?, entryPageNumber?, scanOffset?, charOffset?, charLength?, matchString? } \u2014 localBinaryInspect. matchString filters text-producing modes (extract/decompress/strings) over the current fetched payload. For large strings dumps, follow next.search on data.localPath for lossless ripgrep paging; next.artifactContent (charOffset) = next inline text window; next.artifactStrings (scanOffset) = next binary scan window. extract/unpack/decompress \u2192 tree at data.localPath (next.structure/next.files).',diff:"{ prNumber, files? } (PR patch via ghHistoryResearch) | { baseRef, headRef, path } (direct two-ref file diff via ghGetFileContent + local line diff); neither shape -> invalidQuery repair",research:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:("symbols"|"files"|"dependencies"|"relations")[], mode?:"plan"|"analyze"|"prove", maxFiles? } \u2014 TWO-PHASE: page:1+itemsPerPage:1 \u2192 data.summary (full-scope counts) and may include a bounded first packet page; page:2+ \u2192 data.packets[] continuation pages (candidates w/ retainedBy edges + per-packet next.*). Always evidence:"candidate"/answerReady:false (normal). Follow the row's pre-filled next.graph (proof:"lsp", proofLimit-bounded) to upgrade a page to LSP-proven proofStatus.`,graph:`{ goal?, intent?:"general"|"reachability"|"dependencies"|"symbols", facets?:(\u2026)[], mode?:"plan"|"analyze"|"prove", maxFiles?, subject?, subjectKind?, relation?, verdict?, direction?:"incoming"|"outgoing"|"both", proof?:"none"|"lsp", proofLimit?, includePackets?, includeFacts?, includeEdges? } \u2014 UPGRADE PATH: run a research row's pre-filled next.graph directly. proof:"lsp" sets per-row proofStatus: "confirmed-by-lsp" (refs=0 in bounded workspace; still inspect entrypoints/exports before deletion), "conflicting-evidence" (refs>0 \u2192 retained, check retainedBy), "needs-framework-graph" (maybe an entrypoint). answerReady:false is normal \u2014 follow next.* for more pages/proof.`,materialize:'(no params; no `where`) clone/cache a bounded corpus (from:{kind:"github",repo} + scope.path) and return a stable materialized checkpoint row (localPath/repoRoot/ref/cache/complete) with next.structure/next.files. Use after GitHub providerUnindexed; for CLI alternatives use clone owner/repo[/path] or cache fetch owner/repo [path] --depth file|tree|clone.'},predicates:{text:'{ kind:"text", value, case?, wholeWord? }',regex:'{ kind:"regex", value, dialect?:"rust"|"pcre2"|"provider", case?, wholeWord?, multiline?, dotAll? }',structural:'{ kind:"structural", lang, pattern? | rule? } (exactly one; rule is a JSON object or grep-compatible YAML rule string) \u2014 pattern must match the COMPLETE node, so include the parts the real node has: a fn WITH a return type only matches if the pattern has one too (`function $N($$$A): $R { $$$B }`); omitting it returns 0. Shapes: `function $N($$$A) { $$$B }` (no-return-type fn), `($$$A) => $$$B` (arrow, block+expression), `$F($$$A)` (call), `$O.$M($$$A)` (method). For "find symbol X" the ROBUST form is a rule, not a pattern: `{ kind:"function_declaration", has:{ pattern:"X" } }`. 0 matches + no parse error = pattern shape \u2260 real node (add `: $R`, or switch to a rule). Note: $$$-only patterns skip files with no literal anchor \u2192 low counts; add a literal name or use a regex where.',field:'{ kind:"field", field:"path"|"basename"|"extension"|"size"|"modified"|"accessed"|"empty"|"permissions"|"executable"|"readable"|"writable"|"entryType", op:"="|"!="|"in"|"exists"|"glob"|"regex"|">"|">="|"<"|"<="|"within"|"before", value? } (use symbolic ops like "="; aliases such as "eq" are invalid; there is no "contains" op \u2014 use op:"glob", value:"*term*" or op:"regex"; "within"/"before" compare modified/accessed times; empty/executable/readable/writable are boolean file attributes paired with op:"exists" or op:"=")',boolean:'{ kind:"all"|"any", of: Predicate[] } | { kind:"not", predicate }'},batch:{queries:"OqlQuery[] (1-5)",combine:"independent | merge"},explainRoutes:{PUSHDOWN:"Backend evaluates this predicate exactly \u2014 good. No residual work.",RESIDUAL:"Backend narrows candidates but OQL must finish evaluation locally.",ROUTE:"OQL must use a different lane, often materialization.",UNSUPPORTED:"OQL cannot execute this predicate safely on the chosen source."},defaults:qt};function cr(){return JSON.stringify(vt,null,2)}import{completeMetadata as lr}from"@octocodeai/octocode-core";var se=null;function ur(){return se||(se=lr),se}async function pr(){return ur()}export{Tt as DIRECT_TOOL_CATEGORIES,$n as DIRECT_TOOL_DEFINITIONS,w as DirectToolInputError,vt as OQL_SCHEMA_DOC,Vn as buildDirectToolCommandPatterns,Ha as buildDirectToolExampleQuery,$ as findDirectToolDefinition,Pt as formatDirectToolCommandPattern,Da as formatDirectToolMetadataSchemaText,Ga as formatDirectToolOutputSchemaText,Ia as formatDirectToolSchemaText,Jn as formatDirectToolValidationIssues,Qa as getDirectToolAutoFilledFields,U as getDirectToolCategory,Na as getDirectToolDescription,_t as getDirectToolDisplayFields,Ma as getDirectToolOutputFields,pr as loadToolContent,cr as oqlSchemaText,Zn as prepareDirectToolInput,ja as prepareDirectToolInputFromJsonText,Fa as sortDirectToolNames};
|
|
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 gr}from"@octocodeai/octocode-core";var se=null;function fr(){return se||(se=gr),se}async function yr(){return fr()}export{kt as DIRECT_TOOL_CATEGORIES,Wn as DIRECT_TOOL_DEFINITIONS,O as DirectToolInputError,F as OQL_SCHEMA_DOC,Zn as buildDirectToolCommandPatterns,Va as buildDirectToolExampleQuery,$ as findDirectToolDefinition,Pt as formatDirectToolCommandPattern,ja as formatDirectToolMetadataSchemaText,Ua as formatDirectToolOutputSchemaText,Ha as formatDirectToolSchemaText,er as formatDirectToolValidationIssues,Ba as getDirectToolAutoFilledFields,U as getDirectToolCategory,$a as getDirectToolDescription,_t as getDirectToolDisplayFields,za as getDirectToolOutputFields,yr as loadToolContent,dr as oqlCompactSchemeJson,hr as oqlCompactSchemeText,pr as oqlSchemaText,Yn as prepareDirectToolInput,Xa as prepareDirectToolInputFromJsonText,Na as sortDirectToolNames};
|
|
@@ -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
|
-
var L=1,
|
|
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
|
|
8
|
+
var L=1,le=".octocoderc";var A={apiUrl:"https://api.github.com"},l={enabled:!0,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},d={enabled:null,enableAdditional:null,disabled:null},C={timeout:3e4,maxRetries:3},v={configPath:void 0},p={format:"yaml",pagination:{defaultCharLength:2e4}},k={version:1,github:A,local:l,tools:d,network:C,lsp:v,output:p},m=5e3,O=3e5,h=0,R=10,T=1e3,_=5e4;import{existsSync as z,readFileSync as Ce}from"node:fs";import{existsSync as Xe,mkdirSync as Ve}from"node:fs";import{join as u,resolve as pe}from"node:path";import w from"node:os";import ce from"node:path";var x=w.platform()==="win32",I=w.platform()==="darwin",de=w.platform()==="linux",g=w.homedir();function M(){return x?process.env.APPDATA||ce.join(g,"AppData","Roaming"):g}var P=".octocode";function K(e){let n=process.env[e];return n&&n.trim().length>0?n:void 0}function ge(){let e=K("OCTOCODE_HOME");return e?pe(e):x?u(M(),P):I?u(g,P):u(K("XDG_CONFIG_HOME")??u(g,".config"),P)}var a=ge(),F={home:a,config:u(a,".octocoderc"),credentials:u(a,"credentials.json"),key:u(a,".key"),session:u(a,"session.json"),stats:u(a,"stats.json"),tmp:u(a,"tmp"),clone:u(a,"tmp","clone"),tree:u(a,"tmp","tree"),binary:u(a,"tmp","binary"),repos:u(a,"tmp","clone"),unzip:u(a,"tmp","unzip"),cliConfig:u(a,"config.json"),lspConfig:u(a,"lsp-servers.json")};import{z as s}from"zod";var D=s.looseObject({$schema:s.string().optional(),version:s.number().int().optional(),github:s.record(s.string(),s.unknown()).optional(),local:s.record(s.string(),s.unknown()).optional(),tools:s.record(s.string(),s.unknown()).optional(),network:s.record(s.string(),s.unknown()).optional(),lsp:s.record(s.string(),s.unknown()).optional(),output:s.record(s.string(),s.unknown()).optional()});var y=F.config;function me(e){let n="",o=0,t=!1,r="";for(;o<e.length;){let i=e[o],f=e[o+1];if(!t&&(i==='"'||i==="'")){t=!0,r=i,n+=i,o++;continue}if(t){if(n+=i,i==="\\"&&o+1<e.length){n+=e[o+1],o+=2;continue}i===r&&(t=!1),o++;continue}if(i==="/"&&f==="/"){for(;o<e.length&&e[o]!==`
|
|
9
|
+
`;)o++;continue}if(i==="/"&&f==="*"){for(o+=2;o<e.length-1;){if(e[o]==="*"&&e[o+1]==="/"){o+=2;break}o++}continue}n+=i,o++}return n=n.replace(/,(\s*[}\]])/g,"$1"),n}function 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};
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Which interface is driving the shared tool core right now.
|
|
3
3
|
*
|
|
4
4
|
* Some config defaults differ by surface (see `resolveLocal`):
|
|
5
|
-
* - `cli`:
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* - `cli`: local tools default to ENABLED; clone defaults to ENABLED.
|
|
6
|
+
* - `mcp`: local tools default to ENABLED; clone defaults to DISABLED.
|
|
7
|
+
*
|
|
8
|
+
* `ENABLE_LOCAL=false` or `local.enabled=false` explicitly disables local tools
|
|
9
|
+
* on every surface.
|
|
9
10
|
*
|
|
10
11
|
* Defaults to `mcp`, the primary consumer. The CLI binary calls
|
|
11
12
|
* `setRuntimeSurface('cli')` at startup before any tool runs.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { TokenSource } from './types.js';
|
|
2
|
-
export declare const ENV_TOKEN_VARS: readonly ["OCTOCODE_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
|
2
|
+
export declare const ENV_TOKEN_VARS: readonly ["OCTOCODE_TOKEN", "GH_TOKEN", "GITHUB_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN"];
|
|
3
3
|
export declare function getTokenFromEnv(): string | null;
|
|
4
4
|
export declare function getEnvTokenSource(): TokenSource;
|
|
5
5
|
export declare function hasEnvToken(): boolean;
|
|
@@ -5,4 +5,4 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
function l(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function f(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let r=new Date;return t.getTime()-r.getTime()<300*1e3}function E(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var
|
|
8
|
+
function l(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function f(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let r=new Date;return t.getTime()-r.getTime()<300*1e3}function E(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var S=new Map,pe=300*1e3;function de(e){let t=l(e),r=S.get(t);return!r||Date.now()-r.cachedAt>=pe?!1:r.credentials?!f(r.credentials):!0}function A(e){e?S.delete(l(e)):S.clear()}function K(e){let t=l(e);if(de(t))return S.get(t).credentials}function U(e,t){let r=l(e);S.set(r,{credentials:t,cachedAt:Date.now()})}import{existsSync as b,readFileSync as q,writeFileSync as J,unlinkSync as Y,statSync as Re,chmodSync as ve}from"node:fs";import{createCipheriv as Ee,createDecipheriv as Ae,randomBytes as Z}from"node:crypto";import{existsSync as ge,mkdirSync as ke}from"node:fs";import{join as a,resolve as Te}from"node:path";import O from"node:os";import he from"node:path";var _=O.platform()==="win32",P=O.platform()==="darwin",me=O.platform()==="linux",k=O.homedir();function H(){return _?process.env.APPDATA||he.join(k,"AppData","Roaming"):k}var N=".octocode",Ce=448;function B(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function xe(){let e=B("OCTOCODE_HOME");return e?Te(e):_?a(H(),N):P?a(k,N):a(B("XDG_CONFIG_HOME")??a(k,".config"),N)}var c=xe(),T={home:c,config:a(c,".octocoderc"),credentials:a(c,"credentials.json"),key:a(c,".key"),session:a(c,"session.json"),stats:a(c,"stats.json"),tmp:a(c,"tmp"),clone:a(c,"tmp","clone"),tree:a(c,"tmp","tree"),binary:a(c,"tmp","binary"),repos:a(c,"tmp","clone"),unzip:a(c,"tmp","unzip"),cliConfig:a(c,"config.json"),lspConfig:a(c,"lsp-servers.json")};function V(){ge(T.home)||ke(T.home,{recursive:!0,mode:Ce})}import{z as i}from"zod";var ye=i.object({token:i.string(),tokenType:i.literal("oauth"),scopes:i.array(i.string()).optional(),refreshToken:i.string().optional(),expiresAt:i.string().optional(),refreshTokenExpiresAt:i.string().optional()}),Se=i.object({hostname:i.string(),username:i.string(),token:ye,gitProtocol:i.enum(["ssh","https"]),createdAt:i.string(),updatedAt:i.string()}),$=i.object({version:i.number(),credentials:i.record(i.string(),Se)});var X=T.home,p=T.credentials,u=T.key,Q="aes-256-gcm",Oe=16;function R(){V()}function ee(){if(R(),b(u))return Re(u).mode&511&63&&ve(u,384),Buffer.from(q(u,"utf8"),"hex");let e=Z(32);return J(u,e.toString("hex"),{mode:384}),e}function F(e){let t=ee(),r=Z(Oe),n=Ee(Q,t,r),o=n.update(e,"utf8","hex");o+=n.final("hex");let s=n.getAuthTag();return`${r.toString("hex")}:${s.toString("hex")}:${o}`}function G(e){let t=ee(),[r,n,o]=e.split(":");if(!r||!n||!o)throw new Error("Invalid encrypted data format");let s=Buffer.from(r,"hex"),g=Buffer.from(n,"hex"),m=Ae(Q,t,s);m.setAuthTag(g);let y=m.update(o,"hex","utf8");return y+=m.final("utf8"),y}function d(){if(R(),!b(p))return{version:1,credentials:{}};try{let e=q(p,"utf8"),t=G(e),r=JSON.parse(t),n=$.safeParse(r);return n.success?n.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function I(e){R();let t=F(JSON.stringify(e,null,2));J(p,t,{mode:384})}function te(){try{b(p)&&Y(p),b(u)&&Y(u)}catch{}}import{refreshToken as _e}from"@octokit/oauth-methods";import{request as be}from"@octokit/request";var C="178c6fc778ccc68e1d6a",h="github.com";function De(e){return e.replace(/\b(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9]{36,}\b/g,"***MASKED***").replace(/\b[a-zA-Z0-9]{40,}\b/g,"***MASKED***")}function we(e){return e==="github.com"||e===h?"https://api.github.com":`https://${e}/api/v3`}async function L(e,t=h,r=C){let n=await e.getCredentials(t);if(!n)return{success:!1,error:`Not logged in to ${t}`};if(!n.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(E(n))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await _e({clientType:"github-app",clientId:r,clientSecret:"",refreshToken:n.token.refreshToken,request:be.defaults({baseUrl:we(t)})}),s={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,s),{success:!0,username:n.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?De(o.message):"Token refresh failed"}}}async function re(e,t=h,r=C){let n=await e.getCredentials(t);if(!n||!n.token)return{token:null,source:"none"};if(!f(n))return{token:n.token.token,source:"stored",username:n.username};if(n.token.refreshToken){let o=await L(e,t,r);if(o.success){let s=await e.getCredentials(t);if(s?.token.token)return{token:s.token.token,source:"refreshed",username:s.username}}return{token:null,source:"none",refreshError:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var v=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN"];function W(){for(let e of v){let t=process.env[e];if(t&&t.trim())return t.trim()}return null}function ne(){for(let e of v){let t=process.env[e];if(t&&t.trim())return`env:${e}`}return null}function oe(){return W()!==null}function se(){for(let e of v){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}import{execFile as Pe}from"child_process";var He=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function j(e){return new Promise(t=>{let r=["auth","token"];e&&r.push("--hostname",e);let n=process.env.PATH??"",o=new Set(n.split(":")),s=He.filter(m=>!o.has(m)),g=s.length?`${s.join(":")}:${n}`:n;Pe("gh",r,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:g}},(m,y)=>{if(m||!y){t(null);return}t(y.trim()||null)})})}var D=null;function ie(e){D=e}function ae(){D=null}function Ne(){if(!D)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return D}async function w(e){let t=e?.hostname??h,r=e?.clientId??C,n=e?.getGhCliToken??j,o=se();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let s=await Ne().getTokenWithRefresh(t,r);if(s.token)return{token:s.token,source:"octocode-storage",wasRefreshed:s.source==="refreshed",username:s.username};try{let g=await Promise.resolve(n(t));if(g?.trim())return{token:g.trim(),source:"gh-cli",wasRefreshed:!1}}catch{}return null}async function ce(e=h){let t=await w({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function le(e=h,t=C){let r=await w({hostname:e,clientId:t,getGhCliToken:()=>null});return r?{token:r.token,source:r.source,wasRefreshed:r.wasRefreshed,username:r.username}:null}async function ue(e){let t=l(e.hostname),r={...e,hostname:t,updatedAt:new Date().toISOString()};try{let n=d();return n.credentials[t]=r,I(n),A(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function x(e="github.com",t){let r=l(e);if(!t?.bypassCache){let s=K(r);if(s!==void 0)return s}let o=d().credentials[r]||null;return U(r,o),o}function M(e="github.com"){let t=l(e);return d().credentials[t]||null}async function Fe(e="github.com"){let t=l(e),r=!1,n=d();return n.credentials[t]&&(delete n.credentials[t],Object.keys(n.credentials).length===0?te():I(n),r=!0),A(t),{success:r,deletedFromFile:r}}async function Ge(){let e=d();return Object.keys(e.credentials)}function Ie(){let e=d();return Object.keys(e.credentials)}async function Le(e="github.com"){return await x(e)!==null}function We(e="github.com"){return M(e)!==null}async function z(e,t){let r=await x(e);return r?(r.token=t,r.updatedAt=new Date().toISOString(),await ue(r),!0):!1}function je(){return p}async function Me(e="github.com"){let t=await x(e);return!t||!t.token||f(t)?null:t.token.token}function ze(e="github.com"){let t=M(e);return!t||!t.token||f(t)?null:t.token.token}async function Ke(e,t){return L({getCredentials:x,updateToken:z},e,t)}async function fe(e,t){return re({getCredentials:x,updateToken:z},e,t)}ie({getTokenWithRefresh:fe});export{p as CREDENTIALS_FILE,v as ENV_TOKEN_VARS,u as KEY_FILE,X as OCTOCODE_DIR,G as decrypt,Fe as deleteCredentials,F as encrypt,R as ensureOctocodeDir,x as getCredentials,je as getCredentialsFilePath,M as getCredentialsSync,ne as getEnvTokenSource,j as getGhCliToken,Me as getToken,W as getTokenFromEnv,ze as getTokenSync,fe as getTokenWithRefresh,Le as hasCredentials,We as hasCredentialsSync,oe as hasEnvToken,A as invalidateCredentialsCache,E as isRefreshTokenExpired,f as isTokenExpired,Ge as listStoredHosts,Ie as listStoredHostsSync,d as readCredentialsStore,Ke as refreshAuthToken,ae as resetTokenResolution,ce as resolveToken,w as resolveTokenFull,le as resolveTokenWithRefresh,ue as storeCredentials,z as updateToken};
|
|
@@ -25,4 +25,4 @@ export interface CredentialsStore {
|
|
|
25
25
|
version: number;
|
|
26
26
|
credentials: Record<string, StoredCredentials>;
|
|
27
27
|
}
|
|
28
|
-
export type TokenSource = 'env:OCTOCODE_TOKEN' | 'env:GH_TOKEN' | 'env:GITHUB_TOKEN' | 'octocode-storage' | 'gh-cli' | null;
|
|
28
|
+
export type TokenSource = 'env:OCTOCODE_TOKEN' | 'env:GH_TOKEN' | 'env:GITHUB_TOKEN' | 'env:GITHUB_PERSONAL_ACCESS_TOKEN' | 'octocode-storage' | 'gh-cli' | null;
|
package/dist/shared/paths.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Octocode's home directory.
|
|
2
|
+
* Octocode's home directory. Set OCTOCODE_HOME to isolate caches in tests/CI.
|
|
3
|
+
* Default per platform:
|
|
3
4
|
* - macOS: `~/.octocode`
|
|
4
5
|
* - Linux: `${XDG_CONFIG_HOME:-~/.config}/.octocode`
|
|
5
6
|
* - Windows: `%APPDATA%\.octocode`
|
package/dist/shared/paths.js
CHANGED
|
@@ -5,4 +5,4 @@ import { dirname as __dirname_fn } from 'path';
|
|
|
5
5
|
const require = __createRequire(import.meta.url);
|
|
6
6
|
const __filename = __fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __dirname_fn(__filename);
|
|
8
|
-
import{existsSync as n,mkdirSync as i}from"node:fs";import{join as e}from"node:path";import
|
|
8
|
+
import{existsSync as n,mkdirSync as i}from"node:fs";import{join as e,resolve as A}from"node:path";import c from"node:os";import x from"node:path";var u=c.platform()==="win32",m=c.platform()==="darwin",v=c.platform()==="linux",r=c.homedir();function d(){return u?process.env.APPDATA||x.join(r,"AppData","Roaming"):r}var l=".octocode",s=448;function g(p){let f=process.env[p];return f&&f.trim().length>0?f:void 0}function O(){let p=g("OCTOCODE_HOME");return p?A(p):u?e(d(),l):m?e(r,l):e(g("XDG_CONFIG_HOME")??e(r,".config"),l)}var t=O(),o={home:t,config:e(t,".octocoderc"),credentials:e(t,"credentials.json"),key:e(t,".key"),session:e(t,"session.json"),stats:e(t,"stats.json"),tmp:e(t,"tmp"),clone:e(t,"tmp","clone"),tree:e(t,"tmp","tree"),binary:e(t,"tmp","binary"),repos:e(t,"tmp","clone"),unzip:e(t,"tmp","unzip"),cliConfig:e(t,"config.json"),lspConfig:e(t,"lsp-servers.json")};function D(){n(o.home)||i(o.home,{recursive:!0,mode:s})}function _(){h()}function a(){D(),n(o.tmp)||i(o.tmp,{recursive:!0,mode:s})}function h(){a(),n(o.clone)||i(o.clone,{recursive:!0,mode:s})}function z(){a(),n(o.tree)||i(o.tree,{recursive:!0,mode:s})}function N(){a(),n(o.binary)||i(o.binary,{recursive:!0,mode:s})}function R(){a(),n(o.unzip)||i(o.unzip,{recursive:!0,mode:s})}export{t as OCTOCODE_HOME,N as ensureBinary,h as ensureClone,D as ensureHome,_ as ensureRepos,a as ensureTmp,z as ensureTree,R as ensureUnzip,O as getDefaultOctocodeHome,o as paths};
|