@octocodeai/octocode-tools-core 16.5.1 → 16.6.0

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