@octocodeai/octocode-tools-core 16.5.1 → 16.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +200 -254
  2. package/dist/direct.js +37 -33
  3. package/dist/errors/localToolErrors.d.ts +1 -0
  4. package/dist/github/githubAPI.d.ts +22 -0
  5. package/dist/github/history.d.ts +3 -0
  6. package/dist/github/prTransformation.d.ts +1 -1
  7. package/dist/index.d.ts +6 -8
  8. package/dist/index.js +44 -40
  9. package/dist/oql/adapters/compile.d.ts +25 -0
  10. package/dist/oql/adapters/github.d.ts +3 -0
  11. package/dist/oql/adapters/local.d.ts +8 -0
  12. package/dist/oql/adapters/materialize.d.ts +11 -0
  13. package/dist/oql/adapters/pagination.d.ts +21 -0
  14. package/dist/oql/adapters/researchTargets.d.ts +50 -0
  15. package/dist/oql/adapters/resultMap.d.ts +20 -0
  16. package/dist/oql/adapters/ruleYaml.d.ts +11 -0
  17. package/dist/oql/adapters/runner.d.ts +14 -0
  18. package/dist/oql/adapters/v2.d.ts +32 -0
  19. package/dist/oql/capabilities.d.ts +31 -0
  20. package/dist/oql/defaults.d.ts +26 -0
  21. package/dist/oql/diagnostics.d.ts +25 -0
  22. package/dist/oql/diffLanes.d.ts +29 -0
  23. package/dist/oql/envelope.d.ts +21 -0
  24. package/dist/oql/features.d.ts +7 -0
  25. package/dist/oql/index.d.ts +27 -0
  26. package/dist/oql/index.js +49 -0
  27. package/dist/oql/normalize.d.ts +5 -0
  28. package/dist/oql/planner.d.ts +7 -0
  29. package/dist/oql/research/analyze.d.ts +134 -0
  30. package/dist/oql/research/packets.d.ts +80 -0
  31. package/dist/oql/run.d.ts +32 -0
  32. package/dist/oql/schema.d.ts +1018 -0
  33. package/dist/oql/schemeText.d.ts +154 -0
  34. package/dist/oql/shorthand.d.ts +177 -0
  35. package/dist/oql/targetParams.d.ts +20 -0
  36. package/dist/oql/transformers/contract.d.ts +19 -0
  37. package/dist/oql/transformers/github/code.d.ts +17 -0
  38. package/dist/oql/transformers/github/common.d.ts +8 -0
  39. package/dist/oql/transformers/language.d.ts +1 -0
  40. package/dist/oql/transformers/registry.d.ts +16 -0
  41. package/dist/oql/transformers/types.d.ts +11 -0
  42. package/dist/oql/types.d.ts +640 -0
  43. package/dist/oql/v2params.d.ts +22 -0
  44. package/dist/providers/types.d.ts +1 -1
  45. package/dist/schema.d.ts +13 -0
  46. package/dist/schema.js +9 -0
  47. package/dist/serverConfig.d.ts +0 -1
  48. package/dist/session.d.ts +2 -24
  49. package/dist/shared/config/defaults.d.ts +1 -2
  50. package/dist/shared/config/index.d.ts +2 -3
  51. package/dist/shared/config/index.js +2 -3
  52. package/dist/shared/config/resolverSections.d.ts +1 -3
  53. package/dist/shared/config/runtimeSurface.d.ts +5 -4
  54. package/dist/shared/config/schemas.d.ts +0 -1
  55. package/dist/shared/config/types.d.ts +0 -8
  56. package/dist/shared/credentials/envTokens.d.ts +1 -1
  57. package/dist/shared/credentials/index.js +1 -2
  58. package/dist/shared/credentials/types.d.ts +1 -1
  59. package/dist/shared/index.d.ts +0 -1
  60. package/dist/shared/languageSelectors.d.ts +23 -0
  61. package/dist/shared/paths.d.ts +2 -3
  62. package/dist/shared/paths.js +1 -1
  63. package/dist/shared/session/index.js +1 -2
  64. package/dist/tools/directToolCatalog.d.ts +15 -56
  65. package/dist/tools/directToolCatalog.exec.d.ts +11 -0
  66. package/dist/tools/directToolCatalog.meta.d.ts +83 -0
  67. package/dist/tools/github_clone_repo/cache.d.ts +1 -1
  68. package/dist/tools/github_clone_repo/types.d.ts +2 -0
  69. package/dist/tools/github_fetch_content/scheme.d.ts +81 -59
  70. package/dist/tools/github_fetch_content/types.d.ts +27 -0
  71. package/dist/tools/local_binary_inspect/binaryInspector.d.ts +0 -4
  72. package/dist/tools/lsp/semantic_content/scheme.d.ts +164 -10
  73. package/dist/tools/lsp/shared/resolveSymbolAnchor.d.ts +2 -2
  74. package/dist/tools/lsp/shared/semanticTypes.d.ts +34 -5
  75. package/dist/tools/oql_search/execution.d.ts +7 -0
  76. package/dist/tools/package_search/execution.d.ts +33 -0
  77. package/dist/tools/package_search/scheme.d.ts +8 -0
  78. package/dist/tools/providerMappers.d.ts +7 -7
  79. package/dist/tools/toolConfig.d.ts +1 -0
  80. package/dist/tools/toolNames.d.ts +2 -0
  81. package/dist/types/server.d.ts +1 -2
  82. package/dist/types/session.d.ts +0 -19
  83. package/dist/utils/contextUtils.d.ts +15 -1
  84. package/dist/utils/core/types.d.ts +2 -1
  85. package/dist/utils/markdownOutline.d.ts +10 -0
  86. package/dist/utils/response/groupedFinalizer.d.ts +0 -23
  87. package/package.json +14 -3
  88. package/dist/commands/BaseCommandBuilder.d.ts +0 -14
  89. package/dist/commands/FindCommandBuilder.d.ts +0 -23
  90. package/dist/commands/LsCommandBuilder.d.ts +0 -15
  91. package/dist/shared/logger/index.d.ts +0 -2
  92. package/dist/shared/logger/logger.d.ts +0 -17
  93. package/dist/utils/pagination/outputSizeLimit.d.ts +0 -16
  94. package/dist/utils/ranking/evidenceRanker.d.ts +0 -86
  95. package/dist/utils/response/structuredPagination.d.ts +0 -9
package/dist/index.js CHANGED
@@ -5,53 +5,57 @@ 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{withSecurityValidation as Gm,withBasicSecurityValidation as Um}from"@octocodeai/octocode-engine/security";function Qa(e,t){let n=Gm(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function ja(e,t){let n=Um(r=>e(r),t);return(r,o)=>n(r,o)}var $a=class{command;args=[];constructor(t){this.command=t}addFlag(t){return this.args.push(t),this}addOption(t,n){return this.args.push(t,String(n)),this}addArg(t){return this.args.push(t),this}build(){return{command:this.command,args:[...this.args]}}reset(){return this.args=[],this}getArgs(){return[...this.args]}};var Be=30,pe=100,Gx=10,Ux=100,Va=200,Mt=20,Wa=100,Ka=20,Hr=50,tn=1e4,nn=20,Gr=1e3,Ya=100,rn=5e4,Xa=8e3,Ur=1e5,Ja=500;var hi={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},bt={PROMISES_NOT_ARRAY:{code:"VALIDATION_PROMISES_NOT_ARRAY",message:"promises must be an array"},TIMEOUT_NOT_POSITIVE:{code:"VALIDATION_TIMEOUT_NOT_POSITIVE",message:"timeout must be positive"},CONCURRENCY_NOT_POSITIVE:{code:"VALIDATION_CONCURRENCY_NOT_POSITIVE",message:"concurrency must be positive"}},St={FETCH_NOT_AVAILABLE:{code:"FETCH_NOT_AVAILABLE",message:"Global fetch is not available in this environment."},FETCH_FAILED_AFTER_RETRIES:{code:"FETCH_FAILED_AFTER_RETRIES",message:(e,t)=>`Failed to fetch after ${e} attempts: ${t}`},FETCH_HTTP_ERROR:{code:"FETCH_HTTP_ERROR",message:(e,t)=>`Failed to fetch (${e} ${t})`}},Bm={INVALID_FORMAT:{code:"TOOL_METADATA_INVALID_FORMAT",message:"Invalid tool metadata format from remote source."},INVALID_API_RESPONSE:{code:"TOOL_METADATA_INVALID_API_RESPONSE",message:"Invalid API response structure"}},Oe={PATH_IS_DIRECTORY:{code:"FILE_PATH_IS_DIRECTORY",message:e=>`Path is a directory. Use ${e} to list directory contents`},FILE_TOO_LARGE:{code:"FILE_TOO_LARGE",message:(e,t,n)=>`File too large (${e}KB > ${t}KB). Use ${n} to search within the file or use startLine/endLine parameters to get specific sections`},FILE_EMPTY:{code:"FILE_EMPTY",message:"File is empty - no content to display"},BINARY_FILE:{code:"FILE_BINARY",message:"Binary file detected. Cannot display as text - download directly from GitHub"},DECODE_FAILED:{code:"FILE_DECODE_FAILED",message:"Failed to decode file. Encoding may not be supported (expected UTF-8)"},UNSUPPORTED_TYPE:{code:"FILE_UNSUPPORTED_TYPE",message:e=>`Unsupported file type: ${e}`}},et={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},oe={QUERY_EMPTY:{code:"SEARCH_QUERY_EMPTY",message:"Search query cannot be empty"},NO_VALID_PARAMETERS:{code:"SEARCH_NO_VALID_PARAMETERS",message:"No valid search parameters provided"},PR_REQUIRED_PARAMS:{code:"SEARCH_PR_REQUIRED_PARAMS",message:"Owner, repo, and prNumber are required parameters"},PR_SINGLE_VALUES:{code:"SEARCH_PR_SINGLE_VALUES",message:"Owner and repo must be single values"},PULL_REQUEST_SEARCH_FAILED:{code:"SEARCH_PR_SEARCH_FAILED",message:e=>`Pull request search failed: ${e}`},PULL_REQUEST_LIST_FAILED:{code:"SEARCH_PR_LIST_FAILED",message:e=>`Pull request list failed: ${e}`},PULL_REQUEST_FETCH_FAILED:{code:"SEARCH_PR_FETCH_FAILED",message:(e,t)=>`Failed to fetch pull request #${e}: ${t}`}},zm={NO_TOOLS_REGISTERED:{code:"STARTUP_NO_TOOLS_REGISTERED",message:"No tools were successfully registered"},UNCAUGHT_EXCEPTION:{code:"STARTUP_UNCAUGHT_EXCEPTION",message:e=>`Uncaught exception: ${e}`},UNHANDLED_REJECTION:{code:"STARTUP_UNHANDLED_REJECTION",message:e=>`Unhandled rejection: ${e}`},STARTUP_FAILED:{code:"STARTUP_FAILED",message:e=>`Startup failed: ${e}`}},Ct={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},Br={EXECUTION_FAILED:{code:"TOOL_EXECUTION_FAILED",message:(e,t)=>`Tool ${e} execution failed: ${t}`},SECURITY_VALIDATION_FAILED:{code:"TOOL_SECURITY_VALIDATION_FAILED",message:(e,t)=>`Security validation failed for ${e}: ${t}`}},zx={...hi,...bt,...St,...Bm,...Oe,...et,...oe,...zm,...Ct,...Br};var H={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed"},Qm=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(Qm||{}),Za={[H.PATH_VALIDATION_FAILED]:{code:H.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[H.FILE_ACCESS_FAILED]:{code:H.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[H.FILE_READ_FAILED]:{code:H.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[H.FILE_TOO_LARGE]:{code:H.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[H.BINARY_FILE_UNSUPPORTED]:{code:H.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[H.NO_MATCHES]:{code:H.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[H.OUTPUT_TOO_LARGE]:{code:H.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[H.COMMAND_NOT_AVAILABLE]:{code:H.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[H.COMMAND_EXECUTION_FAILED]:{code:H.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[H.COMMAND_TIMEOUT]:{code:H.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[H.TOOL_EXECUTION_FAILED]:{code:H.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"}};var Te=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=Za[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
9
- Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}};function yi(e){return e instanceof Te}function qa(e,t=H.TOOL_EXECUTION_FAILED,n){if(yi(e))return e;if(e instanceof Error)return new Te(t,e.message,n,e);let r=String(e);return new Te(t,r,n)}import{redactPath as Nn}from"@octocodeai/octocode-engine/pathUtils";var De={pathValidationFailed:(e,t,n)=>new Te(H.PATH_VALIDATION_FAILED,t||`Path validation failed: ${Nn(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=Nn(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Te(H.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Te(H.FILE_READ_FAILED,`Failed to read file: ${Nn(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Te(H.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Te(H.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${Nn(e)}`,{path:e}),outputTooLarge:(e,t)=>new Te(H.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Te(H.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new Te(H.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Te(H.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)};import{Octokit as oh}from"octokit";import{throttling as ih}from"@octokit/plugin-throttling";import{createHash as sh}from"crypto";var Ri=null;function jm(e){let t=`[${e.module}]`,n=e.data&&Object.keys(e.data).length>0?` ${JSON.stringify(e.data)}`:"";process.stderr.write(`${t} ${e.level}: ${e.message}${n}
10
- `)}function ec(e){Ri=e}function tc(){return Ri}function tt(e){function t(n,r,o){let i={level:n,module:e,message:r,...o&&{data:o}};(Ri??jm)(i)}return{debug:(n,r)=>t("debug",n,r),info:(n,r)=>t("info",n,r),warn:(n,r)=>t("warn",n,r),error:(n,r)=>t("error",n,r)}}function nt(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function ct(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let n=new Date;return t.getTime()-n.getTime()<300*1e3}function Dn(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Hn=new Map,$m=300*1e3;function Vm(e){let t=nt(e),n=Hn.get(t);return!n||Date.now()-n.cachedAt>=$m?!1:n.credentials?!ct(n.credentials):!0}function Gn(e){e?Hn.delete(nt(e)):Hn.clear()}function nc(e){let t=nt(e);if(Vm(t))return Hn.get(t).credentials}function rc(e,t){let n=nt(e);Hn.set(n,{credentials:t,cachedAt:Date.now()})}import{existsSync as Qr,readFileSync as fc,writeFileSync as mc,unlinkSync as dc,statSync as tg,chmodSync as ng}from"node:fs";import{createCipheriv as rg,createDecipheriv as og,randomBytes as gc}from"node:crypto";import{existsSync as Dt,mkdirSync as Ht}from"node:fs";import{join as fe}from"node:path";import on from"node:os";import oc from"node:path";var Nt=on.platform()==="win32",Un=on.platform()==="darwin",bi=on.platform()==="linux",ut=on.homedir();function zr(){return Nt?process.env.APPDATA||oc.join(ut,"AppData","Roaming"):ut}function ic(){return Nt?process.env.LOCALAPPDATA||oc.join(ut,"AppData","Local"):ut}function sc(){return Un?"macOS":Nt?"Windows":bi?"Linux":on.platform()}function ac(){return on.arch()}var Si=".octocode",Gt=448;function Wm(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function cc(){return Nt?fe(zr(),Si):Un?fe(ut,Si):fe(Wm("XDG_CONFIG_HOME")??fe(ut,".config"),Si)}var be=cc(),W={home:be,config:fe(be,".octocoderc"),credentials:fe(be,"credentials.json"),key:fe(be,".key"),session:fe(be,"session.json"),stats:fe(be,"stats.json"),tmp:fe(be,"tmp"),clone:fe(be,"tmp","clone"),tree:fe(be,"tmp","tree"),binary:fe(be,"tmp","binary"),repos:fe(be,"tmp","clone"),logs:fe(be,"logs"),unzip:fe(be,"tmp","unzip"),cliConfig:fe(be,"config.json"),lspConfig:fe(be,"lsp-servers.json")};function Bn(){Dt(W.home)||Ht(W.home,{recursive:!0,mode:Gt})}function Km(){uc()}function zn(){Bn(),Dt(W.tmp)||Ht(W.tmp,{recursive:!0,mode:Gt})}function uc(){zn(),Dt(W.clone)||Ht(W.clone,{recursive:!0,mode:Gt})}function Ym(){Bn(),Dt(W.logs)||Ht(W.logs,{recursive:!0,mode:Gt})}function Xm(){zn(),Dt(W.tree)||Ht(W.tree,{recursive:!0,mode:Gt})}function Jm(){zn(),Dt(W.binary)||Ht(W.binary,{recursive:!0,mode:Gt})}function Zm(){zn(),Dt(W.unzip)||Ht(W.unzip,{recursive:!0,mode:Gt})}import{z as me}from"zod";var qm=me.object({token:me.string(),tokenType:me.literal("oauth"),scopes:me.array(me.string()).optional(),refreshToken:me.string().optional(),expiresAt:me.string().optional(),refreshTokenExpiresAt:me.string().optional()}),eg=me.object({hostname:me.string(),username:me.string(),token:qm,gitProtocol:me.enum(["ssh","https"]),createdAt:me.string(),updatedAt:me.string()}),lc=me.object({version:me.number(),credentials:me.record(me.string(),eg)});var pc=tt("token-storage");function ig(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 Ci=W.home,Ye=W.credentials,rt=W.key,hc="aes-256-gcm",sg=16;function Pt(){Bn()}function yc(){if(Pt(),Qr(rt))return tg(rt).mode&511&63&&ng(rt,384),Buffer.from(fc(rt,"utf8"),"hex");let e=gc(32);return mc(rt,e.toString("hex"),{mode:384}),e}function jr(e){let t=yc(),n=gc(sg),r=rg(hc,t,n),o=r.update(e,"utf8","hex");o+=r.final("hex");let i=r.getAuthTag();return`${n.toString("hex")}:${i.toString("hex")}:${o}`}function $r(e){let t=yc(),[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"hex"),s=Buffer.from(r,"hex"),a=og(hc,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function lt(){if(Pt(),!Qr(Ye))return{version:1,credentials:{}};try{let e=fc(Ye,"utf8"),t=$r(e),n=JSON.parse(t),r=lc.safeParse(n);return r.success?r.data:(pc.warn("Credentials file has invalid format \u2014 starting fresh",{file:Ye}),{version:1,credentials:{}})}catch(e){let t=e instanceof Error&&e.message?ig(e.message):void 0;return pc.warn("Could not read credentials file \u2014 you may need to login again",{file:Ye,...t&&{reason:t}}),{version:1,credentials:{}}}}function Pi(e){Pt();let t=jr(JSON.stringify(e,null,2));mc(Ye,t,{mode:384})}function Rc(){try{Qr(Ye)&&dc(Ye),Qr(rt)&&dc(rt)}catch{}}import{refreshToken as ag}from"@octokit/oauth-methods";import{request as cg}from"@octokit/request";var sn="178c6fc778ccc68e1d6a",Et="github.com";function ug(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 lg(e){return e==="github.com"||e===Et?"https://api.github.com":`https://${e}/api/v3`}async function Ei(e,t=Et,n=sn){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(Dn(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await ag({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:cg.defaults({baseUrl:lg(t)})}),i={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,i),{success:!0,username:r.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?ug(o.message):"Token refresh failed"}}}async function bc(e,t=Et,n=sn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!ct(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Ei(e,t,n);if(o.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:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var an=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN"];function Vr(){for(let e of an){let t=process.env[e];if(t&&t.trim())return t.trim()}return null}function Ti(){for(let e of an){let t=process.env[e];if(t&&t.trim())return`env:${e}`}return null}function xi(){return Vr()!==null}function Sc(){for(let e of an){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}import{execFile as dg}from"child_process";var pg=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"];function Wr(e){return new Promise(t=>{let n=["auth","token"];e&&n.push("--hostname",e);let r=process.env.PATH??"",o=new Set(r.split(":")),i=pg.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;dg("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var Kr=null;function Cc(e){Kr=e}function _i(){Kr=null}function fg(){if(!Kr)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Kr}async function Tt(e){let t=e?.hostname??Et,n=e?.clientId??sn,r=e?.getGhCliToken??Wr,o=Sc();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await fg().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch{}return null}async function wi(e=Et){let t=await Tt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function Ai(e=Et,t=sn){let n=await Tt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var mg=tt("token-storage");async function Li(e){let t=nt(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=lt();return r.credentials[t]=n,Pi(r),Gn(t),{success:!0}}catch(r){let o=r instanceof Error?r.message:String(r);throw mg.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 Ut(e="github.com",t){let n=nt(e);if(!t?.bypassCache){let i=nc(n);if(i!==void 0)return i}let o=lt().credentials[n]||null;return rc(n,o),o}function Yr(e="github.com"){let t=nt(e);return lt().credentials[t]||null}async function Pc(e="github.com"){let t=nt(e),n=!1,r=lt();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Rc():Pi(r),n=!0),Gn(t),{success:n,deletedFromFile:n}}async function Ec(){let e=lt();return Object.keys(e.credentials)}function Tc(){let e=lt();return Object.keys(e.credentials)}async function xc(e="github.com"){return await Ut(e)!==null}function _c(e="github.com"){return Yr(e)!==null}async function Xr(e,t){let n=await Ut(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Li(n),!0):!1}function wc(){return Ye}async function Ac(e="github.com"){let t=await Ut(e);return!t||!t.token||ct(t)?null:t.token.token}function Lc(e="github.com"){let t=Yr(e);return!t||!t.token||ct(t)?null:t.token.token}async function Oc(e,t){return Ei({getCredentials:Ut,updateToken:Xr},e,t)}async function Oi(e,t){return bc({getCredentials:Ut,updateToken:Xr},e,t)}Cc({getTokenWithRefresh:Oi});import{randomUUID as Ag}from"node:crypto";import{existsSync as Ii,readFileSync as Mc,writeFileSync as bg,unlinkSync as Sg,renameSync as Cg}from"node:fs";import{z}from"zod";var gg=z.object({rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),calls:z.number()}),hg=z.object({hits:z.record(z.string(),z.number()).default({}),rateLimits:z.number().default(0)}),Jr=z.record(z.string(),z.number()).default({}),yg=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:Jr,rawChars:z.number(),responseChars:z.number(),savedChars:z.number(),charSavingsCalls:z.number(),githubCacheHits:z.number(),githubCacheRateLimits:z.number(),packageRegistryFailures:z.number().default(0),packageRegistryFailuresByRegistry:Jr}),Zr=z.object({toolCalls:z.number(),errors:z.number(),rateLimits:z.number(),rateLimitsByProvider:Jr,charsSavedByTool:z.record(z.string(),gg).default({}),githubCacheHits:hg.default({hits:{},rateLimits:0}),packageRegistryFailures:Jr,totalUsage:yg.optional()}),Ic=z.object({version:z.literal(1),sessionId:z.string(),createdAt:z.string(),lastActiveAt:z.string(),stats:Zr.optional()}),kc=z.object({version:z.literal(1),stats:Zr});function vc(e){return Object.values(e).reduce((t,n)=>t+n,0)}function Rg(e){let t=e.charsSavedByTool??{},n=e.githubCacheHits??{hits:{},rateLimits:0},r=e.rateLimitsByProvider??{},o=e.packageRegistryFailures??{},i=Object.values(t).reduce((s,a)=>({rawChars:s.rawChars+a.rawChars,responseChars:s.responseChars+a.responseChars,savedChars:s.savedChars+a.savedChars,charSavingsCalls:s.charSavingsCalls+a.calls}),{rawChars:0,responseChars:0,savedChars:0,charSavingsCalls:0});return{toolCalls:e.toolCalls,errors:e.errors,rateLimits:e.rateLimits,rateLimitsByProvider:r,...i,githubCacheHits:vc(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:vc(o),packageRegistryFailuresByRegistry:o}}function dt(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:Rg(t)}}function Qn(){return dt({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Nc=tt("session"),xt=W.session,_t=W.stats;function Fc(e,t){let n=`${e}.tmp`;bg(n,JSON.stringify(t,null,2),{mode:384}),Cg(n,e)}function Pg(e){let{stats:t,...n}=e;return n}function Eg(e){let t=JSON.parse(e),n=kc.safeParse(t);if(n.success)return dt(n.data.stats);let r=Zr.safeParse(t);return r.success?dt(r.data):null}function Tg(e){let t=e?dt(e):Qn();if(!Ii(_t))return t;try{let n=Mc(_t,"utf8"),r=Eg(n);return r||(Nc.warn("Stats file has invalid format",{file:_t}),t)}catch{return t}}function qr(e){Pt(),Fc(_t,{version:e.version,stats:dt(e.stats)}),Fc(xt,Pg(e))}function Dc(){if(!Ii(xt))return null;try{let e=Mc(xt,"utf8"),t=JSON.parse(e),n=Ic.safeParse(t);return n.success?{...n.data,stats:Tg(n.data.stats)}:(Nc.warn("Session file has invalid format",{file:xt}),null)}catch{return null}}function Hc(){let e=!1;for(let t of[xt,_t])if(Ii(t))try{Sg(t),e=!0}catch{return!1}return e}var xg=6e4,Xe=null,wt=!1,cn=null,ki=!1,jn=null,$n=null,Vn=null,eo=!1;function _g(){ki||(ki=!0,jn=()=>{Wn()},$n=()=>{Wn()},Vn=()=>{Wn()},process.on("exit",jn),process.on("SIGINT",$n),process.on("SIGTERM",Vn))}function vi(){jn&&(process.removeListener("exit",jn),jn=null),$n&&(process.removeListener("SIGINT",$n),$n=null),Vn&&(process.removeListener("SIGTERM",Vn),Vn=null),ki=!1}function wg(){cn||(cn=setInterval(()=>{wt&&Xe&&(qr(Xe),wt=!1)},xg),cn.unref())}function Fi(){cn&&(clearInterval(cn),cn=null)}function Kn(){if(Xe)return Xe;let e=Dc();return e&&(Xe=e),e}function un(e){Xe=e,wt=!0,_g(),wg()}function Yn(){wt&&Xe&&(qr(Xe),wt=!1)}function Wn(){if(!eo&&wt&&Xe){eo=!0;try{qr(Xe),wt=!1}catch{}finally{eo=!1}}}function Mi(){Xe=null,wt=!1,eo=!1}function Gc(){Mi(),Fi(),vi()}var Lg=1;function Og(e){return dt(e)}function Ig(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let i=n[r]??{rawChars:0,responseChars:0,savedChars:0,calls:0};n[r]={rawChars:i.rawChars+o.rawChars,responseChars:i.responseChars+o.responseChars,savedChars:i.savedChars+o.savedChars,calls:i.calls+o.calls}}return n}function Uc(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function kg(e,t){if(!t)return e;let n={...e.hits};for(let[r,o]of Object.entries(t.hits??{}))n[r]=(n[r]??0)+o;return{hits:n,rateLimits:e.rateLimits+(t.rateLimits??0)}}function Bc(){let e=new Date().toISOString();return{version:Lg,sessionId:Ag(),createdAt:e,lastActiveAt:e,stats:Qn()}}function zc(){Yn()}function Qc(){Wn()}function to(e){if(e?.forceNew){let r=Bc();return un(r),Yn(),r}let t=Kn();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return un(r),Yn(),r}let n=Bc();return un(n),Yn(),n}function jc(){return Kn()?.sessionId??null}function He(e){let t=Kn();if(!t)return{success:!1,session:null};let n=Og(t.stats),r=dt({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:Uc(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:Ig(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:kg(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:Uc(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return un(o),{success:!0,session:o}}function no(e=1){return He({toolCalls:e})}function ro(e=1){return He({errors:e})}function oo(e=1){return He({rateLimits:e})}function $c(e,t=1){return He({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function io(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return He({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function so(e,t=1){return He({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ao(e=1){return He({githubCacheHits:{hits:{},rateLimits:e}})}function Vc(e,t=1){return He({packageRegistryFailures:{[e]:t}})}function Wc(){let e=Kn();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:Qn()};return un(t),{success:!0,session:t}}function Kc(){return Mi(),Fi(),vi(),Hc()}function Yc(){Gc()}var Xn=1,Xc=".octocoderc";var Jn={apiUrl:"https://api.github.com"},At={enabled:!1,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},Bt={enabled:null,enableAdditional:null,disabled:null},ln={timeout:3e4,maxRetries:3},Zn={logging:!0},qn={configPath:void 0},pt={format:"yaml",pagination:{defaultCharLength:2e4}},co={version:1,github:Jn,local:At,tools:Bt,network:ln,telemetry:Zn,lsp:qn,output:pt},dn=5e3,pn=3e5,fn=0,mn=10,gn=1e3,hn=5e4;import{existsSync as Jc,readFileSync as vg}from"node:fs";import{z as te}from"zod";var uo=te.looseObject({$schema:te.string().optional(),version:te.number().int().optional(),github:te.record(te.string(),te.unknown()).optional(),local:te.record(te.string(),te.unknown()).optional(),tools:te.record(te.string(),te.unknown()).optional(),network:te.record(te.string(),te.unknown()).optional(),telemetry:te.record(te.string(),te.unknown()).optional(),lsp:te.record(te.string(),te.unknown()).optional(),output:te.record(te.string(),te.unknown()).optional()});var er=W.config;function Fg(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
11
- `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t=t.replace(/,(\s*[}\]])/g,"$1"),t}function Mg(e){let t=Fg(e);return JSON.parse(t)}function lo(){return Jc(er)}async function Zc(){return tr()}function tr(){let e=er;if(!Jc(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=vg(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=Mg(t),r=uo.safeParse(n);return r.success?{success:!0,config:r.data,path:e}:{success:!1,error:`Config file has invalid structure: ${r.error.issues[0]?.message??"unknown error"}`,path:e}}catch(t){return{success:!1,error:`Failed to parse config file: ${t instanceof Error?t.message:"Unknown error"}`,path:e}}}function qc(){return er}function zt(){return W.home}function Ng(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function Di(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function Hi(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function eu(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function Dg(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function Ni(e,t){return e===void 0||e===null?null:eu(e,t)}function tu(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function Hg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=Ng(e.apiUrl,"github.apiUrl");r&&t.push(r)}function Gg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=Hi(n.enabled,"local.enabled");r&&t.push(r);let o=Hi(n.enableClone,"local.enableClone");o&&t.push(o);let i=eu(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=Dg(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=tu(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function Ug(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=Ni(n.enabled,"tools.enabled");r&&t.push(r);let o=Ni(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=Ni(n.disabled,"tools.disabled");i&&t.push(i)}function Bg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=Di(n.timeout,"network.timeout",dn,pn);r&&t.push(r);let o=Di(n.maxRetries,"network.maxRetries",fn,mn);o&&t.push(o)}function zg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("telemetry: Must be an object");return}let r=Hi(e.logging,"telemetry.logging");r&&t.push(r)}function Qg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=tu(e.configPath,"lsp.configPath");r&&t.push(r)}function jg(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=Di(r.defaultCharLength,"output.pagination.defaultCharLength",gn,hn);o&&t.push(o)}}function po(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>1&&n.push(`version: Config version ${r.version} is newer than supported version ${1}`)),Hg(r.github,t),Gg(r.local,t),Ug(r.tools,t),Bg(r.network,t),zg(r.telemetry,t),Qg(r.lsp,t),jg(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","telemetry","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}var $g="__octocodeRuntimeSurface__";function Gi(){return globalThis[$g]??"mcp"}function nu(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Ui(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function fo(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function Bi(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!=="")return!(t==="false"||t==="0")}function ru(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||Jn.apiUrl}}function ou(e){let t=Gi()==="cli",n=nu(process.env.ENABLE_LOCAL),r=nu(process.env.ENABLE_CLONE),o=fo(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??(t?!0:At.enabled),enableClone:r??e?.enableClone??(t?!0:At.enableClone),allowedPaths:o??e?.allowedPaths??At.allowedPaths,workspaceRoot:i??e?.workspaceRoot??At.workspaceRoot}}function iu(e){let t=fo(process.env.TOOLS_TO_RUN),n=fo(process.env.ENABLE_TOOLS),r=fo(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??Bt.enabled,enableAdditional:n??e?.enableAdditional??Bt.enableAdditional,disabled:r??e?.disabled??Bt.disabled}}function su(e){let t=Ui(process.env.REQUEST_TIMEOUT),n=Ui(process.env.MAX_RETRIES),r=t??e?.timeout??ln.timeout;r=Math.max(dn,Math.min(pn,r));let o=n??e?.maxRetries??ln.maxRetries;return o=Math.max(fn,Math.min(mn,o)),{timeout:r,maxRetries:o}}function au(e){return{logging:Bi(process.env.LOG)??e?.logging??Zn.logging}}function cu(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??qn.configPath}}var Vg=new Set(["yaml","json"]);function uu(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=Ui(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||pt.format,o=n??e?.pagination?.defaultCharLength??pt.pagination.defaultCharLength,i=Math.max(gn,Math.min(hn,o));return{format:Vg.has(r)?r:pt.format,pagination:{defaultCharLength:i}}}var mo=tt("octocode-config");function zi(e,t){let n=e!==void 0,r=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,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??co.version,github:ru(e?.github),local:ou(e?.local),tools:iu(e?.tools),network:su(e?.network),telemetry:au(e?.telemetry),lsp:cu(e?.lsp),output:uu(e?.output),source:o,configPath:n?t:void 0}}function rr(){let e=tr();if(e.success&&e.config){let t=po(e.config);if(t.warnings.length>0)for(let n of t.warnings)mo.warn(`Warning: ${n}`);if(!t.valid){for(let n of t.errors)mo.warn(`Validation error: ${n}`);return mo.warn("Config file has validation errors \u2014 falling back to defaults with env overrides"),zi(void 0)}return zi(e.config,e.path)}return e.error&&lo()&&mo.warn(e.error),zi(void 0)}async function Qi(){return rr()}var Qt=null,nr=0,Wg=6e4;function ae(){let e=Date.now();return Qt&&e-nr<Wg||(Qt=rr(),nr=e),Qt}async function go(){return ae()}async function ji(){return yn(),go()}function yn(){Qt=null,nr=0}function $i(){Qt=null,nr=0}function Vi(){return{cached:Qt!==null,timestamp:nr}}function lu(e){let t=ae(),n=e.split("."),r=t;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}import{existsSync as Kg,readdirSync as Yg,lstatSync as Xg}from"node:fs";import{join as Jg}from"node:path";function or(e){if(!Kg(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Yg(r)}catch{continue}for(let i of o){let s=Jg(r,i);try{let a=Xg(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function Zg(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}var ft="16.5.1";import{maskSensitiveData as eh}from"@octocodeai/octocode-engine/mask";var jt=null,Rn=null,Wi=Tt;function RA(e){e.resolveTokenFull&&(Wi=e.resolveTokenFull)}function bA(){Wi=Tt}var th=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","octocode-storage","gh-cli","none"]);async function Ki(){try{let e=await Wi({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:th.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function du(){if(jt!==null)return;if(Rn!==null)return Rn;let e=(async()=>{let t=ae(),n=await Ki();jt={version:ft,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,loggingEnabled:t.telemetry.logging,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();Rn=e;try{await e}catch(t){throw Rn===e&&(jt=null,Rn=null),t}}function SA(){jt=null,Rn=null,yn()}function ho(){if(!jt){let e=eh(hi.NOT_INITIALIZED.message);throw new Error(e)}return jt}async function pu(){return(await Ki()).token}function CA(){return ho().enableLocal}function PA(){let e=ho();return e.enableLocal&&e.enableClone}function fu(){return jt?.loggingEnabled??!1}async function EA(){return(await Ki()).source}function ir(){return"github"}function Yi(){let e=ae().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}import{completeMetadata as nh}from"@octocodeai/octocode-core";var Ie="lspGetSemantics",mu=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation"];function bn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function Xi(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var ge=nh.toolNames,rh=new Set([ge.LOCAL_RIPGREP,ge.LOCAL_FETCH_CONTENT,ge.LOCAL_FIND_FILES,ge.LOCAL_VIEW_STRUCTURE,ge.LOCAL_BINARY_INSPECT,Ie]);function Ji(e){return rh.has(e)}var Zi=class{session;logEndpoint="https://octocode-mcp-host.onrender.com/log";constructor(){this.session=to()}getSessionId(){return this.session.sessionId}getSession(){return this.session}async logInit(){await this.sendLog("init",{})}async logToolCall(t,n,r,o,i){let s=no(1);s.session&&(this.session=s.session);let a={tool_name:t,repos:Ji(t)?[]:n.map(()=>"[redacted]"),provider:Ji(t)?void 0:ir()};await this.sendLog("tool_call",a)}async logError(t,n){let r=ro(1);r.session&&(this.session=r.session),await this.sendLog("error",{error:`${t}:${n}`})}async logRateLimit(t){let n=t.provider?He({rateLimits:1,rateLimitsByProvider:{[t.provider]:1}}):oo(1);if(n.session&&(this.session=n.session),t.provider==="github"){let r=ao(1);r.session&&(this.session=r.session)}await this.sendLog("rate_limit",t)}logPackageRegistryFailure(t){let n=He({packageRegistryFailures:{[t]:1}});n.session&&(this.session=n.session)}async sendLog(t,n){if(!(t!=="init"&&!fu()))try{let r={sessionId:this.session.sessionId,intent:t,data:n,timestamp:new Date().toISOString(),version:ft};await fetch(this.logEndpoint,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)})}catch{}}},sr=null;function vA(){return sr||(sr=new Zi),sr}function Sn(){return sr}async function FA(){let e=Sn();e&&await e.logInit()}async function MA(e,t,n,r,o){let i=Sn();i&&await i.logToolCall(e,t,n,r,o)}async function NA(e){let t=Sn();t&&await t.logToolCall(e,[],void 0,void 0,void 0)}async function M(e,t){let n=Sn();n&&await n.logError(e,t)}async function Lt(e){let t=Sn();t&&await t.logRateLimit(e)}function gu(e){let t=Sn();t&&t.logPackageRegistryFailure(e)}function DA(){sr=null}function ah(e){return sh("sha256").update(e).digest("hex").substring(0,16)}var ch=oh.plugin(ih),uh=300*1e3,qi=50,lh=60*1e3;function es(e){return Date.now()-e.createdAt>uh}var ze=new Map,Cn=null,Ot=null;function Cu(){for(let[e,t]of ze.entries())es(t)&&ze.delete(e);if(ze.size>qi){let e=[...ze.entries()].filter(([n])=>n!=="DEFAULT").sort((n,r)=>n[1].createdAt-r[1].createdAt),t=ze.size-qi;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&ze.delete(r[0])}}}function dh(){Ot||(Ot=setInterval(Cu,lh),typeof Ot=="object"&&"unref"in Ot&&Ot.unref())}var hu=3,yu=60;function Ru(e,t,n){Lt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}var ph=()=>({onRateLimit:(e,t,n,r)=>(Ru("primary",e,t),r<hu&&e<yu),onSecondaryRateLimit:(e,t,n,r)=>(Ru("secondary",e,t),r<hu&&e<yu)});function bu(e){let t=ho(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${ft}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:ph(),log:r,...e&&{auth:e}};return new ch(o)}async function ie(e){if(dh(),e?.token){let n=ah(e.token),r=ze.get(n);if(r&&!es(r))return r.client;ze.size>=qi&&Cu();let o=bu(e.token);return ze.set(n,{client:o,createdAt:Date.now()}),o}let t=ze.get("DEFAULT");return t&&!es(t)?t.client:Cn||(Cn=(async()=>{try{let n=await pu(),r=bu(n??void 0);return ze.set("DEFAULT",{client:r,createdAt:Date.now()}),r}finally{Cn=null}})(),Cn)}var fh=200,Pn=new Map;async function Ge(e,t,n){let r=`${e}/${t}`,o=Pn.get(r);if(o)return o;let i=await ie(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Su(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),Su(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Su(e,t){if(Pn.size>=fh){let n=Pn.keys().next().value;n!==void 0&&Pn.delete(n)}Pn.set(e,t)}function VA(){ze.clear(),Cn=null,Pn.clear(),Ot&&(clearInterval(Ot),Ot=null)}import{ContentSanitizer as Kh}from"@octocodeai/octocode-engine/contentSanitizer";import{createRequire as mh}from"node:module";var gh=mh(import.meta.url),Pu="@octocodeai/octocode-engine",yo,hh=()=>gh(Pu),ts=class extends Error{constructor(n){super(`Failed to load native dependency ${Pu}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};function K(){if(yo)return yo;try{return yo=hh(),yo}catch(e){throw new ts(e)}}var O={applyContentViewMinification(e,t){return K().applyContentViewMinification(e,t)},applyMinification(e,t){return K().applyMinification(e,t)},minifyContent(e,t){return K().minifyContent(e,t)},minifyContentSync(e,t){return K().minifyContentSync(e,t)},minifyContentResult(e,t){return K().minifyContentResult(e,t)},minifyMarkdownCore(e){return K().minifyMarkdownCore(e)},extractSignatures(e,t){return K().extractSignatures(e,t)},extractJsSymbols(e,t){return K().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return K().findInFileReferences(e,t,n,r)},getSupportedJsTsExtensions(){return K().getSupportedJsTsExtensions()},structuralSearch(e,t,n,r){return K().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return K().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return K().getSupportedStructuralExtensions()},inspectBinaryNative(e){return K().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return K().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return K().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return K().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return K().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return K().parseRipgrepJson(e,t)},searchRipgrep(e){return K().searchRipgrep(e)},queryFileSystem(e){return K().queryFileSystem(e)},extractMatchingLines(e,t,n){return K().extractMatchingLines(e,t,n)},filterPatch(e,t){return K().filterPatch(e,t)},charToByteOffset(e,t){return K().charToByteOffset(e,t)},byteToCharOffset(e,t){return K().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return K().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return K().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return K().SIGNATURES_ONLY_HINT}};import{RequestError as xu}from"octokit";var G={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},le={[G.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[G.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[G.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[G.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[G.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[G.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[G.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[G.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[G.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[G.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Eu={401:G.AUTH_REQUIRED,403:G.FORBIDDEN_PERMISSIONS,404:G.NOT_FOUND,422:G.INVALID_REQUEST,502:G.SERVER_UNAVAILABLE,503:G.SERVER_UNAVAILABLE,504:G.SERVER_UNAVAILABLE},ns={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},rs={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ro={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60};function xe(e){return t=>{}}function Tu(e,t){return n=>t}var yh=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"];function $t(e){if(!(e instanceof xu)||e.status!==422)return!1;let t=e.response?.data?.errors;return!Array.isArray(t)||t.length===0?!1:t.some(n=>{let r=typeof n?.message=="string"?n.message.toLowerCase():"";return yh.some(o=>r.includes(o))})}function Z(e){return e instanceof xu?Rh(e):e instanceof Error?_h(e):{error:typeof e=="string"?e:le[G.UNKNOWN].message,type:"unknown"}}function Rh(e){let{status:t,message:n,response:r}=e;if(t===403)return Sh(n,r);if(t===429)return bh(n,r);let o=Eu[t];return o?xh(o,t):En(G.UNKNOWN,{error:n||le[G.UNKNOWN].message,status:t})}function os(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function bh(e,t){let n=t?.headers,r=os(n,"retry-after"),o=os(n,"x-ratelimit-reset"),i=os(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ro.RESET_BUFFER_SECONDS,0):void 0);return Lt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}).catch(xe("rate-limit logging")),En(G.RATE_LIMIT_PRIMARY,{error:e||le[G.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:le[G.RATE_LIMIT_PRIMARY].suggestion})}function Sh(e,t){let n=t?.headers;if(rs.SECONDARY.test(e))return Ch(n);let r=n?.["x-ratelimit-remaining"],o=Th(t);return r!==void 0&&String(r)==="0"||o?Ph(n):Eh(n)}function Ch(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ro.SECONDARY_FALLBACK_SECONDS:t;return Lt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}).catch(xe("rate-limit logging")),En(G.RATE_LIMIT_SECONDARY,{error:le[G.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:le[G.RATE_LIMIT_SECONDARY].suggestion})}function Ph(e){let t=e?.["x-ratelimit-reset"],n=t?parseInt(String(t),10):NaN,r=isNaN(n)?null:new Date(n*1e3),o=r?Math.max(Math.ceil((r.getTime()-Date.now())/1e3)+Ro.RESET_BUFFER_SECONDS,0):void 0,i=r?le[G.RATE_LIMIT_PRIMARY].messageWithTime(r,o):le[G.RATE_LIMIT_PRIMARY].messageWithoutTime;return Lt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}).catch(xe("rate-limit logging")),En(G.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:le[G.RATE_LIMIT_PRIMARY].suggestion})}function Eh(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=le[G.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=wh(String(t),String(n))),En(G.FORBIDDEN_PERMISSIONS,{error:le[G.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Th(e){return e?.data?.errors?.some(n=>n.type===rs.GRAPHQL_TYPE)??!1}function xh(e,t){let n=le[e];return En(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function _h(e){return ns.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:le[G.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:le[G.NETWORK_CONNECTION_FAILED].suggestion}:ns.TIMEOUT.some(t=>e.message.includes(t))?{error:le[G.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:le[G.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function En(e,t){return{type:"http",...t}}function wh(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?le[G.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):le[G.FORBIDDEN_PERMISSIONS].fallbackSuggestion}function Ah(e){return`user:${e}`}var Lh=/[@/]/,Oh=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,Ih=/^[A-Za-z0-9_-]+$/;function _u(e){return e.startsWith('"')||Ih.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}var ar=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(Ah(r))});return this}addDateFilters(t){return Object.entries({created:"created",updated:"updated","author-date":"author-date","committer-date":"committer-date","merged-at":"merged",closed:"closed"}).forEach(([r,o])=>{let i=t[r];i&&this.queryParts.push(`${o}:${i}`)}),this}addArrayFilter(t,n,r=!1){return t&&t!==null&&(Array.isArray(t)?t:[t]).forEach(i=>{let s=r?`"${i}"`:i;this.queryParts.push(`${n}:${s}`)}),this}addBooleanFilter(t,n,r){return t===!0?this.queryParts.push(n):t===!1&&this.queryParts.push(r),this}addSimpleFilter(t,n){return t!=null&&this.queryParts.push(`${n}:${t}`),this}addQuotedFilter(t,n){if(t!=null){let o=Lh.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},is=class extends ar{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(_u))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(Oh):null;return o&&(r=o[1],n=n.slice(0,o.index)||void 0),this.addSimpleFilter(r,"filename"),this.addSimpleFilter(t.extension,"extension"),this.addQuotedFilter(n,"path"),t.language&&this.queryParts.push(`language:${t.language}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="file"?this.queryParts.push("in:file"):r==="path"&&this.queryParts.push("in:path")}),this}},ss=class extends ar{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(_u)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},as=class extends ar{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}};function wu(e){return new is().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function Au(e){return new ss().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function Lu(e){return new as().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function Ou(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}import kh from"node-cache";import vh from"crypto";var Fh="v1",Mh=300*1e3,Qe=new kh({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Se={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},Iu={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},Tn=new Map;function Nh(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function Dh(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function Hh(e){let t=Nh(e);if(!(!t||!Dh(t)))try{so(t,1)}catch{}}function Gh(){let e=Date.now();for(let[t,n]of Tn.entries())e-n.startedAt>Mh&&Tn.delete(t)}var Uh=new Set([]);function Bh(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t=e,n=!1,r={};for(let o of Object.keys(t)){if(Uh.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function _e(e,t,n){let r=cs(Bh(t)),o=n?`${n}:${r}`:r,i=vh.createHash("sha256").update(o).digest("hex");return`${Fh}-${e}:${i}`}function cs(e,t=new WeakSet){return e===null?"null":e===void 0?"undefined":typeof e!="object"?String(e):t.has(e)?'"[Circular]"':(t.add(e),Array.isArray(e)?`[${e.map(o=>cs(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${cs(i,t)}`}).join(",")}}`)}function zh(e){return Iu[e]||Iu.default}function Qh(e,t,n){try{return Qe.set(e,t,n),Se.sets++,Se.totalKeys=Qe.keys().length,!0}catch{try{let r=Qe.keys();for(let o of r)Qe.get(o);return Qe.set(e,t,n),Se.sets++,Se.totalKeys=Qe.keys().length,!0}catch{return!1}}}async function we(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=Qe.get(e);if(i!==void 0)return Se.hits++,Hh(e),i}catch{}Gh();let r=Tn.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Se.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let u=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=zh(u)}Qh(e,i,a)}return i}finally{Tn.delete(e)}})();return Tn.set(e,{promise:o,startedAt:Date.now()}),o}function aL(){Qe.flushAll(),Tn.clear(),Se.hits=0,Se.misses=0,Se.sets=0,Se.totalKeys=0,Se.lastReset=new Date}function It(e){let t=Qe.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||Qe.del(r)>0&&n++}return n>0&&(Se.totalKeys=Qe.keys().length),n}function cL(){return It("local-")}function uL(){return It("lsp-")}function lL(){let e=0;return e+=It("gh-api-"),e+=It("bb-api-"),e+=It("gh-repo-"),e+=It("bb-repo-"),e+=It("github-user"),e+=It("npm-search"),e}function dL(){let e=Se.hits+Se.misses;return{...Se,hitRate:e>0?Se.hits/e*100:0,cacheSize:Qe.keys().length}}import{DISCOVERY_IGNORED_FILE_EXTENSIONS as gL,DISCOVERY_IGNORED_FILE_NAMES as hL,DISCOVERY_IGNORED_FOLDER_NAMES as yL,getDiscoveryExtension as ku,shouldIgnoreDiscoveryDir as cr,shouldIgnoreDiscoveryFile as xn}from"@octocodeai/octocode-engine/security";import{completeMetadata as us}from"@octocodeai/octocode-core";var S=new Proxy({},{get(e,t){return us.toolNames[t]},ownKeys(){return Object.keys(us.toolNames)},getOwnPropertyDescriptor(e,t){let n=us.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});import{completeMetadata as jh}from"@octocodeai/octocode-core";var ls=new Proxy({},{get(e,t){return jh.tools[t]?.description??""}});import{completeMetadata as $h}from"@octocodeai/octocode-core";function ds(e){return Object.prototype.hasOwnProperty.call($h.tools,e)}import{completeMetadata as Vh}from"@octocodeai/octocode-core";function ps(){return Vh.baseSchema}var Wh=new Proxy({},{get(e,t){return ps()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(ps())]))},getOwnPropertyDescriptor(e,t){let n=ps();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}});var vu=Symbol.for("octocode.rawResponseChars");function N(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function Fu(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function U(e,t){let n=typeof t=="number"?Fu(t):N(t);if(n===void 0)return e;try{Object.defineProperty(e,vu,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function ne(e){if(!(typeof e!="object"||e===null))return Fu(e[vu])}function bo(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var Mu=30;async function Nu(e,t,n){let r=_e("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await we(r,async()=>await Yh(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Yh(e,t){try{let n=await ie(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(R=>R&&R.trim()).length===0)return await M(S.GITHUB_SEARCH_CODE,oe.QUERY_EMPTY.code),{error:oe.QUERY_EMPTY.message,type:"http",status:400};let r=wu(e);if(!r.trim())return await M(S.GITHUB_SEARCH_CODE,oe.QUERY_EMPTY.code),{error:oe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:Mu,100),i=e.page||1,s={q:r,per_page:o,page:i,headers:{Accept:"application/vnd.github.v3.text-match+json"}},a=await n.rest.search.code(s),c=await Xh(a.data.items,a.data.total_count),u=a.data.incomplete_results===!0,l=c.total_count,d=Math.min(l,1e3),m=Math.min(Math.ceil(d/o),10),p=Math.min(i,Math.max(1,m)),f=p<m,g=Math.min(d,m*o);return{data:{total_count:c.total_count,items:c.items,...u?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:p,totalPages:m,perPage:o,totalMatches:d,reportedTotalMatches:l,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:l>d,hasMore:f,...f?{nextPage:p+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:bo(a.headers),rawResponseChars:N(a.data)}}catch(n){if($t(n)){let o=Math.min(typeof e.limit=="number"?e.limit:Mu,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}async function Xh(e,t){let n=Jh(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(p=>!xn(p.path)),c=0,u=0,l=await Promise.allSettled(a.map(async p=>{s.add(p.path);let f=[],g=await Promise.allSettled((p.text_matches||[]).map(async x=>{let C=x.fragment,_=Kh.sanitizeContent(C||"",p.path);C=_.content,_.hasSecrets&&r.add(`Secrets detected in ${p.path}: ${_.secretsDetected.join(", ")}`),_.warnings.length>0&&_.warnings.forEach(I=>r.add(`${p.path}: ${I}`));try{let I=await O.minifyContent(C||"",p.path);C=I.content,I.failed?o=!0:I.type!=="failed"&&(f.push(I.type),i.push(I.type))}catch{o=!0}return{context:C||"",positions:x.matches?.map(I=>Array.isArray(I.indices)&&I.indices.length>=2?[I.indices[0],I.indices[1]]:[0,0])||[]}})),h=g.filter(x=>x.status==="fulfilled").map(x=>x.value),R=g.filter(x=>x.status==="rejected").length;R>0&&(u+=R);let b=p,P=Array.from(new Set(f));return{path:p.path,matches:h,url:p.html_url,repository:{nameWithOwner:p.repository.full_name,url:p.repository.url,pushedAt:p.repository.pushed_at||void 0},...b.last_modified_at&&{lastModifiedAt:b.last_modified_at},...P.length>0&&{minificationType:P.join(",")}}})),d=l.filter(p=>p.status==="fulfilled").map(p=>p.value);c=l.filter(p=>p.status==="rejected").length;let m={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let p=n.full_name.split("/");return p.length===2&&p[0]&&p[1]?{owner:p[0],repo:p[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(m.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),u>0&&r.add(`${u} match(es) dropped due to processing errors`),r.size>0&&(m.matchLocations=Array.from(r)),m.minified=!o,m.minificationFailed=o,i.length>0&&(m.minificationTypes=Array.from(new Set(i))),m}function Jh(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}import{writeFileSync as Yu,mkdirSync as ys,existsSync as yr,rmSync as Sy,readdirSync as Cy,statSync as Xu}from"node:fs";import{join as Po,dirname as Ju,resolve as Rs,sep as bs}from"node:path";import{RequestError as Du}from"octokit";async function Zh(e,t,n,r,o,i,s,a){let c=await Ge(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let l=Z(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,m=await Bu(e,r,o,i,s||c);return m.length>0&&(l.hints=[...l.hints||[],...Uu(i,m)]),{...l,...d&&{scopesSuggestion:d}}}async function qh(e,t,n,r,o,i){let s=Z(t),a=await Bu(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...Uu(o,a)]),s}async function Hu(e,t){let n=e.replace(/\s/g,"");if(!n)return await M(S.GITHUB_FETCH_CONTENT,Oe.FILE_EMPTY.code),{error:Oe.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?(await M(S.GITHUB_FETCH_CONTENT,Oe.BINARY_FILE.code),{error:Oe.BINARY_FILE.message,type:"unknown",status:415}):{data:r.toString("utf-8"),status:200}}catch{return await M(S.GITHUB_FETCH_CONTENT,Oe.DECODE_FAILED.code),{error:Oe.DECODE_FAILED.message,type:"unknown",status:422}}}async function Gu(e,t,n,r,o){try{let i=await e.rest.git.getBlob({owner:t,repo:n,file_sha:r}),{content:s,encoding:a}=i.data;return a==="base64"?Hu(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return Z(i)}}async function ey(e,t,n,r,o,i){try{let s=r.split("/").slice(0,-1).join("/"),a=r.split("/").pop();if(!a)return{error:`Cannot determine file name from path: ${r}`,type:"unknown",status:400};let c=o||await Ge(t,n,i).catch(()=>"HEAD"),u=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(u.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let l=u.data.find(m=>m.name===a&&m.type==="file");if(!l)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await Gu(e,t,n,l.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return Z(s)}}async function So(e,t){try{let n=await ie(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,u=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof Du&&d.status===404)if(s){let m=await Zh(n,d,a,r,o,i,s,t);if("result"in m)c=m.result,u=m.actualBranch;else return m}else return await qh(n,d,r,o,i,s);else{if(d instanceof Du&&d.status===413)return await ey(n,r,o,i,s||u,t);throw d}}let l=c.data;if(Array.isArray(l))return await M(S.GITHUB_FETCH_CONTENT,Oe.PATH_IS_DIRECTORY.code),{error:Oe.PATH_IS_DIRECTORY.message(S.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in l&&l.type==="file"){let d=typeof l.content=="string"?l.content:"",m=l.size??0,p;if(d.length>0)p=await Hu(d,i);else if(m>0&&"sha"in l&&typeof l.sha=="string"&&l.sha)p=await Gu(n,r,o,l.sha,i);else return await M(S.GITHUB_FETCH_CONTENT,Oe.FILE_EMPTY.code),{error:Oe.FILE_EMPTY.message,type:"unknown",status:404};if("error"in p)return p;if(!u&&!s)try{u=await Ge(r,o,t)}catch{}return{data:{rawContent:p.data,branch:u||void 0,resolvedRef:u||s||"HEAD"},status:200,rawResponseChars:N(l)}}return await M(S.GITHUB_FETCH_CONTENT,Oe.UNSUPPORTED_TYPE.code),{error:Oe.UNSUPPORTED_TYPE.message(l.type),type:"unknown",status:415}}catch(n){return Z(n)}}function Uu(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function Bu(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,u=[],l=c.find(p=>p.name.toLowerCase()===s.toLowerCase());l&&u.push(l.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(p=>p.name===s?!1:!!p.name.startsWith(d+".")).forEach(p=>u.push(p.path)),u.length===0&&d.length>=3&&c.filter(f=>{let g=f.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(f=>u.push(f.path)),Array.from(new Set(u)).slice(0,3)}catch{return[]}}import{existsSync as pr,readFileSync as ty,writeFileSync as ny,mkdirSync as ry,rmSync as lr,readdirSync as oy,statSync as iy}from"node:fs";import{join as je}from"node:path";import{createHash as sy}from"node:crypto";var ay=1440*60*1e3,cy=600*1e3,uy=2*1024*1024*1024,ly=50,Qu=".octocode-clone-meta.json",_n=null;function sO(e){return fs(e)}function fs(e){return je(e,"tmp","clone")}function ju(e){return je(e,"tmp","tree")}function dy(e){return e?`__sp_${sy("sha256").update(e).digest("hex").substring(0,6)}`:""}function $u(e,t,n,r,o){let i=`${r}${dy(o)}`;return je(fs(e),t,n,i)}function ms(e,t,n,r){return je(ju(e),t,n,r)}function py(e){return typeof e=="object"&&e!==null}function fy(e){if(!py(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),t}function gs(e){let t=je(e,Qu);if(!pr(t))return null;try{return fy(JSON.parse(ty(t,"utf-8")))}catch{return null}}function fr(e,t){try{ny(je(e,Qu),JSON.stringify(t,null,2),"utf-8")}catch{}}function Vu(e){return Date.now()<new Date(e.expiresAt).getTime()}function mr(e){let t=gs(e);return t?Vu(t)?pr(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function my(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return ay}function gy(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return uy}function hy(){let e=process.env.OCTOCODE_MAX_CLONES;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return Math.floor(t)}return ly}function gr(e,t,n,r,o,i){let s=new Date;return{clonedAt:s.toISOString(),expiresAt:new Date(s.getTime()+my()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{}}}function hr(e){let t=je(e,"..");try{pr(t)||ry(t,{recursive:!0,mode:448})}catch(n){throw new Error(`Failed to create clone parent directory '${t}': ${n instanceof Error?n.message:String(n)}`)}}function hs(e){try{pr(e)&&lr(e,{recursive:!0,force:!0})}catch{}}function ur(e){try{return iy(e).isDirectory()}catch{return!1}}function Vt(e){try{return oy(e)}catch{return[]}}function*Wu(e){for(let t of Vt(e)){let n=je(e,t);if(ur(n))for(let r of Vt(n)){let o=je(n,r);if(ur(o))for(let i of Vt(o)){let s=je(o,i);ur(s)&&(yield s)}}}}function zu(e){for(let t of[...Vt(e)]){let n=je(e,t);if(ur(n)){for(let r of[...Vt(n)]){let o=je(n,r);if(ur(o)&&Vt(o).length===0)try{lr(o,{recursive:!0,force:!0})}catch{}}if(Vt(n).length===0)try{lr(n,{recursive:!0,force:!0})}catch{}}}}function yy(e){let t=0;for(let n of Wu(e))try{let r=gs(n);(!r||!Vu(r))&&(lr(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Ry(e){let t=[];for(let n of Wu(e)){let r=gs(n);if(!r)continue;let o=Number.isNaN(Date.parse(r.clonedAt))?0:Date.parse(r.clonedAt);t.push({branchDir:n,clonedAtMs:o,sizeBytes:r.sizeBytes??or(n)})}return t}function by(e,t,n){let r=e.reduce((s,a)=>s+a.sizeBytes,0),o=e.length;if(r<=t&&o<=n)return 0;e.sort((s,a)=>s.clonedAtMs-a.clonedAtMs);let i=0;for(let s of e){if(r<=t&&o<=n)break;try{lr(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Ku(e){if(!pr(e))return 0;let t=0;try{t+=yy(e)}catch{return t}zu(e);let n=by(Ry(e),gy(),hy());return t+=n,n>0&&zu(e),t}function Co(e){return Ku(fs(e))}function dr(e){return Ku(ju(e))}function aO(e){_n||(Co(e),dr(e),_n=setInterval(()=>{Co(e),dr(e)},cy),_n.unref())}function cO(){_n&&(clearInterval(_n),_n=null)}var Py=50,Ey=5*1024*1024,Ty=300*1024,xy=5,_y=1e4,wy=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".eot",".otf",".pyc",".class",".o",".obj",".lock",".min.js",".min.css"]);async function Zu(e,t,n,r,o,i=!1){let s=zt(),a=ms(s,e,t,r),c=Rs(Po(a,n));if(!c.startsWith(a+bs)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=mr(a);if(u.hit&&!i&&yr(c)){let P=Iy(c,a);return{localPath:c,repoRoot:a,files:P.files,fileCount:P.fileCount,totalSize:P.totalSize,cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let l=await ie(o),{data:d}=await l.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(d))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let m=d.filter(P=>{if(P.type!=="file"||!P.download_url||P.size>Ty)return!1;let x=ku(P.name,{lowercase:!0,leadingDot:!0});return!wy.has(x)}).slice(0,Py),p=o?.token,f=await Ay(m,xy,p),g=0,h=[];for(let{entry:P,content:x}of f){if(g+x.length>Ey)break;g+=x.length,h.push({entry:P,content:x})}dr(s),hr(a),yr(c)&&Sy(c,{recursive:!0,force:!0}),ys(c,{recursive:!0,mode:448});let R=[];for(let{entry:P,content:x}of h){let C=Rs(Po(a,P.path));if(!C.startsWith(a+bs))continue;let _=Ju(C);yr(_)||ys(_,{recursive:!0,mode:448}),Yu(C,x,"utf-8"),R.push({path:P.path,size:x.length,type:"file"})}let b=gr(e,t,r,"treeFetch");return fr(a,b),{localPath:c,repoRoot:a,files:R,fileCount:R.length,totalSize:g,cached:!1,expiresAt:b.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function qu(e,t,n,r,o,i=!1){let s=zt(),a=ms(s,e,t,r),c=Rs(Po(a,n));if(!c.startsWith(a+bs)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let u=mr(a);if(!i&&u.hit&&yr(c))return{localPath:c,repoRoot:a,path:n,size:ky(c),cached:!0,expiresAt:u.meta.expiresAt,owner:e,repo:t,branch:r};let l=await So({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in l)||!l.data){let f="error"in l?l.error:void 0;throw new Error(f||`Failed to fetch ${e}/${t}/${n}`)}dr(s),hr(a);let d=Ju(c);yr(d)||ys(d,{recursive:!0,mode:448}),Yu(c,l.data.rawContent,"utf-8");let m=l.data.branch||r,p=gr(e,t,m,"treeFetch");return fr(a,p),{localPath:c,repoRoot:a,path:n,size:l.data.rawContent.length,cached:!1,expiresAt:p.expiresAt,owner:e,repo:t,branch:m}}async function Ay(e,t,n){let r=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),s=await Promise.allSettled(i.map(async a=>{let c=await Oy(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}var Ly=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"]);async function Oy(e,t){try{let o=new URL(e);if(!Ly.has(o.hostname))throw new Error(`Blocked fetch to unexpected host: ${o.hostname}. Only GitHub download URLs are allowed.`)}catch(o){throw o instanceof TypeError?new Error(`Invalid download URL: ${e}`):o}let n=new AbortController,r=setTimeout(()=>n.abort(),_y);try{let o={"User-Agent":"octocode-mcp"};t&&(o.Authorization=`token ${t}`);let i=await fetch(e,{signal:n.signal,headers:o});if(!i.ok)throw new Error(`HTTP ${i.status} fetching ${e}`);return await i.text()}finally{clearTimeout(r)}}function Iy(e,t){let n=[],r=0;function o(i){let s;try{s=Cy(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Po(i,a);try{let u=Xu(c);if(u.isDirectory())o(c);else if(u.isFile()){let l=c.substring(t.length+1);r+=u.size,n.push({path:l,size:u.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function ky(e){try{return Xu(e).size}catch{return 0}}function Ce(){try{return ae().output.pagination.defaultCharLength}catch{return pt.pagination.defaultCharLength}}var el=1e5;function tl(e){let t=Math.min(Math.max(Ce(),1),el),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,el)}import{ContentSanitizer as il}from"@octocodeai/octocode-engine/contentSanitizer";function Rr(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Wt(e){return Rr(e).length}function vy(e,t,n){return O.byteSliceContent(e,t,n)}function Eo(e,t){return O.byteToCharOffset(e,t)}function nl(e,t){return O.charToByteOffset(e,t)}function rl(e){return O.charToByteOffset(e,e.length)}function EO(e,t,n){let r=vy(e,t,t+n);return{charOffset:Eo(e,t),charLength:r.length,text:r}}function Ss(e,t,n,r){return O.sliceContent(e,t,n,r)}function mt(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=rl(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,u,l,d,m,p,f,g;if(o==="bytes"){let h=Math.min(t,s),R=Math.min(h+n,s);d=Eo(e,h),m=Eo(e,R),m<i&&nl(e,m)<R&&(m+=1);let b=Ss(e,d,m-d);c=b.text,d=b.charOffset,m=b.charOffset+b.charLength,u=b.byteOffset,l=b.byteOffset+b.byteLength,p=l<s;let P=r.actualOffset??h;f=Math.floor(P/a)+1,g=Math.max(f,Math.ceil(s/a))}else{let h=Ss(e,t,n);c=h.text,d=h.charOffset,m=h.charOffset+h.charLength,u=h.byteOffset,l=h.byteOffset+h.byteLength,p=m<i;let R=r.actualOffset??d;f=Math.floor(R/a)+1,g=Math.max(f,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:u,byteLength:l-u,totalBytes:s,nextByteOffset:p?l:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:p?m:void 0,hasMore:p,estimatedTokens:Math.ceil(c.length/4),currentPage:f,totalPages:g}}function _O(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function br(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}function wO(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
12
- `){let u=e.lastIndexOf(`
13
- `,o-1);o=u===-1?0:u+1}let i=o,s=0;for(;i<r;){let u=e.indexOf(`
14
- `,i);if(u===-1){i=r;break}if(i=u+1,s++,i-o>=n)break}let a=e.substring(o,i),c=i<r;return{sliced:a,actualOffset:o,actualLength:a.length,hasMore:c,lineCount:s,totalChars:r,nextOffset:c?i:void 0}}var Fy=8e3,My="__octocode_generic__.unknown";function Ny(e){return e&&e.trim().length>0?e:My}function ol(e,t){return O.getSemanticBoundaryOffsets(e,Ny(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function Dy(e,t){let n=e.indexOf(`
15
- `,t);return n===-1?void 0:n+1}function Sr(e){let t=e.trimEnd().split(`
16
- `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function Cr(e,t,n){let r=Dy(e,Math.max(0,t));if(r!==void 0)return ol(e,n).find(o=>o>=r&&o>t)}function OO(e,t,n,r,o){if(!Sr(e))return;let i=Cr(t,n,o);if(i===void 0)return;let s=i-n,a=`Page cut mid-block at char ${n}. Next top-level definition at char ${i}. Re-request with charLength=${r+s} to extend this page to the next boundary, or use charOffset=${n} to continue page-by-page.`;return{nextBlockChar:i,hint:a}}function To(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=ol(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(l=>l>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=Fy?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}function xo(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Invalid regex pattern: ${l}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
17
- `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=O.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(u=>({start:u.start,end:u.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(u=>u)}}function Hy(){let e=Ce();return Math.min(e,8e3)}function _o(e,t){return{sourceChars:e,sourceBytes:t}}function sl(e,t,n){let r=e.content??"",o=n??Hy();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=To(r,t,o,i),c=mt(r,t,s),u;if(c.hasMore&&a==="char-limit"&&Sr(c.paginatedContent)){let l=c.charOffset+c.charLength;u=Cr(r,l,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,chunkMode:a,...u!==void 0&&{nextBlockChar:u}}}}async function al(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function cl(e,t,n,r,o,i,s,a,c=5,u,l,d,m="standard"){let p=e.length,f=Buffer.byteLength(e,"utf-8"),g=m==="standard"||m==="symbols",h=g?"standard":"none",R;if(m==="symbols"){let $=O.extractSignatures(e,o);if($===null&&(R=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),$!==null){let D=il.sanitizeContent($,o),Re=O.applyContentViewMinification(D.content,o),ue=[O.SIGNATURES_ONLY_HINT];return u&&ue.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),D.hasSecrets&&ue.push(`Secrets detected and redacted: ${D.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:Re,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Wt(e),..._o(p,f),isPartial:!1,signaturesExtracted:!0,hints:ue}}}let b=new Set,P=e,x=P.split(`
18
- `),C=Wt(P),_=e,I,j,w=!1,A;if(i)_=e;else if(u){let $=d===!0,D;try{D=xo(x,u,c,l??!1,$)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:C,..._o(p,f),matchNotFound:!0,searchedFor:u,hints:[`Invalid regex "${u}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(D.matchCount===0){let V=l?[`Regex "${u}" matched no lines. Verify the pattern, check flags (case-${$?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${u}" not found in file${$?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:C,..._o(p,f),matchNotFound:!0,searchedFor:u,hints:V}}_=D.lines.join(`
19
- `);let Re=D.matchRanges[0],ue=D.matchRanges[D.matchRanges.length-1];s=Re.start,a=ue.end,I=Re.start,j=ue.end,w=!0,D.matchRanges.length>1&&(A=D.matchRanges);let at=D.matchingLines.slice(0,5).join(", "),en=D.matchingLines.length>5?` and ${D.matchingLines.length-5} more`:"";b.add(D.matchCount>1?`Found ${D.matchCount} occurrences of "${u}" on lines ${at}${en} \u2014 all shown as ${D.matchRanges.length} slice${D.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${u}" on line ${D.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let $=s||1,D=a||C;if($<1||$>C)_=e;else if(D<$)_=e;else{let Re=Math.max(1,$),ue=Math.min(C,D),at=x.slice(Re-1,ue);I=Re,j=ue,w=!0,_=at.join(`
20
- `),D>C&&b.add(`Requested endLine ${D} adjusted to ${C} (file end)`)}}let Q=il.sanitizeContent(_,o);if(_=g?O.applyContentViewMinification(Q.content,o):Q.content,Q.hasSecrets&&b.add(`Secrets detected and redacted: ${Q.secretsDetected.join(", ")}`),Q.warnings.length>0&&Q.warnings.forEach($=>b.add($)),C>2e3&&m!=="symbols"&&!u&&!s&&!a&&!i){let $=Math.max(1,C-200);b.add(`Large file (${C} lines) \u2014 minify:"symbols" for an export index, or startLine=${$} for the tail.`)}let se=Array.from(b);return{owner:t,repo:n,path:o,content:_,...h!=="standard"&&{contentView:h},branch:r,totalLines:C,..._o(p,f),...w&&{startLine:I,endLine:j,isPartial:w},...A&&{matchRanges:A},...se.length>0&&{matchLocations:se},...(se.length>0||R)&&{warnings:[...R?[R]:[],...se]}}}async function ul(e,t,n){let r=_e("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await we(r,async()=>await So(e,t),{shouldCache:p=>"data"in p&&!p.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await cl(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,u=e.charOffset??0,l=e.charLength,d=a?c:sl(c,u,l),m=(e.charOffset??0)>0;if(!e.noTimestamp&&!m)try{let p=await ie(t),f=await we(_e("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>al(p,e.owner,e.repo,e.path,e.branch),{shouldCache:g=>g!==null,forceRefresh:e.forceRefresh===!0});f&&(d.lastModified=f.lastModified,d.lastModifiedBy=f.lastModifiedBy)}catch{}return{data:d,status:200,rawResponseChars:o.rawResponseChars}}import{ContentSanitizer as pl}from"@octocodeai/octocode-engine/contentSanitizer";var Gy=2,Uy=20;function Pr(e,t=Uy){let n=e?Rr(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function ll(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return O.filterPatch(e,r)}function dl(e){return e?O.filterPatch(e,{trimContext:!0,contextLines:Gy}):""}function Cs(e){let t=pl.sanitizeContent(e.title??""),n=e.body?pl.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}var By=Ce(),zy=Math.round(Ce()/4),fl=3;function ml(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function Er(e,t={}){let n=t.charOffset??0,r=t.charLength??By,o=t.charLength??zy,i=typeof e.body=="string"?O.minifyMarkdownCore(e.body):e.body,s=ml(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((f,g)=>{let h=f.commentType==="review_inline"?0:1,R=g.commentType==="review_inline"?0:1;return h-R}),c=a.filter(f=>f.commentType==="review_inline").length,u=a.length-c,l=t.includeFullCommentDetails?a:a.slice(0,fl),d=l.map(f=>{let g=ml(f.body,n,o,!t.includeFullCommentDetails);return{...f,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),m=!t.includeFullCommentDetails&&(a.length>l.length||d.some(f=>"body_pagination"in f)),p=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...m?[`PR comments are paginated/summarized to ${fl} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(f=>({id:0,name:f,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:u}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((f,g)=>f+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((f,g)=>f+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(f=>({filename:f.filename,status:f.status,additions:f.additions,deletions:f.deletions,patch:f.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...m?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||p.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...p]}}}function Tr(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function wo(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?ll(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?dl(a.patch):a.patch}))}import{ContentSanitizer as Ps}from"@octocodeai/octocode-engine/contentSanitizer";function Ao(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function gl(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function hl(e){let t=gl(e);return t?t.discussion!==!1:!1}function yl(e){let t=gl(e);return t?t.reviewInline!==!1:!1}function Rl(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function bl(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function Sl(e){return!!e.content?.comments?.includeBots}var Qy=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"]);function Cl(e){let t=e.toLowerCase();return t.endsWith("[bot]")||Qy.has(t.replace(/\[bot\]$/,""))}function Es(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
8
+ var yP=Object.defineProperty;var y=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var bP=(e,t)=>{for(var n in t)yP(e,n,{get:t[n],enumerable:!0})};import{withSecurityValidation as RP,withBasicSecurityValidation as SP}from"@octocodeai/octocode-engine/security";function uf(e,t){let n=RP(e,(r,o,i)=>t(r,o,i));return(r,o)=>n(r,o)}function df(e,t){let n=SP(r=>e(r),t);return(r,o)=>n(r,o)}var Ac=y(()=>{"use strict"});var ot,Ee,kN,ON,pf,fn,ff,mf,zi,Ot,jn,Bi,gf,$n,hf,Qi,yf,me=y(()=>{"use strict";ot=30,Ee=100,kN=10,ON=100,pf=200,fn=20,ff=100,mf=20,zi=50,Ot=1e4,jn=20,Bi=1e3,gf=100,$n=5e4,hf=8e3,Qi=1e5,yf=500});var Lc,Xr,Jr,CP,qt,qn,qe,PP,Zr,xP,AN,pt=y(()=>{"use strict";Lc={NOT_INITIALIZED:{code:"CONFIG_NOT_INITIALIZED",message:"Configuration not initialized. Call initialize() and await its completion before calling getServerConfig()."}},Xr={PROMISES_NOT_ARRAY:{code:"VALIDATION_PROMISES_NOT_ARRAY",message:"promises must be an array"},TIMEOUT_NOT_POSITIVE:{code:"VALIDATION_TIMEOUT_NOT_POSITIVE",message:"timeout must be positive"},CONCURRENCY_NOT_POSITIVE:{code:"VALIDATION_CONCURRENCY_NOT_POSITIVE",message:"concurrency must be positive"}},Jr={FETCH_NOT_AVAILABLE:{code:"FETCH_NOT_AVAILABLE",message:"Global fetch is not available in this environment."},FETCH_FAILED_AFTER_RETRIES:{code:"FETCH_FAILED_AFTER_RETRIES",message:(e,t)=>`Failed to fetch after ${e} attempts: ${t}`},FETCH_HTTP_ERROR:{code:"FETCH_HTTP_ERROR",message:(e,t)=>`Failed to fetch (${e} ${t})`}},CP={INVALID_FORMAT:{code:"TOOL_METADATA_INVALID_FORMAT",message:"Invalid tool metadata format from remote source."},INVALID_API_RESPONSE:{code:"TOOL_METADATA_INVALID_API_RESPONSE",message:"Invalid API response structure"}},qt={PATH_IS_DIRECTORY:{code:"FILE_PATH_IS_DIRECTORY",message:e=>`Path is a directory. Use ${e} to list directory contents`},FILE_TOO_LARGE:{code:"FILE_TOO_LARGE",message:(e,t,n)=>`File too large (${e}KB > ${t}KB). Use ${n} to search within the file or use startLine/endLine parameters to get specific sections`},FILE_EMPTY:{code:"FILE_EMPTY",message:"File is empty - no content to display"},BINARY_FILE:{code:"FILE_BINARY",message:"Binary file detected. Cannot display as text - download directly from GitHub"},DECODE_FAILED:{code:"FILE_DECODE_FAILED",message:"Failed to decode file. Encoding may not be supported (expected UTF-8)"},UNSUPPORTED_TYPE:{code:"FILE_UNSUPPORTED_TYPE",message:e=>`Unsupported file type: ${e}`}},qn={NOT_FOUND:{code:"REPO_NOT_FOUND",message:(e,t,n)=>`Repository "${e}/${t}" not found or not accessible: ${n}`},PATH_NOT_FOUND:{code:"REPO_PATH_NOT_FOUND",message:(e,t,n,r)=>`Path "${e}" not found in repository "${t}/${n}" on branch "${r}"`},PATH_NOT_FOUND_ANY_BRANCH:{code:"REPO_PATH_NOT_FOUND_ANY_BRANCH",message:(e,t,n)=>`Path "${e}" not found in repository "${t}/${n}" on any common branch`},ACCESS_FAILED:{code:"REPO_ACCESS_FAILED",message:(e,t,n)=>`Failed to access repository "${e}/${t}": ${n}`},STRUCTURE_EXPLORATION_FAILED:{code:"REPO_STRUCTURE_EXPLORATION_FAILED",message:"Failed to explore repository structure"}},qe={QUERY_EMPTY:{code:"SEARCH_QUERY_EMPTY",message:"Search query cannot be empty"},NO_VALID_PARAMETERS:{code:"SEARCH_NO_VALID_PARAMETERS",message:"No valid search parameters provided"},PR_REQUIRED_PARAMS:{code:"SEARCH_PR_REQUIRED_PARAMS",message:"Owner, repo, and prNumber are required parameters"},PR_SINGLE_VALUES:{code:"SEARCH_PR_SINGLE_VALUES",message:"Owner and repo must be single values"},PULL_REQUEST_SEARCH_FAILED:{code:"SEARCH_PR_SEARCH_FAILED",message:e=>`Pull request search failed: ${e}`},PULL_REQUEST_LIST_FAILED:{code:"SEARCH_PR_LIST_FAILED",message:e=>`Pull request list failed: ${e}`},PULL_REQUEST_FETCH_FAILED:{code:"SEARCH_PR_FETCH_FAILED",message:(e,t)=>`Failed to fetch pull request #${e}: ${t}`}},PP={NO_TOOLS_REGISTERED:{code:"STARTUP_NO_TOOLS_REGISTERED",message:"No tools were successfully registered"},UNCAUGHT_EXCEPTION:{code:"STARTUP_UNCAUGHT_EXCEPTION",message:e=>`Uncaught exception: ${e}`},UNHANDLED_REJECTION:{code:"STARTUP_UNHANDLED_REJECTION",message:e=>`Unhandled rejection: ${e}`},STARTUP_FAILED:{code:"STARTUP_FAILED",message:e=>`Startup failed: ${e}`}},Zr={TIMEOUT:{code:"PROMISE_TIMEOUT",message:(e,t)=>`Promise ${e} timed out after ${t}ms`},NOT_A_FUNCTION:{code:"PROMISE_NOT_A_FUNCTION",message:e=>`Promise function at index ${e} is not a function`},FUNCTION_UNDEFINED:{code:"PROMISE_FUNCTION_UNDEFINED",message:"Promise function is undefined"}},xP={EXECUTION_FAILED:{code:"TOOL_EXECUTION_FAILED",message:(e,t)=>`Tool ${e} execution failed: ${t}`},SECURITY_VALIDATION_FAILED:{code:"TOOL_SECURITY_VALIDATION_FAILED",message:(e,t)=>`Security validation failed for ${e}: ${t}`}},AN={...Lc,...Xr,...Jr,...CP,...qt,...qn,...qe,...PP,...Zr,...xP}});var Q,wP,bf,mn=y(()=>{"use strict";Q={PATH_VALIDATION_FAILED:"pathValidationFailed",FILE_ACCESS_FAILED:"fileAccessFailed",FILE_READ_FAILED:"fileReadFailed",FILE_TOO_LARGE:"fileTooLarge",BINARY_FILE_UNSUPPORTED:"binaryFileUnsupported",NO_MATCHES:"noMatches",OUTPUT_TOO_LARGE:"outputTooLarge",COMMAND_NOT_AVAILABLE:"commandNotAvailable",COMMAND_EXECUTION_FAILED:"commandExecutionFailed",COMMAND_TIMEOUT:"commandTimeout",TOOL_EXECUTION_FAILED:"toolExecutionFailed",LSP_SERVER_UNAVAILABLE:"lspServerUnavailable"},wP=(i=>(i.FILE_SYSTEM="FILE_SYSTEM",i.VALIDATION="VALIDATION",i.SEARCH="SEARCH",i.PAGINATION="PAGINATION",i.EXECUTION="EXECUTION",i))(wP||{}),bf={[Q.PATH_VALIDATION_FAILED]:{code:Q.PATH_VALIDATION_FAILED,category:"VALIDATION",description:"Path validation failed - invalid or unsafe path",recoverability:"user-action-required"},[Q.FILE_ACCESS_FAILED]:{code:Q.FILE_ACCESS_FAILED,category:"FILE_SYSTEM",description:"Cannot access file - may not exist or lack permissions",recoverability:"unrecoverable"},[Q.FILE_READ_FAILED]:{code:Q.FILE_READ_FAILED,category:"FILE_SYSTEM",description:"Failed to read file contents",recoverability:"unrecoverable"},[Q.FILE_TOO_LARGE]:{code:Q.FILE_TOO_LARGE,category:"FILE_SYSTEM",description:"File exceeds size limits for operation",recoverability:"user-action-required"},[Q.BINARY_FILE_UNSUPPORTED]:{code:Q.BINARY_FILE_UNSUPPORTED,category:"FILE_SYSTEM",description:"Binary file is not supported by text content reader",recoverability:"user-action-required"},[Q.NO_MATCHES]:{code:Q.NO_MATCHES,category:"SEARCH",description:"Search pattern found no matches",recoverability:"user-action-required"},[Q.OUTPUT_TOO_LARGE]:{code:Q.OUTPUT_TOO_LARGE,category:"PAGINATION",description:"Output exceeds size limits",recoverability:"user-action-required"},[Q.COMMAND_NOT_AVAILABLE]:{code:Q.COMMAND_NOT_AVAILABLE,category:"EXECUTION",description:"Required CLI command is not installed or not in PATH",recoverability:"user-action-required"},[Q.COMMAND_EXECUTION_FAILED]:{code:Q.COMMAND_EXECUTION_FAILED,category:"EXECUTION",description:"System command execution failed",recoverability:"unrecoverable"},[Q.COMMAND_TIMEOUT]:{code:Q.COMMAND_TIMEOUT,category:"EXECUTION",description:"Command execution timed out",recoverability:"user-action-required"},[Q.TOOL_EXECUTION_FAILED]:{code:Q.TOOL_EXECUTION_FAILED,category:"EXECUTION",description:"Generic tool execution failure",recoverability:"unrecoverable"},[Q.LSP_SERVER_UNAVAILABLE]:{code:Q.LSP_SERVER_UNAVAILABLE,category:"EXECUTION",description:"No language server available for semantic analysis \u2014 use text search (localSearchCode) and localGetFileContent instead",recoverability:"user-action-required"}}});function _c(e){return e instanceof Oe}function Rf(e,t=Q.TOOL_EXECUTION_FAILED,n){if(_c(e))return e;if(e instanceof Error)return new Oe(t,e.message,n,e);let r=String(e);return new Oe(t,r,n)}var Oe,eo=y(()=>{"use strict";mn();Oe=class e extends Error{errorCode;category;recoverability;context;constructor(t,n,r,o){let i=bf[t],s=n||i.description;super(s,o?{cause:o}:void 0),this.name="ToolError",this.errorCode=t,this.category=i.category,this.recoverability=i.recoverability,this.context=r,o&&o.stack&&(this.stack=`${this.stack}
9
+ Caused by: ${o.stack}`),Object.setPrototypeOf(this,e.prototype)}isRecoverable(){return this.recoverability==="recoverable"}requiresUserAction(){return this.recoverability==="user-action-required"}toJSON(){return{name:this.name,errorCode:this.errorCode,category:this.category,message:this.message,recoverability:this.recoverability,context:this.context,stack:this.stack}}}});import{redactPath as to}from"@octocodeai/octocode-engine/pathUtils";var Ic=y(()=>{"use strict"});var Xe,no=y(()=>{"use strict";eo();mn();Ic();Xe={pathValidationFailed:(e,t,n)=>new Oe(Q.PATH_VALIDATION_FAILED,t||`Path validation failed: ${to(e,n)}`,{path:e}),fileAccessFailed:(e,t,n)=>{let r=to(e,n),o=`Cannot access file: ${r}`,i=t?.code;return i==="ENOENT"?o=`File not found: ${r}. Verify the path exists using localFindFiles.`:i==="EACCES"?o=`Permission denied: ${r}. Check file permissions.`:i==="EISDIR"?o=`Path is a directory: ${r}. Use localViewStructure instead.`:i==="ENOTDIR"?o=`Invalid path: ${r}. A component of the path is not a directory.`:i==="ENAMETOOLONG"&&(o=`Path too long: ${r}`),new Oe(Q.FILE_ACCESS_FAILED,o,{path:e,errorCode:i},t)},fileReadFailed:(e,t,n)=>new Oe(Q.FILE_READ_FAILED,`Failed to read file: ${to(e,n)}`,{path:e,errorCode:t?.code},t),fileTooLarge:(e,t,n)=>new Oe(Q.FILE_TOO_LARGE,(()=>{let r=o=>Number.isInteger(o)?`${o}KB`:`${o.toFixed(1)}KB`;return`File too large: ${r(t)} (limit: ${r(n)})`})(),{path:e,sizeKB:t,limitKB:n}),binaryFileUnsupported:e=>new Oe(Q.BINARY_FILE_UNSUPPORTED,`Binary file unsupported: ${to(e)}. Use localBinaryInspect to read its format/strings, or localSearchCode to grep embedded strings.`,{path:e}),outputTooLarge:(e,t)=>new Oe(Q.OUTPUT_TOO_LARGE,`Output too large: ${e} (limit: ${t})`,{size:e,limit:t}),commandNotAvailable:(e,t)=>new Oe(Q.COMMAND_NOT_AVAILABLE,`Command '${e}' is not available. ${t||"Please install it and ensure it is in your PATH."}`,{command:e,installHint:t}),commandExecutionFailed:(e,t,n)=>new Oe(Q.COMMAND_EXECUTION_FAILED,n?`Command '${e}' failed: ${n}`:`Command execution failed: ${e}`,{command:e,stderr:n},t),toolExecutionFailed:(e,t)=>new Oe(Q.TOOL_EXECUTION_FAILED,`Tool execution failed: ${e}`,{toolName:e},t)}});function Ct(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/$/,"")}function vt(e){if(!e.token.expiresAt)return!1;let t=new Date(e.token.expiresAt);if(isNaN(t.getTime()))return!0;let n=new Date;return t.getTime()-n.getTime()<300*1e3}function ro(e){if(!e.token.refreshTokenExpiresAt)return!1;let t=new Date(e.token.refreshTokenExpiresAt);return isNaN(t.getTime())?!0:new Date>=t}var Ui=y(()=>{"use strict"});function TP(e){let t=Ct(e),n=oo.get(t);return!n||Date.now()-n.cachedAt>=EP?!1:n.credentials?!vt(n.credentials):!0}function io(e){e?oo.delete(Ct(e)):oo.clear()}function Sf(e){let t=Ct(e);if(TP(t))return oo.get(t).credentials}function Cf(e,t){let n=Ct(e);oo.set(n,{credentials:t,cachedAt:Date.now()})}var oo,EP,Pf=y(()=>{"use strict";Ui();oo=new Map,EP=300*1e3});import Vn from"node:os";import xf from"node:path";function ji(){return gn?process.env.APPDATA||xf.join(At,"AppData","Roaming"):At}function wf(){return gn?process.env.LOCALAPPDATA||xf.join(At,"AppData","Local"):At}function Ef(){return so?"macOS":gn?"Windows":Fc?"Linux":Vn.platform()}function Tf(){return Vn.arch()}var gn,so,Fc,At,kf=y(()=>{"use strict";gn=Vn.platform()==="win32",so=Vn.platform()==="darwin",Fc=Vn.platform()==="linux",At=Vn.homedir()});var $i=y(()=>{"use strict";kf()});import{existsSync as Wn,mkdirSync as Kn}from"node:fs";import{join as ve,resolve as kP}from"node:path";function Of(e){let t=process.env[e];return t&&t.trim().length>0?t:void 0}function vf(){let e=Of("OCTOCODE_HOME");return e?kP(e):gn?ve(ji(),Mc):so?ve(At,Mc):ve(Of("XDG_CONFIG_HOME")??ve(At,".config"),Mc)}function qi(){Wn(ne.home)||Kn(ne.home,{recursive:!0,mode:Yn})}function OP(){Af()}function ao(){qi(),Wn(ne.tmp)||Kn(ne.tmp,{recursive:!0,mode:Yn})}function Af(){ao(),Wn(ne.clone)||Kn(ne.clone,{recursive:!0,mode:Yn})}function vP(){ao(),Wn(ne.tree)||Kn(ne.tree,{recursive:!0,mode:Yn})}function AP(){ao(),Wn(ne.binary)||Kn(ne.binary,{recursive:!0,mode:Yn})}function LP(){ao(),Wn(ne.unzip)||Kn(ne.unzip,{recursive:!0,mode:Yn})}var Mc,Yn,Ne,ne,hn=y(()=>{"use strict";$i();Mc=".octocode",Yn=448;Ne=vf(),ne={home:Ne,config:ve(Ne,".octocoderc"),credentials:ve(Ne,"credentials.json"),key:ve(Ne,".key"),session:ve(Ne,"session.json"),stats:ve(Ne,"stats.json"),tmp:ve(Ne,"tmp"),clone:ve(Ne,"tmp","clone"),tree:ve(Ne,"tmp","tree"),binary:ve(Ne,"tmp","binary"),repos:ve(Ne,"tmp","clone"),unzip:ve(Ne,"tmp","unzip"),cliConfig:ve(Ne,"config.json"),lspConfig:ve(Ne,"lsp-servers.json")}});import{z as Te}from"zod";var _P,IP,Lf,_f=y(()=>{"use strict";_P=Te.object({token:Te.string(),tokenType:Te.literal("oauth"),scopes:Te.array(Te.string()).optional(),refreshToken:Te.string().optional(),expiresAt:Te.string().optional(),refreshTokenExpiresAt:Te.string().optional()}),IP=Te.object({hostname:Te.string(),username:Te.string(),token:_P,gitProtocol:Te.enum(["ssh","https"]),createdAt:Te.string(),updatedAt:Te.string()}),Lf=Te.object({version:Te.number(),credentials:Te.record(Te.string(),IP)})});import{existsSync as Vi,readFileSync as Ff,writeFileSync as Mf,unlinkSync as If,statSync as FP,chmodSync as MP}from"node:fs";import{createCipheriv as DP,createDecipheriv as NP,randomBytes as Df}from"node:crypto";function Vt(){qi()}function Gf(){if(Vt(),Vi(Pt))return FP(Pt).mode&511&63&&MP(Pt,384),Buffer.from(Ff(Pt,"utf8"),"hex");let e=Df(32);return Mf(Pt,e.toString("hex"),{mode:384}),e}function Wi(e){let t=Gf(),n=Df(GP),r=DP(Nf,t,n),o=r.update(e,"utf8","hex");o+=r.final("hex");let i=r.getAuthTag();return`${n.toString("hex")}:${i.toString("hex")}:${o}`}function Ki(e){let t=Gf(),[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"hex"),s=Buffer.from(r,"hex"),a=NP(Nf,t,i);a.setAuthTag(s);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}function _t(){if(Vt(),!Vi(Lt))return{version:1,credentials:{}};try{let e=Ff(Lt,"utf8"),t=Ki(e),n=JSON.parse(t),r=Lf.safeParse(n);return r.success?r.data:{version:1,credentials:{}}}catch{return{version:1,credentials:{}}}}function Nc(e){Vt();let t=Wi(JSON.stringify(e,null,2));Mf(Lt,t,{mode:384})}function Hf(){try{Vi(Lt)&&If(Lt),Vi(Pt)&&If(Pt)}catch{}}var Dc,Lt,Pt,Nf,GP,zf=y(()=>{"use strict";hn();_f();Dc=ne.home,Lt=ne.credentials,Pt=ne.key,Nf="aes-256-gcm",GP=16});var Xn,Wt,Gc=y(()=>{"use strict";Xn="178c6fc778ccc68e1d6a",Wt="github.com"});import{refreshToken as HP}from"@octokit/oauth-methods";import{request as zP}from"@octokit/request";function BP(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 QP(e){return e==="github.com"||e===Wt?"https://api.github.com":`https://${e}/api/v3`}async function Hc(e,t=Wt,n=Xn){let r=await e.getCredentials(t);if(!r)return{success:!1,error:`Not logged in to ${t}`};if(!r.token.refreshToken)return{success:!1,error:"Token does not support refresh (OAuth App tokens do not expire)"};if(ro(r))return{success:!1,error:"Refresh token has expired. Please login again."};try{let o=await HP({clientType:"github-app",clientId:n,clientSecret:"",refreshToken:r.token.refreshToken,request:zP.defaults({baseUrl:QP(t)})}),i={token:o.authentication.token,tokenType:"oauth",refreshToken:o.authentication.refreshToken,expiresAt:o.authentication.expiresAt,refreshTokenExpiresAt:o.authentication.refreshTokenExpiresAt};return await e.updateToken(t,i),{success:!0,username:r.username,hostname:t}}catch(o){return{success:!1,error:o instanceof Error?BP(o.message):"Token refresh failed"}}}async function Bf(e,t=Wt,n=Xn){let r=await e.getCredentials(t);if(!r||!r.token)return{token:null,source:"none"};if(!vt(r))return{token:r.token.token,source:"stored",username:r.username};if(r.token.refreshToken){let o=await Hc(e,t,n);if(o.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:o.error}}return{token:null,source:"none",refreshError:"Token expired and no refresh token available"}}var Qf=y(()=>{"use strict";Ui();Gc()});function Yi(){for(let e of Jn){let t=process.env[e];if(t&&t.trim())return t.trim()}return null}function zc(){for(let e of Jn){let t=process.env[e];if(t&&t.trim())return`env:${e}`}return null}function Bc(){return Yi()!==null}function Uf(){for(let e of Jn){let t=process.env[e];if(t?.trim())return{token:t.trim(),source:`env:${e}`}}return null}var Jn,Qc=y(()=>{"use strict";Jn=["OCTOCODE_TOKEN","GH_TOKEN","GITHUB_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN"]});import{execFile as UP}from"child_process";function Xi(e){return new Promise(t=>{let n=["auth","token"];e&&n.push("--hostname",e);let r=process.env.PATH??"",o=new Set(r.split(":")),i=jP.filter(a=>!o.has(a)),s=i.length?`${i.join(":")}:${r}`:r;UP("gh",n,{encoding:"utf8",timeout:5e3,env:{...process.env,PATH:s}},(a,c)=>{if(a||!c){t(null);return}t(c.trim()||null)})})}var jP,Uc=y(()=>{"use strict";jP=["/opt/homebrew/bin","/usr/local/bin","/home/linuxbrew/.linuxbrew/bin"]});function jf(e){Ji=e}function jc(){Ji=null}function $P(){if(!Ji)throw new Error("Token resolution not initialized. Call initTokenResolution() first.");return Ji}async function Kt(e){let t=e?.hostname??Wt,n=e?.clientId??Xn,r=e?.getGhCliToken??Xi,o=Uf();if(o)return{token:o.token,source:o.source,wasRefreshed:!1};let i=await $P().getTokenWithRefresh(t,n);if(i.token)return{token:i.token,source:"octocode-storage",wasRefreshed:i.source==="refreshed",username:i.username};try{let s=await Promise.resolve(r(t));if(s?.trim())return{token:s.trim(),source:"gh-cli",wasRefreshed:!1}}catch{}return null}async function $c(e=Wt){let t=await Kt({hostname:e,getGhCliToken:()=>null});return t?{token:t.token,source:t.source}:null}async function qc(e=Wt,t=Xn){let n=await Kt({hostname:e,clientId:t,getGhCliToken:()=>null});return n?{token:n.token,source:n.source,wasRefreshed:n.wasRefreshed,username:n.username}:null}var Ji,$f=y(()=>{"use strict";Qc();Uc();Gc();Ji=null});async function Vc(e){let t=Ct(e.hostname),n={...e,hostname:t,updatedAt:new Date().toISOString()};try{let r=_t();return r.credentials[t]=n,Nc(r),io(t),{success:!0}}catch{throw new Error("Failed to store credentials")}}async function yn(e="github.com",t){let n=Ct(e);if(!t?.bypassCache){let i=Sf(n);if(i!==void 0)return i}let o=_t().credentials[n]||null;return Cf(n,o),o}function Zi(e="github.com"){let t=Ct(e);return _t().credentials[t]||null}async function qf(e="github.com"){let t=Ct(e),n=!1,r=_t();return r.credentials[t]&&(delete r.credentials[t],Object.keys(r.credentials).length===0?Hf():Nc(r),n=!0),io(t),{success:n,deletedFromFile:n}}async function Vf(){let e=_t();return Object.keys(e.credentials)}function Wf(){let e=_t();return Object.keys(e.credentials)}async function Kf(e="github.com"){return await yn(e)!==null}function Yf(e="github.com"){return Zi(e)!==null}async function es(e,t){let n=await yn(e);return n?(n.token=t,n.updatedAt=new Date().toISOString(),await Vc(n),!0):!1}function Xf(){return Lt}async function Jf(e="github.com"){let t=await yn(e);return!t||!t.token||vt(t)?null:t.token.token}function Zf(e="github.com"){let t=Zi(e);return!t||!t.token||vt(t)?null:t.token.token}async function em(e,t){return Hc({getCredentials:yn,updateToken:es},e,t)}async function Wc(e,t){return Bf({getCredentials:yn,updateToken:es},e,t)}var Kc=y(()=>{"use strict";Pf();zf();Qf();$f();Qc();Ui();jf({getTokenWithRefresh:Wc})});var Yc=y(()=>{"use strict";Kc();Uc()});import{z as Y}from"zod";var qP,VP,ts,WP,ns,tm,nm,rm=y(()=>{"use strict";qP=Y.object({rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),calls:Y.number()}),VP=Y.object({hits:Y.record(Y.string(),Y.number()).default({}),rateLimits:Y.number().default(0)}),ts=Y.record(Y.string(),Y.number()).default({}),WP=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:ts,rawChars:Y.number(),responseChars:Y.number(),savedChars:Y.number(),charSavingsCalls:Y.number(),githubCacheHits:Y.number(),githubCacheRateLimits:Y.number(),packageRegistryFailures:Y.number().default(0),packageRegistryFailuresByRegistry:ts}),ns=Y.object({toolCalls:Y.number(),errors:Y.number(),rateLimits:Y.number(),rateLimitsByProvider:ts,charsSavedByTool:Y.record(Y.string(),qP).default({}),githubCacheHits:VP.default({hits:{},rateLimits:0}),packageRegistryFailures:ts,totalUsage:WP.optional()}),tm=Y.object({version:Y.literal(1),sessionId:Y.string(),createdAt:Y.string(),lastActiveAt:Y.string(),stats:ns.optional()}),nm=Y.object({version:Y.literal(1),stats:ns})});function om(e){return Object.values(e).reduce((t,n)=>t+n,0)}function KP(e){let t=e.charsSavedByTool??{},n=e.githubCacheHits??{hits:{},rateLimits:0},r=e.rateLimitsByProvider??{},o=e.packageRegistryFailures??{},i=Object.values(t).reduce((s,a)=>({rawChars:s.rawChars+a.rawChars,responseChars:s.responseChars+a.responseChars,savedChars:s.savedChars+a.savedChars,charSavingsCalls:s.charSavingsCalls+a.calls}),{rawChars:0,responseChars:0,savedChars:0,charSavingsCalls:0});return{toolCalls:e.toolCalls,errors:e.errors,rateLimits:e.rateLimits,rateLimitsByProvider:r,...i,githubCacheHits:om(n.hits),githubCacheRateLimits:n.rateLimits,packageRegistryFailures:om(o),packageRegistryFailuresByRegistry:o}}function It(e){let t={...e,rateLimitsByProvider:e.rateLimitsByProvider??{},charsSavedByTool:e.charsSavedByTool??{},githubCacheHits:e.githubCacheHits??{hits:{},rateLimits:0},packageRegistryFailures:e.packageRegistryFailures??{}};return{...t,totalUsage:KP(t)}}function co(){return It({toolCalls:0,errors:0,rateLimits:0,rateLimitsByProvider:{},charsSavedByTool:{},githubCacheHits:{hits:{},rateLimits:0},packageRegistryFailures:{}})}var Xc=y(()=>{"use strict"});import{existsSync as Jc,readFileSync as sm,writeFileSync as YP,unlinkSync as XP,renameSync as JP}from"node:fs";function im(e,t){let n=`${e}.tmp`;YP(n,JSON.stringify(t,null,2),{mode:384}),JP(n,e)}function ZP(e){let{stats:t,...n}=e;return n}function ex(e){let t=JSON.parse(e),n=nm.safeParse(t);if(n.success)return It(n.data.stats);let r=ns.safeParse(t);return r.success?It(r.data):null}function tx(e){let t=e?It(e):co();if(!Jc(Rn))return t;try{let n=sm(Rn,"utf8"),r=ex(n);return r||t}catch{return t}}function rs(e){Vt(),im(Rn,{version:e.version,stats:It(e.stats)}),im(bn,ZP(e))}function am(){if(!Jc(bn))return null;try{let e=sm(bn,"utf8"),t=JSON.parse(e),n=tm.safeParse(t);return n.success?{...n.data,stats:tx(n.data.stats)}:null}catch{return null}}function cm(){let e=!1;for(let t of[bn,Rn])if(Jc(t))try{XP(t),e=!0}catch{return!1}return e}var bn,Rn,os=y(()=>{"use strict";Kc();hn();rm();Xc();bn=ne.session,Rn=ne.stats});function rx(){Zc||(Zc=!0,lo=()=>{fo()},uo=()=>{fo()},po=()=>{fo()},process.on("exit",lo),process.on("SIGINT",uo),process.on("SIGTERM",po))}function el(){lo&&(process.removeListener("exit",lo),lo=null),uo&&(process.removeListener("SIGINT",uo),uo=null),po&&(process.removeListener("SIGTERM",po),po=null),Zc=!1}function ox(){Zn||(Zn=setInterval(()=>{Yt&&ft&&(rs(ft),Yt=!1)},nx),Zn.unref())}function tl(){Zn&&(clearInterval(Zn),Zn=null)}function mo(){if(ft)return ft;let e=am();return e&&(ft=e),e}function er(e){ft=e,Yt=!0,rx(),ox()}function go(){Yt&&ft&&(rs(ft),Yt=!1)}function fo(){if(!is&&Yt&&ft){is=!0;try{rs(ft),Yt=!1}catch{}finally{is=!1}}}function nl(){ft=null,Yt=!1,is=!1}function lm(){nl(),tl(),el()}var nx,ft,Yt,Zn,Zc,lo,uo,po,is,um=y(()=>{"use strict";os();nx=6e4,ft=null,Yt=!1,Zn=null,Zc=!1,lo=null,uo=null,po=null,is=!1});import{randomUUID as ix}from"node:crypto";function ax(e){return It(e)}function cx(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let i=n[r]??{rawChars:0,responseChars:0,savedChars:0,calls:0};n[r]={rawChars:i.rawChars+o.rawChars,responseChars:i.responseChars+o.responseChars,savedChars:i.savedChars+o.savedChars,calls:i.calls+o.calls}}return n}function dm(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function lx(e,t){if(!t)return e;let n={...e.hits};for(let[r,o]of Object.entries(t.hits??{}))n[r]=(n[r]??0)+o;return{hits:n,rateLimits:e.rateLimits+(t.rateLimits??0)}}function pm(){let e=new Date().toISOString();return{version:sx,sessionId:ix(),createdAt:e,lastActiveAt:e,stats:co()}}function fm(){go()}function mm(){fo()}function gm(e){if(e?.forceNew){let r=pm();return er(r),go(),r}let t=mo();if(t){let r={...t,lastActiveAt:new Date().toISOString()};return er(r),go(),r}let n=pm();return er(n),go(),n}function hm(){return mo()?.sessionId??null}function Je(e){let t=mo();if(!t)return{success:!1,session:null};let n=ax(t.stats),r=It({toolCalls:n.toolCalls+(e.toolCalls??0),errors:n.errors+(e.errors??0),rateLimits:n.rateLimits+(e.rateLimits??0),rateLimitsByProvider:dm(n.rateLimitsByProvider,e.rateLimitsByProvider),charsSavedByTool:cx(n.charsSavedByTool,e.charsSavedByTool),githubCacheHits:lx(n.githubCacheHits,e.githubCacheHits),packageRegistryFailures:dm(n.packageRegistryFailures,e.packageRegistryFailures)}),o={...t,lastActiveAt:new Date().toISOString(),stats:r};return er(o),{success:!0,session:o}}function ym(e=1){return Je({toolCalls:e})}function bm(e=1){return Je({errors:e})}function ss(e=1){return Je({rateLimits:e})}function Rm(e,t=1){return Je({rateLimits:t,rateLimitsByProvider:{[e]:t}})}function as(e,t,n){let r=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)?Math.max(0,n):0;return Je({charsSavedByTool:{[e]:{rawChars:r,responseChars:o,savedChars:Math.max(0,r-o),calls:1}}})}function cs(e,t=1){return Je({githubCacheHits:{hits:{[e]:t},rateLimits:0}})}function ls(e=1){return Je({githubCacheHits:{hits:{},rateLimits:e}})}function Sm(e,t=1){return Je({packageRegistryFailures:{[e]:t}})}function Cm(){let e=mo();if(!e)return{success:!1,session:null};let t={...e,lastActiveAt:new Date().toISOString(),stats:co()};return er(t),{success:!0,session:t}}function Pm(){return nl(),tl(),el(),cm()}function xm(){lm()}var sx,ho=y(()=>{"use strict";os();Xc();um();os();sx=1});var rl=y(()=>{"use strict";ho();ho();ho();ho()});var yo,wm,ol=y(()=>{"use strict";yo=1,wm=".octocoderc"});var bo,Xt,Sn,tr,Ro,Ft,us,nr,rr,or,ir,sr,ar,So=y(()=>{"use strict";bo={apiUrl:"https://api.github.com"},Xt={enabled:!0,enableClone:!1,allowedPaths:[],workspaceRoot:void 0},Sn={enabled:null,enableAdditional:null,disabled:null},tr={timeout:3e4,maxRetries:3},Ro={configPath:void 0},Ft={format:"yaml",pagination:{defaultCharLength:2e4}},us={version:1,github:bo,local:Xt,tools:Sn,network:tr,lsp:Ro,output:Ft},nr=5e3,rr=3e5,or=0,ir=10,sr=1e3,ar=5e4});import{z as ye}from"zod";var ds,il=y(()=>{"use strict";ds=ye.looseObject({$schema:ye.string().optional(),version:ye.number().int().optional(),github:ye.record(ye.string(),ye.unknown()).optional(),local:ye.record(ye.string(),ye.unknown()).optional(),tools:ye.record(ye.string(),ye.unknown()).optional(),network:ye.record(ye.string(),ye.unknown()).optional(),lsp:ye.record(ye.string(),ye.unknown()).optional(),output:ye.record(ye.string(),ye.unknown()).optional()})});import{existsSync as Em,readFileSync as ux}from"node:fs";function dx(e){let t="",n=0,r=!1,o="";for(;n<e.length;){let i=e[n],s=e[n+1];if(!r&&(i==='"'||i==="'")){r=!0,o=i,t+=i,n++;continue}if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===o&&(r=!1),n++;continue}if(i==="/"&&s==="/"){for(;n<e.length&&e[n]!==`
10
+ `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<e.length-1;){if(e[n]==="*"&&e[n+1]==="/"){n+=2;break}n++}continue}t+=i,n++}return t=t.replace(/,(\s*[}\]])/g,"$1"),t}function px(e){let t=dx(e);return JSON.parse(t)}function Tm(){return Em(Co)}async function km(){return Po()}function Po(){let e=Co;if(!Em(e))return{success:!1,error:"Config file does not exist",path:e};try{let t=ux(e,"utf-8");if(!t.trim())return{success:!0,config:{},path:e};let n=px(t),r=ds.safeParse(n);return r.success?{success:!0,config:r.data,path:e}:{success:!1,error:`Config file has invalid structure: ${r.error.issues[0]?.message??"unknown error"}`,path:e}}catch(t){return{success:!1,error:`Failed to parse config file: ${t instanceof Error?t.message:"Unknown error"}`,path:e}}}function Om(){return Co}function Cn(){return ne.home}var Co,ps=y(()=>{"use strict";hn();il();Co=ne.config});function fx(e,t){if(e==null)return null;if(typeof e!="string")return`${t}: Must be a string`;try{let n=new URL(e);return["http:","https:"].includes(n.protocol)?null:`${t}: Only http/https URLs allowed`}catch{return`${t}: Invalid URL format`}}function al(e,t,n,r){return e==null?null:typeof e!="number"||isNaN(e)?`${t}: Must be a number`:e<n||e>r?`${t}: Must be between ${n} and ${r}`:null}function vm(e,t){return e==null?null:typeof e!="boolean"?`${t}: Must be a boolean`:null}function Am(e,t){if(e==null)return null;if(!Array.isArray(e))return`${t}: Must be an array`;for(let n=0;n<e.length;n++)if(typeof e[n]!="string")return`${t}[${n}]: Must be a string`;return null}function mx(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];typeof r=="string"&&(r.trim()===""?t.push(`local.allowedPaths[${n}]: empty or whitespace-only path`):!r.startsWith("/")&&!r.startsWith("~")?t.push(`local.allowedPaths[${n}]: must be absolute path or start with ~ (got "${r}")`):r.includes("..")&&t.push(`local.allowedPaths[${n}]: path traversal (..) not allowed (got "${r}")`))}return t}function sl(e,t){return e===void 0||e===null?null:Am(e,t)}function Lm(e,t){return e==null?null:typeof e!="string"?`${t}: Must be a string`:null}function gx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("github: Must be an object");return}let r=fx(e.apiUrl,"github.apiUrl");r&&t.push(r)}function hx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("local: Must be an object");return}let n=e,r=vm(n.enabled,"local.enabled");r&&t.push(r);let o=vm(n.enableClone,"local.enableClone");o&&t.push(o);let i=Am(n.allowedPaths,"local.allowedPaths");if(i)t.push(i);else if(Array.isArray(n.allowedPaths)){let s=mx(n.allowedPaths);t.push(...s)}if(n.workspaceRoot!==void 0&&n.workspaceRoot!==null){let s=Lm(n.workspaceRoot,"local.workspaceRoot");s?t.push(s):typeof n.workspaceRoot=="string"&&!n.workspaceRoot.startsWith("/")&&!n.workspaceRoot.startsWith("~")?t.push('local.workspaceRoot: must be an absolute path or start with ~ (got "'+n.workspaceRoot+'")'):typeof n.workspaceRoot=="string"&&n.workspaceRoot.includes("..")&&t.push('local.workspaceRoot: path traversal (..) not allowed (got "'+n.workspaceRoot+'")')}}function yx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("tools: Must be an object");return}let n=e,r=sl(n.enabled,"tools.enabled");r&&t.push(r);let o=sl(n.enableAdditional,"tools.enableAdditional");o&&t.push(o);let i=sl(n.disabled,"tools.disabled");i&&t.push(i)}function bx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("network: Must be an object");return}let n=e,r=al(n.timeout,"network.timeout",nr,rr);r&&t.push(r);let o=al(n.maxRetries,"network.maxRetries",or,ir);o&&t.push(o)}function Rx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("lsp: Must be an object");return}let r=Lm(e.configPath,"lsp.configPath");r&&t.push(r)}function Sx(e,t){if(e==null)return;if(typeof e!="object"||Array.isArray(e)){t.push("output: Must be an object");return}let n=e;if(n.format!==void 0&&(typeof n.format!="string"?t.push("output.format: Must be a string"):["yaml","json"].includes(n.format)||t.push("output.format: Must be one of: yaml, json")),n.pagination!==void 0&&n.pagination!==null)if(typeof n.pagination!="object"||Array.isArray(n.pagination))t.push("output.pagination: Must be an object");else{let r=n.pagination,o=al(r.defaultCharLength,"output.pagination.defaultCharLength",sr,ar);o&&t.push(o)}}function fs(e){let t=[],n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Configuration must be a JSON object"],warnings:[]};let r=e;r.version!==void 0&&(typeof r.version!="number"||!Number.isInteger(r.version)?t.push("version: Must be an integer"):r.version>1&&n.push(`version: Config version ${r.version} is newer than supported version ${1}`)),gx(r.github,t),hx(r.local,t),yx(r.tools,t),bx(r.network,t),Rx(r.lsp,t),Sx(r.output,t);let o=new Set(["$schema","version","github","local","tools","network","lsp","output"]);for(let i of Object.keys(r))o.has(i)||n.push(`Unknown configuration key: ${i}`);return{valid:t.length===0,errors:t,warnings:n,config:t.length===0?e:void 0}}var cl=y(()=>{"use strict";ol();So()});function xo(){return globalThis[Cx]??"mcp"}var Cx,ms=y(()=>{"use strict";Cx="__octocodeRuntimeSurface__"});function _m(e){if(e==null)return;let t=e.trim().toLowerCase();if(t!==""){if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function ll(e){if(e==null)return;let t=e.trim();if(t==="")return;let n=parseInt(t,10);if(!isNaN(n))return n}function gs(e){if(e==null)return;let t=e.trim();if(t!=="")return t.split(",").map(n=>n.trim()).filter(n=>n.length>0)}function Im(e){return{apiUrl:process.env.GITHUB_API_URL?.trim()||e?.apiUrl||bo.apiUrl}}function Fm(e){let t=xo()==="cli",n=_m(process.env.ENABLE_LOCAL),r=_m(process.env.ENABLE_CLONE),o=gs(process.env.ALLOWED_PATHS),i=process.env.WORKSPACE_ROOT?.trim()||void 0;return{enabled:n??e?.enabled??Xt.enabled,enableClone:r??e?.enableClone??(t?!0:Xt.enableClone),allowedPaths:o??e?.allowedPaths??Xt.allowedPaths,workspaceRoot:i??e?.workspaceRoot??Xt.workspaceRoot}}function Mm(e){let t=gs(process.env.TOOLS_TO_RUN),n=gs(process.env.ENABLE_TOOLS),r=gs(process.env.DISABLE_TOOLS);return{enabled:t??e?.enabled??Sn.enabled,enableAdditional:n??e?.enableAdditional??Sn.enableAdditional,disabled:r??e?.disabled??Sn.disabled}}function Dm(e){let t=ll(process.env.REQUEST_TIMEOUT),n=ll(process.env.MAX_RETRIES),r=t??e?.timeout??tr.timeout;r=Math.max(nr,Math.min(rr,r));let o=n??e?.maxRetries??tr.maxRetries;return o=Math.max(or,Math.min(ir,o)),{timeout:r,maxRetries:o}}function Nm(e){return{configPath:(process.env.OCTOCODE_LSP_CONFIG?.trim()||void 0)??e?.configPath??Ro.configPath}}function Gm(e){let t=process.env.OCTOCODE_OUTPUT_FORMAT?.trim().toLowerCase(),n=ll(process.env.OCTOCODE_OUTPUT_DEFAULT_CHAR_LENGTH),r=t||e?.format||Ft.format,o=n??e?.pagination?.defaultCharLength??Ft.pagination.defaultCharLength,i=Math.max(sr,Math.min(ar,o));return{format:Px.has(r)?r:Ft.format,pagination:{defaultCharLength:i}}}var Px,Hm=y(()=>{"use strict";So();ms();Px=new Set(["yaml","json"])});function ul(e,t){let n=e!==void 0,r=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,o;return n&&r?o="mixed":n?o="file":o="defaults",{version:e?.version??us.version,github:Im(e?.github),local:Fm(e?.local),tools:Mm(e?.tools),network:Dm(e?.network),lsp:Nm(e?.lsp),output:Gm(e?.output),source:o,configPath:n?t:void 0}}function Eo(){let e=Po();return e.success&&e.config&&fs(e.config).valid?ul(e.config,e.path):ul(void 0)}async function dl(){return Eo()}function ge(){let e=Date.now();return Pn&&e-wo<xx||(Pn=Eo(),wo=e),Pn}async function hs(){return ge()}async function pl(){return cr(),hs()}function cr(){Pn=null,wo=0}function fl(){Pn=null,wo=0}function ml(){return{cached:Pn!==null,timestamp:wo}}var Pn,wo,xx,gl=y(()=>{"use strict";So();ps();cl();Hm();Pn=null,wo=0,xx=6e4});function zm(e){let t=ge(),n=e.split("."),r=t;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}var Bm=y(()=>{"use strict";gl();gl()});var hl=y(()=>{"use strict";ol();So();ps();ps();cl();Bm();ms();il()});import{existsSync as wx,readdirSync as Ex,lstatSync as Tx}from"node:fs";import{join as kx}from"node:path";function To(e){if(!wx(e))return 0;let t=0,n=[e];for(;n.length>0;){let r=n.pop(),o;try{o=Ex(r)}catch{continue}for(let i of o){let s=kx(r,i);try{let a=Tx(s);if(a.isSymbolicLink())continue;a.isDirectory()?n.push(s):a.isFile()&&(t+=a.size)}catch{}}}return t}function Ox(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}var yl=y(()=>{"use strict"});var _e=y(()=>{"use strict";Yc();$i();rl();hl();hn();yl()});var xn,ys=y(()=>{xn="16.6.2"});import{maskSensitiveData as Ax}from"@octocodeai/octocode-engine/mask";function XH(e){e.resolveTokenFull&&(bl=e.resolveTokenFull)}function JH(){bl=Kt}async function Rl(){try{let e=await bl({hostname:"github.com"});if(e?.token){let t=e.source??"none";return{token:e.token,source:Lx.has(t)?t:"none"}}return{token:null,source:"none"}}catch{return{token:null,source:"none"}}}async function Qm(){if(ur!==null)return;if(lr!==null)return lr;let e=(async()=>{let t=ge(),n=await Rl();ur={version:xn,githubApiUrl:t.github.apiUrl,toolsToRun:t.tools.enabled??void 0,enableTools:t.tools.enableAdditional??void 0,disableTools:t.tools.disabled??void 0,timeout:t.network.timeout,maxRetries:t.network.maxRetries,enableLocal:t.local.enabled,enableClone:t.local.enableClone,outputFormat:t.output.format,tokenSource:n.source}})();lr=e;try{await e}catch(t){throw lr===e&&(ur=null,lr=null),t}}function ZH(){ur=null,lr=null,cr()}function bs(){if(!ur){let e=Ax(Lc.NOT_INITIALIZED.message);throw new Error(e)}return ur}async function Um(){return(await Rl()).token}function ez(){return bs().enableLocal}function tz(){let e=bs();return e.enableLocal&&e.enableClone}async function nz(){return(await Rl()).source}function Sl(){return"github"}function Cl(){let e=ge().github.apiUrl;return{provider:"github",baseUrl:e!=="https://api.github.com"?e:void 0}}var ur,lr,bl,Lx,dr=y(()=>{"use strict";_e();ys();pt();ur=null,lr=null,bl=Kt;Lx=new Set(["env:OCTOCODE_TOKEN","env:GH_TOKEN","env:GITHUB_TOKEN","env:GITHUB_PERSONAL_ACCESS_TOKEN","octocode-storage","gh-cli","none"])});function Jt(e){(e.provider?Je({rateLimits:1,rateLimitsByProvider:{[e.provider]:1}}):ss(1)).session&&e.provider==="github"&&ls(1)}function jm(e){Je({packageRegistryFailures:{[e]:1}})}var ko=y(()=>{"use strict";_e()});import{Octokit as _x}from"octokit";import{throttling as Ix}from"@octokit/plugin-throttling";import{createHash as Fx}from"crypto";function Mx(e){return Fx("sha256").update(e).digest("hex").substring(0,16)}function Km(e){return Date.now()-e.createdAt>Nx}function Ym(){for(let[e,t]of xt.entries())Km(t)&&xt.delete(e);if(xt.size>Pl){let e=[...xt.entries()].sort((n,r)=>n[1].createdAt-r[1].createdAt),t=xt.size-Pl;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&xt.delete(r[0])}}}function Hx(){Zt||(Zt=setInterval(Ym,Gx),typeof Zt=="object"&&"unref"in Zt&&Zt.unref())}function Vm(e,t,n){Jt({limit_type:e,retry_after_seconds:t,api_method:n.method,api_url:n.url,provider:"github"})}function Bx(e){let t=bs(),n=t.githubApiUrl,r={debug:()=>{},info:()=>{},warn:()=>{},error:(...i)=>console.error(...i)},o={userAgent:`octocode-mcp/${xn}`,baseUrl:n,request:{timeout:t.timeout||3e4,log:r},throttle:zx(),log:r,...e&&{auth:e}};return new Dx(o)}async function pe(e){Hx();let t=e?.token??await Um(),n=t?Mx(t):"ANONYMOUS",r=xt.get(n);if(r&&!Km(r))return r.client;xt.size>=Pl&&Ym();let o=Bx(t??void 0);return xt.set(n,{client:o,createdAt:Date.now()}),o}async function Ze(e,t,n){let r=`${e}/${t}`,o=pr.get(r);if(o)return o;let i=await pe(n);try{let{data:a}=await i.rest.repos.get({owner:e,repo:t}),c=a.default_branch;return Wm(r,c),c}catch{}let s=["main","master"];for(let a of s)try{return await i.rest.repos.getBranch({owner:e,repo:t,branch:a}),Wm(r,a),a}catch{}throw new Error(`Could not determine default branch for ${e}/${t}. The repository may not exist, require authentication, or be inaccessible.`)}function Wm(e,t){if(pr.size>=Qx){let n=pr.keys().next().value;n!==void 0&&pr.delete(n)}pr.set(e,t)}function fz(){xt.clear(),pr.clear(),Zt&&(clearInterval(Zt),Zt=null)}var Dx,Nx,Pl,Gx,xt,Zt,$m,qm,zx,Qx,pr,Ge=y(()=>{"use strict";dr();dr();ys();ko();Dx=_x.plugin(Ix),Nx=300*1e3,Pl=50,Gx=60*1e3;xt=new Map,Zt=null;$m=3,qm=60;zx=()=>({onRateLimit:(e,t,n,r)=>(Vm("primary",e,t),r<$m&&e<qm),onSecondaryRateLimit:(e,t,n,r)=>(Vm("secondary",e,t),r<$m&&e<qm)});Qx=200,pr=new Map});import{createRequire as Ux}from"node:module";function J(){if(Rs)return Rs;try{return Rs=$x(),Rs}catch(e){throw new xl(e)}}var jx,Xm,Rs,$x,xl,F,be=y(()=>{"use strict";jx=Ux(import.meta.url),Xm="@octocodeai/octocode-engine",$x=()=>jx(Xm),xl=class extends Error{constructor(n){super(`Failed to load native dependency ${Xm}`);this.cause=n;this.name="ContextUtilsLoadError"}cause};F={applyContentViewMinification(e,t){return J().applyContentViewMinification(e,t)},applyMinification(e,t){return J().applyMinification(e,t)},minifyContent(e,t){return J().minifyContent(e,t)},minifyContentSync(e,t){return J().minifyContentSync(e,t)},minifyContentResult(e,t){return J().minifyContentResult(e,t)},minifyMarkdownCore(e){return J().minifyMarkdownCore(e)},extractSignatures(e,t){return J().extractSignatures(e,t)},extractJsSymbols(e,t){return J().extractJsSymbols(e,t)},findInFileReferences(e,t,n,r){return J().findInFileReferences(e,t,n,r)},extractGraphFacts(e,t){return J().extractGraphFacts(e,t)},getSupportedJsTsExtensions(){return J().getSupportedJsTsExtensions()},getSupportedGraphFactExtensions(){return J().getSupportedGraphFactExtensions()},getGraphFactCapabilities(){return J().getGraphFactCapabilities()},structuralSearch(e,t,n,r){return J().structuralSearch(e,t,n,r)},structuralSearchFiles(e){return J().structuralSearchFiles(e)},getSupportedStructuralExtensions(){return J().getSupportedStructuralExtensions()},inspectBinaryNative(e){return J().inspectBinaryNative(e)},extractBinaryStringsNative(e,t,n,r=0){return J().extractBinaryStringsNative(e,t,n,r)},validateRipgrepPattern(e,t,n){return J().validateRipgrepPattern(e,t,n)},getSemanticBoundaryOffsets(e,t){return J().getSemanticBoundaryOffsets(e,t)},jsonToYamlString(e,t){return J().jsonToYamlString(e,t)},parseRipgrepJson(e,t){return J().parseRipgrepJson(e,t)},searchRipgrep(e){return J().searchRipgrep(e)},queryFileSystem(e){return J().queryFileSystem(e)},extractMatchingLines(e,t,n){return J().extractMatchingLines(e,t,n)},filterPatch(e,t){return J().filterPatch(e,t)},charToByteOffset(e,t){return J().charToByteOffset(e,t)},byteToCharOffset(e,t){return J().byteToCharOffset(e,t)},byteSliceContent(e,t,n){return J().byteSliceContent(e,t,n)},sliceContent(e,t,n,r){return J().sliceContent(e,t,n,r)},get SIGNATURES_ONLY_HINT(){return J().SIGNATURES_ONLY_HINT}}});var q,Se,Jm,wl,El,Ss,Tl=y(()=>{"use strict";q={AUTH_REQUIRED:"AUTH_REQUIRED",RATE_LIMIT_PRIMARY:"RATE_LIMIT_PRIMARY",RATE_LIMIT_SECONDARY:"RATE_LIMIT_SECONDARY",FORBIDDEN_PERMISSIONS:"FORBIDDEN_PERMISSIONS",NOT_FOUND:"NOT_FOUND",INVALID_REQUEST:"INVALID_REQUEST",SERVER_UNAVAILABLE:"SERVER_UNAVAILABLE",NETWORK_CONNECTION_FAILED:"NETWORK_CONNECTION_FAILED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",UNKNOWN:"UNKNOWN"},Se={[q.AUTH_REQUIRED]:{message:"GitHub authentication required",suggestion:"TELL THE USER: Refresh your GitHub token! Run 'gh auth login' OR 'gh auth refresh' OR set a new GITHUB_TOKEN/GH_TOKEN environment variable",explanation:"API request requires authentication. GitHub APIs have different rate limits for authenticated (5000/hour) vs unauthenticated (60/hour) requests."},[q.RATE_LIMIT_PRIMARY]:{message:"GitHub API rate limit exceeded",messageWithTime:(e,t)=>`GitHub API rate limit exceeded. Resets at ${e.toISOString()} (in ${t} seconds)`,messageWithoutTime:"GitHub API rate limit exceeded. Reset time unavailable - check GitHub status or try again later",suggestion:"Set GITHUB_TOKEN for higher rate limits (5000/hour vs 60/hour)",explanation:"Primary rate limit tracks total API calls per hour. Authenticated users get 5000 requests/hour, unauthenticated get 60 requests/hour."},[q.RATE_LIMIT_SECONDARY]:{message:e=>`GitHub secondary rate limit triggered. Retry after ${e} seconds`,suggestion:"Reduce request frequency to avoid abuse detection",explanation:"Secondary rate limits prevent API abuse by limiting request frequency. Triggered by making too many requests too quickly, regardless of remaining quota.",fallbackRetryAfter:60},[q.FORBIDDEN_PERMISSIONS]:{message:"Access forbidden - insufficient permissions",suggestion:"Check repository permissions or authentication",suggestionWithScopes:e=>`Missing required scopes: ${e.join(", ")}. Run: gh auth refresh -s ${e.join(" -s ")}`,fallbackSuggestion:"Token may not have sufficient permissions for this operation",explanation:"GitHub tokens require specific OAuth scopes for different operations. Common scopes: repo (full repository access), read:org (organization access), gist (gist access)."},[q.NOT_FOUND]:{message:"Repository, resource, or path not found",explanation:"Resource not found or not accessible. Could be: incorrect path, deleted resource, private repository without access, wrong branch name."},[q.INVALID_REQUEST]:{message:"Invalid search query or request parameters",suggestion:"Check search syntax and parameter values",explanation:"Request was well-formed but contains invalid parameters. Common causes: invalid search syntax, parameters out of range, invalid filter combinations."},[q.SERVER_UNAVAILABLE]:{message:"GitHub API temporarily unavailable",suggestion:"Retry the request after a short delay",explanation:"GitHub servers are temporarily unavailable. Usually resolves quickly. Check https://www.githubstatus.com for service status."},[q.NETWORK_CONNECTION_FAILED]:{message:"Network connection failed",suggestion:"Check internet connection and GitHub API status",explanation:"Cannot establish connection to GitHub API. Check internet connectivity, DNS settings, and firewall/proxy configuration."},[q.REQUEST_TIMEOUT]:{message:"Request timeout",suggestion:"Retry the request or check network connectivity",explanation:"Request exceeded timeout limit. Could be slow network, large response size, or GitHub server delay."},[q.UNKNOWN]:{message:"Unknown error occurred",explanation:"An unexpected error occurred that does not match known error patterns."}},Jm={401:q.AUTH_REQUIRED,403:q.FORBIDDEN_PERMISSIONS,404:q.NOT_FOUND,422:q.INVALID_REQUEST,502:q.SERVER_UNAVAILABLE,503:q.SERVER_UNAVAILABLE,504:q.SERVER_UNAVAILABLE},wl={CONNECTION_FAILED:["ENOTFOUND","ECONNREFUSED"],TIMEOUT:["timeout"]},El={SECONDARY:/\bsecondary rate\b/i,GRAPHQL_TYPE:"RATE_LIMITED"},Ss={RESET_BUFFER_SECONDS:1,SECONDARY_FALLBACK_SECONDS:60}});import{RequestError as Zm}from"octokit";function wn(e){if(!(e instanceof Zm)||e.status!==422)return!1;let t=e.response?.data?.errors;return!Array.isArray(t)||t.length===0?!1:t.some(n=>{let r=typeof n?.message=="string"?n.message.toLowerCase():"";return qx.some(o=>r.includes(o))})}function re(e){return e instanceof Zm?Vx(e):e instanceof Error?tw(e):{error:typeof e=="string"?e:Se[q.UNKNOWN].message,type:"unknown"}}function Vx(e){let{status:t,message:n,response:r}=e;if(t===403)return Kx(n,r);if(t===429)return Wx(n,r);let o=Jm[t];return o?ew(o,t):fr(q.UNKNOWN,{error:n||Se[q.UNKNOWN].message,status:t})}function kl(e,t){let n=e?.[t],r=n===void 0?NaN:parseInt(String(n),10);return isNaN(r)?void 0:r}function Wx(e,t){let n=t?.headers,r=kl(n,"retry-after"),o=kl(n,"x-ratelimit-reset"),i=kl(n,"x-ratelimit-remaining")??0,s=o?new Date(o*1e3):null,a=r??(s?Math.max(Math.ceil((s.getTime()-Date.now())/1e3)+Ss.RESET_BUFFER_SECONDS,0):void 0);return Jt({limit_type:"primary",retry_after_seconds:a,rate_limit_remaining:i,rate_limit_reset_ms:s?s.getTime():void 0,provider:"github"}),fr(q.RATE_LIMIT_PRIMARY,{error:e||Se[q.RATE_LIMIT_PRIMARY].messageWithoutTime,status:429,rateLimitRemaining:i,rateLimitReset:s?s.getTime():void 0,retryAfter:a,scopesSuggestion:Se[q.RATE_LIMIT_PRIMARY].suggestion})}function Kx(e,t){let n=t?.headers;if(El.SECONDARY.test(e))return Yx(n);let r=n?.["x-ratelimit-remaining"],o=Zx(t);return r!==void 0&&String(r)==="0"||o?Xx(n):Jx(n)}function Yx(e){let t=Number(e?.["retry-after"]),n=isNaN(t)?Ss.SECONDARY_FALLBACK_SECONDS:t;return Jt({limit_type:"secondary",retry_after_seconds:n,provider:"github"}),fr(q.RATE_LIMIT_SECONDARY,{error:Se[q.RATE_LIMIT_SECONDARY].message(n),status:403,rateLimitRemaining:0,retryAfter:n,scopesSuggestion:Se[q.RATE_LIMIT_SECONDARY].suggestion})}function Xx(e){let t=e?.["x-ratelimit-reset"],n=t?parseInt(String(t),10):NaN,r=isNaN(n)?null:new Date(n*1e3),o=r?Math.max(Math.ceil((r.getTime()-Date.now())/1e3)+Ss.RESET_BUFFER_SECONDS,0):void 0,i=r?Se[q.RATE_LIMIT_PRIMARY].messageWithTime(r,o):Se[q.RATE_LIMIT_PRIMARY].messageWithoutTime;return Jt({limit_type:"primary",retry_after_seconds:o,rate_limit_remaining:0,rate_limit_reset_ms:r?r.getTime():void 0,provider:"github"}),fr(q.RATE_LIMIT_PRIMARY,{error:i,status:403,rateLimitRemaining:0,rateLimitReset:r?r.getTime():void 0,retryAfter:o,scopesSuggestion:Se[q.RATE_LIMIT_PRIMARY].suggestion})}function Jx(e){let t=e?.["x-accepted-oauth-scopes"],n=e?.["x-oauth-scopes"],r=Se[q.FORBIDDEN_PERMISSIONS].suggestion;return t&&n&&(r=nw(String(t),String(n))),fr(q.FORBIDDEN_PERMISSIONS,{error:Se[q.FORBIDDEN_PERMISSIONS].message,status:403,scopesSuggestion:r})}function Zx(e){return e?.data?.errors?.some(n=>n.type===El.GRAPHQL_TYPE)??!1}function ew(e,t){let n=Se[e];return fr(e,{error:n.message,status:t,..."suggestion"in n&&{scopesSuggestion:n.suggestion}})}function tw(e){return wl.CONNECTION_FAILED.some(t=>e.message.includes(t))?{error:Se[q.NETWORK_CONNECTION_FAILED].message,type:"network",scopesSuggestion:Se[q.NETWORK_CONNECTION_FAILED].suggestion}:wl.TIMEOUT.some(t=>e.message.includes(t))?{error:Se[q.REQUEST_TIMEOUT].message,type:"network",scopesSuggestion:Se[q.REQUEST_TIMEOUT].suggestion}:{error:e.message,type:"unknown"}}function fr(e,t){return{type:"http",...t}}function nw(e,t){let n=e.split(",").map(i=>i.trim()).filter(Boolean),r=t.split(",").map(i=>i.trim()).filter(Boolean),o=n.filter(i=>!r.includes(i));return o.length>0?Se[q.FORBIDDEN_PERMISSIONS].suggestionWithScopes(o):Se[q.FORBIDDEN_PERMISSIONS].fallbackSuggestion}var qx,wt=y(()=>{"use strict";Tl();ko();qx=["cannot be searched","do not exist","does not exist","could not be found","cannot be found"]});function rw(e){return`user:${e}`}function eg(e){return e.startsWith('"')||sw.test(e)?e:`"${e.replace(/"/g,'\\"')}"`}function tg(e){return new Ol().addQueryTerms(e).addSearchFilters(e).addOwnerRepo(e).addMatchFilters(e).build()}function ng(e){return new vl().addQueryTerms(e).addOwnerRepo(e).addRepoFilters(e).addMatchFilters(e).addQualityFilters(e).build()}function rg(e){return new Al().addBasicFilters(e).addOwnerRepo(e).addStateFilters(e).addUserFilters(e).addBranchFilters(e).addDateFilters(e).addEngagementFilters(e).addReviewFilters(e).addOrganizationFilters(e).addNegativeFilters(e).addMiscFilters(e).build()}function og(e){return e.draft!==void 0||e.author!==void 0||e.assignee!==void 0||typeof e.query=="string"&&e.query.trim().length>0||e.label&&e.label.length>0||e.mentions!==void 0||e.commenter!==void 0||e.involves!==void 0||e["reviewed-by"]!==void 0||e["review-requested"]!==void 0||e.reactions!==void 0||e.comments!==void 0||e.interactions!==void 0||e["no-assignee"]!==void 0||e["no-label"]!==void 0||e["no-milestone"]!==void 0||e["no-project"]!==void 0||e.state==="merged"||e.milestone!==void 0||e.language!==void 0||e.checks!==void 0||e.review!==void 0||e.locked!==void 0||e.visibility!==void 0||e["team-mentions"]!==void 0||e.project!==void 0||e.created!==void 0||e.updated!==void 0||e["merged-at"]!==void 0||e.closed!==void 0||e.merged!==void 0||e.match!==void 0&&e.match.length>0||e.sort==="comments"||e.sort==="reactions"||Array.isArray(e.owner)||Array.isArray(e.repo)}var ow,iw,sw,Oo,Ol,vl,Al,vo=y(()=>{"use strict";ow=/[@/]/,iw=/(?:^|\/)([^/]+\.[A-Za-z][A-Za-z0-9]{0,9})$/,sw=/^[A-Za-z0-9_-]+$/;Oo=class{queryParts=[];addOwnerRepo(t){if(t.owner&&t.repo){let n=Array.isArray(t.owner)?t.owner:[t.owner],r=Array.isArray(t.repo)?t.repo:[t.repo];n.forEach(o=>{r.forEach(i=>{this.queryParts.push(`repo:${o}/${i}`)})})}else t.owner&&(Array.isArray(t.owner)?t.owner:[t.owner]).forEach(r=>{this.queryParts.push(rw(r))});return this}addDateFilters(t){return Object.entries({created:"created",updated:"updated","author-date":"author-date","committer-date":"committer-date","merged-at":"merged",closed:"closed"}).forEach(([r,o])=>{let i=t[r];i&&this.queryParts.push(`${o}:${i}`)}),this}addArrayFilter(t,n,r=!1){return t&&t!==null&&(Array.isArray(t)?t:[t]).forEach(i=>{let s=r?`"${i}"`:i;this.queryParts.push(`${n}:${s}`)}),this}addBooleanFilter(t,n,r){return t===!0?this.queryParts.push(n):t===!1&&this.queryParts.push(r),this}addSimpleFilter(t,n){return t!=null&&this.queryParts.push(`${n}:${t}`),this}addQuotedFilter(t,n){if(t!=null){let o=ow.test(t)&&!t.startsWith('"')?`"${t}"`:t;this.queryParts.push(`${n}:${o}`)}return this}build(){return this.queryParts.join(" ").trim()}},Ol=class extends Oo{addQueryTerms(t){if(Array.isArray(t.keywords)&&t.keywords.length>0){let n=t.keywords.filter(r=>r&&r.trim());n.length>0&&this.queryParts.push(...n.map(eg))}return this}addSearchFilters(t){let n=t.path,r=t.filename,o=typeof n=="string"&&!r?n.match(iw):null;return o&&(r=o[1],n=n.slice(0,o.index)||void 0),this.addSimpleFilter(r,"filename"),this.addSimpleFilter(t.extension,"extension"),this.addQuotedFilter(n,"path"),t.language&&this.queryParts.push(`language:${t.language}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="file"?this.queryParts.push("in:file"):r==="path"&&this.queryParts.push("in:path")}),this}},vl=class extends Oo{addQueryTerms(t){return Array.isArray(t.keywords)&&t.keywords.length>0&&this.queryParts.push(...t.keywords.map(eg)),this}addRepoFilters(t){this.addArrayFilter(t.topicsToSearch,"topic"),this.addSimpleFilter(t.stars,"stars"),this.addSimpleFilter(t.size,"size"),this.addSimpleFilter(t.created,"created"),t.updated&&this.queryParts.push(`pushed:${t.updated}`),t.language&&this.queryParts.push(`language:${t.language}`);let n=t;return typeof n.forks=="string"&&this.queryParts.push(`forks:${n.forks}`),typeof n.license=="string"&&this.queryParts.push(`license:${n.license}`),typeof n.goodFirstIssues=="string"&&this.queryParts.push(`good-first-issues:${n.goodFirstIssues}`),this}addMatchFilters(t){return t.match&&(Array.isArray(t.match)?t.match:[t.match]).forEach(r=>{r==="name"?this.queryParts.push("in:name"):r==="description"?this.queryParts.push("in:description"):r==="readme"&&this.queryParts.push("in:readme")}),this}addQualityFilters(t){let n=t,r=n?.archived;this.queryParts.push(r===!0?"archived:true":"is:not-archived");let o=n?.visibility;return o==="public"?this.queryParts.push("is:public"):o==="private"&&this.queryParts.push("is:private"),this}},Al=class extends Oo{addBasicFilters(t){return t.query&&t.query.trim()&&(this.queryParts.push(t.query.trim()),t.match&&t.match.length>0&&this.queryParts.push(`in:${t.match.join(",")}`)),this.queryParts.push("is:pr"),this}addStateFilters(t){return t.merged===!0&&t.state==="closed"||this.addSimpleFilter(t.state,"is"),this.addBooleanFilter(t.draft,"is:draft","-is:draft"),this.addBooleanFilter(t.merged,"is:merged","is:unmerged"),this}addUserFilters(t){return this.addSimpleFilter(t.author,"author"),this.addSimpleFilter(t.assignee,"assignee"),this.addSimpleFilter(t.mentions,"mentions"),this.addSimpleFilter(t.commenter,"commenter"),this.addSimpleFilter(t.involves,"involves"),this.addSimpleFilter(t["reviewed-by"],"reviewed-by"),this.addSimpleFilter(t["review-requested"],"review-requested"),this}addBranchFilters(t){return this.addSimpleFilter(t.head,"head"),this.addSimpleFilter(t.base,"base"),this}addEngagementFilters(t){return this.addSimpleFilter(t.comments,"comments"),this.addSimpleFilter(t.reactions,"reactions"),this.addSimpleFilter(t.interactions,"interactions"),this}addReviewFilters(t){return t.review&&this.queryParts.push(`review:${t.review}`),this}addOrganizationFilters(t){return this.addArrayFilter(t.label,"label",!0),t.milestone&&this.queryParts.push(`milestone:"${t.milestone}"`),this}addNegativeFilters(t){return t["no-assignee"]&&this.queryParts.push("no:assignee"),t["no-label"]&&this.queryParts.push("no:label"),t["no-milestone"]&&this.queryParts.push("no:milestone"),t["no-project"]&&this.queryParts.push("no:project"),t.locked===!0?this.queryParts.push("is:locked"):t.locked===!1&&this.queryParts.push("is:unlocked"),t.visibility==="public"?this.queryParts.push("is:public"):t.visibility==="private"&&this.queryParts.push("is:private"),t["team-mentions"]&&this.queryParts.push(`team:${t["team-mentions"]}`),t.project&&this.queryParts.push(`project:${t.project}`),this}addMiscFilters(t){return this.queryParts.push(t.archived===!0?"archived:true":"archived:false"),t.language&&this.queryParts.push(`language:${t.language}`),t.checks&&this.queryParts.push(`status:${t.checks}`),this}}});import aw from"node-cache";import cw from"crypto";function dw(e){return e.match(/^v\d+-([^:]+):/)?.[1]}function pw(e){return e.startsWith("gh-api-")||e.startsWith("gh-repo-")||e==="github-user"}function fw(e){let t=dw(e);if(!(!t||!pw(t)))try{cs(t,1)}catch{}}function mw(){let e=Date.now();for(let[t,n]of mr.entries())e-n.startedAt>uw&&mr.delete(t)}function hw(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t=e,n=!1,r={};for(let o of Object.keys(t)){if(gw.has(o)){n=!0;continue}r[o]=t[o]}return n?r:e}function He(e,t,n){let r=Ll(hw(t)),o=n?`${n}:${r}`:r,i=cw.createHash("sha256").update(o).digest("hex");return`${lw}-${e}:${i}`}function Ll(e,t=new WeakSet){return e===null?"null":e===void 0?"undefined":typeof e!="object"?String(e):t.has(e)?'"[Circular]"':(t.add(e),Array.isArray(e)?`[${e.map(o=>Ll(o,t)).join(",")}]`:`{${Object.keys(e).sort().map(o=>{let i=e[o];return`"${o}":${Ll(i,t)}`}).join(",")}}`)}function yw(e){return ig[e]||ig.default}function bw(e,t,n){try{return it.set(e,t,n),Ie.sets++,Ie.totalKeys=it.keys().length,!0}catch{try{let r=it.keys();for(let o of r)it.get(o);return it.set(e,t,n),Ie.sets++,Ie.totalKeys=it.keys().length,!0}catch{return!1}}}async function ze(e,t,n={}){if(n.skipCache)return await t();if(!n.forceRefresh)try{let i=it.get(e);if(i!==void 0)return Ie.hits++,fw(e),i}catch{}mw();let r=mr.get(e);if(r)return r.promise;let o=(async()=>{try{let i=await t();if(n.forceRefresh||Ie.misses++,(n.shouldCache??(()=>!0))(i)){let a=n.ttl;if(!a){let l=e.match(/^v\d+-([^:]+):/)?.[1]??"default";a=yw(l)}bw(e,i,a)}return i}finally{mr.delete(e)}})();return mr.set(e,{promise:o,startedAt:Date.now()}),o}function Tz(){it.flushAll(),mr.clear(),Ie.hits=0,Ie.misses=0,Ie.sets=0,Ie.totalKeys=0,Ie.lastReset=new Date}function en(e){let t=it.keys(),n=0;for(let r of t){let i=r.match(/^v\d+-([^:]+):/)?.[1];!i||!i.startsWith(e)||it.del(r)>0&&n++}return n>0&&(Ie.totalKeys=it.keys().length),n}function kz(){return en("local-")}function Oz(){return en("lsp-")}function vz(){let e=0;return e+=en("gh-api-"),e+=en("bb-api-"),e+=en("gh-repo-"),e+=en("bb-repo-"),e+=en("github-user"),e+=en("npm-search"),e}function Az(){let e=Ie.hits+Ie.misses;return{...Ie,hitRate:e>0?Ie.hits/e*100:0,cacheSize:it.keys().length}}var lw,uw,it,Ie,ig,mr,gw,Mt=y(()=>{"use strict";_e();lw="v1",uw=300*1e3,it=new aw({stdTTL:86400,checkperiod:300,maxKeys:5e3,deleteOnExpire:!0,useClones:!1}),Ie={hits:0,misses:0,sets:0,totalKeys:0,lastReset:new Date},ig={"gh-api-code":3600,"gh-api-repos":7200,"gh-api-prs":1800,"gh-api-file-content":300,"gh-repo-structure-api":7200,"github-user":900,"npm-search":14400,default:86400},mr=new Map;gw=new Set([])});import{DISCOVERY_IGNORED_FILE_EXTENSIONS as Fz,DISCOVERY_IGNORED_FILE_NAMES as Mz,DISCOVERY_IGNORED_FOLDER_NAMES as Dz,getDiscoveryExtension as sg,shouldIgnoreDiscoveryDir as Ao,shouldIgnoreDiscoveryFile as gr}from"@octocodeai/octocode-engine/security";var hr=y(()=>{"use strict"});function U(e){if(typeof e=="string")return e.length;try{return JSON.stringify(e)?.length??0}catch{return String(e).length}}function cg(e){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.max(0,e)}function $(e,t){let n=typeof t=="number"?cg(t):U(t);if(n===void 0)return e;try{Object.defineProperty(e,ag,{value:n,enumerable:!1,configurable:!0})}catch{}return e}function le(e){if(!(typeof e!="object"||e===null))return cg(e[ag])}var ag,oe=y(()=>{"use strict";ag=Symbol.for("octocode.rawResponseChars")});function Cs(e){let t={};if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r:typeof r=="number"&&Number.isFinite(r)&&(t[n]=String(r));return t}var Ps=y(()=>{"use strict"});import{ContentSanitizer as Rw}from"@octocodeai/octocode-engine/contentSanitizer";async function ug(e,t,n){let r=He("gh-api-code",{keywords:e.keywords,owner:e.owner,repo:e.repo,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page},n);return await ze(r,async()=>await Sw(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Sw(e,t){try{let n=await pe(t);if(e.keywords&&e.keywords.length>0&&e.keywords.filter(C=>C&&C.trim()).length===0)return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let r=tg(e);if(!r.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let o=Math.min(typeof e.limit=="number"?e.limit:lg,100),i=e.page||1,s={q:r,per_page:o,page:i,headers:{Accept:"application/vnd.github.v3.text-match+json"}},a=await n.rest.search.code(s),c=await Cw(a.data.items,a.data.total_count),l=a.data.incomplete_results===!0,u=c.total_count,d=Math.min(u,1e3),p=Math.min(Math.ceil(d/o),10),f=Math.min(i,Math.max(1,p)),m=f<p,g=Math.min(d,p*o);return{data:{total_count:c.total_count,items:c.items,...l?{incompleteResults:!0}:{},repository:c.repository,matchLocations:c.matchLocations,minified:c.minified,minificationFailed:c.minificationFailed,minificationTypes:c.minificationTypes,_researchContext:c._researchContext,pagination:{currentPage:f,totalPages:p,perPage:o,totalMatches:d,reportedTotalMatches:u,reachableTotalMatches:g,totalMatchesKind:"reported",totalMatchesCapped:u>d,hasMore:m,...m?{nextPage:f+1}:{},uniqueFileCount:c._researchContext?.uniqueFileCount}},status:200,headers:Cs(a.headers),rawResponseChars:U(a.data)}}catch(n){if(wn(n)){let o=Math.min(typeof e.limit=="number"?e.limit:lg,100);return{data:{total_count:0,items:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:o,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return re(n)}}async function Cw(e,t){let n=Pw(e),r=new Set,o=!1,i=[],s=new Set,a=e.filter(f=>!gr(f.path)),c=0,l=0,u=await Promise.allSettled(a.map(async f=>{s.add(f.path);let m=[],g=await Promise.allSettled((f.text_matches||[]).map(async L=>{let k=L.fragment,O=Rw.sanitizeContent(k||"",f.path);k=O.content,O.hasSecrets&&r.add(`Secrets detected in ${f.path}: ${O.secretsDetected.join(", ")}`),O.warnings.length>0&&O.warnings.forEach(w=>r.add(`${f.path}: ${w}`));try{let w=await F.minifyContent(k||"",f.path);k=w.content,w.failed?o=!0:w.type!=="failed"&&(m.push(w.type),i.push(w.type))}catch{o=!0}return{context:k||"",positions:L.matches?.map(w=>Array.isArray(w.indices)&&w.indices.length>=2?[w.indices[0],w.indices[1]]:[0,0])||[]}})),b=g.filter(L=>L.status==="fulfilled").map(L=>L.value),C=g.filter(L=>L.status==="rejected").length;C>0&&(l+=C);let S=f,T=Array.from(new Set(m));return{path:f.path,matches:b,url:f.html_url,repository:{nameWithOwner:f.repository.full_name,url:f.repository.url,pushedAt:f.repository.pushed_at||void 0},...S.last_modified_at&&{lastModifiedAt:S.last_modified_at},...T.length>0&&{minificationType:T.join(",")}}})),d=u.filter(f=>f.status==="fulfilled").map(f=>f.value);c=u.filter(f=>f.status==="rejected").length;let p={items:d,total_count:t!==void 0?t:a.length,_researchContext:{uniqueFileCount:s.size,repositoryContext:n?(()=>{let f=n.full_name.split("/");return f.length===2&&f[0]&&f[1]?{owner:f[0],repo:f[1],branch:n.default_branch||void 0}:void 0})():void 0}};return n&&(p.repository={name:n.full_name,url:n.url,createdAt:n.created_at||void 0,updatedAt:n.updated_at||void 0,pushedAt:n.pushed_at||void 0}),c>0&&r.add(`${c} item(s) dropped due to processing errors`),l>0&&r.add(`${l} match(es) dropped due to processing errors`),r.size>0&&(p.matchLocations=Array.from(r)),p.minified=!o,p.minificationFailed=o,i.length>0&&(p.minificationTypes=Array.from(new Set(i))),p}function Pw(e){if(e.length===0)return null;let t=e[0]?.repository;return t&&e.every(r=>r.repository.full_name===t.full_name)?t:null}var lg,_l=y(()=>{"use strict";be();Ge();wt();vo();Mt();hr();pt();oe();Ps();me();lg=30});import{completeMetadata as Il}from"@octocodeai/octocode-core";var A,Fl=y(()=>{"use strict";A=new Proxy({},{get(e,t){return Il.toolNames[t]},ownKeys(){return Object.keys(Il.toolNames)},getOwnPropertyDescriptor(e,t){let n=Il.toolNames;if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});import{completeMetadata as xw}from"@octocodeai/octocode-core";var Ml,Dl=y(()=>{"use strict";Ml=new Proxy({},{get(e,t){return xw.tools[t]?.description??""}})});import{completeMetadata as ww}from"@octocodeai/octocode-core";function Nl(e){return Object.prototype.hasOwnProperty.call(ww.tools,e)}var Gl=y(()=>{"use strict"});import{completeMetadata as Ew}from"@octocodeai/octocode-core";function Hl(){return Ew.baseSchema}var Tw,zl=y(()=>{"use strict";Tw=new Proxy({},{get(e,t){return Hl()[t]},ownKeys(){return Array.from(new Set([...Reflect.ownKeys(Hl())]))},getOwnPropertyDescriptor(e,t){let n=Hl();if(t in n)return{enumerable:!0,configurable:!0,value:n[t]}}})});var fe=y(()=>{"use strict";Fl();Dl();Gl();zl()});import{RequestError as dg}from"octokit";async function kw(e,t,n,r,o,i,s,a){let c=await Ze(r,o,a);if((s==="main"||s==="master")&&s!==c)try{return{result:await e.rest.repos.getContent({...n,ref:c}),actualBranch:c}}catch{throw t}let u=re(t),d=s===c?void 0:`Branch '${s}' not found. Default branch is '${c}'. Ask user: Do you want to get the file from '${c}' instead?`,p=await gg(e,r,o,i,s||c);return p.length>0&&(u.hints=[...u.hints||[],...mg(i,p)]),{...u,...d&&{scopesSuggestion:d}}}async function Ow(e,t,n,r,o,i){let s=re(t),a=await gg(e,n,r,o,i||"main");return a.length>0&&(s.hints=[...s.hints||[],...mg(o,a)]),s}async function pg(e,t){let n=e.replace(/\s/g,"");if(!n)return{error:qt.FILE_EMPTY.message,type:"unknown",status:404};try{let r=Buffer.from(n,"base64");return r.indexOf(0)!==-1?{error:qt.BINARY_FILE.message,type:"unknown",status:415}:{data:r.toString("utf-8"),status:200}}catch{return{error:qt.DECODE_FAILED.message,type:"unknown",status:422}}}async function fg(e,t,n,r,o){try{let i=await e.rest.git.getBlob({owner:t,repo:n,file_sha:r}),{content:s,encoding:a}=i.data;return a==="base64"?pg(s,o):a==="utf-8"?{data:s,status:200}:{error:`Unsupported blob encoding: ${a}`,type:"unknown",status:415}}catch(i){return re(i)}}async function vw(e,t,n,r,o,i){try{let s=r.split("/").slice(0,-1).join("/"),a=r.split("/").pop();if(!a)return{error:`Cannot determine file name from path: ${r}`,type:"unknown",status:400};let c=o||await Ze(t,n,i).catch(()=>"HEAD"),l=await e.rest.repos.getContent({owner:t,repo:n,path:s||"",ref:c});if(!Array.isArray(l.data))return{error:`Expected directory listing for ${s||"root"}`,type:"unknown",status:500};let u=l.data.find(p=>p.name===a&&p.type==="file");if(!u)return{error:`File ${a} not found in ${s||"root"}`,type:"unknown",status:404};let d=await fg(e,t,n,u.sha,r);return"error"in d?d:{data:{rawContent:d.data,branch:typeof c=="string"?c:void 0,resolvedRef:typeof c=="string"?c:"HEAD"},status:200}}catch(s){return re(s)}}async function xs(e,t){try{let n=await pe(t),{owner:r,repo:o,path:i,branch:s}=e,a={owner:r,repo:o,path:i,...s&&{ref:s}},c,l=s;try{c=await n.rest.repos.getContent(a)}catch(d){if(d instanceof dg&&d.status===404)if(s){let p=await kw(n,d,a,r,o,i,s,t);if("result"in p)c=p.result,l=p.actualBranch;else return p}else return await Ow(n,d,r,o,i,s);else{if(d instanceof dg&&d.status===413)return await vw(n,r,o,i,s||l,t);throw d}}let u=c.data;if(Array.isArray(u))return{error:qt.PATH_IS_DIRECTORY.message(A.GITHUB_VIEW_REPO_STRUCTURE),type:"unknown",status:400};if("content"in u&&u.type==="file"){let d=typeof u.content=="string"?u.content:"",p=u.size??0,f;if(d.length>0)f=await pg(d,i);else if(p>0&&"sha"in u&&typeof u.sha=="string"&&u.sha)f=await fg(n,r,o,u.sha,i);else return{error:qt.FILE_EMPTY.message,type:"unknown",status:404};if("error"in f)return f;if(!l&&!s)try{l=await Ze(r,o,t)}catch{}return{data:{rawContent:f.data,branch:l||void 0,resolvedRef:l||s||"HEAD"},status:200,rawResponseChars:U(u)}}return{error:qt.UNSUPPORTED_TYPE.message(u.type),type:"unknown",status:415}}catch(n){return re(n)}}function mg(e,t){let n=e.split("/").pop()||"",r=t.some(i=>{let s=i.split("/").pop()||"";return s.toLowerCase()===n.toLowerCase()&&s!==n}),o=[];return r&&o.push("GitHub Contents API paths are case-sensitive. Verify exact file casing with ghViewRepoStructure."),o.push(`Did you mean: ${t.join(", ")}?`),o}async function gg(e,t,n,r,o){try{let i=r.split("/").slice(0,-1).join("/"),s=r.split("/").pop();if(!s)return[];let a=await e.rest.repos.getContent({owner:t,repo:n,path:i,ref:o});if(!Array.isArray(a.data))return[];let c=a.data,l=[],u=c.find(f=>f.name.toLowerCase()===s.toLowerCase());u&&l.push(u.path);let d=s.replace(/\.[^/.]+$/,"");return c.filter(f=>f.name===s?!1:!!f.name.startsWith(d+".")).forEach(f=>l.push(f.path)),l.length===0&&d.length>=3&&c.filter(m=>{let g=m.name.replace(/\.[^/.]+$/,"");return g!==d&&g.length>=3&&(d.startsWith(g)||g.startsWith(d))}).forEach(m=>l.push(m.path)),Array.from(new Set(l)).slice(0,3)}catch{return[]}}var ws=y(()=>{"use strict";Ge();wt();fe();pt();oe()});import{existsSync as Fo,readFileSync as Aw,writeFileSync as Lw,mkdirSync as _w,rmSync as _o,readdirSync as Iw,statSync as Fw}from"node:fs";import{join as st}from"node:path";import{createHash as Mw}from"node:crypto";function PB(e){return Bl(e)}function Bl(e){return st(e,"tmp","clone")}function bg(e){return st(e,"tmp","tree")}function zw(e){return e?`__sp_${Mw("sha256").update(e).digest("hex").substring(0,6)}`:""}function Rg(e,t,n,r,o){let i=`${r}${zw(o)}`;return st(Bl(e),t,n,i)}function Ql(e,t,n,r){return st(bg(e),t,n,r)}function Bw(e){return typeof e=="object"&&e!==null}function Qw(e){if(!Bw(e)||typeof e.clonedAt!="string"||typeof e.expiresAt!="string"||typeof e.owner!="string"||typeof e.repo!="string"||typeof e.branch!="string"||e.source!=="clone"&&e.source!=="directoryFetch"&&e.source!=="treeFetch")return null;let t={clonedAt:e.clonedAt,expiresAt:e.expiresAt,owner:e.owner,repo:e.repo,branch:e.branch,source:e.source};return typeof e.sparsePath=="string"&&(t.sparsePath=e.sparsePath),typeof e.sizeBytes=="number"&&(t.sizeBytes=e.sizeBytes),typeof e.commitSha=="string"&&e.commitSha.length===40&&(t.commitSha=e.commitSha),t}function Ul(e){let t=st(e,yg);if(!Fo(t))return null;try{return Qw(JSON.parse(Aw(t,"utf-8")))}catch{return null}}function Mo(e,t){try{Lw(st(e,yg),JSON.stringify(t,null,2),"utf-8")}catch{}}function Sg(e){return Date.now()<new Date(e.expiresAt).getTime()}function Do(e){let t=Ul(e);return t?Sg(t)?Fo(e)?{hit:!0,meta:t}:{hit:!1}:{hit:!1}:{hit:!1}}function Uw(){let e=process.env.OCTOCODE_CACHE_TTL_MS;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Dw}function jw(){let e=process.env.OCTOCODE_MAX_CACHE_SIZE;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return t}return Gw}function $w(){let e=process.env.OCTOCODE_MAX_CLONES;if(e!=null){let t=Number(e);if(!Number.isNaN(t)&&t>0)return Math.floor(t)}return Hw}function No(e,t,n,r,o,i,s){let a=new Date;return{clonedAt:a.toISOString(),expiresAt:new Date(a.getTime()+Uw()).toISOString(),owner:e,repo:t,branch:n,source:r,...o?{sparsePath:o}:{},...i!=null?{sizeBytes:i}:{},...s?{commitSha:s}:{}}}function Tn(e){let t=st(e,"..");try{Fo(t)||_w(t,{recursive:!0,mode:448})}catch(n){throw new Error(`Failed to create clone parent directory '${t}': ${n instanceof Error?n.message:String(n)}`)}}function Ts(e){try{Fo(e)&&_o(e,{recursive:!0,force:!0})}catch{}}function Lo(e){try{return Fw(e).isDirectory()}catch{return!1}}function En(e){try{return Iw(e)}catch{return[]}}function*Cg(e){for(let t of En(e)){let n=st(e,t);if(Lo(n))for(let r of En(n)){let o=st(n,r);if(Lo(o))for(let i of En(o)){let s=st(o,i);Lo(s)&&(yield s)}}}}function hg(e){for(let t of[...En(e)]){let n=st(e,t);if(Lo(n)){for(let r of[...En(n)]){let o=st(n,r);if(Lo(o)&&En(o).length===0)try{_o(o,{recursive:!0,force:!0})}catch{}}if(En(n).length===0)try{_o(n,{recursive:!0,force:!0})}catch{}}}}function qw(e){let t=0;for(let n of Cg(e))try{let r=Ul(n);(!r||!Sg(r))&&(_o(n,{recursive:!0,force:!0}),t++)}catch{}return t}function Vw(e){let t=[];for(let n of Cg(e)){let r=Ul(n);if(!r)continue;let o=Number.isNaN(Date.parse(r.clonedAt))?0:Date.parse(r.clonedAt);t.push({branchDir:n,clonedAtMs:o,sizeBytes:r.sizeBytes??To(n)})}return t}function Ww(e,t,n){let r=e.reduce((s,a)=>s+a.sizeBytes,0),o=e.length;if(r<=t&&o<=n)return 0;e.sort((s,a)=>s.clonedAtMs-a.clonedAtMs);let i=0;for(let s of e){if(r<=t&&o<=n)break;try{_o(s.branchDir,{recursive:!0,force:!0}),i++,r-=s.sizeBytes,o-=1}catch{}}return i}function Pg(e){if(!Fo(e))return 0;let t=0;try{t+=qw(e)}catch{return t}hg(e);let n=Ww(Vw(e),jw(),$w());return t+=n,n>0&&hg(e),t}function Es(e){return Pg(Bl(e))}function Io(e){return Pg(bg(e))}function xB(e){yr||(Es(e),Io(e),yr=setInterval(()=>{Es(e),Io(e)},Nw),yr.unref())}function wB(){yr&&(clearInterval(yr),yr=null)}var Dw,Nw,Gw,Hw,yg,yr,ks=y(()=>{"use strict";_e();Dw=1440*60*1e3,Nw=600*1e3,Gw=2*1024*1024*1024,Hw=50,yg=".octocode-clone-meta.json",yr=null});import{writeFileSync as Tg,mkdirSync as jl,existsSync as Go,rmSync as Kw,readdirSync as Yw,statSync as kg}from"node:fs";import{join as Os,dirname as Og,resolve as $l,sep as ql}from"node:path";function wg(){return{nonFile:0,missingDownloadUrl:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function eE(e){return Object.values(e).every(t=>t===0)}function Eg(e,t){if(!t&&e)return["Cannot verify completeness against remote tree; use forceRefresh or ghCloneRepo if completeness matters."];if(!e)return["Directory materialization is partial; inspect skipped counts or use ghCloneRepo before repo-wide reachability/dead-code conclusions."]}async function Lg(e,t,n,r,o,i=!1){let s=Cn(),a=Ql(s,e,t,r),c=$l(Os(a,n));if(!c.startsWith(a+ql)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Do(a);if(l.hit&&!i&&Go(c)){let v=oE(c,a),B=wg();return{localPath:c,repoRoot:a,files:v.files,fileCount:v.fileCount,totalSize:v.totalSize,complete:!0,verified:!1,...l.meta.commitSha?{commitSha:l.meta.commitSha}:{},directoryEntryCount:v.fileCount,eligibleFileCount:v.fileCount,savedFileCount:v.fileCount,skipped:B,limits:xg,warnings:Eg(!0,!1),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}let u=await pe(o),d;try{d=(await u.rest.repos.getBranch({owner:e,repo:t,branch:r})).data.commit.sha}catch{}let{data:p}=await u.rest.repos.getContent({owner:e,repo:t,path:n,ref:r});if(!Array.isArray(p))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let f=p,m=wg(),g=[];for(let v of f){if(v.type!=="file"){m.nonFile+=1;continue}if(!v.download_url){m.missingDownloadUrl+=1;continue}if(v.size>Ag){m.oversized+=1;continue}let B=sg(v.name,{lowercase:!0,leadingDot:!0});if(Zw.has(B)){m.binary+=1;continue}g.push(v)}m.fileLimit=Math.max(0,g.length-Vl);let b=g.slice(0,Vl),C=o?.token,S=await tE(b,Xw,C);m.fetchFailed=b.length-S.length;let T=0,L=[];for(let v=0;v<S.length;v+=1){let{entry:B,content:z}=S[v];if(T+z.length>vg){m.totalSizeLimit=S.length-v;break}T+=z.length,L.push({entry:B,content:z})}Io(s),Tn(a),Go(c)&&Kw(c,{recursive:!0,force:!0}),jl(c,{recursive:!0,mode:448});let k=[];for(let{entry:v,content:B}of L){let z=$l(Os(a,v.path));if(!z.startsWith(a+ql)){m.pathTraversal+=1;continue}let X=Og(z);Go(X)||jl(X,{recursive:!0,mode:448}),Tg(z,B,"utf-8"),k.push({path:v.path,size:B.length,type:"file"})}let O=No(e,t,r,"treeFetch",void 0,void 0,d);Mo(a,O);let w=eE(m),N=w,I=m.nonFile>0;return{localPath:c,repoRoot:a,files:k,fileCount:k.length,totalSize:T,complete:w,verified:N,...d?{commitSha:d}:{},...I?{hasSubdirectories:!0}:{},directoryEntryCount:f.length,eligibleFileCount:g.length,savedFileCount:k.length,skipped:m,limits:xg,warnings:Eg(w,N),cached:!1,expiresAt:O.expiresAt,owner:e,repo:t,branch:r,directoryPath:n}}async function _g(e,t,n,r,o,i=!1){let s=Cn(),a=Ql(s,e,t,r),c=$l(Os(a,n));if(!c.startsWith(a+ql)&&c!==a)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let l=Do(a);if(!i&&l.hit&&Go(c))return{localPath:c,repoRoot:a,path:n,size:iE(c),cached:!0,expiresAt:l.meta.expiresAt,owner:e,repo:t,branch:r};let u=await xs({owner:e,repo:t,path:n,type:"file",branch:r,fullContent:!0,contextLines:0,minify:"none",mainResearchGoal:"Materialize GitHub file content for local research",researchGoal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},o);if(!("data"in u)||!u.data){let m="error"in u?u.error:void 0;throw new Error(m||`Failed to fetch ${e}/${t}/${n}`)}Io(s),Tn(a);let d=Og(c);Go(d)||jl(d,{recursive:!0,mode:448}),Tg(c,u.data.rawContent,"utf-8");let p=u.data.branch||r,f=No(e,t,p,"treeFetch");return Mo(a,f),{localPath:c,repoRoot:a,path:n,size:u.data.rawContent.length,cached:!1,expiresAt:f.expiresAt,owner:e,repo:t,branch:p}}async function tE(e,t,n){let r=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),s=await Promise.allSettled(i.map(async a=>{let c=await rE(a.download_url,n);return{entry:a,content:c}}));for(let a of s)a.status==="fulfilled"&&r.push(a.value)}return r}async function rE(e,t){try{let o=new URL(e);if(!nE.has(o.hostname))throw new Error(`Blocked fetch to unexpected host: ${o.hostname}. Only GitHub download URLs are allowed.`)}catch(o){throw o instanceof TypeError?new Error(`Invalid download URL: ${e}`):o}let n=new AbortController,r=setTimeout(()=>n.abort(),Jw);try{let o={"User-Agent":"octocode-mcp"};t&&(o.Authorization=`token ${t}`);let i=await fetch(e,{signal:n.signal,headers:o});if(!i.ok)throw new Error(`HTTP ${i.status} fetching ${e}`);return await i.text()}finally{clearTimeout(r)}}function oE(e,t){let n=[],r=0;function o(i){let s;try{s=Yw(i)}catch{return}for(let a of s){if(a.startsWith("."))continue;let c=Os(i,a);try{let l=kg(c);if(l.isDirectory())o(c);else if(l.isFile()){let u=c.substring(t.length+1);r+=l.size,n.push({path:u,size:l.size,type:"file"})}}catch{}}}return o(e),{files:n,fileCount:n.length,totalSize:r}}function iE(e){try{return kg(e).size}catch{return 0}}var Vl,vg,Ag,Xw,Jw,Zw,xg,nE,Wl=y(()=>{"use strict";_e();Ge();ws();ks();hr();Vl=50,vg=5*1024*1024,Ag=300*1024,Xw=5,Jw=1e4,Zw=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".eot",".otf",".pyc",".class",".o",".obj",".lock",".min.js",".min.css"]),xg={maxDirectoryFiles:Vl,maxTotalSize:vg,maxFileSize:Ag};nE=new Set(["raw.githubusercontent.com","objects.githubusercontent.com","github.com"])});function et(){try{return ge().output.pagination.defaultCharLength}catch{return Ft.pagination.defaultCharLength}}function DB(e){let t=Math.min(Math.max(et(),1),Ig),n=Math.max(Math.floor(e)||0,1);return Math.min(t*n,Ig)}var Ig,br=y(()=>{"use strict";_e();_e();Ig=1e5});function Ho(e){if(e.length===0)return[];let t=e.split(/\r?\n/);return t.length>0&&t[t.length-1]===""&&t.pop(),t}function Dt(e){return Ho(e).length}var Rr=y(()=>{"use strict"});function sE(e,t,n){return F.byteSliceContent(e,t,n)}function vs(e,t){return F.byteToCharOffset(e,t)}function Fg(e,t){return F.charToByteOffset(e,t)}function Mg(e){return F.charToByteOffset(e,e.length)}function zB(e,t,n){let r=sE(e,t,t+n);return{charOffset:vs(e,t),charLength:r.length,text:r}}function Kl(e,t,n,r){return F.sliceContent(e,t,n,r)}var Yl=y(()=>{"use strict";be()});function Sr(e,t=0,n,r={}){let o=r.mode??"characters",i=e.length,s=Mg(e);if(n===void 0)return{paginatedContent:e,byteOffset:0,byteLength:s,totalBytes:s,nextByteOffset:void 0,charOffset:0,charLength:i,totalChars:i,nextCharOffset:void 0,hasMore:!1,estimatedTokens:Math.ceil(e.length/4),currentPage:1,totalPages:1};let a=Math.max(1,r.pageSize??n),c,l,u,d,p,f,m,g;if(o==="bytes"){let b=Math.min(t,s),C=Math.min(b+n,s);d=vs(e,b),p=vs(e,C),p<i&&Fg(e,p)<C&&(p+=1);let S=Kl(e,d,p-d);c=S.text,d=S.charOffset,p=S.charOffset+S.charLength,l=S.byteOffset,u=S.byteOffset+S.byteLength,f=u<s;let T=r.actualOffset??b;m=Math.floor(T/a)+1,g=Math.max(m,Math.ceil(s/a))}else{let b=Kl(e,t,n);c=b.text,d=b.charOffset,p=b.charOffset+b.charLength,l=b.byteOffset,u=b.byteOffset+b.byteLength,f=p<i;let C=r.actualOffset??d;m=Math.floor(C/a)+1,g=Math.max(m,Math.ceil(i/a))}return{paginatedContent:c,byteOffset:l,byteLength:u-l,totalBytes:s,nextByteOffset:f?u:void 0,charOffset:d,charLength:c.length,totalChars:i,nextCharOffset:f?p:void 0,hasMore:f,estimatedTokens:Math.ceil(c.length/4),currentPage:m,totalPages:g}}function UB(e,t=!1){return t?JSON.stringify(e,null,2):JSON.stringify(e)}function Dg(e){return{currentPage:e.currentPage,totalPages:e.totalPages,hasMore:e.hasMore,charOffset:e.charOffset,charLength:e.charLength,totalChars:e.totalChars,...e.nextCharOffset!==void 0&&{nextCharOffset:e.nextCharOffset}}}function jB(e,t,n){let r=e.length;if(r===0)return{sliced:"",actualOffset:0,actualLength:0,hasMore:!1,lineCount:0,totalChars:0};if(t>=r)return{sliced:"",actualOffset:r,actualLength:0,hasMore:!1,lineCount:0,totalChars:r,nextOffset:r};let o=t;if(o>0&&e[o-1]!==`
11
+ `){let l=e.lastIndexOf(`
12
+ `,o-1);o=l===-1?0:l+1}let i=o,s=0;for(;i<r;){let l=e.indexOf(`
13
+ `,i);if(l===-1){i=r;break}if(i=l+1,s++,i-o>=n)break}let a=e.substring(o,i),c=i<r;return{sliced:a,actualOffset:o,actualLength:a.length,hasMore:c,lineCount:s,totalChars:r,nextOffset:c?i:void 0}}var zo=y(()=>{"use strict";Yl()});function lE(e){return e&&e.trim().length>0?e:cE}function Ng(e,t){return F.getSemanticBoundaryOffsets(e,lE(t)).filter(n=>Number.isInteger(n)&&n>=0&&n<=e.length)}function uE(e,t){let n=e.indexOf(`
14
+ `,t);return n===-1?void 0:n+1}function Bo(e){let t=e.trimEnd().split(`
15
+ `).at(-1)??"";return t.length>0&&(t[0]===" "||t[0]===" ")}function Qo(e,t,n){let r=uE(e,Math.max(0,t));if(r!==void 0)return Ng(e,n).find(o=>o>=r&&o>t)}function VB(e,t,n,r,o){if(!Bo(e))return;let i=Qo(t,n,o);if(i===void 0)return;let s=i-n,a=`Page cut mid-block at char ${n}. Next top-level definition at char ${i}. Re-request with charLength=${r+s} to extend this page to the next boundary, or use charOffset=${n} to continue page-by-page.`;return{nextBlockChar:i,hint:a}}function As(e,t,n,r){let o=Math.min(Math.max(0,t),e.length),i=Math.max(1,n),s=o+i;if(s>=e.length)return{length:e.length-o,chunkMode:"char-limit"};let a=Ng(e,r);if(a.length===0)return{length:i,chunkMode:"char-limit"};let c=a.find(u=>u>s);return c===void 0?{length:i,chunkMode:"char-limit"}:c-s<=aE?{length:c-o,chunkMode:"semantic"}:{length:i,chunkMode:"char-limit"}}var aE,cE,Ls=y(()=>{"use strict";be();aE=8e3,cE="__octocode_generic__.unknown"});function _s(e,t,n,r=!1,o=!1,i){if(r)try{new RegExp(t)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`Invalid regex pattern: ${u}`)}if(i!==void 0&&i<=0)return{lines:[],matchRanges:[],matchCount:0,matchingLines:[]};let s=e.join(`
16
+ `),a={isRegex:r,caseSensitive:o,contextLines:n,maxMatches:i},c=F.extractMatchingLines(s,t,a);return{lines:c.lines,matchRanges:c.matchRanges.map(l=>({start:l.start,end:l.end})),matchCount:c.matchCount,matchingLines:c.matchingLines.map(l=>l)}}var Is=y(()=>{"use strict";be()});function pE(e){return dE.test(e.split(/[?#]/,1)[0]??e)}function Gg(e,t){return pE(t)?mE(fE(e)):null}function Fs(e,t){let n=Gg(e,t);if(n===null||n.length===0)return null;let r=[];return zg(n,r),r.join(`
17
+ `)}function Hg(e,t){let n=Gg(e,t);return n===null?null:n.map(Bg)}function fE(e){let t=[],n=e.split(/\r?\n/),r;return n.forEach((o,i)=>{let s=o.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(s?.[1]){let l=s[1][0],u=s[1].length;r?r.marker===l&&u>=r.length&&(r=void 0):r={marker:l,length:u};return}if(r)return;let a=o.match(/^[ \t]{0,3}(#{1,6})(?:[ \t]+|$)(.*)$/);if(!a?.[1])return;let c=(a[2]??"").replace(/[ \t]+#+[ \t]*$/,"").trim();t.push({line:i+1,level:a[1].length,text:c.length>0?c:"(untitled heading)",children:[]})}),t}function mE(e){let t=[],n=[];for(let r of e){for(;n.length>0&&n[n.length-1].level>=r.level;)n.pop();let o=n[n.length-1];o?o.children.push(r):t.push(r),n.push(r)}return t}function zg(e,t){for(let n of e){let r=String(n.line).padStart(4," "),o=" ".repeat(Math.max(0,n.level-1));t.push(`${r}| ${o}${"#".repeat(n.level)} ${n.text}`),zg(n.children,t)}}function Bg(e){let t=`${"#".repeat(e.level)} ${e.text}`;return{name:t,kind:"markdownHeading",range:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},selectionRange:{start:{line:e.line-1,character:0},end:{line:e.line-1,character:t.length}},children:e.children.map(Bg)}}var dE,Ms=y(()=>{"use strict";dE=/\.(?:md|markdown|mdx)$/i});import{ContentSanitizer as Qg}from"@octocodeai/octocode-engine/contentSanitizer";function gE(){let e=et();return Math.min(e,8e3)}function Uo(e,t){return{sourceChars:e,sourceBytes:t}}function Ug(e,t,n){let r=e.content??"",o=n??gE();if(r.length<=o&&t===0)return e;let i=e.path??void 0,{length:s,chunkMode:a}=As(r,t,o,i),c=Sr(r,t,s),l;if(c.hasMore&&a==="char-limit"&&Bo(c.paginatedContent)){let u=c.charOffset+c.charLength;l=Qo(r,u,i)}return{...e,content:c.paginatedContent,pagination:{currentPage:c.currentPage,totalPages:c.totalPages,hasMore:c.hasMore,charOffset:c.charOffset,charLength:c.charLength,totalChars:c.totalChars,...c.nextCharOffset!==void 0&&{nextCharOffset:c.nextCharOffset},chunkMode:a,...l!==void 0&&{nextBlockChar:l}}}}async function jg(e,t,n,r,o){try{let i=await e.rest.repos.listCommits({owner:t,repo:n,path:r,per_page:1,...o&&{sha:o}});if(i.data.length>0){let s=i.data[0],a=s?.commit?.committer?.date,c=s?.commit?.author?.name||s?.author?.login||"Unknown";return{lastModified:a||"Unknown",lastModifiedBy:c}}return null}catch{return null}}async function $g(e,t,n,r,o,i,s,a,c=5,l,u,d,p="standard"){let f=e.length,m=Buffer.byteLength(e,"utf-8"),g=p==="standard"||p==="symbols",b=g?"standard":"none",C;if(p==="symbols"){let X=F.extractSignatures(e,o);if(X===null){let j=Fs(e,o);if(j!==null)return{owner:t,repo:n,path:o,content:j,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Dt(e),...Uo(f,m),isPartial:!1,signaturesExtracted:!0,hints:[F.SIGNATURES_ONLY_HINT]};C=`minify:"symbols" is not supported for this file type (${o.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(X!==null){let j=Qg.sanitizeContent(X,o),xe=F.applyContentViewMinification(j.content,o),we=[F.SIGNATURES_ONLY_HINT];return l&&we.push('matchString was ignored \u2014 minify:"symbols" returns the full skeleton index. Use startLine/endLine from the gutter to read the matching body.'),j.hasSecrets&&we.push(`Secrets detected and redacted: ${j.secretsDetected.join(", ")}`),{owner:t,repo:n,path:o,content:xe,contentView:"symbols",isSkeleton:!0,branch:r,totalLines:Dt(e),...Uo(f,m),isPartial:!1,signaturesExtracted:!0,hints:we}}}let S=new Set,T=e,L=T.split(`
18
+ `),k=Dt(T),O=e,w,N,I=!1,v;if(i)O=e;else if(l){let X=d===!0,j;try{j=_s(L,l,c,u??!1,X)}catch{return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:k,...Uo(f,m),matchNotFound:!0,searchedFor:l,hints:[`Invalid regex "${l}". Check syntax (e.g. escape backslashes: "\\\\w+" not "\\w+") or disable matchStringIsRegex=false for a literal search.`]}}if(j.matchCount===0){let ee=u?[`Regex "${l}" matched no lines. Verify the pattern, check flags (case-${X?"sensitive":"insensitive"}), or use fullContent=true to inspect the file.`]:[`"${l}" not found in file${X?" (case-sensitive)":""}. Try matchStringIsRegex=true for pattern matching, broaden the search, or use fullContent=true.`];return{owner:t,repo:n,path:o,content:"",branch:r,totalLines:k,...Uo(f,m),matchNotFound:!0,searchedFor:l,hints:ee}}O=j.lines.join(`
19
+ `);let xe=j.matchRanges[0],we=j.matchRanges[j.matchRanges.length-1];s=xe.start,a=we.end,w=xe.start,N=we.end,I=!0,j.matchRanges.length>1&&(v=j.matchRanges);let jt=j.matchingLines.slice(0,5).join(", "),$t=j.matchingLines.length>5?` and ${j.matchingLines.length-5} more`:"";S.add(j.matchCount>1?`Found ${j.matchCount} occurrences of "${l}" on lines ${jt}${$t} \u2014 all shown as ${j.matchRanges.length} slice${j.matchRanges.length===1?"":"s"}, \xB1${c} lines of context each.`:`Found "${l}" on line ${j.matchingLines[0]}`)}else if(s!==void 0||a!==void 0){let X=s||1,j=a||k;if(X<1||X>k)O=e;else if(j<X)O=e;else{let xe=Math.max(1,X),we=Math.min(k,j),jt=L.slice(xe-1,we);w=xe,N=we,I=!0,O=jt.join(`
20
+ `),j>k&&S.add(`Requested endLine ${j} adjusted to ${k} (file end)`)}}let B=Qg.sanitizeContent(O,o);if(O=g?F.applyContentViewMinification(B.content,o):B.content,B.hasSecrets&&S.add(`Secrets detected and redacted: ${B.secretsDetected.join(", ")}`),B.warnings.length>0&&B.warnings.forEach(X=>S.add(X)),k>2e3&&p!=="symbols"&&!l&&!s&&!a&&!i){let X=Math.max(1,k-200);S.add(`Large file (${k} lines) \u2014 minify:"symbols" for an export index, or startLine=${X} for the tail.`)}let z=Array.from(S);return{owner:t,repo:n,path:o,content:O,...b!=="standard"&&{contentView:b},branch:r,totalLines:k,...Uo(f,m),...I&&{startLine:w,endLine:N,isPartial:I},...v&&{matchRanges:v},...z.length>0&&{matchLocations:z},...(z.length>0||C)&&{warnings:[...C?[C]:[],...z]}}}var Xl=y(()=>{"use strict";br();me();be();Rr();zo();Ls();Is();Ms()});async function qg(e,t,n){let r=He("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},n),o=await ze(r,async()=>await xs(e,t),{shouldCache:m=>"data"in m&&!m.error,forceRefresh:e.forceRefresh===!0});if(!("data"in o)||!o.data)return o;let i=o.data.branch||o.data.resolvedRef||e.branch||"",s=await $g(o.data.rawContent,e.owner,e.repo,i,e.path,e.fullContent||!1,e.startLine,e.endLine,e.contextLines??5,e.matchString,e.matchStringIsRegex,e.matchStringCaseSensitive,e.minify??"standard");if("error"in s)return{error:s.error||"Unknown error",status:500,type:"unknown"};let{signaturesExtracted:a,...c}=s,l=e.charOffset??0,u=e.charLength,d=e.fullContent===!0&&l===0&&u===void 0,p=a||d?c:Ug(c,l,u),f=(e.charOffset??0)>0;if(!e.noTimestamp&&!f)try{let m=await pe(t),g=await ze(He("gh-api-file-content",{owner:e.owner,repo:e.repo,path:e.path,branch:e.branch,ts:!0},n),()=>jg(m,e.owner,e.repo,e.path,e.branch),{shouldCache:b=>b!==null,forceRefresh:e.forceRefresh===!0});g&&(p.lastModified=g.lastModified,p.lastModifiedBy=g.lastModifiedBy)}catch{}return{data:p,status:200,rawResponseChars:o.rawResponseChars}}var Jl=y(()=>{"use strict";Ge();Mt();ws();Xl()});function jo(e,t=yE){let n=e?Ho(e):[];return{lines:n.slice(0,t),moreCount:Math.max(0,n.length-t)}}function Vg(e,t,n){if(!e)return"";if(t===void 0&&n===void 0)return e;let r={additions:t,deletions:n};return F.filterPatch(e,r)}function Wg(e){return e?F.filterPatch(e,{trimContext:!0,contextLines:hE}):""}var hE,yE,$o=y(()=>{"use strict";be();Rr();hE=2,yE=20});import{ContentSanitizer as Kg}from"@octocodeai/octocode-engine/contentSanitizer";function Zl(e){let t=Kg.sanitizeContent(e.title??""),n=e.body?Kg.sanitizeContent(e.body):{content:void 0,warnings:[]},r=new Set([...t.warnings,...n.warnings]),i=e.state?.toLowerCase()==="closed"?"closed":"open";return{prData:{number:e.number,title:t.content,body:n.content,state:i,author:e.user?.login??"",labels:e.labels?.map(a=>typeof a=="string"?a:a.name??"")??[],created_at:e.created_at??"",updated_at:e.updated_at??"",closed_at:e.closed_at??null,url:e.html_url,comments:[],...typeof e.comments=="number"&&e.comments>0?{total_comment_count:e.comments}:{},reactions:0,draft:e.draft??!1,head:e.head?.ref,head_sha:e.head?.sha,base:e.base?.ref,base_sha:e.base?.sha,...e.merged_at&&{merged_at:e.merged_at}},sanitizationWarnings:r}}function Xg(e,t,n,r){if(typeof e!="string"||!r)return{value:e};let o=e.length,i=Math.min(Math.max(0,t),o),s=Math.max(1,n),a=Math.min(i+s,o),c=a<o;return i===0&&a===o?{value:e}:{value:e.slice(i,a),pagination:{charOffset:i,charLength:a-i,totalChars:o,hasMore:c,...c?{nextCharOffset:a}:{}}}}function qo(e,t={}){let n=t.charOffset??0,r=t.charLength??bE,o=t.charLength??RE,i=typeof e.body=="string"?F.minifyMarkdownCore(e.body):e.body,s=Xg(i,n,r,!t.includeFullBody),a=(e.comments??[]).sort((m,g)=>{let b=m.commentType==="review_inline"?0:1,C=g.commentType==="review_inline"?0:1;return b-C}),c=a.filter(m=>m.commentType==="review_inline").length,l=a.length-c,u=t.includeFullCommentDetails?a:a.slice(0,Yg),d=u.map(m=>{let g=Xg(m.body,n,o,!t.includeFullCommentDetails);return{...m,body:g.value??"",...g.pagination?{body_pagination:g.pagination}:{}}}),p=!t.includeFullCommentDetails&&(a.length>u.length||d.some(m=>"body_pagination"in m)),f=[...s.pagination&&t.includeFullBody?[`PR body paginated at charOffset=${s.pagination.charOffset}, charLength=${s.pagination.charLength}, totalChars=${s.pagination.totalChars}. Re-call with prNumber and charOffset=${s.pagination.nextCharOffset??s.pagination.totalChars} to continue this body.`]:[],...p?[`PR comments are paginated/summarized to ${Yg} comment(s) per search result with ${o} chars each. Use prNumber with content.comments={discussion:true,reviewInline:true} and charOffset to continue specific comment bodies.`]:[]];return{number:e.number,title:e.title,url:e.url,state:e.state,draft:e.draft??!1,merged:e.state==="closed"&&!!e.merged_at,created_at:e.created_at,updated_at:e.updated_at,closed_at:e.closed_at??void 0,merged_at:e.merged_at,author:e.author,...e.labels?.length?{labels:e.labels.map(m=>({id:0,name:m,color:""}))}:{},head_ref:e.head||"",...e.head_sha?{head_sha:e.head_sha}:{},base_ref:e.base||"",...e.base_sha?{base_sha:e.base_sha}:{},body:s.value,...s.pagination?{body_pagination:s.pagination}:{},comments:e.total_comment_count??a.length,...a.length>0&&{comment_details_breakdown:{inline_review:c,discussion:l}},commits:e.commits?.length||0,additions:e.file_changes?.files.reduce((m,g)=>m+g.additions,0)||e.additions||0,deletions:e.file_changes?.files.reduce((m,g)=>m+g.deletions,0)||e.deletions||0,changed_files:e.file_changes?.total_count||0,...e.file_changes&&{file_changes:e.file_changes.files?.map(m=>({filename:m.filename,status:m.status,additions:m.additions,deletions:m.deletions,patch:m.patch}))},...e.reviews&&{reviews:e.reviews},...e.commits&&{commit_details:e.commits},...d.length>0&&{comment_details:d,comment_details_shown:d.length,comment_details_total:a.length,...p?{comment_details_paginated:!0}:{}},...(e._sanitization_warnings||f.length>0)&&{_sanitization_warnings:[...e._sanitization_warnings||[],...f]}}}function Vo(e){let t=Array.isArray(e.owner)?e.owner[0]||void 0:e.owner,n=Array.isArray(e.repo)?e.repo[0]||void 0:e.repo;return{owner:t,repo:n}}function Ds(e,t){let r=t.content?.patches,o=r?.mode??(t.reviewMode==="full"?"all":"none"),i=new Map(r?.ranges?.map(a=>[a.file,a])||[]),s=new Set([...r?.files??[],...i.keys()]);return o==="none"?e.map(a=>({...a,patch:void 0})):o==="selected"?e.filter(a=>s.has(a.filename)).map(a=>{let c=i.get(a.filename);return{...a,patch:a.patch?Vg(a.patch,c?.additions,c?.deletions):void 0}}):e.map(a=>({...a,patch:a.patch?Wg(a.patch):a.patch}))}var bE,RE,Yg,Wo=y(()=>{"use strict";$o();be();br();bE=et(),RE=Math.round(et()/4),Yg=3});import{ContentSanitizer as eu}from"@octocodeai/octocode-engine/contentSanitizer";function Ns(e){let t=e.content;return!!(e.reviewMode==="full"||t?.changedFiles||t?.patches?.mode&&t.patches.mode!=="none")}function Jg(e){return e.reviewMode==="full"?{discussion:!0,reviewInline:!0}:e.content?.comments??null}function Zg(e){let t=Jg(e);return t?t.discussion!==!1:!1}function eh(e){let t=Jg(e);return t?t.reviewInline!==!1:!1}function th(e){let t=e.content;return!!(e.reviewMode==="full"||t?.commits)}function nh(e){let t=e.content;return!!(e.reviewMode==="full"||t?.reviews)}function rh(e){return!!e.content?.comments?.includeBots}function oh(e){let t=e.toLowerCase();return t.endsWith("[bot]")||SE.has(t.replace(/\[bot\]$/,""))}function tu(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/^\[vc\]:\s*#.*$/gm,"").replace(/^[A-Za-z0-9+/]{120,}={0,2}$/gm,"").replace(/\n{3,}/g,`
21
21
 
22
- `).trim()}async function Pl(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Cl(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=O.minifyMarkdownCore(Es(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Ps.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"discussion"}}),m=[];return l>0&&m.push(`${l} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:U([],0)}}}async function El(e,t,n,r){try{let{items:o,rawResponseChars:i}=await Ts(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return U(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:Ps.sanitizeContent(O.minifyMarkdownCore(Es(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return U([],0)}}async function Tl(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let p=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=N(p.data),i.push(...p.data),c=p.data.length===100,a++}while(c);let u=o?i:i.filter(p=>!Cl(p.user?.login??"")),l=i.length-u.length,d=u.map(p=>{let f=O.minifyMarkdownCore(Es(p.body??""));return{id:String(p.id),user:p.user?.login??"unknown",body:Ps.sanitizeContent(f).content,created_at:p.created_at??"",updated_at:p.updated_at??"",commentType:"review_inline",path:p.path,line:p.line??p.original_line??void 0,...p.in_reply_to_id!=null?{in_reply_to_id:p.in_reply_to_id}:{}}}),m=[];return l>0&&m.push(`${l} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:U(d,s),note:m.length>0?m.join("; "):void 0}}catch{return{comments:U([],0)}}}async function xl(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Cs(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:u,repo:l}=Tr(t);if(u&&l){let d=await n.rest.pulls.get({owner:u,repo:l,pull_number:e.number});if(d.data&&(s+=N(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Ao(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Ao(t))){let m=await _l(u,l,e.number);m&&(s+=ne(m)??0,m.files=wo(m.files,t),o.file_changes=m)}}}catch(u){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${u instanceof Error?u.message:String(u)}`]}let a=hl(t),c=yl(t);if(a||c){let{owner:u,repo:l}=Tr(t);if(u&&l){let d=Sl(t),m=()=>Promise.resolve({comments:U([],0)}),[{comments:p,note:f},{comments:g,note:h}]=await Promise.all([a?Pl(n,u,l,e.number,d):m(),c?Tl(n,u,l,e.number,d):m()]);o.comments=[...p,...g],s+=(ne(p)??0)+(ne(g)??0);let R=[f,h].filter(b=>typeof b=="string");R.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...R])}}if(bl(t))try{let{owner:u,repo:l}=Tr(t);if(u&&l){let d=await El(n,u,l,e.number);s+=ne(d)??0,o.reviews=d}}catch(u){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${u instanceof Error?u.message:String(u)}`]}if(Rl(t))try{let{owner:u,repo:l}=Tr(t);if(u&&l){let d=await wl(u,l,e.number,t);d&&(s+=ne(d)??0,o.commits=d)}}catch(u){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(u)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${u instanceof Error?u.message:String(u)}`]}return U(o,s)}async function Ts(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=N(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function _l(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Ts(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U({total_count:i.length,files:i},s)}async function jy(e,t,n,r){let o=await ie(r),{items:i,rawResponseChars:s}=await Ts(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return U(i,s)}async function $y(e,t,n,r){try{let i=await(await ie(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return U(i.data.files||[],i.data)}catch{return null}}async function wl(e,t,n,r,o){let i=await jy(e,t,n,o);if(!i)return null;let s=ne(i)??0,a=[...i].sort((u,l)=>{let d=u.commit.author?.date?new Date(u.commit.author.date).getTime():0;return(l.commit.author?.date?new Date(l.commit.author.date).getTime():0)-d}),c=await Promise.all(a.map(async u=>{let l=await $y(e,t,u.sha,o),d=[];return l&&(s+=ne(l)??0,d=wo(l,r)),{sha:u.sha,message:u.commit.message,author:u.commit.author?.name||"unknown",date:u.commit.author?.date||"",files:d}}));return U(c,s)}async function Lo(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Cs(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Ao(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ao(t))try{let d=await _l(a,c,e.number,r);d&&(s+=ne(d)??0,d.files=wo(d.files,t),o.file_changes=d)}catch(d){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(d)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let u=hl(t),l=yl(t);if(u||l){let d=Sl(t),m=()=>Promise.resolve({comments:U([],0)}),[{comments:p,note:f},{comments:g,note:h}]=await Promise.all([u?Pl(n,a,c,e.number,d):m(),l?Tl(n,a,c,e.number,d):m()]);o.comments=[...p,...g],s+=(ne(p)??0)+(ne(g)??0);let R=[f,h].filter(b=>typeof b=="string");R.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...R])}if(bl(t))try{let d=await El(n,a,c,e.number);s+=ne(d)??0,o.reviews=d}catch(d){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(d)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(Rl(t))try{let d=await wl(a,c,e.number,t,r);d&&(s+=ne(d)??0,o.commits=d)}catch(d){M(S.GITHUB_SEARCH_PULL_REQUESTS,String(d)),o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return U(o,s)}function Vy(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function SI(e,t,n){let r=_e("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode},n);return await we(r,async()=>await xs(e,t),{shouldCache:i=>!i.error})}async function xs(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PR_REQUIRED_PARAMS.code),{pull_requests:[],total_count:0,error:oe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PR_SINGLE_VALUES.code),{pull_requests:[],total_count:0,error:oe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await ie(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Lo(a,e,i,t);return{pull_requests:[Er(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:N(s.data)+(ne(c)??0)}}catch(i){let s=Z(i);return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PULL_REQUEST_FETCH_FAILED.code),Vy(s,oe.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}function Al(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function Ll(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function Ol(e,t,n){let r=_e("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await we(r,async()=>await Wy(e,t,n),{shouldCache:i=>!i.error})}async function Wy(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await xs(e,t);let r=await ie(t);if(!Ou(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await Ky(r,e);let i=Lu(e);if(!i)return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.NO_VALID_PARAMETERS.code),{pull_requests:[],total_count:0,error:oe.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let s=e.sort&&e.sort!=="best-match"?e.sort:void 0,a=Math.min(e.limit||30,100),c=e.page||1,u=i,l=await r.rest.search.issuesAndPullRequests({q:i,sort:s,order:e.order||"desc",per_page:a,page:c}),d=l.data.items?.filter(C=>!!C.pull_request)||[],m=await Promise.all(d.map(async C=>await xl(C,e,r))),p=m.reduce((C,_)=>C+(ne(_)??0),0),f=m.map(C=>Er(C,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:e.charOffset,charLength:e.charLength})),g=l.data.total_count,h=Math.min(g,1e3),R=Math.min(Math.ceil(h/a),10),b=Math.min(c,Math.max(1,R)),P=b<R,x=Math.min(h,R*a);return{pull_requests:f,total_count:l.data.total_count,effectiveQuery:u,...l.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:b,totalPages:R,perPage:a,totalMatches:h,reportedTotalMatches:g,reachableTotalMatches:x,totalMatchesKind:"reported",totalMatchesCapped:g>h,hasMore:P,...P?{nextPage:b+1}:{}},rawResponseChars:N(l.data)+p}}catch(r){if($t(r))return Ll(e);let o=Z(r);return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PULL_REQUEST_SEARCH_FAILED.code),Al(o,oe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function Ky(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async m=>await Lo(m,t,e))),c=a.reduce((m,p)=>m+(ne(p)??0),0),u=a.map(m=>Er(m,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),l=s.data.length===o,d=(i-1)*o+u.length;return{pull_requests:u,total_count:u.length,pagination:{currentPage:i,totalPages:l?i+1:i,perPage:o,totalMatches:d+(l?1:0),reachableTotalMatches:d,totalMatchesKind:l?"lowerBound":"exact",hasMore:l,...l?{nextPage:i+1}:{}},rawResponseChars:N(s.data)+c}}catch(n){if($t(n))return Ll(t);let r=Z(n);return await M(S.GITHUB_SEARCH_PULL_REQUESTS,oe.PULL_REQUEST_LIST_FAILED.code),Al(r,oe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}function Yy(e){return e?e.includes('rel="next"'):!1}function Il(e,t){if(e)return!t||e.length<=t?e:e.slice(0,t)}async function kl(e,t){try{let n=await ie(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=Yy(i),a=o.data.map(l=>{let d=l.commit.author,m=l.commit.committer,p=m?.date??d?.date??"",f=l.commit.message,g=f.split(`
23
- `)[0]??f;return{sha:l.sha,date:p,message:f,messageHeadline:g,url:l.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...l.author?.login?{login:l.author.login}:{}},...m?{committer:{name:m.name??"unknown",email:m.email??"",...l.committer?.login?{login:l.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let u=await Promise.all(a.map(async(l,d)=>{try{let m=o.data[d]?.sha??l.sha,p=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:m});if(e.type==="file"&&e.path){let f=e.path,g=p.data.files?.find(h=>h.filename===f||h.previous_filename===f);if(g){let h=g.patch!==void 0?Il(g.patch,e.charLength):void 0;return{...l,additions:g.additions,deletions:g.deletions,status:g.status,...h!==void 0?{patch:h,diff:Pr(h)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let f=e.path,g=(p.data.files??[]).filter(h=>!f||h.filename.startsWith(f)).map(h=>{let R=h.patch!==void 0?Il(h.patch,e.charLength):void 0;return{filename:h.filename,status:h.status,additions:h.additions,deletions:h.deletions,...R!==void 0?{patch:R,diff:Pr(R)}:{},...h.previous_filename?{previousFilename:h.previous_filename}:{}}});return{...l,files:g}}}catch{}return l}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:u,pagination:c},status:200}}catch(n){return Z(n)}}var vl=30;function Fl(e){let t={},n=e.license;n?.spdx_id&&n.spdx_id!=="NOASSERTION"&&(t.license=n.spdx_id);let r=e.homepage;return r&&(t.homepage=r),t}async function Ml(e,t,n){let r=_e("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await we(r,async()=>await Jy(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function Xy(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch{try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(p){return Z(p)}}let a=i.map(p=>{let g=p.full_name.split("/"),h=g[0]||"",R=g[1]||"";return{owner:h,repo:R,defaultBranch:p.default_branch,stars:p.stargazers_count||0,description:p.description?p.description.length>150?p.description.substring(0,150)+"...":p.description:"No description",url:p.html_url,createdAt:p.created_at,updatedAt:p.updated_at,pushedAt:p.pushed_at,visibility:p.visibility,...p.topics&&p.topics.length>0&&{topics:p.topics},...p.forks_count&&p.forks_count>0&&{forksCount:p.forks_count},...p.open_issues_count&&p.open_issues_count>0&&{openIssuesCount:p.open_issues_count},...p.language&&{language:p.language},...Fl(p)}}),c=a.length,u=c===n,l=(r-1)*n+c,d=s??l+(u?1:0),m=s!==void 0||!u?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:u?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:l,totalMatchesKind:m,hasMore:u,...u?{nextPage:r+1}:{}}},status:200,rawResponseChars:N(i)}}async function Jy(e,t){try{let n=await ie(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await Xy({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=Au(e);if(!i.trim())return await M(S.GITHUB_SEARCH_REPOSITORIES,oe.QUERY_EMPTY.code),{error:oe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||vl,100),a=e.page||1,c={q:i,per_page:s,page:a},u=["stars","forks","help-wanted-issues","updated"];e.sort&&u.includes(e.sort)&&(c.sort=e.sort);let l=await n.rest.search.repos(c),d=l.data.items.map(b=>{let x=b.full_name.split("/"),C=x[0]||"",_=x[1]||"";return{owner:C,repo:_,defaultBranch:b.default_branch,stars:b.stargazers_count||0,description:b.description?b.description.length>150?b.description.substring(0,150)+"...":b.description:"No description",url:b.html_url,createdAt:b.created_at,updatedAt:b.updated_at,pushedAt:b.pushed_at,visibility:b.visibility,...b.topics&&b.topics.length>0&&{topics:b.topics},...b.forks_count&&b.forks_count>0&&{forksCount:b.forks_count},...b.open_issues_count&&b.open_issues_count>0&&{openIssuesCount:b.open_issues_count},...b.language&&{language:b.language},...Fl(b)}}),m=l.data.total_count,p=Math.min(m,1e3),f=Math.min(Math.ceil(p/s),10),g=Math.min(a,Math.max(1,f)),h=g<f,R=Math.min(p,f*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:f,perPage:s,totalMatches:p,reportedTotalMatches:m,reachableTotalMatches:R,totalMatchesKind:"reported",totalMatchesCapped:m>p,hasMore:h,...h?{nextPage:g+1}:{}}},status:200,headers:bo(l.headers),rawResponseChars:N(l.data)}}catch(n){if($t(n)){let r=Math.min(e.limit||vl,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return Z(n)}}import{RequestError as nR}from"octokit";var Kt={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200};function Zy(e,t){return t?e>5e4?[`Response ~${e.toLocaleString()} tokens \u2014 exceeds typical context. Reduce charLength or refine the query.`]:e>3e4?[`Response ~${e.toLocaleString()} tokens \u2014 approaching context limit. Consider reducing charLength.`]:[]:[]}function qy(e){if(e.hasMore&&e.nextCharOffset!==void 0){let t=e.charOffset+1,n=e.charOffset+e.charLength;return[`Page ${e.currentPage}/${e.totalPages} (chars ${t}-${n} of ${e.totalChars}). Next: charOffset=${e.nextCharOffset}`]}return[]}function ZI(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...Zy(e.estimatedTokens,n)),o.push(...qy(e)),o}function Oo(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}function Nl(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:w,...A}=e;return A}let r=t.itemsPerPage??Kt.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),u=n.slice(a,c),l=Object.create(null),d=e.path==="/"?"":e.path,m=w=>{let A=w;d&&w.startsWith(d)&&(A=w.slice(d.length),A.startsWith("/")&&(A=A.slice(1)));let Q=A.lastIndexOf("/");return Q===-1?".":A.slice(0,Q)},p=w=>{let A=w.lastIndexOf("/");return A===-1?w:w.slice(A+1)};for(let w of u){let A=m(w.path);l[A]||(l[A]={files:[],folders:[]});let Q=p(w.path);w.type==="file"?l[A].files.push(Q):l[A].folders.push(Q)}for(let w of Object.keys(l)){let A=l[w];A&&(A.files.sort(),A.folders.sort())}let f=Object.create(null),g=Object.keys(l).sort((w,A)=>w==="."?-1:A==="."?1:w.localeCompare(A));for(let w of g){let A=l[w];A&&(f[w]=A)}let h=u.filter(w=>w.type==="file").length,R=u.filter(w=>w.type==="dir").length,b=n.filter(w=>w.type==="file").length,P=n.filter(w=>w.type==="dir").length,x=o<s,C={currentPage:o,totalPages:s,hasMore:x,...x?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},_=Oo(C,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:h,pageFolders:R,allFiles:b,allFolders:P}),I,j=e._cachedFileSizeMap;if(j){let w=new Set(u.filter(se=>se.type==="file").map(se=>se.path)),A=e.path==="/"?"":e.path,Q=Object.create(null);for(let[se,$]of Object.entries(j))for(let[D,Re]of Object.entries($)){let ue=se==="."?A?`${A}/${D}`:D:A?`${A}/${se}/${D}`:`${se}/${D}`;w.has(ue)&&(Q[se]||(Q[se]=Object.create(null)),Q[se][D]=Re)}Object.keys(Q).length>0&&(I=Q)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:b,totalFolders:P,truncated:x,filtered:!0,originalCount:i},structure:f,...I!==void 0&&{fileSizeMap:I},...j!==void 0&&{_cachedFileSizeMap:j},pagination:C,hints:_,rawResponseChars:e.rawResponseChars}}import{RequestError as eR}from"octokit";var Hl=Symbol.for("octocode.recursiveFetchFailures"),tR=new Set([401,403,429]);function Dl(e){return e instanceof eR&&tR.has(e.status)}function _s(e,t){try{Object.defineProperty(e,Hl,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function ws(e){if(typeof e!="object"||e===null)return 0;let t=e[Hl];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function As(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return _s(U([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(f){if(Dl(f))throw f;return _s(U([],0),1)}let u=N(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(f=>f.type==="file"||f.type==="dir").map(f=>({name:f.name,path:f.path,type:f.type,size:"size"in f?f.size:void 0,download_url:"download_url"in f?f.download_url:void 0,url:f.url,html_url:f.html_url,git_url:f.git_url,sha:f.sha})),m=[...d],p=0;if(i<s){let f=d.filter(h=>h.type==="dir"),g=3;for(let h=0;h<f.length;h+=g){let R=f.slice(h,h+g),b=await Promise.allSettled(R.map(P=>As(e,t,n,r,P.path,i+1,s,a)));for(let P of b)if(P.status==="fulfilled"){let x=P.value;u+=ne(x)??0,p+=ws(x),m.push(...x)}else{if(Dl(P.reason))throw P.reason;p+=1}}}return _s(U(m,u),p)}var Io=S.GITHUB_VIEW_REPO_STRUCTURE;async function rR(e,t,n,r,o,i){let s;try{s=o??await Ge(t,n,i)}catch(a){let c=Z(a);return await M(Io,et.NOT_FOUND.code),{error:et.NOT_FOUND.message(t,n,c.error),status:c.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s}}catch(a){if(!(a instanceof nR&&a.status===404)){let u=Z(a);return await M(Io,et.ACCESS_FAILED.code),{error:et.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let c=Z(a);return await M(Io,et.PATH_NOT_FOUND.code),{error:et.PATH_NOT_FOUND.message(r,t,n,s),status:c.status}}}function oR(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function iR(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let u=c.lastIndexOf("/");return u===-1?".":c.slice(0,u)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let u=o(a.path);a.type==="file"?n[c].files.push(u):n[c].folders.push(u)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function Gl(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function Ul(e,t,n){let r=_e("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await we(r,async()=>await sR({...e,itemsPerPage:e.itemsPerPage??Kt.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Nl(o,e):o}async function sR(e,t){try{let n=await ie(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),u=await rR(n,r,o,c,i,t);if("error"in u)return u;let{data:l,workingBranch:d,repoDefaultBranch:m}=u,p=N(l),f=Array.isArray(l)?l:[l],g=oR(f),h=0;if(a>1){let V=await As(n,r,o,d,c,1,a);h=ws(V),p+=ne(V)??0,g=[...g,...V].filter((Mn,Dr,Dm)=>Dm.findIndex(Hm=>Hm.path===Mn.path)===Dr)}let R=g.filter(V=>V.type==="dir"?!cr(V.name):!xn(V.path));R.sort((V,qe)=>{if(V.type!==qe.type)return V.type==="dir"?-1:1;let Mn=V.path.split("/").length,Dr=qe.path.split("/").length;return Mn!==Dr?Mn-Dr:V.path.localeCompare(qe.path)});let b=e.itemsPerPage??Kt.ENTRIES_PER_PAGE,P=e.page??1,x=R.length,C=Math.max(1,Math.ceil(x/b)),_=(P-1)*b,I=Math.min(_+b,x),j=R.slice(_,I),w=iR(j,c),A=e.includeSizes===!0?Gl(R,c):void 0,Q=A!==void 0?Gl(j,c):void 0,se=j.filter(V=>V.type==="file").length,$=j.filter(V=>V.type==="dir").length,D=R.filter(V=>V.type==="file").length,Re=R.filter(V=>V.type==="dir").length,ue=P<C,at={currentPage:P,totalPages:C,hasMore:ue,...ue?{nextPage:P+1}:{},entriesPerPage:b,totalEntries:x},en=Oo(at,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:se,pageFolders:$,allFiles:D,allFolders:Re});return h>0&&en.unshift(`Partial tree: ${h} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...m!==void 0&&{defaultBranch:m},path:c||"/",apiSource:!0,summary:{totalFiles:D,totalFolders:Re,truncated:ue,filtered:!0,originalCount:R.length},structure:w,...Q!==void 0&&{fileSizeMap:Q},...A!==void 0&&{_cachedFileSizeMap:A},pagination:at,hints:en,rawResponseChars:p,_cachedItems:R.map(V=>({path:V.path,type:V.type}))}}catch(n){let r=Z(n);return await M(Io,et.STRUCTURE_EXPLORATION_FAILED.code),{error:et.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var Bl={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}};function Yt(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function aR(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function cR(e){return!!(e&&typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"full_name"in e&&typeof e.full_name=="string"&&"private"in e&&typeof e.private=="boolean")}function de(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function uR(e){if(e.rateLimitRemaining===void 0&&e.retryAfter===void 0&&e.rateLimitReset===void 0)return;let t=e.rateLimitReset,n=t&&!isNaN(t)?Math.floor(t/1e3):Math.floor(Date.now()/1e3)+(e.retryAfter??3600);return{remaining:e.rateLimitRemaining??0,reset:n,retryAfter:e.retryAfter}}function gt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:uR(e)}}function ko(e){return lR(e)?gt({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function lR(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||dR(n)}function dR(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}function zl(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function pR(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...zl(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function fR(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...zl(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Ql(e,t,n=de){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await Nu(s,t);return Yt(a)?gt(a):a.data?{data:pR(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function jl(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await Ml(n,t);return"error"in r?ko(r)??{error:"Unknown GitHub API error",status:500,provider:"github"}:!("data"in r)||!r.data?{error:"No data returned from GitHub API",status:500,provider:"github"}:{data:fR(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??N(r.data)}}function gR(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:hR(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function hR(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function $l(e,t,n=de){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await ul(i,t);if(Yt(s))return gt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:gR(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s.data),...a?.length?{hints:a}:{}}}function RR(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function bR(e,t,n=de){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...RR(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function Vl(e,t,n=de){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await Ol(s,t);return a.error?gt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:bR(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??N(a)}}function CR(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function Wl(e,t,n=de){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await Ul(i,t);return"error"in s?ko(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:CR(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??N(s)}}var vo=class{type="github";capabilities=Bl.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Ql(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await $l(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await jl(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await Vl(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Wl(t,this.authInfo,de)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=de(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ge(n,r,this.authInfo)}handleError(t){let n=Z(t);return gt(n)}};import{createHash as ER}from"crypto";var TR=3600*1e3,Ls=20,Je=new Map;function Kl(e){return Date.now()-e.createdAt<TR}function xR(){for(let[e,t]of Je.entries())Kl(t)||Je.delete(e);if(Je.size>Ls){let e=[...Je.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=Je.size-Ls;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&Je.delete(r[0])}}}function _R(e){return e?ER("sha256").update(e).digest("hex").slice(0,16):"default"}function wR(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function AR(e,t){let n=wR(t?.baseUrl||"default"),r=_R(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Os(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=AR(e,t),r=Je.get(n);if(r&&Kl(r))return r.lastAccessedAt=Date.now(),r.provider;r&&Je.delete(n),Je.size>=Ls&&xR();let o=new vo({...t,type:e}),i=Date.now();return Je.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function Yk(){Je.clear()}async function Yl(){try{return Os("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
24
- `),[{provider:"github",ok:!1,error:t}]}}import{maskSensitiveData as Is}from"@octocodeai/octocode-engine/mask";import{ContentSanitizer as ks}from"@octocodeai/octocode-engine/contentSanitizer";var LR={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};function Xl(){try{return ae().output.format}catch{return"yaml"}}function nv(e){if(e==null||typeof e!="object")return{content:[{type:"text",text:`error: "Invalid result options"
25
- `}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:xr({data:t,instructions:n})}],isError:!!r}}var Fo={system(e,t=1){return{type:"text",text:e,annotations:{audience:["assistant"],priority:t,role:"system"}}},assistant(e,t=.8){return{type:"text",text:e,annotations:{audience:["assistant","user"],priority:t,role:"assistant"}}},user(e,t=.6){return{type:"text",text:e,annotations:{audience:["user"],priority:t,role:"user"}}},data(e,t){let n=t??Xl(),r;try{r=n==="yaml"?O.jsonToYamlString(wn(e)):JSON.stringify(wn(e),null,2)}catch{r=`error: "Data serialization failed"
26
- `}return{type:"text",text:IR(r),annotations:{audience:["assistant"],priority:.3,role:"assistant"}}}},Mo={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};function No(e){let t=[],{system:n,assistant:r,user:o,data:i,isError:s}=e;if(n){let a=[];if(n.instructions&&a.push(n.instructions),n.pagination){let{currentPage:c,totalPages:u,hasMore:l}=n.pagination;a.push(`Page ${c}/${u}${l?" (more available)":""}`)}n.warnings?.length&&a.push(`\u26A0\uFE0F Warnings:
22
+ `).trim()}async function ih(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.issues.listComments({owner:t,repo:n,issue_number:r,per_page:100,page:a});s+=U(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!oh(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=F.minifyMarkdownCore(tu(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:eu.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"discussion"}}),p=[];return u>0&&p.push(`${u} bot comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:$([],0)}}}async function sh(e,t,n,r){try{let{items:o,rawResponseChars:i}=await nu(s=>e.rest.pulls.listReviews({owner:t,repo:n,pull_number:r,per_page:100,page:s}));return $(o.map(s=>({id:String(s.id),user:s.user?.login??"unknown",state:s.state??"",body:eu.sanitizeContent(F.minifyMarkdownCore(tu(s.body??""))).content,submitted_at:s.submitted_at??void 0,commit_id:s.commit_id??void 0})),i)}catch{return $([],0)}}async function ah(e,t,n,r,o=!1){try{let i=[],s=0,a=1,c=!0;do{let f=await e.rest.pulls.listReviewComments({owner:t,repo:n,pull_number:r,per_page:100,page:a});s+=U(f.data),i.push(...f.data),c=f.data.length===100,a++}while(c);let l=o?i:i.filter(f=>!oh(f.user?.login??"")),u=i.length-l.length,d=l.map(f=>{let m=F.minifyMarkdownCore(tu(f.body??""));return{id:String(f.id),user:f.user?.login??"unknown",body:eu.sanitizeContent(m).content,created_at:f.created_at??"",updated_at:f.updated_at??"",commentType:"review_inline",path:f.path,line:f.line??f.original_line??void 0,...f.in_reply_to_id!=null?{in_reply_to_id:f.in_reply_to_id}:{}}}),p=[];return u>0&&p.push(`${u} bot inline comment(s) hidden (set content.comments.includeBots:true to include)`),{comments:$(d,s),note:p.length>0?p.join("; "):void 0}}catch{return{comments:$([],0)}}}async function ch(e,t,n){let r=e,{prData:o,sanitizationWarnings:i}=Zl(r);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0;if(e.pull_request)try{let{owner:l,repo:u}=Vo(t);if(l&&u){let d=await n.rest.pulls.get({owner:l,repo:u,pull_number:e.number});if(d.data&&(s+=U(d.data),o.head=d.data.head?.ref,o.head_sha=d.data.head?.sha,o.base=d.data.base?.ref,o.base_sha=d.data.base?.sha,o.draft=d.data.draft??!1,d.data.merged_at&&(o.merged_at=d.data.merged_at),o.additions=d.data.additions??0,o.deletions=d.data.deletions??0,Ns(t)||(o.file_changes={total_count:d.data.changed_files??0,files:[]}),Ns(t))){let p=await lh(l,u,e.number);p&&(s+=le(p)??0,p.files=Ds(p.files,t),o.file_changes=p)}}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${l instanceof Error?l.message:String(l)}`]}let a=Zg(t),c=eh(t);if(a||c){let{owner:l,repo:u}=Vo(t);if(l&&u){let d=rh(t),p=()=>Promise.resolve({comments:$([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([a?ih(n,l,u,e.number,d):p(),c?ah(n,l,u,e.number,d):p()]);o.comments=[...f,...g],s+=(le(f)??0)+(le(g)??0);let C=[m,b].filter(S=>typeof S=="string");C.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...C])}}if(nh(t))try{let{owner:l,repo:u}=Vo(t);if(l&&u){let d=await sh(n,l,u,e.number);s+=le(d)??0,o.reviews=d}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${l instanceof Error?l.message:String(l)}`]}if(th(t))try{let{owner:l,repo:u}=Vo(t);if(l&&u){let d=await uh(l,u,e.number,t);d&&(s+=le(d)??0,o.commits=d)}}catch(l){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${l instanceof Error?l.message:String(l)}`]}return $(o,s)}async function nu(e){let t=[],n=0,r=1,o=!0;do{let i=await e(r);n+=U(i.data),t.push(...i.data),o=i.data.length===100,r++}while(o);return{items:t,rawResponseChars:n}}async function lh(e,t,n,r){let o=await pe(r),{items:i,rawResponseChars:s}=await nu(a=>o.rest.pulls.listFiles({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $({total_count:i.length,files:i},s)}async function CE(e,t,n,r){let o=await pe(r),{items:i,rawResponseChars:s}=await nu(a=>o.rest.pulls.listCommits({owner:e,repo:t,pull_number:n,per_page:100,page:a}));return $(i,s)}async function PE(e,t,n,r){try{let i=await(await pe(r)).rest.repos.getCommit({owner:e,repo:t,ref:n});return $(i.data.files||[],i.data)}catch{return null}}async function uh(e,t,n,r,o){let i=await CE(e,t,n,o);if(!i)return null;let s=le(i)??0,a=[...i].sort((l,u)=>{let d=l.commit.author?.date?new Date(l.commit.author.date).getTime():0;return(u.commit.author?.date?new Date(u.commit.author.date).getTime():0)-d}),c=await Promise.all(a.map(async l=>{let u=await PE(e,t,l.sha,o),d=[];return u&&(s+=le(u)??0,d=Ds(u,r)),{sha:l.sha,message:l.commit.message,author:l.commit.author?.name||"unknown",date:l.commit.author?.date||"",files:d}}));return $(c,s)}async function Gs(e,t,n,r){let{prData:o,sanitizationWarnings:i}=Zl(e);i.size>0&&(o._sanitization_warnings=Array.from(i));let s=0,a=t.owner,c=t.repo;if(o.additions="additions"in e?e.additions??0:0,o.deletions="deletions"in e?e.deletions??0:0,Ns(t)||(o.file_changes={total_count:"changed_files"in e?e.changed_files??0:0,files:[]}),Ns(t))try{let d=await lh(a,c,e.number,r);d&&(s+=le(d)??0,d.files=Ds(d.files,t),o.file_changes=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (files): ${d instanceof Error?d.message:String(d)}`]}let l=Zg(t),u=eh(t);if(l||u){let d=rh(t),p=()=>Promise.resolve({comments:$([],0)}),[{comments:f,note:m},{comments:g,note:b}]=await Promise.all([l?ih(n,a,c,e.number,d):p(),u?ah(n,a,c,e.number,d):p()]);o.comments=[...f,...g],s+=(le(f)??0)+(le(g)??0);let C=[m,b].filter(S=>typeof S=="string");C.length>0&&(o._sanitization_warnings=[...o._sanitization_warnings||[],...C])}if(nh(t))try{let d=await sh(n,a,c,e.number);s+=le(d)??0,o.reviews=d}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch reviews: ${d instanceof Error?d.message:String(d)}`]}if(th(t))try{let d=await uh(a,c,e.number,t,r);d&&(s+=le(d)??0,o.commits=d)}catch(d){o._sanitization_warnings=[...o._sanitization_warnings||[],`Partial Data: Failed to fetch details (commits): ${d instanceof Error?d.message:String(d)}`]}return $(o,s)}var SE,Hs=y(()=>{"use strict";be();Ge();Wo();oe();SE=new Set(["vercel","pkg-pr-new","coderabbitai","github-actions","codecov","changeset-bot","netlify","sonarcloud","socket-security"])});function xE(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}async function MQ(e,t,n){let r=He("gh-api-prs",{owner:e.owner,repo:e.repo,prNumber:e.prNumber,content:e.content,reviewMode:e.reviewMode},n);return await ze(r,async()=>await ru(e,t),{shouldCache:i=>!i.error})}async function ru(e,t){let{owner:n,repo:r,prNumber:o}=e;if(!n||!r||!o)return{pull_requests:[],total_count:0,error:qe.PR_REQUIRED_PARAMS.message,hints:["Provide owner, repo, and prNumber"]};if(Array.isArray(n)||Array.isArray(r))return{pull_requests:[],total_count:0,error:qe.PR_SINGLE_VALUES.message,hints:["Do not use array for owner or repo when fetching by number"]};try{let i=await pe(t),s=await i.rest.pulls.get({owner:n,repo:r,pull_number:o}),a=s.data,c=await Gs(a,e,i,t);return{pull_requests:[qo(c,{includeFullBody:!0,includeFullCommentDetails:!0})],total_count:1,rawResponseChars:U(s.data)+(le(c)??0)}}catch(i){let s=re(i);return xE(s,qe.PULL_REQUEST_FETCH_FAILED.message(o,s.error),[`Verify that pull request #${o} exists in ${n}/${r}`,"Check if you have access to this repository","Ensure the PR number is correct"])}}var ou=y(()=>{"use strict";pt();Ge();wt();Mt();Wo();Hs();oe()});function dh(e,t,n){return{pull_requests:[],total_count:0,error:t,status:e.status,hints:n,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}}function ph(e){let t=Math.min(e.limit||30,100);return{pull_requests:[],total_count:0,pagination:{currentPage:e.page||1,totalPages:0,perPage:t,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}}}async function wE(e,t){if(!t.owner||!t.repo||Array.isArray(t.owner)||Array.isArray(t.repo))return t;try{let n=await e.rest.repos.get({owner:t.owner,repo:t.repo}),[r,o]=n.data.full_name?.split("/")??[];return!r||!o||r===t.owner&&o===t.repo?t:{...t,owner:r,repo:o}}catch{return t}}async function fh(e,t,n){let r=He("gh-api-prs",{query:e.query,owner:e.owner,repo:e.repo,prNumber:e.prNumber,state:e.state,draft:e.draft,merged:e.merged,author:e.author,assignee:e.assignee,mentions:e.mentions,commenter:e.commenter,involves:e.involves,"reviewed-by":e["reviewed-by"],"review-requested":e["review-requested"],head:e.head,base:e.base,created:e.created,updated:e.updated,"merged-at":e["merged-at"],closed:e.closed,comments:e.comments,reactions:e.reactions,interactions:e.interactions,label:e.label,"no-assignee":e["no-assignee"],"no-label":e["no-label"],"no-milestone":e["no-milestone"],"no-project":e["no-project"],match:e.match,sort:e.sort,order:e.order,limit:e.limit,page:e.page,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage},n);return await ze(r,async()=>await EE(e,t,n),{shouldCache:i=>!i.error})}async function EE(e,t,n){try{if(e.prNumber&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await ru(e,t);let r=await pe(t);if(!og(e)&&e.owner&&e.repo&&!Array.isArray(e.owner)&&!Array.isArray(e.repo))return await TE(r,e);let i=await wE(r,e),s=rg(i);if(!s)return{pull_requests:[],total_count:0,error:qe.NO_VALID_PARAMETERS.message,hints:["Provide search query or filters like owner/repo"]};let a=i.sort&&i.sort!=="best-match"?i.sort:void 0,c=Math.min(i.limit||30,100),l=i.page||1,u=s,d=await r.rest.search.issuesAndPullRequests({q:s,sort:a,order:e.order||"desc",per_page:c,page:l}),p=d.data.items?.filter(O=>!!O.pull_request)||[],f=await Promise.all(p.map(async O=>await ch(O,i,r))),m=f.reduce((O,w)=>O+(le(w)??0),0),g=f.map(O=>qo(O,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:i.charOffset,charLength:i.charLength})),b=d.data.total_count,C=Math.min(b,1e3),S=Math.min(Math.ceil(C/c),10),T=Math.min(l,Math.max(1,S)),L=T<S,k=Math.min(C,S*c);return{pull_requests:g,total_count:d.data.total_count,effectiveQuery:u,...d.data.incomplete_results&&{incomplete_results:!0},pagination:{currentPage:T,totalPages:S,perPage:c,totalMatches:C,reportedTotalMatches:b,reachableTotalMatches:k,totalMatchesKind:"reported",totalMatchesCapped:b>C,hasMore:L,...L?{nextPage:T+1}:{}},rawResponseChars:U(d.data)+m}}catch(r){if(wn(r))return ph(e);let o=re(r);return dh(o,qe.PULL_REQUEST_SEARCH_FAILED.message(o.error),["Verify authentication and search parameters"])}}async function TE(e,t){try{let n=t.owner,r=t.repo,o=Math.min(t.limit||30,100),i=t.page||1,s=await e.rest.pulls.list({owner:n,repo:r,state:(t.state==="merged"?"closed":t.state)||"open",per_page:o,page:i,sort:t.sort==="updated"?"updated":"created",direction:t.order||"desc",...t.head&&{head:t.head},...t.base&&{base:t.base}}),a=await Promise.all(s.data.map(async p=>await Gs(p,t,e))),c=a.reduce((p,f)=>p+(le(f)??0),0),l=a.map(p=>qo(p,{includeFullBody:!1,includeFullCommentDetails:!1,charOffset:t.charOffset,charLength:t.charLength})),u=s.data.length===o,d=(i-1)*o+l.length;return{pull_requests:l,total_count:l.length,pagination:{currentPage:i,totalPages:u?i+1:i,perPage:o,totalMatches:d+(u?1:0),reachableTotalMatches:d,totalMatchesKind:u?"lowerBound":"exact",hasMore:u,...u?{nextPage:i+1}:{}},rawResponseChars:U(s.data)+c}}catch(n){if(wn(n))return ph(t);let r=re(n);return dh(r,qe.PULL_REQUEST_LIST_FAILED.message(r.error),["Verify repository access and authentication"])}}var iu=y(()=>{"use strict";me();pt();Ge();wt();vo();Mt();oe();Wo();Hs();ou()});function kE(e){return e?e.includes('rel="next"'):!1}function mh(e,t,n){if(!e)return;if(!n&&!t)return{patch:e};let r=e.length,o=Math.min(Math.max(0,t??0),r),i=Math.max(1,n??r),s=Math.min(o+i,r),a=s<r;return{patch:e.slice(o,s),patchPagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}async function gh(e,t){try{let n=await pe(t),r={owner:e.owner,repo:e.repo,per_page:e.perPage,page:e.page,...e.path?{path:e.path}:{},...e.branch?{sha:e.branch}:{},...e.since?{since:e.since}:{},...e.until?{until:e.until}:{},...e.author?{author:e.author}:{}},o=await n.rest.repos.listCommits(r),i=o.headers.link,s=kE(i),a=o.data.map(u=>{let d=u.commit.author,p=u.commit.committer,f=p?.date??d?.date??"",m=u.commit.message,g=m.split(`
23
+ `)[0]??m;return{sha:u.sha,date:f,message:m,messageHeadline:g,url:u.html_url,author:{name:d?.name??"unknown",email:d?.email??"",...u.author?.login?{login:u.author.login}:{}},...p?{committer:{name:p.name??"unknown",email:p.email??"",...u.committer?.login?{login:u.committer.login}:{}}}:{}}}),c={currentPage:e.page,perPage:e.perPage,hasMore:s,...s?{nextPage:e.page+1}:{}};if(!e.includeDiff)return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:a,pagination:c},status:200};let l=await Promise.all(a.map(async(u,d)=>{try{let p=o.data[d]?.sha??u.sha,f=await n.rest.repos.getCommit({owner:e.owner,repo:e.repo,ref:p});if(e.type==="file"&&e.path){let m=e.path,g=f.data.files?.find(b=>b.filename===m||b.previous_filename===m);if(g){let b=g.patch!==void 0?mh(g.patch,e.charOffset,e.charLength):void 0;return{...u,additions:g.additions,deletions:g.deletions,status:g.status,...b!==void 0?{patch:b.patch,...b.patchPagination?{patchPagination:b.patchPagination}:{},diff:jo(b.patch)}:{},...g.previous_filename?{previousFilename:g.previous_filename}:{}}}}else{let m=e.path,g=(f.data.files??[]).filter(w=>!m||w.filename.startsWith(m)).map(w=>{let N=w.patch!==void 0?mh(w.patch,e.charOffset,e.charLength):void 0;return{filename:w.filename,status:w.status,additions:w.additions,deletions:w.deletions,...N!==void 0?{patch:N.patch,...N.patchPagination?{patchPagination:N.patchPagination}:{},diff:jo(N.patch)}:{},...w.previous_filename?{previousFilename:w.previous_filename}:{}}}),b=Math.max(1,e.filePage??1),C=Math.max(1,e.itemsPerPage??20),S=g.length,T=Math.max(1,Math.ceil(S/C)),L=Math.min(b,T),k=(L-1)*C,O=g.slice(k,k+C);return{...u,files:O,filesPagination:{currentPage:L,totalPages:T,itemsPerPage:C,totalFiles:S,hasMore:L<T,...L<T?{nextFilePage:L+1}:{}}}}}catch{}return u}));return{data:{type:e.type,owner:e.owner,repo:e.repo,...e.path?{path:e.path}:{},commits:l,pagination:c},status:200}}catch(n){return re(n)}}var su=y(()=>{"use strict";Ge();wt();$o()});function yh(e){let t={},n=e.license;n?.spdx_id&&n.spdx_id!=="NOASSERTION"&&(t.license=n.spdx_id);let r=e.homepage;return r&&(t.homepage=r),t}async function bh(e,t,n){let r=He("gh-api-repos",{keywords:e.keywords,topicsToSearch:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,sort:e.sort,limit:e.limit,page:e.page},n);return await ze(r,async()=>await vE(e,t),{shouldCache:i=>"data"in i&&!i.error})}async function OE(e,t){let n=Math.min(e.limit||100,100),r=e.page||1,o=e.sort==="updated"?"updated":"full_name",i,s;try{i=(await t.rest.repos.listForOrg({org:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(f){if(f?.status!==404)return re(f);try{i=(await t.rest.repos.listForUser({username:e.owner,per_page:n,page:r,sort:o})).data,s=void 0}catch(g){return re(g)}}let a=i.map(f=>{let g=f.full_name.split("/"),b=g[0]||"",C=g[1]||"";return{owner:b,repo:C,defaultBranch:f.default_branch,stars:f.stargazers_count||0,description:f.description?f.description:"No description",url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at,pushedAt:f.pushed_at,visibility:f.visibility,...f.topics&&f.topics.length>0&&{topics:f.topics},...f.forks_count&&f.forks_count>0&&{forksCount:f.forks_count},...f.open_issues_count&&f.open_issues_count>0&&{openIssuesCount:f.open_issues_count},...f.language&&{language:f.language},...yh(f)}}),c=a.length,l=c===n,u=(r-1)*n+c,d=s??u+(l?1:0),p=s!==void 0||!l?"exact":"lowerBound";return{data:{repositories:a,pagination:{currentPage:r,totalPages:l?r+1:r,perPage:n,totalMatches:d,reachableTotalMatches:u,totalMatchesKind:p,hasMore:l,...l?{nextPage:r+1}:{}}},status:200,rawResponseChars:U(i)}}async function vE(e,t){try{let n=await pe(t),r=(e.keywords?.length??0)>0||(e.topicsToSearch?.length??0)>0,o=typeof e.owner=="string"?e.owner:Array.isArray(e.owner)?e.owner[0]:void 0;if(!r&&o)return await OE({owner:o,sort:e.sort,limit:e.limit,page:e.page},n);let i=ng(e);if(!i.trim())return{error:qe.QUERY_EMPTY.message,type:"http",status:400};let s=Math.min(e.limit||hh,100),a=e.page||1,c={q:i,per_page:s,page:a},l=["stars","forks","help-wanted-issues","updated"];e.sort&&l.includes(e.sort)&&(c.sort=e.sort);let u=await n.rest.search.repos(c),d=u.data.items.map(S=>{let L=S.full_name.split("/"),k=L[0]||"",O=L[1]||"";return{owner:k,repo:O,defaultBranch:S.default_branch,stars:S.stargazers_count||0,description:S.description?S.description:"No description",url:S.html_url,createdAt:S.created_at,updatedAt:S.updated_at,pushedAt:S.pushed_at,visibility:S.visibility,...S.topics&&S.topics.length>0&&{topics:S.topics},...S.forks_count&&S.forks_count>0&&{forksCount:S.forks_count},...S.open_issues_count&&S.open_issues_count>0&&{openIssuesCount:S.open_issues_count},...S.language&&{language:S.language},...yh(S)}}),p=u.data.total_count,f=Math.min(p,1e3),m=Math.min(Math.ceil(f/s),10),g=Math.min(a,Math.max(1,m)),b=g<m,C=Math.min(f,m*s);return{data:{repositories:d,pagination:{currentPage:g,totalPages:m,perPage:s,totalMatches:f,reportedTotalMatches:p,reachableTotalMatches:C,totalMatchesKind:"reported",totalMatchesCapped:p>f,hasMore:b,...b?{nextPage:g+1}:{}}},status:200,headers:Cs(u.headers),rawResponseChars:U(u.data)}}catch(n){if(wn(n)){let r=Math.min(e.limit||hh,100);return{data:{repositories:[],nonExistentScope:!0,pagination:{currentPage:e.page||1,totalPages:0,perPage:r,totalMatches:0,reportedTotalMatches:0,reachableTotalMatches:0,totalMatchesKind:"exact",totalMatchesCapped:!1,hasMore:!1}},status:200,rawResponseChars:0}}return re(n)}}var hh,au=y(()=>{"use strict";Ge();wt();vo();Mt();pt();oe();Ps();me();hh=30});var kn,Ko=y(()=>{"use strict";kn={ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200}});function AE(e,t){return t?e>5e4?[`Response ~${e.toLocaleString()} tokens \u2014 exceeds typical context. Reduce charLength or refine the query.`]:e>3e4?[`Response ~${e.toLocaleString()} tokens \u2014 approaching context limit. Consider reducing charLength.`]:[]:[]}function LE(e){if(e.hasMore&&e.nextCharOffset!==void 0){let t=e.charOffset+1,n=e.charOffset+e.charLength;return[`Page ${e.currentPage}/${e.totalPages} (chars ${t}-${n} of ${e.totalChars}). Next: charOffset=${e.nextCharOffset}`]}return[]}function lU(e,t={}){let{enableWarnings:n=!0,customHints:r=[]}=t,o=[];return o.push(...r),e.estimatedTokens&&o.push(...AE(e.estimatedTokens,n)),o.push(...LE(e)),o}function zs(e,t){return e.hasMore?[`Page ${e.currentPage}/${e.totalPages}. Next: page=${e.currentPage+1}`]:[]}var Bs=y(()=>{"use strict"});function Rh(e,t){let n=e._cachedItems;if(!n||n.length===0){let{_cachedItems:I,...v}=e;return v}let r=t.itemsPerPage??kn.ENTRIES_PER_PAGE,o=t.page??1,i=n.length,s=Math.max(1,Math.ceil(i/r)),a=(o-1)*r,c=Math.min(a+r,i),l=n.slice(a,c),u=Object.create(null),d=e.path==="/"?"":e.path,p=I=>{let v=I;d&&I.startsWith(d)&&(v=I.slice(d.length),v.startsWith("/")&&(v=v.slice(1)));let B=v.lastIndexOf("/");return B===-1?".":v.slice(0,B)},f=I=>{let v=I.lastIndexOf("/");return v===-1?I:I.slice(v+1)};for(let I of l){let v=p(I.path);u[v]||(u[v]={files:[],folders:[]});let B=f(I.path);I.type==="file"?u[v].files.push(B):u[v].folders.push(B)}for(let I of Object.keys(u)){let v=u[I];v&&(v.files.sort(),v.folders.sort())}let m=Object.create(null),g=Object.keys(u).sort((I,v)=>I==="."?-1:v==="."?1:I.localeCompare(v));for(let I of g){let v=u[I];v&&(m[I]=v)}let b=l.filter(I=>I.type==="file").length,C=l.filter(I=>I.type==="dir").length,S=n.filter(I=>I.type==="file").length,T=n.filter(I=>I.type==="dir").length,L=o<s,k={currentPage:o,totalPages:s,hasMore:L,...L?{nextPage:o+1}:{},entriesPerPage:r,totalEntries:i},O=zs(k,{owner:e.owner,repo:e.repo,branch:e.branch,path:d,depth:t.maxDepth??1,pageFiles:b,pageFolders:C,allFiles:S,allFolders:T}),w,N=e._cachedFileSizeMap;if(N){let I=new Set(l.filter(z=>z.type==="file").map(z=>z.path)),v=e.path==="/"?"":e.path,B=Object.create(null);for(let[z,X]of Object.entries(N))for(let[j,xe]of Object.entries(X)){let we=z==="."?v?`${v}/${j}`:j:v?`${v}/${z}/${j}`:`${z}/${j}`;I.has(we)&&(B[z]||(B[z]=Object.create(null)),B[z][j]=xe)}Object.keys(B).length>0&&(w=B)}return{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,apiSource:e.apiSource,summary:{totalFiles:S,totalFolders:T,truncated:L,filtered:!0,originalCount:i},structure:m,...w!==void 0&&{fileSizeMap:w},...N!==void 0&&{_cachedFileSizeMap:N},pagination:k,hints:O,rawResponseChars:e.rawResponseChars}}var cu=y(()=>{"use strict";Ko();Bs()});import{RequestError as _E}from"octokit";function Sh(e){return e instanceof _E&&IE.has(e.status)}function lu(e,t){try{Object.defineProperty(e,Ch,{value:t,enumerable:!1,configurable:!0})}catch{}return e}function uu(e){if(typeof e!="object"||e===null)return 0;let t=e[Ch];return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}async function du(e,t,n,r,o,i,s,a=new Set){if(i>s||a.has(o))return lu($([],0),0);a.add(o);let c;try{c=await e.rest.repos.getContent({owner:t,repo:n,path:o||"",ref:r})}catch(m){if(Sh(m))throw m;return lu($([],0),1)}let l=U(c.data),d=(Array.isArray(c.data)?c.data:[c.data]).filter(m=>m.type==="file"||m.type==="dir").map(m=>({name:m.name,path:m.path,type:m.type,size:"size"in m?m.size:void 0,download_url:"download_url"in m?m.download_url:void 0,url:m.url,html_url:m.html_url,git_url:m.git_url,sha:m.sha})),p=[...d],f=0;if(i<s){let m=d.filter(b=>b.type==="dir"),g=3;for(let b=0;b<m.length;b+=g){let C=m.slice(b,b+g),S=await Promise.allSettled(C.map(T=>du(e,t,n,r,T.path,i+1,s,a)));for(let T of S)if(T.status==="fulfilled"){let L=T.value;l+=le(L)??0,f+=uu(L),p.push(...L)}else{if(Sh(T.reason))throw T.reason;f+=1}}}return lu($(p,l),f)}var Ch,IE,pu=y(()=>{"use strict";oe();Ch=Symbol.for("octocode.recursiveFetchFailures"),IE=new Set([401,403,429])});import{RequestError as FE}from"octokit";async function ME(e,t,n,r,o,i){let s,a;try{o?s=o:(a=await Ze(t,n,i),s=a)}catch(c){let l=re(c);return{error:qn.NOT_FOUND.message(t,n,l.error),status:l.status}}try{return{data:(await e.rest.repos.getContent({owner:t,repo:n,path:r||"",ref:s})).data,workingBranch:s,...a!==void 0?{repoDefaultBranch:a}:{}}}catch(c){if(!(c instanceof FE&&c.status===404)){let u=re(c);return{error:qn.ACCESS_FAILED.message(t,n,u.error),status:u.status,rateLimitRemaining:u.rateLimitRemaining,rateLimitReset:u.rateLimitReset,retryAfter:u.retryAfter}}let l=re(c);return{error:qn.PATH_NOT_FOUND.message(r,t,n,s),status:l.status}}}function DE(e){return e.map(t=>{let n=t;return{name:n.name,path:n.path,type:n.type,size:"size"in n?n.size:void 0,download_url:"download_url"in n?n.download_url:void 0,url:n.url,html_url:n.html_url,git_url:n.git_url,sha:n.sha}})}function NE(e,t){let n=Object.create(null),r=a=>{let c=a;t&&a.startsWith(t)&&(c=a.slice(t.length),c.startsWith("/")&&(c=c.slice(1)));let l=c.lastIndexOf("/");return l===-1?".":c.slice(0,l)},o=a=>{let c=a.lastIndexOf("/");return c===-1?a:a.slice(c+1)};for(let a of e){let c=r(a.path);n[c]||(n[c]={files:[],folders:[]});let l=o(a.path);a.type==="file"?n[c].files.push(l):n[c].folders.push(l)}for(let a of Object.values(n))a&&(a.files.sort(),a.folders.sort());let i=Object.keys(n).sort((a,c)=>a==="."?-1:c==="."?1:a.localeCompare(c)),s=Object.create(null);for(let a of i){let c=n[a];c&&(s[a]=c)}return s}function Ph(e,t){let n=Object.create(null);for(let r of e){if(r.type!=="file"||r.size===void 0)continue;let o=r.path;t&&r.path.startsWith(t)&&(o=r.path.slice(t.length).replace(/^\//,""));let i=o.lastIndexOf("/"),s=i===-1?".":o.slice(0,i),a=i===-1?o:o.slice(i+1);n[s]||(n[s]=Object.create(null)),n[s][a]=r.size}return n}async function xh(e,t,n){let r=He("gh-repo-structure-api",{owner:e.owner,repo:e.repo,branch:e.branch,path:e.path,depth:e.maxDepth},n),o=await ze(r,async()=>await GE({...e,itemsPerPage:e.itemsPerPage??kn.ENTRIES_PER_PAGE,page:e.page??1},t),{shouldCache:i=>!("error"in i)});return!("error"in o)&&o.structure?Rh(o,e):o}async function GE(e,t){try{let n=await pe(t),{owner:r,repo:o,branch:i,path:s="",maxDepth:a=1}=e,c=s.replace(/^\/+|\/+$/g,""),l=await ME(n,r,o,c,i,t);if("error"in l)return l;let{data:u,workingBranch:d,repoDefaultBranch:p}=l,f=U(u),m=Array.isArray(u)?u:[u],g=DE(m),b=0;if(a>1){let ee=await du(n,r,o,d,c,1,a);b=uu(ee),f+=le(ee)??0,g=[...g,...ee].filter((Yr,Hi,gP)=>gP.findIndex(hP=>hP.path===Yr.path)===Hi)}let C=g.filter(ee=>ee.type==="dir"?!Ao(ee.name):!gr(ee.path));C.sort((ee,St)=>{if(ee.type!==St.type)return ee.type==="dir"?-1:1;let Yr=ee.path.split("/").length,Hi=St.path.split("/").length;return Yr!==Hi?Yr-Hi:ee.path.localeCompare(St.path)});let S=e.itemsPerPage??kn.ENTRIES_PER_PAGE,T=e.page??1,L=C.length,k=Math.max(1,Math.ceil(L/S)),O=(T-1)*S,w=Math.min(O+S,L),N=C.slice(O,w),I=NE(N,c),v=e.includeSizes===!0?Ph(C,c):void 0,B=v!==void 0?Ph(N,c):void 0,z=N.filter(ee=>ee.type==="file").length,X=N.filter(ee=>ee.type==="dir").length,j=C.filter(ee=>ee.type==="file").length,xe=C.filter(ee=>ee.type==="dir").length,we=T<k,jt={currentPage:T,totalPages:k,hasMore:we,...we?{nextPage:T+1}:{},entriesPerPage:S,totalEntries:L},$t=zs(jt,{owner:r,repo:o,branch:d,path:c,depth:a,pageFiles:z,pageFolders:X,allFiles:j,allFolders:xe});return b>0&&$t.unshift(`Partial tree: ${b} subdirectory subtree(s) failed to load and are missing from this structure. The listing is incomplete \u2014 retry or narrow the path/depth.`),{owner:r,repo:o,branch:d,...p!==void 0&&{defaultBranch:p},path:c||"/",apiSource:!0,summary:{totalFiles:j,totalFolders:xe,truncated:we,filtered:!0,originalCount:C.length},structure:I,...B!==void 0&&{fileSizeMap:B},...v!==void 0&&{_cachedFileSizeMap:v},pagination:jt,hints:$t,rawResponseChars:f,_cachedItems:C.map(ee=>({path:ee.path,type:ee.type}))}}catch(n){let r=re(n);return{error:qn.STRUCTURE_EXPLORATION_FAILED.message,status:r.status,rateLimitRemaining:r.rateLimitRemaining,rateLimitReset:r.rateLimitReset,retryAfter:r.retryAfter}}}var fu=y(()=>{"use strict";Ko();Ge();wt();Mt();Bs();hr();pt();oe();cu();pu()});var wh,mu=y(()=>{"use strict";wh={github:{cloneRepo:!0,fetchDirectoryToDisk:!0,requiresScopedCodeSearch:!1,supportsMergedState:!1,supportsMultiTopicSearch:!0}}});function On(e){return!!(e&&typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&"type"in e)}function HE(e){return!!(e&&typeof e=="object"&&e!==null&&"data"in e&&"status"in e&&typeof e.status=="number")}function zE(e){return!!(e&&typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"full_name"in e&&typeof e.full_name=="string"&&"private"in e&&typeof e.private=="boolean")}var Yo=y(()=>{"use strict"});function Ce(e){if(!e)return{owner:void 0,repo:void 0};let t=e.split("/");if(t.length!==2||!t[0]||!t[1])throw new Error(`Invalid GitHub projectId format: '${e}'. Expected 'owner/repo'.`);return{owner:t[0],repo:t[1]}}function BE(e){if(e.rateLimitRemaining===void 0&&e.retryAfter===void 0&&e.rateLimitReset===void 0)return;let t=e.rateLimitReset,n=t&&!isNaN(t)?Math.floor(t/1e3):Math.floor(Date.now()/1e3)+(e.retryAfter??3600);return{remaining:e.rateLimitRemaining??0,reset:n,retryAfter:e.retryAfter}}function Nt(e){return{error:e.error,status:e.status||500,provider:"github",hints:e.hints,rateLimit:BE(e)}}function Qs(e){return QE(e)?Nt({error:typeof e.error=="string"?e.error:String(e.error),status:e.status||500,hints:e.hints,rateLimitRemaining:e.rateLimitRemaining,rateLimitReset:e.rateLimitReset,retryAfter:e.retryAfter}):null}function QE(e){if(typeof e!="object"||e===null||!("error"in e))return!1;let n=e.error;return typeof n=="string"||UE(n)}function UE(e){return typeof e=="object"&&e!==null&&typeof e.toString=="function"}var mt=y(()=>{"use strict"});function Eh(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function jE(e){return{items:e.items.map(n=>({path:n.path,matches:n.matches.map(r=>({context:r.context,positions:r.positions})),url:n.url||"",repository:{id:n.repository.nameWithOwner,name:n.repository.nameWithOwner,url:n.repository.url},lastModifiedAt:n.lastModifiedAt})),totalCount:e.total_count,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Eh(e.pagination)},repositoryContext:e._researchContext?.repositoryContext,nonExistentScope:e.nonExistentScope,incompleteResults:e.incompleteResults}}function $E(e){let t=e.repositories.map(n=>({id:`${n.owner}/${n.repo}`,name:n.repo,fullPath:`${n.owner}/${n.repo}`,description:n.description||null,url:n.url,cloneUrl:`https://github.com/${n.owner}/${n.repo}.git`,defaultBranch:n.defaultBranch||"main",stars:n.stars||0,forks:n.forksCount||0,visibility:n.visibility||"public",topics:n.topics||[],createdAt:n.createdAt,updatedAt:n.updatedAt,lastActivityAt:n.pushedAt||n.updatedAt,openIssuesCount:n.openIssuesCount,language:n.language}));return{repositories:t,totalCount:e.pagination?.totalMatches||t.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...Eh(e.pagination)},nonExistentScope:e.nonExistentScope}}async function Th(e,t,n=Ce){let{owner:r,repo:o}=n(e.projectId),i=r||e.owner,s={keywords:e.keywords,owner:i,repo:o,extension:e.extension,filename:e.filename,language:e.language,path:e.path,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},a=await ug(s,t);return On(a)?Nt(a):a.data?{data:jE(a.data),status:200,provider:"github",rawResponseChars:a.rawResponseChars??U(a.data)}:{error:"No data returned from GitHub API",status:500,provider:"github"}}async function kh(e,t){let n={keywords:e.keywords,topicsToSearch:e.topics,owner:e.owner,stars:e.stars??(e.minStars?`>=${e.minStars}`:void 0),size:e.size,created:e.created,updated:e.updated,language:e.language,match:e.match,archived:e.archived,visibility:e.visibility,forks:e.forks,license:e.license,goodFirstIssues:e.goodFirstIssues,sort:e.sort==="best-match"?void 0:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},r=await bh(n,t);return"error"in r?Qs(r)??{error:"Unknown GitHub API error",status:500,provider:"github"}:!("data"in r)||!r.data?{error:"No data returned from GitHub API",status:500,provider:"github"}:{data:$E(r.data),status:200,provider:"github",rawResponseChars:r.rawResponseChars??U(r.data)}}var gu=y(()=>{"use strict";_l();au();Yo();oe();mt();mt()});function VE(e,t){return{path:e.path||t.path,content:e.content||"",encoding:"utf-8",size:e.content?.length||0,totalLines:e.totalLines,sourceChars:e.sourceChars,sourceBytes:e.sourceBytes,contentView:e.contentView,isSkeleton:e.isSkeleton,ref:e.branch||t.ref||"",lastModified:e.lastModified,lastModifiedBy:e.lastModifiedBy,pagination:e.pagination,isPartial:e.isPartial,startLine:e.startLine,endLine:e.endLine,matchRanges:e.matchRanges,warnings:WE(e,t),matchNotFound:e.matchNotFound,searchedFor:e.searchedFor}}function WE(e,t){if(e.matchNotFound===!0){let n=e;if(Array.isArray(n.hints)&&n.hints.length>0){let a=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"";return n.hints.map(c=>c.replace(" in file",` in file${a}`))}let r=e.searchedFor??t.matchString??"",o=typeof e.totalLines=="number"?` (${e.totalLines} lines scanned)`:"",s=t.matchStringIsRegex===!0?"Try a different pattern, widen the anchor, or use fullContent=true to inspect the file.":"Try matchStringIsRegex=true for pattern matching, a different anchor, or fullContent=true.";return[`No matches for "${r}" in file${o}. ${s}`]}return e.warnings??e.matchLocations}async function Oh(e,t,n=Ce){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for file content",status:400,provider:"github"};let i={owner:r,repo:o,path:e.path,type:"file",branch:e.ref,startLine:e.startLine,endLine:e.endLine,matchString:e.matchString,contextLines:e.contextLines??5,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,charOffset:e.charOffset,charLength:e.charLength,fullContent:e.fullContent,forceRefresh:e.forceRefresh,minify:e.minify??"standard",mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await qg(i,t);if(On(s))return Nt(s);if(!s.data)return{error:"No data returned from GitHub API",status:500,provider:"github"};let a=s.data.hints;return{data:VE(s.data,e),status:200,provider:"github",rawResponseChars:s.rawResponseChars??U(s.data),...a?.length?{hints:a}:{}}}var hu=y(()=>{"use strict";Jl();Yo();oe();mt();mt()});function YE(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{}}}function XE(e,t,n=Ce){let r=(e.pull_requests||[]).map(a=>({number:a.number,title:a.title,body:a.body||null,...a.body_pagination&&{bodyPagination:a.body_pagination},url:a.url,state:a.merged?"merged":a.state,draft:a.draft||!1,author:a.author,assignees:a.assignees?.map(c=>typeof c=="string"?c:String(c.login??""))||[],labels:a.labels?.map(c=>typeof c=="string"?c:c.name??"")||[],sourceBranch:a.head_ref||"",targetBranch:a.base_ref||"",sourceSha:a.head_sha,targetSha:a.base_sha,createdAt:a.created_at,updatedAt:a.updated_at,closedAt:a.closed_at,mergedAt:a.merged_at,commentsCount:a.comments,changedFilesCount:a.changed_files,additions:a.additions,deletions:a.deletions,comments:a.comment_details?.map(c=>({id:c.id,author:c.user,body:c.body,...c.body_pagination&&{bodyPagination:c.body_pagination},createdAt:c.created_at,updatedAt:c.updated_at,...c.commentType&&{commentType:c.commentType},...c.path&&{path:c.path},...c.line!==void 0&&{line:c.line},...c.in_reply_to_id!=null&&{in_reply_to_id:c.in_reply_to_id}})),reviews:a.reviews?.map(c=>({id:c.id,user:c.user,state:c.state,body:c.body,submittedAt:c.submitted_at,commitId:c.commit_id})),commits:a.commit_details?.map(c=>({sha:c.sha,message:c.message,author:c.author,date:c.date})),fileChanges:a.file_changes?.map(c=>({path:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch})),...Array.isArray(a._sanitization_warnings)&&a._sanitization_warnings.length>0?{sanitizationWarnings:a._sanitization_warnings}:{}})),{owner:o,repo:i}=t.projectId?n(t.projectId):{owner:void 0,repo:void 0},s=o||t.owner;return{items:r,totalCount:e.total_count||r.length,pagination:{currentPage:e.pagination?.currentPage||1,totalPages:e.pagination?.totalPages||1,hasMore:e.pagination?.hasMore||!1,...e.pagination?.hasMore?{nextPage:(e.pagination?.currentPage||1)+1}:{},totalMatches:e.pagination?.totalMatches,entriesPerPage:e.pagination?.perPage,...YE(e.pagination)},repositoryContext:s&&i?{owner:s,repo:i}:void 0}}async function vh(e,t,n=Ce){let{owner:r,repo:o}=e.projectId?n(e.projectId):{owner:void 0,repo:void 0},s={owner:r||e.owner,repo:o,query:e.query,prNumber:e.number,state:e.state==="merged"?"closed":e.state==="all"?void 0:e.state,merged:e.state==="merged"?!0:void 0,draft:e.draft,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,"reviewed-by":e.reviewedBy,"review-requested":e.reviewRequested,label:e.labels,"no-assignee":e.noAssignee,"no-label":e.noLabel,"no-milestone":e.noMilestone,"no-project":e.noProject,base:e.baseBranch,head:e.headBranch,created:e.created,updated:e.updated,closed:e.closed,"merged-at":e.mergedAt,comments:e.comments,reactions:e.reactions,interactions:e.interactions,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,"team-mentions":e.teamMentions,project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit,page:e.page,charOffset:e.charOffset,charLength:e.charLength},a=await fh(s,t);return a.error?Nt({error:typeof a.error=="string"?a.error:String(a.error),status:a.status||500,hints:a.hints,rateLimitRemaining:a.rateLimitRemaining,rateLimitReset:a.rateLimitReset,retryAfter:a.retryAfter}):{data:XE(a,e,n),status:200,provider:"github",rawResponseChars:a.rawResponseChars??U(a)}}var yu=y(()=>{"use strict";iu();oe();mt();mt()});function ZE(e){return{projectPath:`${e.owner}/${e.repo}`,branch:e.branch||"",...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},path:e.path||"/",structure:e.structure||{},...e.fileSizeMap!==void 0&&{fileSizeMap:e.fileSizeMap},summary:{totalFiles:e.summary?.totalFiles||0,totalFolders:e.summary?.totalFolders||0,truncated:e.summary?.truncated||!1},pagination:e.pagination,hints:e.hints}}async function Ah(e,t,n=Ce){let{owner:r,repo:o}=n(e.projectId);if(!r||!o)return{error:"Project ID is required for repository structure",status:400,provider:"github"};let i={owner:r,repo:o,branch:e.ref||"HEAD",path:e.path,maxDepth:e.depth,itemsPerPage:e.itemsPerPage,page:e.page,includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning},s=await xh(i,t);return"error"in s?Qs(s)??{error:"Unknown GitHub API error",status:500,provider:"github"}:{data:ZE(s),status:200,provider:"github",rawResponseChars:s.rawResponseChars??U(s)}}var bu=y(()=>{"use strict";fu();oe();mt();mt()});var Us,Ru=y(()=>{"use strict";gu();hu();yu();bu();wt();Ge();mu();mt();Us=class{type="github";capabilities=wh.github;authInfo;constructor(t){t?.authInfo?this.authInfo=t.authInfo:t?.token&&(this.authInfo={token:t.token})}async searchCode(t){try{return await Th(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async getFileContent(t){try{return await Oh(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async searchRepos(t){try{return await kh(t,this.authInfo)}catch(n){return this.handleError(n)}}async searchPullRequests(t){try{return await vh(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async getRepoStructure(t){try{return await Ah(t,this.authInfo,Ce)}catch(n){return this.handleError(n)}}async resolveDefaultBranch(t){let{owner:n,repo:r}=Ce(t);if(!n||!r)throw new Error(`Cannot resolve default branch: invalid projectId '${t}'.`);return Ze(n,r,this.authInfo)}handleError(t){let n=re(t);return Nt(n)}}});import{createHash as tT}from"crypto";function Lh(e){return Date.now()-e.createdAt<nT}function rT(){for(let[e,t]of gt.entries())Lh(t)||gt.delete(e);if(gt.size>Su){let e=[...gt.entries()].sort((n,r)=>n[1].lastAccessedAt-r[1].lastAccessedAt),t=gt.size-Su;for(let n=0;n<t&&n<e.length;n++){let r=e[n];r&&gt.delete(r[0])}}}function oT(e){return e?tT("sha256").update(e).digest("hex").slice(0,16):"default"}function iT(e){if(e==="default")return e;try{let t=new URL(e),n=`${t.protocol}//${t.hostname.toLowerCase()}`;return t.port&&(n+=`:${t.port}`),n+=t.pathname.replace(/\/+$/,"")||"",n}catch{return e.replace(/\/+$/,"")}}function sT(e,t){let n=iT(t?.baseUrl||"default"),r=oT(t?.token||t?.authInfo?.token);return`${e}:${n}:${r}`}function Cu(e="github",t){if(e!=="github")throw new Error(`Unknown provider type: '${e}'. Only 'github' is supported.`);let n=sT(e,t),r=gt.get(n);if(r&&Lh(r))return r.lastAccessedAt=Date.now(),r.provider;r&&gt.delete(n),gt.size>=Su&&rT();let o=new Us({...t,type:e}),i=Date.now();return gt.set(n,{provider:o,createdAt:i,lastAccessedAt:i}),o}function oj(){gt.clear()}async function _h(){try{return Cu("github"),[{provider:"github",ok:!0}]}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`\u26A0\uFE0F github provider failed to initialize: ${t}
24
+ `),[{provider:"github",ok:!1,error:t}]}}var nT,Su,gt,js=y(()=>{"use strict";Ru();nT=3600*1e3,Su=20,gt=new Map});var aT,Pu=y(()=>{"use strict";aT={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"}});import{ContentSanitizer as Ih}from"@octocodeai/octocode-engine/contentSanitizer";function Fh(){try{return ge().output.format}catch{return"yaml"}}function uj(e){if(e==null||typeof e!="object")return{content:[{type:"text",text:`error: "Invalid result options"
25
+ `}],isError:!0};let{data:t,instructions:n,isError:r}=e;return{content:[{type:"text",text:Xo({data:t,instructions:n})}],isError:!!r}}function Vs(e){let t=[],{system:n,assistant:r,user:o,data:i,isError:s}=e;if(n){let a=[];if(n.instructions&&a.push(n.instructions),n.pagination){let{currentPage:c,totalPages:l,hasMore:u}=n.pagination;a.push(`Page ${c}/${l}${u?" (more available)":""}`)}n.warnings?.length&&a.push(`\u26A0\uFE0F Warnings:
27
26
  ${n.warnings.map(c=>`- ${c}`).join(`
28
27
  `)}`),n.hints?.length&&a.push(`Hints:
29
28
  ${n.hints.map(c=>`- ${c}`).join(`
30
- `)}`),a.length>0&&t.push(Fo.system(a.join(`
29
+ `)}`),a.length>0&&t.push($s.system(a.join(`
31
30
 
32
- `)))}if(t.push(Fo.assistant(r.summary)),r.details){let a=r.format==="json"||r.format==="yaml"?r.format:void 0;t.push(Fo.data(r.details,a))}if(o){let a=o.emoji?`${o.emoji} ${o.message}`:o.message;t.push(Fo.user(a))}return{content:t,structuredContent:OR(i),isError:!!s}}var rv={success(e,t,n){return No({system:n?{hints:n}:void 0,assistant:{summary:e},user:{message:"Operation completed",emoji:Mo.success},data:t})},empty(e,t){return No({system:{hints:t||["Try broader search terms","Check spelling"]},assistant:{summary:e},user:{message:"No results found",emoji:Mo.empty},data:{status:"empty",results:[]}})},error(e,t){return No({system:{instructions:"Tool execution failed. Error details provided for self-correction."},assistant:{summary:`Error: ${e}`},user:{message:"An error occurred",emoji:Mo.error},data:{status:"error",error:e,details:t},isError:!0})},paginated(e,t,n,r){return No({system:{pagination:{currentPage:n.page,totalPages:n.total,hasMore:n.hasMore},hints:r},assistant:{summary:e},user:{message:`Page ${n.page} of ${n.total}`,emoji:n.hasMore?"\u{1F4C4}":Mo.success},data:t})}};function OR(e){if(e==null)return;let t=wn(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?ot(t):ot({data:t})}function IR(e){if(e==null||typeof e!="string")return"";let t=ks.sanitizeContent(e);return Is(t.content)}function ot(e){if(e==null)return e;if(typeof e=="string"){let t=ks.sanitizeContent(e);return Is(t.content)}if(Array.isArray(e))return e.map(t=>ot(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ot(r);return t}return e}function ov(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
31
+ `)))}if(t.push($s.assistant(r.summary)),r.details){let a=r.format==="json"||r.format==="yaml"?r.format:void 0;t.push($s.data(r.details,a))}if(o){let a=o.emoji?`${o.emoji} ${o.message}`:o.message;t.push($s.user(a))}return{content:t,structuredContent:cT(i),isError:!!s}}function cT(e){if(e==null)return;let t=Cr(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?ht(t):ht({data:t})}function lT(e){return e==null||typeof e!="string"?"":Ih.sanitizeContent(e).content}function ht(e){if(e==null)return e;if(typeof e=="string")return Ih.sanitizeContent(e).content;if(Array.isArray(e))return e.map(t=>ht(t));if(typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ht(r);return t}return e}function pj(e,t){if(t==="json")return JSON.stringify(e);let n=Array.isArray(e.content)?e.content.map(r=>"text"in r&&typeof r.text=="string"?r.text:"").filter(r=>r.length>0):[];return n.length>0?n.join(`
33
32
 
34
- `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function xr(e,t){let n=wn(e)??{},r=Xl(),o="results"in n?["results","id","status","data"]:["instructions","status","data"],i;r==="json"?i=JSON.stringify(Do(n,t||o),null,2):i=O.jsonToYamlString(n,{keysPriority:t||o});let s=ks.sanitizeContent(i);return Is(s.content)}function Do(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Do(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Do(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Do(n[o],t));return r}var kR=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"]);function vR(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>kR.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function wn(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>wn(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(vR(a))continue;let c=(s==="files"||s==="repositories")&&!n,u=wn(a,{inFilesObject:n||c,depth:c?0:r+1});u!==void 0&&(o[s]=u,i=!0)}return i?o:void 0}return e}import{z as Ho}from"zod";function v(e,t){return Ho.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Ho.number().int().min(e).max(t))}var q=v(1,1e3).optional().default(1),An=v(0,100).optional(),Ln=v(1,1e9).optional(),FR={responseCharOffset:v(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:v(1,5e4).optional().describe("Full-response char window.")};function X(e,t={}){let{maxQueries:n=5}=t;return Ho.object({queries:Ho.array(e).min(1).max(n).describe("Parallel queries."),...FR}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}import{z as he}from"zod";var MR=he.object({currentPage:he.number(),totalPages:he.number(),hasMore:he.boolean(),charOffset:he.number(),charLength:he.number(),totalChars:he.number(),nextCharOffset:he.number().optional()}).optional(),Ae={hints:he.array(he.string()).optional(),base:he.string().optional(),shared:he.record(he.string(),he.union([he.string(),he.number(),he.boolean()])).optional(),responsePagination:MR};function dv(e){return e.extend(Ae)}function NR(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function L(e,t,n={}){let{extra:r}=n,o={status:"error"};if(NR(e))o.error=e;else if(yi(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=qa(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:U(o,n.rawResponse)}function Le(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:L(i,t,{toolName:n.toolName})}}async function Sv(e,t,n){if(e)try{await e(t,n)}catch{M(t,Br.EXECUTION_FAILED.code).catch(()=>{})}}function Pe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:U(s,o.rawResponse)}function Go(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return L(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Ee(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return M(r||n||"unknown_tool",Br.EXECUTION_FAILED.code).catch(()=>{}),L(i,t)}async function ke({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Ee(o,t,r,e)}}import{existsSync as GR}from"fs";import{join as UR}from"path";import{spawn as vs}from"child_process";var wv=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Uo=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],_r=[...Uo,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Jl=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],DR=10*1024*1024,Fs=5e3;function Ms(e={},t=Uo){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function Xt(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Uo,maxOutputSize:a=DR}=n;return new Promise(c=>{let u={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},l=()=>u.stdoutChunks.join(""),d=()=>u.stderrChunks.join(""),m={cwd:o,env:Ms(i,s),stdio:["ignore","pipe","pipe"]},p;try{p=vs(e,t,m)}catch(b){c({stdout:"",stderr:"",exitCode:null,success:!1,error:b instanceof Error?b:new Error(`Failed to spawn command '${e}'`)});return}let f,g=setTimeout(()=>{if(!u.killed){u.killed=!0;try{p.kill("SIGTERM")}catch{}f=setTimeout(()=>{try{p.kill("SIGKILL")}catch{}},Fs),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),h=()=>{clearTimeout(g),f!==void 0&&(clearTimeout(f),f=void 0)},R=()=>{if(u.totalOutputSize>a){if(!u.killed){u.killed=!0;try{p.kill("SIGKILL")}catch{}h(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};p.stdout?.on("data",b=>{if(u.killed)return;let P=b.toString();u.totalOutputSize+=Buffer.byteLength(P),!R()&&u.stdoutChunks.push(P)}),p.stderr?.on("data",b=>{if(u.killed)return;let P=b.toString();u.totalOutputSize+=Buffer.byteLength(P),!R()&&u.stderrChunks.push(P)}),p.on("close",b=>{u.killed||(h(),c({stdout:l(),stderr:d(),exitCode:b,success:b===0}))}),p.on("error",b=>{u.killed||(u.killed=!0,h(),c({stdout:l(),stderr:d(),exitCode:null,success:!1,error:b}))})})}function Zl(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Uo}=r,a;try{a=vs(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Ms({},s)})}catch{o(!1);return}let c,u=()=>{clearTimeout(l),c!==void 0&&(clearTimeout(c),c=void 0)},l=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},Fs),o(!1)}},n);a.on("close",d=>{u(),i||o(d===0)}),a.on("error",()=>{u(),i||o(!1)})})}var HR=1*1024*1024;function Av(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=_r,maxOutputSize:u=HR}=r,l;try{l=vs(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Ms({},c)})}catch{o(null);return}let d,m=()=>{clearTimeout(p),d!==void 0&&(clearTimeout(d),d=void 0)};l.stdout?.on("data",f=>{if(i)return;let g=f.toString();if(a+=Buffer.byteLength(g),a>u){if(!i){i=!0;try{l.kill("SIGKILL")}catch{}m(),o(null)}return}s.push(g)}),l.stderr?.on("data",()=>{});let p=setTimeout(()=>{if(!i){i=!0;try{l.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}},Fs),o(null)}},n);l.on("close",f=>{if(m(),!i)if(f===0){let g=s.join("").trim();o(g||null)}else o(null)}),l.on("error",()=>{m(),i||o(null)})})}function Bo(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var ql=120*1e3,BR=30*1e3,ed=[..._r,"GIT_TERMINAL_PROMPT"];async function td(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await $R();let a=e.branch??await Ge(r,o,t),c=zt(),u=$u(c,r,o,a,i),l=mr(u);if(!s&&l.hit&&l.meta.source==="clone")return{localPath:u,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Co(c),hs(u),hr(u);let d=jR(t,n);if(i){if(await QR(r,o,a,u,i,d),!GR(UR(u,i)))throw hs(u),new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await zR(r,o,a,u,d);let m=gr(r,o,a,"clone",i);return fr(u,m),{localPath:u,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}async function zR(e,t,n,r,o){let i=rd(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",nd(e,t),r),await Ns(i,ql,`full clone of ${e}/${t}`,o)}async function QR(e,t,n,r,o,i){let s=rd(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",nd(e,t),r),await Ns(s,ql,`sparse clone of ${e}/${t}`,i),await Ns(["-C",r,"sparse-checkout","set","--skip-checks","--",o],BR,`sparse-checkout set ${o}`,void 0)}function nd(e,t){return`https://github.com/${e}/${t}.git`}function rd(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function jR(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function $R(){try{if(!(await Xt("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:ed,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function VR(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function Ns(e,t,n,r){let o=await Xt("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:ed,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=VR(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}async function od(e,t={}){if(!Array.isArray(e))throw M("promiseUtils",bt.PROMISES_NOT_ARRAY.code).catch(xe("promise utility session logging")),new Error(bt.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw M("promiseUtils",bt.TIMEOUT_NOT_POSITIVE.code).catch(xe("promise utility session logging")),new Error(bt.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw M("promiseUtils",bt.CONCURRENCY_NOT_POSITIVE.code).catch(xe("promise utility session logging")),new Error(bt.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,u)=>typeof c=="function"?c:()=>(M("promiseUtils",Ct.NOT_A_FUNCTION.code).catch(xe("promise utility session logging")),Promise.reject(new Error(Ct.NOT_A_FUNCTION.message(u)))));if(r<i.length)return WR(i,r,n,o);let s=i.map((c,u)=>id(c,u,n,o));return(await Promise.allSettled(s)).map((c,u)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:u})}async function id(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,u)=>{o=setTimeout(()=>{M("promiseUtils",Ct.TIMEOUT.code).catch(()=>{}),u(new Error(Ct.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function WR(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,u=e[c];if(!u){M("promiseUtils",Ct.FUNCTION_UNDEFINED.code).catch(xe("promise utility session logging")),o[c]={success:!1,error:new Error(Ct.FUNCTION_UNDEFINED.message),index:c};continue}try{let l=await id(u,c,n,r);o[c]=l}catch(l){o[c]={success:!1,error:l instanceof Error?l:new Error(String(l)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}function KR(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}var Hs=["path","uri"];function Ds(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Ds(o,t,n+1);return}let r=e;for(let o of Hs){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let o of Object.values(r))o&&typeof o=="object"&&Ds(o,t,n+1)}function sd(e){let t=[];for(let i of e)Ds(i?.data,t,0);if(t.length===0)return;let n=KR(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return YR(e,r),n}function YR(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){let a=i[s];typeof a=="string"?!Hs.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function XR(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function JR(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}var ZR=new Set([...Hs,"owner","repo","name","id"]);function ad(e){let t=XR(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(ZR.has(i))continue;let s=n[i];JR(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var qR=3,cd=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,eb=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,tb=5e3;function nb(e,t,n){if(e<=1)return cd;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(eb/o),s=Math.max(tb,Math.min(i,cd));return n?Math.max(s,n):s}async function J(e,t,n,r){let o=n.concurrency??qR,{results:i,errors:s}=await sb(e,t,o,n.minQueryTimeoutMs);return rb(n,i,s,e,r)}function rb(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let h=g.result.status;c[g.queryIndex]={id:pd(g.originalQuery,g.queryIndex),...h!==void 0?{status:h}:{},data:ab(g.result)}}),n.forEach(g=>{let h=r[g.queryIndex];h&&(c[g.queryIndex]={id:pd(h,g.queryIndex),status:"error",data:{error:g.error}})});let u=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:u,config:e}),h=ud(g.text,o),R=ld(g.structuredContent,h.pagination);return dd(e.toolName,t,n,h.text.length),{content:[{type:"text",text:h.text}],structuredContent:R,isError:g.isError??(u.length>0&&u.every(P=>P.status==="error"))}}let l={results:u};if(Array.isArray(l.results)){let g=sd(l.results);g&&(l.base=g);let h=ad(l.results);h&&(l.shared=h)}let d=xr(l,a),m=ud(d,o),p=ld(ot(l),m.pagination);return dd(e.toolName,t,n,m.text.length),{content:[{type:"text",text:m.text}],structuredContent:p,isError:u.length>0&&u.every(g=>g.status==="error")}}function Gs(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
35
- `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function ob(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Gs(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function ib(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Gs(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function ud(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=Gs(e,s,i),c=a<o,u=ob(e,s,i),l=ib(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${u}/${l}. Next: responseCharOffset=${a}
36
- `:`# Response page ${u}/${l}.
37
- `}${d}`,pagination:{currentPage:u,totalPages:l,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function ld(e,t){return t?{...e,responsePagination:t}:e}function dd(e,t,n,r){let o=t.reduce((i,s)=>i+(ne(s.result)??N(s.result)),0)+n.reduce((i,s)=>i+N(s),0);try{io(e,o,r)}catch{}}async function sb(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,u)=>()=>t(c,u).then(l=>({result:l,queryIndex:u,originalQuery:c})));return(await od(s,{timeout:nb(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,u)=>{i.push({queryIndex:u,error:c.message})}})).forEach(c=>{c.success&&c.data&&o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}),{results:o,errors:i}}function ab(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function pd(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}function zo(e){return e.data!==void 0&&!e.error}function cb(e){return e.error!==void 0}import{maskSensitiveData as fd}from"@octocodeai/octocode-engine/mask";var Us=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}};function ub(){return Yi().provider??ir()}function lb(e){let t=Yi(),n=t.provider??ir(),{baseUrl:r,token:o}=t;try{let i=Os(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=fd(s);throw new Us(n,`Failed to initialize ${n} provider: ${a}`)}}function $e(e){let t;return()=>t??=lb(e)}function Qo(e,t){return e.capabilities[t]}async function kt(e,t){let n=await t();return zo(n)?{ok:!0,response:n}:{ok:!1,result:Go(n,e)}}async function md(e,t){let n=t??ub(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:fd(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)zo(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}async function gd(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>ke({toolName:S.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!Qo(s,"cloneRepo"))return Ee(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",S.GITHUB_CLONE_REPO);let a;try{a=await td(o,n,s.token)}catch(m){let p=m instanceof Error?m.message:String(m);return L(`Clone failed for ${o.owner}/${o.repo}: ${p}`,o)}let c=or(a.localPath),u={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},l={localSearch:{tool:"localSearchCode",query:{path:a.localPath,keywords:"TODO",mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:u,next:l};return Pe(o,d,!0,S.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:S.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}import{CloneRepoQuerySchema as fb}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as mb}from"@octocodeai/octocode-core/schemas/outputs";import{z as hd}from"zod";function db(e,t){return e?.description&&!t.description?t.describe(e.description):t}function yd(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=db(e.shape[r],o);return n}function pb(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function Rd(e,t){if(!t?.length)return e;let n=new Set(t);return hd.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function re(e,t={},n={}){let r=Rd(e,n.omit),o=pb(r,yd(r,t));return n.strict?o.strict():o}function ce(e,t={},n={}){let r=Rd(e,n.omit),o=hd.object({...r.shape,...yd(r,t)});return n.strict?o.strict():o}var Bs=re(fb),bd=X(Bs),h0=mb.extend(Ae);import{z as E}from"zod";import{FileContentQuerySchema as Sd}from"@octocodeai/octocode-core/schemas";var gb=E.enum(["none","standard","symbols"]).optional().default("standard"),hb=E.object({currentPage:E.number(),totalPages:E.number(),hasMore:E.boolean(),nextPage:E.number().optional(),nextMatchPage:E.number().optional(),charOffset:E.number().optional(),charLength:E.number().optional(),totalChars:E.number().optional(),nextCharOffset:E.number().optional(),filesPerPage:E.number().optional(),totalFiles:E.number().optional(),entriesPerPage:E.number().optional(),totalEntries:E.number().optional(),matchesPerPage:E.number().optional(),totalMatches:E.number().optional()}),yb=E.object({path:E.string(),content:E.string(),localPath:E.string().optional(),repoRoot:E.string().optional(),contentView:E.enum(["none","standard","symbols"]).optional(),isSkeleton:E.boolean().optional(),totalLines:E.number().optional(),sourceChars:E.number().optional(),sourceBytes:E.number().optional(),resolvedBranch:E.string().optional(),pagination:hb.optional(),isPartial:E.boolean().optional(),startLine:E.number().optional(),endLine:E.number().optional(),matchRanges:E.array(E.object({start:E.number(),end:E.number()})).optional(),lastModified:E.string().optional(),lastModifiedBy:E.string().optional(),warnings:E.array(E.string()).optional(),matchNotFound:E.boolean().optional(),searchedFor:E.string().optional(),cached:E.boolean().optional()}),Rb=E.object({path:E.string(),localPath:E.string(),repoRoot:E.string().optional(),fileCount:E.number(),totalSize:E.number(),files:E.array(E.object({path:E.string(),size:E.number(),type:E.string()})).optional(),cached:E.boolean().optional(),resolvedBranch:E.string().optional()}),Cd={startLine:Ln,endLine:Ln,contextLines:An,charOffset:v(0,1e8).optional(),charLength:v(1,5e4).optional(),minify:gb},bb=ce(Sd,Cd),jo=re(Sd,Cd),Pd=X(bb),T0=E.object({base:E.string().optional(),shared:E.record(E.string(),E.union([E.string(),E.number(),E.boolean()])).optional(),responsePagination:Ae.responsePagination,results:E.array(E.object({id:E.string(),owner:E.string(),repo:E.string(),files:E.array(yb).optional(),directories:E.array(Rb).optional()})),errors:E.array(E.object({id:E.string(),owner:E.string().optional(),repo:E.string().optional(),path:E.string().optional(),error:E.string()})).optional()});function Sb(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function Ed(e,t){return e&&t?`${e}/${t}`:void 0}function A0(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,u=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${u} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function Td(e){return{keywords:e.keywords??[],projectId:Ed(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function xd(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function Cb(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function _d(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:u}=Cb(a),l=`${c}/${u}`,d=s,m=o.get(l);if(m||(m={id:l,owner:c,repo:u,matches:[]},o.set(l,m)),n||!s.matches?.length){m.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let p=!0,f=!1;for(let g of s.matches){if(!g.context)continue;let h={path:s.path,value:Sb(g.context)};g.positions?.length>0&&(h.matchIndices=g.positions.map(([R,b])=>({start:R,end:b,lineOffset:(g.context??"").substring(0,R).split(`
38
- `).length-1}))),r&&p&&d.url&&(h.url=d.url,p=!1),m.matches.push(h),f=!0}f||m.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...xd(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function wd(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Ad(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function Pb(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function Ld(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(Pb),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:Ed(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Eb(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function Tb(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function xb(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:Tb(e)}}function Od(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=Eb(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,u=xb(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(l=>({...l,...l.bodyPagination&&{bodyPagination:l.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...u&&{reviewSummary:u},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...xd(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function Id(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function kd(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function vd(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??Kt.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Fd(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[m])=>d==="."?-1:m==="."?1:d.localeCompare(m)).map(([d,m])=>({dir:d,files:m.files,folders:m.folders})),c=e.fileSizeMap,u={};if(c){for(let[d,m]of Object.entries(c))if(n[d]){let p=new Set(n[d].files);for(let[f,g]of Object.entries(m))p.has(f)&&(u[f]=g)}}let l={structure:a,...Object.keys(u).length>0&&{fileSizes:u},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(l.resolvedBranch=i),s&&(l.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(l.pagination=e.pagination),l}function _b(e,t,n,r){let o=Math.max(t,1),i=Math.max(n,0),s=Math.max(r,0),a=Math.max(1,Math.ceil(s/o)),c=s===0?0:Math.min(Math.max(e,0),Math.max(s-1,0));return{currentPage:s===0?1:Math.min(a,Math.floor(c/o)+1),totalPages:a,hasMore:e+i<s,charOffset:e,charLength:i,totalChars:s}}function k0({groups:e,getItems:t,setItems:n,getItemText:r,setItemText:o,charOffset:i,charLength:s,maxItems:a}){let c=r&&o?{get:r,set:o}:null,u=[],l=0;e.forEach((C,_)=>{l+=N(n(C,[]));for(let I of t(C)){let j=c?.get(I);if(c&&j!==void 0){let w=N(c.set(I,"")),A=j.length,Q=l,se=Q+w,$=se+A;u.push({groupIndex:_,item:I,textStart:se,textLen:A,start:Q,end:$}),l=$}else{let w=N(I),A=l;u.push({groupIndex:_,item:I,textStart:A,textLen:0,start:A,end:A+w}),l=A+w}}});let d=l,m=Math.max(s,1),p=Math.min(Math.max(i,0),d),f=Math.min(p+m,d),g=C=>{if(C.textLen===0||!c)return C.item;let _=Math.min(Math.max(p-C.textStart,0),C.textLen),I=Math.min(Math.max(f-C.textStart,0),C.textLen);if(_===0&&I===C.textLen)return C.item;let j=c.get(C.item)??"";return c.set(C.item,j.slice(_,I))},h=new Map,R=p,b=0,P=typeof a=="number"&&a>0?a:void 0;for(let C of u){if(C.end<=p)continue;if(C.start>=f)break;let _=h.get(C.groupIndex)??[];if(_.push(g(C)),h.set(C.groupIndex,_),R=Math.max(R,Math.min(C.end,f)),b+=1,P!==void 0&&b>=P){R=Math.max(R,C.end);break}}if(h.size===0&&p<d){let C=u.find(_=>_.end>p);C&&(h.set(C.groupIndex,[g(C)]),R=Math.max(R,Math.min(C.end,f)))}let x=[];return e.forEach((C,_)=>{let I=h.get(_);I&&x.push(n(C,I))}),{groups:x,pagination:_b(p,m,Math.max(0,R-p),d)}}function wb(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function $o(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=wb(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function Vo(e,t,n){let r=xr(e,[...t]);return{structuredContent:ot(e),text:r,isError:n}}function Md(e){return typeof e=="object"&&e!==null}function Ve(e){return typeof e=="string"&&e.length>0?e:void 0}function it(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ab(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}var Lb=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function Ob(e){if(!Md(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of Lb){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Ib(e,t){return`${e}/${t}`}function kb(e,t,n){let r=Ib(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function vb(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function Fb(e,t){let n=Ob(e.pagination),r=vb(n,t);return{path:Ve(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:Ve(e.localPath),repoRoot:Ve(e.repoRoot),...it(e.fileSize)!==void 0?{fileSize:it(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:it(e.totalLines),sourceChars:it(e.sourceChars),sourceBytes:it(e.sourceBytes),resolvedBranch:Ve(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:it(e.startLine),endLine:it(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:Ve(e.lastModified),lastModifiedBy:Ve(e.lastModifiedBy),warnings:Ab(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:Ve(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function Mb(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(Md).map(o=>({path:Ve(o.path)??"",size:it(o.size)??0,type:Ve(o.type)??"file"}));return{path:String(t.path??""),localPath:Ve(e.localPath)??"",repoRoot:Ve(e.repoRoot),fileCount:it(e.fileCount)??r.length,totalSize:it(e.totalSize)??0,...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:Ve(e.resolvedBranch)}}function Nb(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=kb(n,s,a),u=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(Mb(u,i)),c.directories=d;return}let l=c.files??[];l.push(Fb(u,i)),c.files=l}),Array.from(n.values())}function Db(e,t){return $o(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error}})}function Nd(){return({queries:e,results:t})=>{let n=Nb(t,e),r=Db(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),Vo(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}async function Dd(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{let s=Le(jo,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?Hb(a,n,c):Gb(a,n,c)}catch(s){return Ee(s,o,void 0,S.GITHUB_FETCH_CONTENT)}},{toolName:S.GITHUB_FETCH_CONTENT,finalize:Nd()},e)}async function Hb(e,t,n){let r=ae();if(!(r.local.enabled&&r.local.enableClone))return L("Directory fetch requires local clone support. Set ENABLE_LOCAL=true and ENABLE_CLONE=true.",e);if(!Qo(n,"fetchDirectoryToDisk"))return Ee(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",S.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return L("Directory fetch requires both owner and repo.",e,{rawResponse:0});let o=e.branch??await Ge(e.owner,e.repo,t),i=await Zu(e.owner,e.repo,String(e.path),o,t,!!e.forceRefresh),s={localPath:i.localPath,repoRoot:i.repoRoot,fileCount:i.fileCount,totalSize:i.totalSize,files:i.files,...i.cached?{cached:!0}:{},...e.branch!==i.branch?{resolvedBranch:i.branch}:{}};return Pe(e,s,!0,S.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??N(i)})}async function Gb(e,t,n){let r=await kt(e,()=>n.provider.getFileContent(Id(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await Ub(e,t):void 0,i={...kd(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Pe(e,i,s,S.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function Ub(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ge(e.owner,e.repo,t);return qu(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}function Bb(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function zb(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function Qb(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function jb(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,...n.queryId?{queryId:n.queryId}:{},matches:[a]})}return Array.from(t.values())}function $b(e,t,n){return t.length===0?[]:[{id:e.length===1&&typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",data:{files:jb(t),...n?{pagination:n}:{}}}]}function Vb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wb(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${Vb(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function Kb(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?Qb(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:Wb(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:Yb(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function Yb(e,t){return{...e,matches:t}}function Hd(){return({queries:e,results:t})=>{let n=[],r,o=0,i=[],s=!1;t.forEach((f,g)=>{if(f.status==="error")return;let h=Bb(f);h.incompleteResults&&(s=!0),h.results.reduce((P,x)=>P+x.matches.length,0)===0&&i.push({id:f.id,...h.nonExistentScope?{nonExistentScope:!0}:{},...h.incompleteResults?{incompleteResults:!0}:{}});let b=h.results;n.push({id:f.id,groups:b}),h.pagination&&(r=h.pagination,o+=1)});let a=Array.from(new Set(e.flatMap(f=>{let g=f.keywords;return Array.isArray(g)?g.filter(h=>typeof h=="string"):[]}))),c=Kb(zb(n),a),u=$o(t),l=r&&o===1?r:void 0,d=e.some(f=>f.concise===!0),m=$b(e,c,l);if(d)for(let f of m)f.data.files=f.data.files.map(g=>`${g.owner}/${g.repo}:${g.path}`);let p={results:m};return i.length>0&&(p.emptyQueries=i.map(({id:f,nonExistentScope:g,incompleteResults:h})=>({id:f,...g?{nonExistentScope:g}:{},...h?{incompleteResults:h}:{}}))),u.length>0&&(p.errors=u),s&&(p.warnings=[...Array.isArray(p.warnings)?p.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),Vo(p,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],c.length===0&&u.length>0)}}function Xb(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function Jb(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function Gd(e){let{queries:t}=e,n=$e(e.authInfo);return J(t,async(r,o)=>{try{let i=Jb(r);if(i)return L(i.error,r);if(!Xb(r))return L("At least one search term or scope filter is required.",r);let s=n(),a=await kt(r,()=>s.provider.searchCode(Td(r)));if(a.ok===!1)return a.result;let c=_d(a.response.data,r);return Pe(r,c,c.results.length>0,S.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Ee(i,r,void 0,S.GITHUB_SEARCH_CODE)}},{toolName:S.GITHUB_SEARCH_CODE,finalize:Hd()},e)}import{z as k}from"zod";import{GitHubCodeSearchQuerySchema as Ud}from"@octocodeai/octocode-core/schemas";var Bd={limit:v(1,100).optional(),page:q.default(1)},zd=re(Ud,Bd),Qd=X(ce(Ud,Bd)),lF=k.object({base:k.string().optional(),shared:k.record(k.string(),k.union([k.string(),k.number(),k.boolean()])).optional(),responsePagination:Ae.responsePagination,results:k.array(k.object({id:k.string(),data:k.object({files:k.array(k.object({owner:k.string(),repo:k.string(),path:k.string(),queryId:k.string().optional(),matches:k.array(k.object({value:k.string().optional(),pathOnly:k.boolean().optional(),matchIndices:k.array(k.object({start:k.number(),end:k.number(),lineOffset:k.number()})).optional(),url:k.string().optional()}))})),pagination:k.object({currentPage:k.number(),totalPages:k.number(),perPage:k.number(),totalMatches:k.number(),reportedTotalMatches:k.number().optional(),reachableTotalMatches:k.number().optional(),totalMatchesKind:k.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:k.boolean().optional(),hasMore:k.boolean(),nextPage:k.number().optional(),uniqueFileCount:k.number().optional()}).optional()})})),emptyQueries:k.array(k.object({id:k.string(),nonExistentScope:k.literal(!0).optional(),incompleteResults:k.literal(!0).optional()})).optional(),warnings:k.array(k.string()).optional(),errors:k.array(k.object({id:k.string(),error:k.string()})).optional()});function Zb(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function qb(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function eS(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function jd(e){let{content:t,reviewMode:n}=e,r=Zb(t,n),o=qb(t,n),i=eS(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}function pF(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}function js(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function Ko(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function $s(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function Xo(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Vd(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Wd(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function tS(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Yo(e,t,n){return tS({...Wd(e,t),...n})}function $d(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return Yo(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function zs(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return Yo(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function nS(e,t,n){return{target:Wd(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function Wo(e){return String(e.path??e.filename??"")}function rS(e,t){return{path:Wo(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function oS(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function iS(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=oS(r,n.comments),i=js(t),s=i?o.filter(u=>Ko(u.body,i)):o,{items:a,pagination:c}=$s(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(u=>{let l=Xo(typeof u.body=="string"?u.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:u.id,author:u.author,commentType:u.commentType??"discussion",path:u.path,line:u.line,...u.in_reply_to_id!=null?{in_reply_to_id:u.in_reply_to_id}:{},...l?{body:l.content,bodyPagination:l.pagination}:{bodyPreview:Vd(typeof u.body=="string"?u.body:"")},createdAt:u.createdAt,updatedAt:u.updatedAt}}),commentPagination:c}}function sS(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=js(t);return{reviews:(o?r.filter(s=>Ko(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=Xo(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function aS(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=$s(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function cS(e){return e.split(`
33
+ `):e.structuredContent!==void 0?JSON.stringify(e.structuredContent,null,2):JSON.stringify(e,null,2)}function Xo(e,t){let n=Cr(e)??{},r=ht(n),o=Fh(),i="results"in r?["results","id","status","data"]:["instructions","status","data"];return o==="json"?JSON.stringify(Ws(r,t||i),null,2):F.jsonToYamlString(r,{keysPriority:t||i})}function Ws(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(o=>Ws(o,t));if(typeof e!="object")return e;let n=e,r={};for(let o of t)o in n&&(r[o]=Ws(n[o],t));for(let o of Object.keys(n))o in r||(r[o]=Ws(n[o],t));return r}function dT(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return n.length===0||!n.every(r=>uT.has(r))||t.hasMore!==!1?!1:typeof t.totalPages=="number"?t.totalPages<=1:"charOffset"in t||"nextCharOffset"in t?(t.charOffset??0)===0:!0}function Cr(e,t={}){if(e==null||Number.isNaN(e))return;let{inFilesObject:n=!1,depth:r=0}=t;if(Array.isArray(e)){let o=e.map(s=>Cr(s,{inFilesObject:n,depth:r+1})).filter(s=>s!==void 0),i=n&&r>=2;return o.length>0||i?o:void 0}if(typeof e=="object"&&e!==null){let o={},i=!1;for(let[s,a]of Object.entries(e)){if(s==="results"&&r===0&&Array.isArray(a)&&a.length===0){o[s]=[],i=!0;continue}if(dT(a))continue;let c=(s==="files"||s==="repositories")&&!n,l=Cr(a,{inFilesObject:n||c,depth:c?0:r+1});l!==void 0&&(o[s]=l,i=!0)}return i?o:void 0}return e}var $s,qs,dj,uT,Jo=y(()=>{"use strict";_e();be();Pu();$s={system(e,t=1){return{type:"text",text:e,annotations:{audience:["assistant"],priority:t,role:"system"}}},assistant(e,t=.8){return{type:"text",text:e,annotations:{audience:["assistant","user"],priority:t,role:"assistant"}}},user(e,t=.6){return{type:"text",text:e,annotations:{audience:["user"],priority:t,role:"user"}}},data(e,t){let n=t??Fh(),r;try{r=n==="yaml"?F.jsonToYamlString(Cr(e)):JSON.stringify(Cr(e),null,2)}catch{r=`error: "Data serialization failed"
34
+ `}return{type:"text",text:lT(r),annotations:{audience:["assistant"],priority:.3,role:"assistant"}}}},qs={success:"\u2705",empty:"\u{1F4ED}",error:"\u274C",partial:"\u26A0\uFE0F",searching:"\u{1F50D}",loading:"\u23F3",info:"\u2139\uFE0F",file:"\u{1F4C4}",folder:"\u{1F4C1}",page:"\u{1F4C3}",definition:"\u{1F3AF}",reference:"\u{1F517}",call:"\u{1F4DE}"};dj={success(e,t,n){return Vs({system:n?{hints:n}:void 0,assistant:{summary:e},user:{message:"Operation completed",emoji:qs.success},data:t})},empty(e,t){return Vs({system:{hints:t||["Try broader search terms","Check spelling"]},assistant:{summary:e},user:{message:"No results found",emoji:qs.empty},data:{status:"empty",results:[]}})},error(e,t){return Vs({system:{instructions:"Tool execution failed. Error details provided for self-correction."},assistant:{summary:`Error: ${e}`},user:{message:"An error occurred",emoji:qs.error},data:{status:"error",error:e,details:t},isError:!0})},paginated(e,t,n,r){return Vs({system:{pagination:{currentPage:n.page,totalPages:n.total,hasMore:n.hasMore},hints:r},assistant:{summary:e},user:{message:`Page ${n.page} of ${n.total}`,emoji:n.hasMore?"\u{1F4C4}":qs.success},data:t})}};uT=new Set(["currentPage","totalPages","perPage","itemsPerPage","entriesPerPage","filesPerPage","totalMatches","totalFiles","totalEntries","totalItems","totalResults","totalReferences","reportedTotalMatches","reachableTotalMatches","totalMatchesKind","totalMatchesCapped","hasMore","nextPage","charOffset","charLength","totalChars","totalBytes","nextCharOffset"])});import{z as Ks}from"zod";function G(e,t){return Ks.preprocess(n=>typeof n=="number"&&Number.isFinite(n)?Math.min(Math.max(n,e),t):n,Ks.number().int().min(e).max(t))}function ie(e,t={}){let{maxQueries:n=5}=t;return Ks.object({queries:Ks.array(e).min(1).max(n).describe("Parallel queries."),...pT}).superRefine((r,o)=>{let i=new Set;r.queries.forEach((s,a)=>{s&&typeof s=="object"&&"id"in s&&typeof s.id=="string"&&(i.has(s.id)&&o.addIssue({code:"custom",message:`Duplicate query id "${s.id}" at index ${a}`,path:["queries",a,"id"]}),i.add(s.id))})})}var ae,Pr,xr,pT,Be=y(()=>{"use strict";me();ae=G(1,1e3).optional().default(1),Pr=G(0,100).optional(),xr=G(1,1e9).optional(),pT={responseCharOffset:G(0,1e8).optional().describe("Full-response char offset; re-call with returned value when hasMore."),responseCharLength:G(1,5e4).optional().describe("Full-response char window.")}});import{z as Ae}from"zod";function Rj(e){return e.extend(Qe)}var fT,Qe,Gt=y(()=>{"use strict";fT=Ae.object({currentPage:Ae.number(),totalPages:Ae.number(),hasMore:Ae.boolean(),charOffset:Ae.number(),charLength:Ae.number(),totalChars:Ae.number(),nextCharOffset:Ae.number().optional()}).optional(),Qe={hints:Ae.array(Ae.string()).optional(),base:Ae.string().optional(),shared:Ae.record(Ae.string(),Ae.union([Ae.string(),Ae.number(),Ae.boolean()])).optional(),responsePagination:fT}});function mT(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"&&("type"in e||"status"in e||"scopesSuggestion"in e)}function M(e,t,n={}){let{extra:r}=n,o={status:"error"};if(mT(e))o.error=e;else if(_c(e))o.error=e.message,o.errorCode=e.errorCode;else if(typeof e=="string")o.error=e;else if(e instanceof Error){let i=Rf(e);o.error=i.message,o.errorCode=i.errorCode}else o.error="Unknown error occurred";if(r){let{hints:i,...s}=r;Object.assign(o,s)}return n.rawResponse===void 0?o:$(o,n.rawResponse)}function Ue(e,t,n={}){let r=e.safeParse(t);if(r.success)return{ok:!0,data:r.data};let o=r.error.issues.map(s=>s.message).join("; "),i=n.prefix===!1?o:`Validation error: ${o}`;return{ok:!1,error:M(i,t,{toolName:n.toolName})}}var Ys=y(()=>{"use strict";eo();oe()});async function Tj(e,t,n){if(e)try{await e(t,n)}catch{return}}function Fe(e,t,n,r,o){let i=n?void 0:"empty",s={...i!==void 0?{status:i}:{},...t};return o?.rawResponse===void 0?s:$(s,o.rawResponse)}function Xs(e,t){let n={error:e.error||"Provider error",type:"http",status:e.status,rateLimitRemaining:e.rateLimit?.remaining,rateLimitReset:e.rateLimit?.reset?e.rateLimit.reset*1e3:void 0,retryAfter:e.rateLimit?.retryAfter};return M(n,t,{rawResponse:e.rawResponseChars??e.data??(e.error?e:void 0)})}function Me(e,t,n,r){let o=e instanceof Error?e.message:"Unknown error occurred",i=n?`${n}: ${o}`:o;return M(i,t)}var De=y(()=>{"use strict";Ys();oe()});async function Ve({toolName:e,query:t,execute:n,contextMessage:r}){try{return await n()}catch(o){return Me(o,t,r,e)}}var Ht=y(()=>{"use strict";De()});import{spawn as xu}from"child_process";function Eu(e={},t=Js){let n={};for(let o of t){let i=process.env[o];i!==void 0&&(n[o]=i)}let r=new Set(t);for(let[o,i]of Object.entries(e))r.has(o)&&(i===void 0?delete n[o]:n[o]=i);return n}function vn(e,t,n={}){let{timeout:r=3e4,cwd:o,env:i={},allowEnvVars:s=Js,maxOutputSize:a=gT}=n;return new Promise(c=>{let l={killed:!1,stdoutChunks:[],stderrChunks:[],totalOutputSize:0},u=()=>l.stdoutChunks.join(""),d=()=>l.stderrChunks.join(""),p={cwd:o,env:Eu(i,s),stdio:["ignore","pipe","pipe"]},f;try{f=xu(e,t,p)}catch(S){c({stdout:"",stderr:"",exitCode:null,success:!1,error:S instanceof Error?S:new Error(`Failed to spawn command '${e}'`)});return}let m,g=setTimeout(()=>{if(!l.killed){l.killed=!0;try{f.kill("SIGTERM")}catch{}m=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},wu),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error(`Command timeout after ${r}ms`),timedOut:!0})}},r),b=()=>{clearTimeout(g),m!==void 0&&(clearTimeout(m),m=void 0)},C=()=>{if(l.totalOutputSize>a){if(!l.killed){l.killed=!0;try{f.kill("SIGKILL")}catch{}b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:new Error("Output size limit exceeded"),outputLimitExceeded:!0})}return!0}return!1};f.stdout?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!C()&&l.stdoutChunks.push(T)}),f.stderr?.on("data",S=>{if(l.killed)return;let T=S.toString();l.totalOutputSize+=Buffer.byteLength(T),!C()&&l.stderrChunks.push(T)}),f.on("close",S=>{l.killed||(b(),c({stdout:u(),stderr:d(),exitCode:S,success:S===0}))}),f.on("error",S=>{l.killed||(l.killed=!0,b(),c({stdout:u(),stderr:d(),exitCode:null,success:!1,error:S}))})})}function Dh(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,{allowEnvVars:s=Js}=r,a;try{a=xu(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Eu({},s)})}catch{o(!1);return}let c,l=()=>{clearTimeout(u),c!==void 0&&(clearTimeout(c),c=void 0)},u=setTimeout(()=>{if(!i){i=!0;try{a.kill("SIGTERM")}catch{}c=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}},wu),o(!1)}},n);a.on("close",d=>{l(),i||o(d===0)}),a.on("error",()=>{l(),i||o(!1)})})}function Fj(e,t,n=1e4,r={}){return new Promise(o=>{let i=!1,s=[],a=0,{allowEnvVars:c=Zo,maxOutputSize:l=hT}=r,u;try{u=xu(e,t,{stdio:["ignore","pipe","pipe"],timeout:n,env:Eu({},c)})}catch{o(null);return}let d,p=()=>{clearTimeout(f),d!==void 0&&(clearTimeout(d),d=void 0)};u.stdout?.on("data",m=>{if(i)return;let g=m.toString();if(a+=Buffer.byteLength(g),a>l){if(!i){i=!0;try{u.kill("SIGKILL")}catch{}p(),o(null)}return}s.push(g)}),u.stderr?.on("data",()=>{});let f=setTimeout(()=>{if(!i){i=!0;try{u.kill("SIGTERM")}catch{}d=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},wu),o(null)}},n);u.on("close",m=>{if(p(),!i)if(m===0){let g=s.join("").trim();o(g||null)}else o(null)}),u.on("error",()=>{p(),i||o(null)})})}function Zs(e,t=1e3){for(let n of e){if(n.includes("\0"))return{valid:!1,error:"Null bytes not allowed in arguments"};if(n.length>t)return{valid:!1,error:"Argument too long"}}return{valid:!0}}var Ij,Js,Zo,Mh,gT,wu,hT,ei=y(()=>{"use strict";Ij=["NODE_OPTIONS","GITHUB_TOKEN","GH_TOKEN","OCTOCODE_TOKEN","GITHUB_PERSONAL_ACCESS_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],Js=["PATH","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT"],Zo=[...Js,"HOME","USERPROFILE","APPDATA","LOCALAPPDATA"],Mh=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"],gT=10*1024*1024,wu=5e3;hT=1*1024*1024});import{existsSync as yT,mkdirSync as Tu,renameSync as bT,rmSync as RT}from"fs";import{join as ti}from"path";import{createHash as ST}from"crypto";async function zh(e,t,n){let r=e.owner,o=e.repo,{sparsePath:i,forceRefresh:s}=e;await IT();let a=e.branch??await Ze(r,o,t),c=Cn(),l=Rg(c,r,o,a,i);return ET(c,l,async()=>{let u=Do(l);if(!s&&u.hit&&u.meta.source==="clone")return{localPath:l,cached:!0,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}};Es(c),Tn(l);let d=_T(t,n),p=kT(c,l);Ts(p);try{if(i){if(await LT(r,o,a,p,i,d),!yT(ti(p,i)))throw new Error(`sparsePath "${i}" does not exist in ${r}/${o}@${a} \u2014 nothing was checked out for it. Verify the path with ghViewRepoStructure, then retry with the correct sparsePath (or omit it for a full clone).`)}else await AT(r,o,a,p,d);let f=No(r,o,a,"clone",i);return Mo(p,f),OT(p,l),{localPath:l,cached:!1,owner:r,repo:o,branch:a,...i?{sparsePath:i}:{}}}catch(f){throw Ts(p),f}})}async function ET(e,t,n){Tn(t);let r=TT(e,t);Tu(ti(e,"tmp",Gh),{recursive:!0,mode:448});let o=Date.now();for(;;)try{Tu(r,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()-o>PT)throw new Error(`Timed out waiting for clone cache lock '${r}'.`);await vT(xT)}try{return await n()}finally{RT(r,{recursive:!0,force:!0})}}function Bh(e){return ST("sha256").update(e).digest("hex").slice(0,16)}function TT(e,t){return ti(e,"tmp",Gh,Bh(t))}function kT(e,t){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,r=ti(e,"tmp",wT);return Tu(r,{recursive:!0,mode:448}),ti(r,`${Bh(t)}-${n}`)}function OT(e,t){Ts(t),Tn(t),bT(e,t)}function vT(e){return new Promise(t=>setTimeout(t,e))}async function AT(e,t,n,r,o){let i=Uh(o);i.push("clone","--depth","1","--single-branch","--branch",n,"--",Qh(e,t),r),await ku(i,Nh,`full clone of ${e}/${t}`,o)}async function LT(e,t,n,r,o,i){let s=Uh(i);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",Qh(e,t),r),await ku(s,Nh,`sparse clone of ${e}/${t}`,i),await ku(["-C",r,"sparse-checkout","set","--skip-checks","--",o],CT,`sparse-checkout set ${o}`,void 0)}function Qh(e,t){return`https://github.com/${e}/${t}.git`}function Uh(e){return e?["-c",`http.extraHeader=Authorization: Bearer ${e}`]:[]}function _T(e,t){return e?.token&&typeof e.token=="string"?e.token:t}async function IT(){try{if(!(await vn("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Hh,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function FT(e,t){let n=e;return t&&(n=n.replaceAll(t,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function ku(e,t,n,r){let o=await vn("git",e,{timeout:t,maxOutputSize:5242880,allowEnvVars:Hh,env:{GIT_TERMINAL_PROMPT:"0"}});if(!o.success){let i=FT(o.stderr?.trim()||"",r),s=i?`: ${i}`:"";throw new Error(`git ${n} failed${s}`)}}var Nh,CT,PT,xT,Gh,wT,Hh,Ou=y(()=>{"use strict";_e();Ge();ei();ks();Nh=120*1e3,CT=30*1e3,PT=300*1e3,xT=100,Gh="clone-locks",wT="clone-tmp",Hh=[...Zo,"GIT_TERMINAL_PROMPT"]});async function jh(e,t={}){if(!Array.isArray(e))throw new Error(Xr.PROMISES_NOT_ARRAY.message);if(e.length===0)return[];let{timeout:n=3e4,concurrency:r=e.length,onError:o}=t;if(n<=0)throw new Error(Xr.TIMEOUT_NOT_POSITIVE.message);if(r<=0)throw new Error(Xr.CONCURRENCY_NOT_POSITIVE.message);let i=e.map((c,l)=>typeof c=="function"?c:()=>Promise.reject(new Error(Zr.NOT_A_FUNCTION.message(l))));if(r<i.length)return MT(i,r,n,o);let s=i.map((c,l)=>$h(c,l,n,o));return(await Promise.allSettled(s)).map((c,l)=>c.status==="fulfilled"?c.value:{success:!1,error:c.reason instanceof Error?c.reason:new Error(String(c.reason)),index:l})}async function $h(e,t,n,r){let o,i=()=>{o!==void 0&&(clearTimeout(o),o=void 0)};try{let s=new Promise((c,l)=>{o=setTimeout(()=>{l(new Error(Zr.TIMEOUT.message(t,n)))},n)}),a=await Promise.race([e(),s]);return i(),{success:!0,data:a,index:t}}catch(s){i();let a=s instanceof Error?s:new Error(String(s));if(r)try{r(a,t)}catch(c){}return{success:!1,error:a,index:t}}}async function MT(e,t,n,r){let o=new Array(e.length),i=0,s=async()=>{for(;i<e.length;){let c=i++,l=e[c];if(!l){o[c]={success:!1,error:new Error(Zr.FUNCTION_UNDEFINED.message),index:c};continue}try{let u=await $h(l,c,n,r);o[c]=u}catch(u){o[c]={success:!1,error:u instanceof Error?u:new Error(String(u)),index:c}}}},a=[];for(let c=0;c<Math.min(t,e.length);c++)a.push(s());return await Promise.all(a),o}var vu=y(()=>{"use strict";pt()});function DT(e){if(e.length===0)return"";let t=e[0]??"";for(let r=1;r<e.length;r++){let o=e[r]??"",i=0,s=Math.min(t.length,o.length);for(;i<s&&t[i]===o[i];)i++;if(t=t.slice(0,i),t==="")break}let n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function Au(e,t,n){if(n>8||!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Au(o,t,n+1);return}let r=e;for(let o of Lu){let i=r[o];typeof i=="string"&&(i.startsWith("file:///")?(r[o]=i.slice(7),t.push({obj:r,key:o})):i.startsWith("/")&&t.push({obj:r,key:o}))}for(let[o,i]of Object.entries(r))qh.has(o)||i&&typeof i=="object"&&Au(i,t,n+1)}function Vh(e){let t=[];for(let i of e)Au(i?.data,t,0);if(t.length===0)return;let n=DT(t.map(i=>i.obj[i.key]));if(n.length<=1)return;let r=n+"/",o=r.length;for(let{obj:i,key:s}of t){let a=i[s];a.startsWith(r)&&(i[s]=a.slice(o))}return NT(e,r),n}function NT(e,t){function n(r,o){if(o>8||!r||typeof r!="object")return;if(Array.isArray(r)){for(let s=0;s<r.length;s++){let a=r[s];if(typeof a=="string"){let c="file://"+t;a.includes(c)?r[s]=a.replaceAll(c,""):a.includes(t)&&(r[s]=a.replaceAll(t,""))}else n(a,o+1)}return}let i=r;for(let s of Object.keys(i)){if(qh.has(s))continue;let a=i[s];typeof a=="string"?!Lu.includes(s)&&a.includes(t)&&(i[s]=a.replaceAll(t,"")):n(a,o+1)}}for(let r of e)n(r?.data,0)}function GT(e){let t=[];for(let n of e){let r=n?.data;if(!(!r||typeof r!="object")){for(let o of Object.values(r))if(Array.isArray(o))for(let i of o)i&&typeof i=="object"&&!Array.isArray(i)&&t.push(i)}}return t}function HT(e){return typeof e=="string"&&e!==""||typeof e=="number"||typeof e=="boolean"}function Wh(e){let t=GT(e);if(t.length<2)return;let n=t[0],r;for(let i of Object.keys(n)){if(zT.has(i))continue;let s=n[i];HT(s)&&t.every(a=>a[i]===s)&&((r??={})[i]=s)}if(!r)return;let o=Object.keys(r);for(let i of t)for(let s of o)delete i[s];return r}var Lu,qh,zT,_u=y(()=>{"use strict";Lu=["path","uri"],qh=new Set(["next","location"]);zT=new Set([...Lu,"owner","repo","name","id"])});function jT(e,t,n){if(e<=1)return Kh;let r=Math.min(Math.max(t,1),e),o=Math.ceil(e/r),i=Math.floor(QT/o),s=Math.max(UT,Math.min(i,Kh));return n?Math.max(s,n):s}async function se(e,t,n,r){let o=n.concurrency??BT,{results:i,errors:s}=await WT(e,t,o,n.minQueryTimeoutMs);return $T(n,i,s,e,r)}function $T(e,t,n,r,o){let i=["results","base","shared"],s=["id","status","data"],a=[...new Set([...i,...s,...e.keysPriority||[]])],c=new Array(r.length);t.forEach(g=>{let b=g.result.status;c[g.queryIndex]={id:Zh(g.originalQuery,g.queryIndex),...b!==void 0?{status:b}:{},data:KT(g.result)}}),n.forEach(g=>{let b=r[g.queryIndex];b&&(c[g.queryIndex]={id:Zh(b,g.queryIndex),status:"error",data:{error:g.error}})});let l=c.filter(g=>g!==void 0);if(e.finalize){let g=e.finalize({queries:r,results:l,config:e}),b=Yh(g.text,o),C=Xh(g.structuredContent,b.pagination);return Jh(e.toolName,t,n,b.text.length),{content:[{type:"text",text:b.text}],structuredContent:C,isError:g.isError??(l.length>0&&l.every(T=>T.status==="error"))}}let u={results:l};if(Array.isArray(u.results)){let g=Vh(u.results);g&&(u.base=g);let b=Wh(u.results);b&&(u.shared=b)}let d=Xo(u,a),p=Yh(d,o),f=Xh(ht(u),p.pagination);return Jh(e.toolName,t,n,p.text.length),{content:[{type:"text",text:p.text}],structuredContent:f,isError:l.length>0&&l.every(g=>g.status==="error")}}function Iu(e,t,n){let r=Math.min(t+n,e.length);if(r>=e.length)return e.length;let o=Math.max(1,Math.floor(n/2)),i=[e.lastIndexOf(`
35
+ `,r-1)+1,e.lastIndexOf("\\n",r-1)+2].filter(a=>a>t&&a<=r),s=Math.max(...i,-1);return s-t>=o?s:r}function qT(e,t,n){let r=1,o=0;for(;o<t&&o<e.length;){let i=Iu(e,o,n);if(i<=o)break;o=i,r+=1}return o===t?r:Math.floor(t/n)+1}function VT(e,t){if(e.length===0)return 1;let n=0,r=0;for(;r<e.length;){let o=Iu(e,r,t);if(o<=r)return Math.max(1,Math.ceil(e.length/t));r=o,n+=1}return Math.max(1,n)}function Yh(e,t){let n=t?.responseCharLength,r=t?.responseCharOffset??0;if(n===void 0)return{text:e};let o=e.length,i=Math.max(1,n),s=Math.min(Math.max(0,r),o),a=Iu(e,s,i),c=a<o,l=qT(e,s,i),u=VT(e,i),d=e.slice(s,a);return{text:`${c?`# Response page ${l}/${u}. Next: responseCharOffset=${a}
36
+ `:`# Response page ${l}/${u}.
37
+ `}${d}`,pagination:{currentPage:l,totalPages:u,hasMore:c,charOffset:s,charLength:a-s,totalChars:o,...c?{nextCharOffset:a}:{}}}}function Xh(e,t){return t?{...e,responsePagination:t}:e}function Jh(e,t,n,r){let o=t.reduce((i,s)=>i+(le(s.result)??U(s.result)),0)+n.reduce((i,s)=>i+U(s),0);try{as(e,o,r)}catch{}}async function WT(e,t,n,r){let o=[],i=[];if(!e||e.length===0)return{results:o,errors:i};let s=e.map((c,l)=>()=>t(c,l).then(u=>({result:u,queryIndex:l,originalQuery:c})));return(await jh(s,{timeout:jT(e.length,n,r),continueOnError:!0,concurrency:n,onError:(c,l)=>{i.push({queryIndex:l,error:c.message})}})).forEach(c=>{c.success&&c.data&&o.push({result:c.data.result,queryIndex:c.data.queryIndex,originalQuery:c.data.originalQuery})}),{results:o,errors:i}}function KT(e){let t=new Set(["status","mainResearchGoal","researchGoal","reasoning","researchSuggestions","query"]);e.status!=="error"&&t.add("error");let n={};for(let[r,o]of Object.entries(e))t.has(r)||(n[r]=o);return n}function Zh(e,t){let r=e.id;return typeof r=="string"&&r.trim().length>0?r:typeof r=="number"&&Number.isFinite(r)?String(r):`q${t+1}`}var BT,Kh,QT,UT,je=y(()=>{"use strict";_e();vu();Jo();oe();_u();BT=3,Kh=parseInt(process.env.OCTOCODE_BULK_QUERY_TIMEOUT_MS||"60000",10)||6e4,QT=parseInt(process.env.OCTOCODE_TOOL_TIMEOUT_MS||"60000",10)||6e4,UT=5e3});function ea(e){return e.data!==void 0&&!e.error}function YT(e){return e.error!==void 0}var Fu=y(()=>{"use strict"});import{maskSensitiveData as ey}from"@octocodeai/octocode-engine/mask";function XT(){return Cl().provider??Sl()}function JT(e){let t=Cl(),n=t.provider??Sl(),{baseUrl:r,token:o}=t;try{let i=Cu(n,{type:n,baseUrl:r,token:o,authInfo:e});return{providerType:n,provider:i,capabilities:i.capabilities,baseUrl:r,token:o,authInfo:e}}catch(i){let s=i instanceof Error?i.message:"Unknown provider error",a=ey(s);throw new Mu(n,`Failed to initialize ${n} provider: ${a}`)}}function at(e){let t;return()=>t??=JT(e)}function ta(e,t){return e.capabilities[t]}async function tn(e,t){let n=await t();return ea(n)?{ok:!0,response:n}:{ok:!1,result:Xs(n,e)}}async function ty(e,t){let n=t??XT(),r=await Promise.all(e.map(async s=>{try{return{meta:s.meta,response:await s.operation()}}catch(a){let c=a instanceof Error?a.message:String(a);return{meta:s.meta,response:{error:ey(c),status:500,provider:n}}}})),o=[],i=[];for(let s of r)ea(s.response)?o.push({meta:s.meta,response:s.response}):i.push({meta:s.meta,response:s.response});return{successes:o,failures:i}}var Mu,nn=y(()=>{"use strict";js();Fu();dr();De();Mu=class extends Error{providerType;constructor(t,n){super(n),this.name="ProviderInitializationError",this.providerType=t}}});async function ny(e){let{queries:t,authInfo:n}=e,r=at(n);return se(t,async(o,i)=>Ve({toolName:A.GITHUB_CLONE_REPO,query:o,contextMessage:`Clone failed for ${o.owner}/${o.repo}`,execute:async()=>{let s=r();if(!ta(s,"cloneRepo"))return Me(new Error("ghCloneRepo is only available with the GitHub provider."),o,"Provider not supported",A.GITHUB_CLONE_REPO);let a;try{a=await zh(o,n,s.token)}catch(p){let f=p instanceof Error?p.message:String(p);return M(`Clone failed for ${o.owner}/${o.repo}: ${f}`,o)}let c=To(a.localPath),l={kind:o.sparsePath?"tree":"repo",localPath:a.localPath,repoRoot:a.localPath,source:"clone",cached:a.cached,complete:!o.sparsePath,resolvedBranch:a.branch,...o.sparsePath?{requestedPath:o.sparsePath}:{}},u={localSearch:{tool:"localSearchCode",query:{path:a.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:a.localPath}}},d={owner:o.owner,repo:o.repo,localPath:a.localPath,resolvedBranch:a.branch,cached:a.cached,...o.sparsePath?{sparsePath:o.sparsePath}:{},totalSize:c,location:l,next:u};return Fe(o,d,!0,A.GITHUB_CLONE_REPO,{rawResponse:c})}}),{toolName:A.GITHUB_CLONE_REPO,keysPriority:["localPath","resolvedBranch","cached","sparsePath","totalSize","fileCount","location","error"]},e)}var Du=y(()=>{"use strict";_e();fe();je();De();Ht();nn();Ou()});import{z as ry}from"zod";function ZT(e,t){return e?.description&&!t.description?t.describe(e.description):t}function oy(e,t){let n={};for(let[r,o]of Object.entries(t))n[r]=ZT(e.shape[r],o);return n}function ek(e,t){let n=e;return n.safeExtend?n.safeExtend(t):e.extend(t)}function iy(e,t){if(!t?.length)return e;let n=new Set(t);return ry.object(Object.fromEntries(Object.entries(e.shape).filter(([r])=>!n.has(r))))}function ue(e,t={},n={}){let r=iy(e,n.omit),o=ek(r,oy(r,t));return n.strict?o.strict():o}function he(e,t={},n={}){let r=iy(e,n.omit),o=ry.object({...r.shape,...oy(r,t)});return n.strict?o.strict():o}var tt=y(()=>{"use strict"});import{CloneRepoQuerySchema as tk}from"@octocodeai/octocode-core/schemas";import{GitHubCloneRepoOutputSchema as nk}from"@octocodeai/octocode-core/schemas/outputs";var ni,na,C$,ra=y(()=>{"use strict";Be();tt();Gt();ni=ue(tk),na=ie(ni),C$=nk.extend(Qe)});import{z as E}from"zod";import{FileContentQuerySchema as sy}from"@octocodeai/octocode-core/schemas";var rk,ok,ik,sk,ay,ak,wr,oa,v$,ri=y(()=>{"use strict";me();Be();tt();Gt();rk=E.enum(["none","standard","symbols"]).optional().default("standard"),ok=E.object({currentPage:E.number(),totalPages:E.number(),hasMore:E.boolean(),nextPage:E.number().optional(),nextMatchPage:E.number().optional(),charOffset:E.number().optional(),charLength:E.number().optional(),totalChars:E.number().optional(),nextCharOffset:E.number().optional(),filesPerPage:E.number().optional(),totalFiles:E.number().optional(),entriesPerPage:E.number().optional(),totalEntries:E.number().optional(),matchesPerPage:E.number().optional(),totalMatches:E.number().optional()}),ik=E.object({path:E.string(),content:E.string(),localPath:E.string().optional(),repoRoot:E.string().optional(),contentView:E.enum(["none","standard","symbols"]).optional(),isSkeleton:E.boolean().optional(),totalLines:E.number().optional(),sourceChars:E.number().optional(),sourceBytes:E.number().optional(),resolvedBranch:E.string().optional(),pagination:ok.optional(),isPartial:E.boolean().optional(),startLine:E.number().optional(),endLine:E.number().optional(),matchRanges:E.array(E.object({start:E.number(),end:E.number()})).optional(),lastModified:E.string().optional(),lastModifiedBy:E.string().optional(),warnings:E.array(E.string()).optional(),matchNotFound:E.boolean().optional(),searchedFor:E.string().optional(),cached:E.boolean().optional()}),sk=E.object({path:E.string(),localPath:E.string(),repoRoot:E.string().optional(),fileCount:E.number(),totalSize:E.number(),complete:E.boolean().optional(),directoryEntryCount:E.number().optional(),eligibleFileCount:E.number().optional(),savedFileCount:E.number().optional(),skipped:E.object({nonFile:E.number(),missingDownloadUrl:E.number(),oversized:E.number(),binary:E.number(),fileLimit:E.number(),fetchFailed:E.number(),totalSizeLimit:E.number(),pathTraversal:E.number()}).optional(),limits:E.object({maxDirectoryFiles:E.number(),maxTotalSize:E.number(),maxFileSize:E.number()}).optional(),warnings:E.array(E.string()).optional(),files:E.array(E.object({path:E.string(),size:E.number(),type:E.string()})).optional(),cached:E.boolean().optional(),resolvedBranch:E.string().optional()}),ay={startLine:xr,endLine:xr,contextLines:Pr,charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:rk},ak=he(sy,ay),wr=ue(sy,ay),oa=ie(ak),v$=E.object({base:E.string().optional(),shared:E.record(E.string(),E.union([E.string(),E.number(),E.boolean()])).optional(),responsePagination:Qe.responsePagination,results:E.array(E.object({id:E.string(),data:E.object({owner:E.string(),repo:E.string(),files:E.array(ik).optional(),directories:E.array(sk).optional()}).optional()})),errors:E.array(E.object({id:E.string(),owner:E.string().optional(),repo:E.string().optional(),path:E.string().optional(),error:E.string()})).optional()})});function ck(e,t=500){if(t<=0)return"";let n=[...e];return n.length<=t?e:t<=3?".".repeat(t):n.slice(0,t-3).join("")+"..."}function cy(e,t){return e&&t?`${e}/${t}`:void 0}function I$(e,t){if(e.totalPages<=1)return[];let n=[],r=e.entriesPerPage||e.perPage||10,o=e.totalMatches,i=e.reportedTotalMatches,s=e.reachableTotalMatches,a=(e.currentPage-1)*r+1,c=typeof o=="number"?Math.min(e.currentPage*r,o):e.currentPage*r,l=typeof o!="number"?"total unknown":e.totalMatchesKind==="lowerBound"?`at least ${o}`:typeof i=="number"&&typeof s=="number"&&i>s?`${s} reachable; GitHub reports ${i}`:`${o}`;return e.hasMore&&n.push(typeof o=="number"?`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} of ${l} ${t}). Next: page=${e.currentPage+1}; page through before exhaustive claims.`:`Page ${e.currentPage}/${e.totalPages} (showing ${a}-${c} ${t}; total unknown). Next: page=${e.currentPage+1}; page through before exhaustive claims.`),n}function ly(e){return{keywords:e.keywords??[],projectId:cy(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function uy(e){return{...typeof e?.reportedTotalMatches=="number"?{reportedTotalMatches:e.reportedTotalMatches}:{},...typeof e?.reachableTotalMatches=="number"?{reachableTotalMatches:e.reachableTotalMatches}:{},...e?.totalMatchesKind?{totalMatchesKind:e.totalMatchesKind}:{},...typeof e?.totalMatchesCapped=="boolean"?{totalMatchesCapped:e.totalMatchesCapped}:{},...typeof e?.uniqueFileCount=="number"?{uniqueFileCount:e.uniqueFileCount}:{}}}function lk(e){let t=e.lastIndexOf("/");return t<=0?{owner:"",repo:e}:{owner:e.substring(0,t),repo:e.substring(t+1)}}function dy(e,t){let n=t.match==="path",r=t.verbose===!0,o=new Map;for(let s of e.items){let a=s.repository.name||"",{owner:c,repo:l}=lk(a),u=`${c}/${l}`,d=s,p=o.get(u);if(p||(p={id:u,owner:c,repo:l,matches:[]},o.set(u,p)),n||!s.matches?.length){p.matches.push({path:s.path,...n?{}:{pathOnly:!0},...r&&d.url?{url:d.url}:{}});continue}let f=!0,m=!1;for(let g of s.matches){if(!g.context)continue;let b={path:s.path,value:ck(g.context)};g.positions?.length>0&&(b.matchIndices=g.positions.map(([C,S])=>({start:C,end:S,lineOffset:(g.context??"").substring(0,C).split(`
38
+ `).length-1}))),r&&f&&d.url&&(b.url=d.url,f=!1),p.matches.push(b),m=!0}m||p.matches.push({path:s.path,pathOnly:!0,...r&&d.url?{url:d.url}:{}})}let i={results:Array.from(o.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...uy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function py(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:e.size,created:e.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,forks:t.forks,license:t.license,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function fy(e){let t=n=>{let r=n.lastIndexOf("/");return r<=0?{owner:"",repo:n}:{owner:n.substring(0,r),repo:n.substring(r+1)}};return e.map(n=>{let{owner:r,repo:o}=t(n.fullPath);return{owner:r||"",repo:o||n.name,defaultBranch:n.defaultBranch,stars:n.stars,description:n.description||"",url:n.url,createdAt:n.createdAt,updatedAt:n.updatedAt,pushedAt:n.lastActivityAt,visibility:n.visibility,topics:n.topics,forksCount:n.forks,openIssuesCount:n.openIssuesCount,...n.language&&{language:n.language}}})}function uk(e){return e.startsWith('"')?e:/\s/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}function my(e){let t=(e.keywordsToSearch??[]).filter(o=>o.trim()).map(uk),n=e.query?.trim()??"",r=[...t,...n?[n]:[]].join(" ")||void 0;return{projectId:cy(e.owner,e.repo),owner:e.owner,query:r,number:e.prNumber,state:e.state,author:e.author,assignee:e.assignee,commenter:e.commenter,involves:e.involves,mentions:e.mentions,reviewRequested:e["review-requested"],reviewedBy:e["reviewed-by"],labels:(()=>{let o=e.label;if(o)return Array.isArray(o)?o:[o]})(),noLabel:e["no-label"],noMilestone:e["no-milestone"],noProject:e["no-project"],noAssignee:e["no-assignee"],baseBranch:e.base,headBranch:e.head,created:e.created,updated:e.updated,closed:e.closed,mergedAt:e["merged-at"],comments:e.comments,reactions:e.reactions,interactions:e.interactions,draft:e.draft,match:e.match,milestone:e.milestone,language:e.language,checks:e.checks,review:e.review,locked:e.locked,visibility:e.visibility,teamMentions:e["team-mentions"],project:e.project,archived:e.archived,content:e.content,reviewMode:e.reviewMode,filePage:e.filePage,commentPage:e.commentPage,commitPage:e.commitPage,itemsPerPage:e.itemsPerPage,sort:e.sort,order:e.order,limit:e.limit??30,page:e.page,charOffset:e.charOffset,charLength:e.charLength,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function dk(e){return e?{capped:e,totalCount:e.length,wasTruncated:!1}:{capped:void 0,totalCount:0,wasTruncated:!1}}function pk(e){let t=e.map(r=>r.body.toLowerCase()),n=[];return t.some(r=>/\b(lgtm|looks good|approved|ship it)\b/.test(r))&&n.push("approval"),t.some(r=>/\b(change|fix|concern|blocker|blocking|request changes?)\b/.test(r))&&n.push("changes-requested"),t.some(r=>r.includes("?"))&&n.push("question"),n.length>0?n:["discussion"]}function fk(e){if(!e||e.length===0)return;let t=Array.from(new Set(e.map(o=>o.author))),n=e.map(o=>o.updatedAt||o.createdAt).filter(Boolean).sort().at(-1),r=e.filter(o=>o.commentType==="review_inline").length;return{totalComments:e.length,inlineComments:r,discussionComments:e.length-r,commenters:t.slice(0,8),...n?{latestCommentAt:n}:{},themes:pk(e)}}function gy(e,t={}){let{includeFileChanges:n=!0}=t,r=e.items.map(i=>{let{capped:s,totalCount:a}=dk(i.fileChanges),c=Array.isArray(i.comments)?i.comments:void 0,l=fk(c);return{number:i.number,title:i.title,body:i.body??void 0,...i.bodyPagination&&{bodyPagination:i.bodyPagination},url:i.url,state:i.state,draft:i.draft,author:i.author,assignees:i.assignees,labels:i.labels,sourceBranch:i.sourceBranch,targetBranch:i.targetBranch,sourceSha:i.sourceSha,targetSha:i.targetSha,createdAt:i.createdAt,updatedAt:i.updatedAt,closedAt:i.closedAt,mergedAt:i.mergedAt,commentsCount:i.commentsCount,changedFilesCount:i.changedFilesCount??a,additions:i.additions,deletions:i.deletions,...Array.isArray(i.comments)&&i.comments.length>0&&{comments:i.comments.map(u=>({...u,...u.bodyPagination&&{bodyPagination:u.bodyPagination}}))},...i.reviews&&{reviews:i.reviews},...i.commits&&{commits:i.commits},...l&&{reviewSummary:l},...s&&n?{fileChanges:s}:{},...Array.isArray(i.sanitizationWarnings)&&i.sanitizationWarnings.length>0?{sanitizationWarnings:i.sanitizationWarnings}:{}}}),o=e.pagination?{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,...typeof e.pagination.totalMatches=="number"?{totalMatches:e.pagination.totalMatches}:{},...uy(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}:void 0;return{pullRequests:r,resultData:{pull_requests:r,...o?{pagination:o}:{total_count:e.totalCount||r.length}},pagination:o}}function hy(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function yy(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isSkeleton===!0&&{isSkeleton:!0},...e.isPartial&&{isPartial:e.isPartial},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function by(e,t){return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??kn.ENTRIES_PER_PAGE,page:(()=>{let n=e.page;return typeof n=="number"?n:void 0})(),includeSizes:e.includeSizes,mainResearchGoal:e.mainResearchGoal,researchGoal:e.researchGoal,reasoning:e.reasoning}}function Ry(e,t,n,r){let o=r,i=e.branch??r,s=o&&i&&o!==i&&o!=="HEAD",a=Object.entries(n).sort(([d],[p])=>d==="."?-1:p==="."?1:d.localeCompare(p)).map(([d,p])=>({dir:d,files:p.files,folders:p.folders})),c=e.fileSizeMap,l={};if(c){for(let[d,p]of Object.entries(c))if(n[d]){let f=new Set(n[d].files);for(let[m,g]of Object.entries(p))f.has(m)&&(l[m]=g)}}let u={structure:a,...Object.keys(l).length>0&&{fileSizes:l},summary:{totalFiles:e.summary.totalFiles,totalFolders:e.summary.totalFolders}};return i&&(u.resolvedBranch=i),s&&(u.branchFallback={requestedBranch:o,actualBranch:i,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${o}' not found. Showing '${i}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(u.pagination=e.pagination),u}var An=y(()=>{"use strict";me();Ko()});function mk(e){if(typeof e=="string")return{message:e};if(typeof e=="object"&&e!==null){let t=e,n=typeof t.error=="string"&&t.error.length>0?t.error:"Provider error",r=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0;return{message:n,status:r}}return{message:"Provider error"}}function ia(e){let t=[];for(let n of e){if(n.status!=="error")continue;let{message:r,status:o}=mk(n.data.error),i=o!==void 0?`${r} (HTTP ${o})`:r;t.push({id:n.id,error:i})}return t}function sa(e,t,n){let r=Xo(e,[...t]);return{structuredContent:ht(e),text:r,isError:n}}var aa=y(()=>{"use strict";Jo()});function ca(e){return typeof e=="object"&&e!==null}function ct(e){return typeof e=="string"&&e.length>0?e:void 0}function We(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Sy(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function yt(e,t){return We(e[t])??0}function gk(e){if(ca(e))return{nonFile:yt(e,"nonFile"),missingDownloadUrl:yt(e,"missingDownloadUrl"),oversized:yt(e,"oversized"),binary:yt(e,"binary"),fileLimit:yt(e,"fileLimit"),fetchFailed:yt(e,"fetchFailed"),totalSizeLimit:yt(e,"totalSizeLimit"),pathTraversal:yt(e,"pathTraversal")}}function hk(e){if(ca(e))return{maxDirectoryFiles:yt(e,"maxDirectoryFiles"),maxTotalSize:yt(e,"maxTotalSize"),maxFileSize:yt(e,"maxFileSize")}}function bk(e){if(!ca(e))return;let{currentPage:t,totalPages:n,hasMore:r}=e;if(typeof t!="number"||typeof n!="number"||typeof r!="boolean")return;let o={currentPage:t,totalPages:n,hasMore:r};for(let i of yk){let s=e[i];typeof s=="number"&&Number.isFinite(s)&&(o[i]=s)}return o}function Rk(e,t){return`${e}/${t}`}function Sk(e,t,n){let r=Rk(t,n),o=e.get(r);if(o)return o;let i={id:r,owner:t,repo:n};return e.set(r,i),i}function Ck(e,t){if(!(!e||!e.hasMore||e.nextCharOffset===void 0))return{continueChars:{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,charOffset:e.nextCharOffset,...e.charLength!==void 0?{charLength:e.charLength}:{},...t.minify!==void 0?{minify:t.minify}:{}}}}}function Pk(e,t){let n=bk(e.pagination),r=Ck(n,t);return{path:ct(e.path)??String(t.path??""),content:typeof e.content=="string"?e.content:"",localPath:ct(e.localPath),repoRoot:ct(e.repoRoot),...We(e.fileSize)!==void 0?{fileSize:We(e.fileSize)}:{},contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,...e.isSkeleton===!0?{isSkeleton:!0}:{},totalLines:We(e.totalLines),sourceChars:We(e.sourceChars),sourceBytes:We(e.sourceBytes),resolvedBranch:ct(e.resolvedBranch),pagination:n,...r?{next:r}:{},...e.isPartial===!0?{isPartial:!0}:{},startLine:We(e.startLine),endLine:We(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},lastModified:ct(e.lastModified),lastModifiedBy:ct(e.lastModifiedBy),warnings:Sy(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:ct(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function xk(e,t){let r=(Array.isArray(e.files)?e.files:[]).filter(ca).map(c=>({path:ct(c.path)??"",size:We(c.size)??0,type:ct(c.type)??"file"})),o=gk(e.skipped),i=e.hasSubdirectories===!0||(o?o.nonFile>0:!1),s=o?Object.entries(o).filter(([,c])=>c>0):[],a=s.length>0?Object.fromEntries(s):void 0;return{path:String(t.path??""),localPath:ct(e.localPath)??"",repoRoot:ct(e.repoRoot),fileCount:We(e.fileCount)??r.length,totalSize:We(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...i?{hasSubdirectories:!0}:{},...a?{skippedSummary:a}:{},directoryEntryCount:We(e.directoryEntryCount),eligibleFileCount:We(e.eligibleFileCount),savedFileCount:We(e.savedFileCount),skipped:o,limits:hk(e.limits),warnings:Sy(e.warnings),...r.length>0?{files:r}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:ct(e.resolvedBranch)}}function wk(e,t){let n=new Map;return e.forEach((r,o)=>{if(r.status==="error")return;let i=t[o];if(!i)return;let s=String(i.owner??""),a=String(i.repo??"");if(!s||!a)return;let c=Sk(n,s,a),l=r.data;if(i.type==="directory"){let d=c.directories??[];d.push(xk(l,i)),c.directories=d;return}let u=c.files??[];u.push(Pk(l,i)),c.files=u}),Array.from(n.values()).map(r=>{let o={owner:r.owner,repo:r.repo,...r.files?{files:r.files}:{},...r.directories?{directories:r.directories}:{}};return{id:r.id,data:o}})}function Ek(e,t){return ia(e).map(r=>{let o=e.findIndex(s=>s.id===r.id),i=o>=0?t[o]:void 0;return{id:r.id,owner:i?.owner,repo:i?.repo,path:i?.path?String(i.path):void 0,error:r.error}})}function Cy(){return({queries:e,results:t})=>{let n=wk(t,e),r=Ek(t,e),o={results:n};return r&&r.length>0&&(o.errors=r),sa(o,["results","id","owner","repo","files","directories","path","content","totalLines","startLine","endLine","isPartial","pagination","errors"],n.length===0&&!!(r&&r.length>0))}}var yk,Nu=y(()=>{"use strict";aa();yk=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"]});async function Py(e){let{queries:t,authInfo:n}=e,r=at(n);return se(t,async(o,i)=>{try{let s=Ue(wr,o,{prefix:!1});if(s.ok===!1)return s.error;let a=s.data,c=r();return a.type==="directory"?Tk(a,n,c):kk(a,n,c)}catch(s){return Me(s,o,void 0,A.GITHUB_FETCH_CONTENT)}},{toolName:A.GITHUB_FETCH_CONTENT,finalize:Cy()},e)}async function Tk(e,t,n){let r=ge();if(!(r.local.enabled&&r.local.enableClone))return M("Directory fetch requires local clone support. Set ENABLE_CLONE=true and make sure ENABLE_LOCAL is not false.",e);if(!ta(n,"fetchDirectoryToDisk"))return Me(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",A.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return M("Directory fetch requires both owner and repo.",e,{rawResponse:0});let o=e.branch??await Ze(e.owner,e.repo,t),i=await Lg(e.owner,e.repo,String(e.path),o,t,!!e.forceRefresh),s=(i.skipped?.nonFile??0)>0,a=i.skipped?Object.fromEntries(Object.entries(i.skipped).filter(([,d])=>d>0)):void 0,c={kind:"directory",localPath:i.localPath,repoRoot:i.repoRoot,source:"treeFetch",cached:i.cached,complete:i.complete,verified:i.verified,...i.commitSha?{commitSha:i.commitSha}:{},...s?{hasSubdirectories:!0}:{},...a&&Object.keys(a).length>0?{skippedSummary:a}:{},owner:e.owner,repo:e.repo},l={localSearch:{tool:"localSearchCode",query:{path:i.localPath,mode:"discovery"}},viewStructure:{tool:"localViewStructure",query:{path:i.localPath}},...s?{escalateToClone:{tool:"ghCloneRepo",why:"nonFile skips indicate subdirectories were not fetched; clone for full coverage",query:{owner:e.owner,repo:e.repo,...e.branch?{branch:e.branch}:{},...e.path?{sparsePath:String(e.path)}:{}}}}:{}},u={localPath:i.localPath,repoRoot:i.repoRoot,fileCount:i.fileCount,totalSize:i.totalSize,complete:i.complete,verified:i.verified,...i.commitSha?{commitSha:i.commitSha}:{},directoryEntryCount:i.directoryEntryCount,eligibleFileCount:i.eligibleFileCount,savedFileCount:i.savedFileCount,skipped:i.skipped,limits:i.limits,...i.warnings?{warnings:i.warnings}:{},files:i.files,...i.cached?{cached:!0}:{},...e.branch!==i.branch?{resolvedBranch:i.branch}:{},location:c,next:l};return Fe(e,u,!0,A.GITHUB_FETCH_CONTENT,{rawResponse:i.totalSize??U(i)})}async function kk(e,t,n){let r=await tn(e,()=>n.provider.getFileContent(hy(e)));if(r.ok===!1)return r.result;let o=e.fullContent===!0&&e.minify==="none"?await Ok(e,t):void 0,i={...yy(r.response.data,e),...o?{localPath:o.localPath,repoRoot:o.repoRoot,cached:o.cached,...o.branch!==e.branch?{resolvedBranch:o.branch}:{}}:{}},s=!!(r.response.data.matchNotFound===!0||r.response.data.content&&r.response.data.content.length>0);return Fe(e,i,s,A.GITHUB_FETCH_CONTENT,{rawResponse:r.response.rawResponseChars})}async function Ok(e,t){if(!e.owner||!e.repo||typeof e.path!="string")return;let n=e.branch??await Ze(e.owner,e.repo,t);return _g(e.owner,e.repo,e.path,n,t,!!e.forceRefresh)}var Gu=y(()=>{"use strict";fe();je();De();ri();Wl();Ge();oe();An();nn();Nu();_e()});function vk(e){let t=new Map;for(let n of e)typeof n.id=="string"&&t.set(n.id,n);return t}function Ak(e,t){let n=vk(t);return e.some(r=>{let o=n.get(r.id);return typeof o?.owner=="string"&&typeof o?.repo=="string"})}function Lk(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{}}}function _k(e){let t=new Map;for(let{id:n,groups:r}of e)for(let o of r){let i=`${n}\0${o.id}`,s=t.get(i);if(!s){t.set(i,{id:o.id,queryId:n,owner:o.owner,repo:o.repo,matches:[...o.matches]});continue}s.matches.push(...o.matches)}return Array.from(t.values())}function Ik(e){return[...e].sort((t,n)=>{let r=n.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(n.id)})}function xy(e){let t=new Map;for(let n of e)for(let r of n.matches){let o=`${n.queryId??""}\0${n.owner}\0${n.repo}\0${r.path}`,i=t.get(o),{path:s,...a}=r;if(i){i.matches.push(a);continue}t.set(o,{owner:n.owner,repo:n.repo,path:r.path,matches:[a]})}return Array.from(t.values())}function Fk(e,t,n){if(t.length===0)return[];if(e.length===1){let i=typeof e[0]?.id=="string"?e[0].id:"ghSearchCode",s=typeof e[0]?.id=="string"?e[0].id:void 0,a=s?n.get(s):void 0;return[{id:i,data:{files:xy(t),...a?{pagination:a}:{}}}]}let r=new Map,o=[];for(let i of t){let s=i.queryId??"ghSearchCode",a=r.get(s);a||(a=[],r.set(s,a),o.push(s)),a.push(i)}return o.map(i=>{let s=n.get(i);return{id:i,data:{files:xy(r.get(i)),...s?{pagination:s}:{}}}})}function Mk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dk(e,t){let n=(e.path.split("/").pop()??"").toLowerCase(),r=n.replace(/\.[^.]+$/,""),o=e.value??"",i=0;for(let s of t){let a=s.trim();if(!a)continue;let c=a.toLowerCase();if(n===c||r===c)return 2;(/^[A-Za-z0-9_]+$/.test(a)?new RegExp(`\\b${Mk(a)}\\b`,"i").test(o):o.toLowerCase().includes(c))&&(i=Math.max(i,1))}return i}function Nk(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim());return n.length===0?Ik(e):e.map(o=>{let i=o.matches.map((s,a)=>({match:s,index:a,score:Dk(s,n)}));return i.sort((s,a)=>s.score!==a.score?a.score-s.score:s.index-a.index),{group:Gk(o,i.map(s=>s.match)),hasExact:i.some(s=>s.score>0)}}).sort((o,i)=>{if(o.hasExact!==i.hasExact)return o.hasExact?-1:1;let s=i.group.matches.length-o.group.matches.length;return s!==0?s:o.group.id.localeCompare(i.group.id)}).map(o=>o.group)}function Gk(e,t){return{...e,matches:t}}function wy(){return({queries:e,results:t})=>{let n=[],r=new Map,o=[],i=!1;t.forEach((p,f)=>{if(p.status==="error")return;let m=Lk(p);m.incompleteResults&&(i=!0),m.results.reduce((C,S)=>C+S.matches.length,0)===0&&o.push({id:p.id,...m.nonExistentScope?{nonExistentScope:!0}:{},...m.incompleteResults?{incompleteResults:!0}:{}});let b=m.results;n.push({id:p.id,groups:b}),m.pagination&&r.set(p.id,m.pagination)});let s=Array.from(new Set(e.flatMap(p=>{let f=p.keywords;return Array.isArray(f)?f.filter(m=>typeof m=="string"):[]}))),a=Nk(_k(n),s),c=ia(t),l=e.some(p=>p.concise===!0),u=Fk(e,a,r);if(l)for(let p of u)p.data.files=p.data.files.map(f=>`${f.owner}/${f.repo}:${f.path}`);let d={results:u};return o.length>0&&(d.emptyQueries=o.map(({id:p,nonExistentScope:f,incompleteResults:m})=>({id:p,...f?{nonExistentScope:f}:{},...m?{incompleteResults:m}:{}}))),c.length>0&&(d.errors=c),i&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned incomplete_results: the search index did not fully complete. Empty or partial results may be a false negative \u2014 retry, narrow scope (owner/repo/path), or materialize the repo and search locally before concluding absence."]),o.length>0&&Ak(o,e)&&(d.warnings=[...Array.isArray(d.warnings)?d.warnings:[],"GitHub code search returned no results for a scoped repository query. Treat this as unproven absence: verify the repo/path with ghViewRepoStructure, then materialize or clone a bounded path and search locally before concluding."]),sa(d,["results","id","data","files","path","owner","repo","queryId","matches","value","pathOnly","matchIndices","pagination","emptyQueries","nonExistentScope","incompleteResults","warnings","errors"],a.length===0&&c.length>0)}}var Hu=y(()=>{"use strict";aa()});function Hk(e){return!!((e.keywords??[]).some(n=>n.trim().length>0)||e.owner||e.path||e.extension||e.filename)}function zk(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function Ey(e){let{queries:t}=e,n=at(e.authInfo);return se(t,async(r,o)=>{try{let i=zk(r);if(i)return M(i.error,r);if(!Hk(r))return M("At least one search term or scope filter is required.",r);let s=n(),a=await tn(r,()=>s.provider.searchCode(ly(r)));if(a.ok===!1)return a.result;let c=dy(a.response.data,r);return Fe(r,c,c.results.length>0,A.GITHUB_SEARCH_CODE,{rawResponse:a.response.rawResponseChars})}catch(i){return Me(i,r,void 0,A.GITHUB_SEARCH_CODE)}},{toolName:A.GITHUB_SEARCH_CODE,finalize:wy()},e)}var zu=y(()=>{"use strict";fe();je();De();An();nn();Hu()});import{z as D}from"zod";import{GitHubCodeSearchQuerySchema as Ty}from"@octocodeai/octocode-core/schemas";var ky,la,ua,f1,da=y(()=>{"use strict";me();Be();tt();Gt();ky={limit:G(1,100).optional(),page:ae.default(1)},la=ue(Ty,ky),ua=ie(he(Ty,ky)),f1=D.object({base:D.string().optional(),shared:D.record(D.string(),D.union([D.string(),D.number(),D.boolean()])).optional(),responsePagination:Qe.responsePagination,results:D.array(D.object({id:D.string(),data:D.object({files:D.array(D.object({owner:D.string(),repo:D.string(),path:D.string(),queryId:D.string().optional(),matches:D.array(D.object({value:D.string().optional(),pathOnly:D.boolean().optional(),matchIndices:D.array(D.object({start:D.number(),end:D.number(),lineOffset:D.number()})).optional(),url:D.string().optional()}))})),pagination:D.object({currentPage:D.number(),totalPages:D.number(),perPage:D.number(),totalMatches:D.number(),reportedTotalMatches:D.number().optional(),reachableTotalMatches:D.number().optional(),totalMatchesKind:D.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:D.boolean().optional(),hasMore:D.boolean(),nextPage:D.number().optional(),uniqueFileCount:D.number().optional()}).optional()})})),emptyQueries:D.array(D.object({id:D.string(),nonExistentScope:D.literal(!0).optional(),incompleteResults:D.literal(!0).optional()})).optional(),warnings:D.array(D.string()).optional(),errors:D.array(D.object({id:D.string(),error:D.string()})).optional()})});function Bk(e,t){let n=e?.patches;return n?.mode?{mode:n.mode,...n.files?{files:n.files}:{},...n.ranges?{ranges:n.ranges}:{}}:t==="full"?{mode:"all"}:{mode:"none"}}function Qk(e,t){let n=e?.comments;return n?{discussion:n.discussion??!0,reviewInline:n.reviewInline??!0,includeBots:n.includeBots??!1,...n.file?{file:n.file}:{}}:t==="full"?{discussion:!0,reviewInline:!0,includeBots:!1}:!1}function Uk(e,t){let n=e?.commits;return n?{list:n.list??!0,includeFiles:n.includeFiles??!1}:t==="full"?{list:!0,includeFiles:!1}:!1}function Oy(e){let{content:t,reviewMode:n}=e,r=Bk(t,n),o=Qk(t,n),i=Uk(t,n),s=n==="full";return{body:t?.body??s,changedFiles:(t?.changedFiles??s)||r.mode!=="none",patches:r,comments:o,reviews:t?.reviews??s,commits:i,...n?{reviewMode:n}:{}}}function g1(e){return!!(e.body||e.changedFiles||e.patches.mode!=="none"||e.comments||e.reviews||e.commits)}var Bu=y(()=>{"use strict"});function ju(e){let t=e.matchString;if(typeof t!="string")return;let n=t.trim().toLowerCase();return n.length>0?n:void 0}function fa(e,t){return typeof e=="string"&&e.toLowerCase().includes(t)}function $u(e,t=1,n=20){let r=Math.min(Math.max(1,n),100),o=e.length,i=Math.max(1,Math.ceil(o/r)),s=Math.min(Math.max(1,t),i),a=(s-1)*r,c=Math.min(a+r,o);return{items:e.slice(a,c),pagination:{currentPage:s,totalPages:i,itemsPerPage:r,totalItems:o,hasMore:s<i,...s<i?{nextPage:s+1}:{}}}}function ga(e,t=0,n=12e3){if(typeof e!="string")return;let r=e.length,o=Math.min(Math.max(0,t),r),i=Math.min(Math.max(1,n),5e4),s=Math.min(o+i,r),a=s<r;return{content:e.slice(o,s),pagination:{charOffset:o,charLength:s-o,totalChars:r,hasMore:a,...a?{nextCharOffset:s}:{}}}}function Ay(e,t=500){if(!(typeof e!="string"||e.length===0))return e.length<=t?e:`${e.slice(0,t-3)}...`}function Ly(e,t){return{owner:e.owner,repo:e.repo,prNumber:t}}function jk(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ma(e,t,n){return jk({...Ly(e,t),...n})}function vy(e,t,n,r,o={}){if(!(!r.hasMore||r.nextCharOffset===void 0))return ma(e,t,{content:n,...o,charOffset:r.nextCharOffset,charLength:e.charLength})}function Qu(e,t,n,r,o){if(!(!o.hasMore||o.nextPage===void 0))return ma(e,t,{content:n,[r]:o.nextPage,itemsPerPage:e.itemsPerPage})}function $k(e,t,n){return{target:Ly(e,t),...n.body?{}:{getBody:{content:{body:!0}}},...n.changedFiles?{}:{getChangedFiles:{content:{changedFiles:!0}}},...n.patches.mode!=="none"?{}:{getSelectedPatches:{content:{patches:{mode:"selected",files:["path/from/changedFiles"]}}},getAllPatches:{content:{patches:{mode:"all"}}}},...n.comments?{}:{getComments:{content:{comments:{discussion:!0,reviewInline:!0}}}},...n.reviews?{}:{getReviews:{content:{reviews:!0}}},...n.commits?{}:{getCommits:{content:{commits:{list:!0}}}},...n.reviewMode==="full"?{}:{fullReview:{reviewMode:"full"}}}}function pa(e){return String(e.path??e.filename??"")}function qk(e,t){return{path:pa(e),status:String(e.status??""),additions:Number(e.additions??0),deletions:Number(e.deletions??0),...t&&typeof e.patch=="string"?{patch:e.patch}:{}}}function Vk(e,t){return e.filter(n=>{let r=n.commentType;return t.file&&n.path!==t.file?!1:r==="review_inline"?t.reviewInline:t.discussion})}function Wk(e,t,n){if(!n.comments)return{};let r=Array.isArray(e.comments)?e.comments:[],o=Vk(r,n.comments),i=ju(t),s=i?o.filter(l=>fa(l.body,i)):o,{items:a,pagination:c}=$u(s,t.commentPage??t.page??1,t.itemsPerPage??20);return{comments:a.map(l=>{let u=ga(typeof l.body=="string"?l.body:"",t.commentBodyOffset??0,t.charLength??12e3);return{id:l.id,author:l.author,commentType:l.commentType??"discussion",path:l.path,line:l.line,...l.in_reply_to_id!=null?{in_reply_to_id:l.in_reply_to_id}:{},...u?{body:u.content,bodyPagination:u.pagination}:{bodyPreview:Ay(typeof l.body=="string"?l.body:"")},createdAt:l.createdAt,updatedAt:l.updatedAt}}),commentPagination:c}}function Kk(e,t,n){if(!n.reviews)return{};let r=Array.isArray(e.reviews)?e.reviews:[],o=ju(t);return{reviews:(o?r.filter(s=>fa(s.body,o)):r).map(s=>{let a=typeof s.body=="string"?s.body:"",c=ga(a||void 0,0,t.charLength??12e3);return{id:s.id,user:s.user,state:s.state,...c?{body:c.content,bodyPagination:c.pagination}:{},submittedAt:s.submittedAt??s.submitted_at,commitId:s.commitId??s.commit_id}})}}function Yk(e,t,n){if(!n.commits)return{};let r=Array.isArray(e.commits)?e.commits:[],{items:o,pagination:i}=$u(r,t.commitPage??t.page??1,t.itemsPerPage??20);return{commits:o.map(s=>({sha:s.sha,message:s.message,author:s.author,date:s.date,...n.commits&&n.commits.includeFiles&&Array.isArray(s.files)?{files:s.files}:{}})),commitPagination:i}}function Xk(e){return e.split(`
39
39
  `).filter(t=>{if(!t.startsWith("+"))return!0;let n=t.slice(1).trim();return n!==""&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")}).map(t=>t.startsWith("+")?"+"+t.slice(1).replace(/\s*\/\/.*$/,"").trimEnd():t).join(`
40
- `)}function uS(e){return e.replace(/\n{3,}/g,`
40
+ `)}function Jk(e){return e.replace(/\n{3,}/g,`
41
41
 
42
- `)}function lS(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(p=>i.includes(Wo(p))):o,a=js(t),c=a?s.filter(p=>Ko(Wo(p),a)||Ko(p.patch,a)):s,{items:u,pagination:l}=$s(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",m=u.map(p=>{let f=rS(p,!1);if(!d||typeof p.patch!="string")return f;let g=r&&!a?cS(p.patch):p.patch,h=Xo(g,t.charOffset??0,t.charLength??12e3);return{...f,patch:h?.content??"",diff:Pr(h?.content),...h?{patchPagination:h.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:m,filePagination:l}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(Wo).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function wr(e){return typeof e=="object"&&e!==null}function Qs(e){if(wr(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function Vs(e){if(wr(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function dS(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function pS(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!wr(n))continue;let r=Vs(n.patchPagination);if(r?.hasMore)return r}}function fS(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!wr(n))continue;let r=Vs(n.bodyPagination);if(r?.hasMore)return r}}function mS(e,t,n,r){let o={},i=Vs(e.bodyPagination),s=Qs(e.filePagination),a=Qs(e.commentPagination),c=Qs(e.commitPagination),u=pS(e),l=fS(e),d=dS(n);i&&(o.body={...i,nextQuery:$d(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:zs(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:zs(t,r,{comments:n.comments},"commentPage",a)}),l?.hasMore&&l.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...l,nextQuery:Yo(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:l.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:zs(t,r,{commits:n.commits},"commitPage",c)}),u&&n.patches.mode!=="none"&&(o.patches={...u,nextQuery:$d(t,r,{patches:n.patches},u,{filePage:t.filePage??t.page})});let m=e.filePathsPagination;return wr(m)&&(o.filePaths={...m,hasMore:m.hasMore===!0,nextQuery:m.hasMore===!0?Yo(t,r,{content:{changedFiles:!0},filePage:m.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function gS(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function Kd(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?uS(s):s,c=n.body?Xo(a,t.charOffset??0,t.charLength??12e3):void 0,u=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,l=o!==void 0?o:u,m=t.prNumber!==void 0||t.verbose===!0,f={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...m?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...m?{updatedAt:e.updatedAt}:{},...m||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...m&&!c?{bodyPreview:Vd(typeof e.body=="string"?e.body:void 0)}:{},...l?{next:nS(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...lS(e,t,n,r),...iS(e,t,n),...sS(e,t,n),...aS(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=mS(f,t,n,i);return gS(f),g&&(f.contentPagination=g),f}import{z as Jt}from"zod";import{GitHubPullRequestSearchQuerySchema as Yd}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as hS}from"@octocodeai/octocode-core/schemas/outputs";var Xd={perPage:v(1,100).optional().default(30),prNumber:v(1,1e9).optional(),limit:v(1,100).optional().default(30),page:q.default(1),filePage:q.optional(),commentPage:q.optional(),commitPage:q.optional(),itemsPerPage:v(1,100).optional().default(20),charOffset:v(0,1e8).optional(),commentBodyOffset:v(0,1e8).optional(),charLength:v(1,5e4).optional()},yS=ce(Yd,Xd),Jo=re(Yd,Xd),Jd=X(yS),TF=hS.extend({results:Jt.array(Jt.object({id:Jt.string().optional(),status:Jt.string().optional(),data:Jt.object({pull_requests:Jt.array(Jt.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Ae});async function Zd(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{let s=Le(Jo,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let _=s.data;if(!_.owner||!_.repo)return L("owner and repo are required for commits mode.",o);let I=_.path,j=I&&!I.endsWith("/")?"file":"repo";if(j==="file"&&!I)return L("path is required when querying a specific file in commits mode.",o);let w=await kl({type:j,owner:_.owner,repo:_.repo,path:I,branch:_.branch,since:_.since,until:_.until,author:_.author,page:Number(_.page)||1,perPage:Number(_.perPage)||30,includeDiff:!!_.includeDiff,charLength:typeof _.charLength=="number"?_.charLength:void 0},n);if(Yt(w))return L(w,o,{toolName:S.GITHUB_SEARCH_PULL_REQUESTS});let{commits:A}=w.data,Q=A.length>0;return Pe(o,w.data,Q,S.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:w.rawResponseChars})}let a=r(),c={...s.data},u=jd(c),l=c.prNumber!==void 0;if(l||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return L("At least one valid search parameter, filter, or PR number is required.",o);let m=await kt(c,()=>a.provider.searchPullRequests(Ld(c)));if(m.ok===!1)return m.result;let p=l?u.changedFiles||u.patches.mode!=="none":!1,{pullRequests:f,resultData:g}=Od(m.response.data,{includeFileChanges:p});c.prNumber!==void 0&&delete g.pagination;let h=!l&&(!!o.content||!!o.reviewMode),R={...u,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},b=c.minify==="standard",P=l,x=f.map(_=>Kd(_,c,h?R:u,b,P));g.pull_requests=x,!l&&c.concise===!0&&(g.pull_requests=x.map(_=>{let I=_;return`#${I.number} ${I.title}`}));let C=x.length>0;return Pe(c,g,C,S.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:m.response.rawResponseChars})}catch(s){return Ee(s,o,void 0,S.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:S.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}function qd(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}function RS(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function BF(e){let t=e,r=[`${t.owner?`${t.owner}/`:""}${t.repo}`];if(typeof t.stars=="number"&&r.push(`${t.stars} stars`),typeof t.forksCount=="number"&&t.forksCount>0&&r.push(`${t.forksCount} forks`),typeof t.openIssuesCount=="number"&&t.openIssuesCount>0&&r.push(`${t.openIssuesCount} issues`),t.language&&r.push(t.language),t.license&&r.push(t.license),t.pushedAt&&r.push(t.pushedAt.slice(0,10)),t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"&&r.push(`@${t.defaultBranch}`),t.visibility&&t.visibility!=="public"&&r.push(t.visibility),Array.isArray(t.topics)&&t.topics.length>0&&r.push(`#${t.topics.slice(0,4).join(",")}`),t.description&&t.description!=="No description"){let o=t.description.replace(/\s+/g," ").trim();r.push(o.length>100?`${o.slice(0,99)}...`:o)}return r.join(" | ")}function bS(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(RS)}}}function np(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function rp(e){return!!(e.keywords&&e.keywords.length>0)}function SS(e){return!!(rp(e)||np(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function ep(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function CS(e){let t=np(e),n=rp(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:ep(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:ep(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function PS(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function ES(e,t){return[...e].sort((n,r)=>{let o=TS(n,r,t.sort);if(o!==0)return o;let i=tp(r,t)-tp(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Ws(n).localeCompare(Ws(r))})}function TS(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return qd(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function tp(e,t){let n=xS(t),r=Ws(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(l=>l.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((l,d)=>o===d||r===d?l+80:o.includes(d)||r.includes(d)?l+40:s.includes(d)?l+35:i.includes(d)?l+10:l,0)+(c&&a===c?20:0)}function xS(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Ws(e){return`${e.owner}/${e.repo}`}function _S(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function wS(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function AS(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??N(n.response.data??n.response)),0)}async function op(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{if(!SS(o))return L("At least one repository search term or filter is required.",o);let s=r(),a=CS(o),{successes:c,failures:u}=await md(a.map(C=>({meta:{label:C.label,query:C.query},operation:()=>s.provider.searchRepos(wd(C.query))}))),l=c.map(C=>({label:C.meta.label,query:C.meta.query,response:C.response})),d=u.map(C=>({label:C.meta.label,query:C.meta.query,response:C.response}));if(l.length===0){let C=d[0];return C?Go(C.response,o):Ee(new Error("Repository search produced no provider results"),o,void 0,S.GITHUB_SEARCH_REPOSITORIES)}let m=o.limit,p=ES(PS(l.flatMap(C=>Ad(C.response.data.repositories))),o),f=m!=null?p.slice(0,m):p,g=l.length===1?l[0]:void 0,R=l.length>1?wS(l):g?.response.data.pagination,b=R?_S(R):void 0,P=f.length>0,x=bS({repositories:f,pagination:b},o);return Pe(o,x.data,P,S.GITHUB_SEARCH_REPOSITORIES,{rawResponse:AS([...l,...d])})}catch(s){return Ee(s,o,void 0,S.GITHUB_SEARCH_REPOSITORIES)}},{toolName:S.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}import{z as B}from"zod";import{GitHubReposSearchSingleQuerySchema as ip}from"@octocodeai/octocode-core/schemas";var sp={limit:v(1,100).optional(),page:q.default(1)},ap=re(ip,sp),cp=X(ce(ip,sp)),LS=B.object({owner:B.string(),repo:B.string(),stars:B.number().optional(),forks:B.number().optional(),openIssuesCount:B.number().optional(),language:B.string().optional(),license:B.string().optional(),description:B.string().optional(),homepage:B.string().optional(),pushedAt:B.string().optional(),createdAt:B.string().optional(),defaultBranch:B.string().optional(),topics:B.array(B.string()).optional(),visibility:B.string().optional(),url:B.string().optional(),updatedAt:B.string().optional()}),OS=B.object({currentPage:B.number(),totalPages:B.number(),hasMore:B.boolean(),perPage:B.number().optional(),totalMatches:B.number().optional(),reportedTotalMatches:B.number().optional(),reachableTotalMatches:B.number().optional(),totalMatchesKind:B.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:B.boolean().optional(),nextPage:B.number().optional()}).optional(),IS=B.object({repositories:B.array(B.union([B.string(),LS])).optional(),pagination:OS}).passthrough(),qF=B.object({results:B.array(B.object({id:B.string().optional(),status:B.string().optional(),data:IS.optional()}).passthrough()).optional()}).extend(Ae);function kS(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function vS(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&cr(o))continue;let i=r.files.filter(a=>!xn(a)),s=r.folders.filter(a=>!cr(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function up(e){let{queries:t,authInfo:n}=e,r=$e(n);return J(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),u=await kt(o,()=>s.provider.getRepoStructure(vd(o,c)));if(u.ok===!1)return kS(u.result,o);let l=vS(u.response.data.structure),d=Object.keys(l).length>0,m=Fd(u.response.data,o,l,c);return Pe(o,m,d,S.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(s){return Ee(s,o,"Failed to explore repository structure",S.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:S.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}import{GitHubViewRepoStructureQuerySchema as lp}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as FS}from"@octocodeai/octocode-core/schemas/outputs";var dp={maxDepth:v(0,20).optional(),page:q.default(1),itemsPerPage:v(1,200).optional()},pp=re(lp,dp),fp=X(ce(lp,dp)),gM=FS.extend(Ae);import{z as mp}from"zod";import{LocalBinaryInspectQuerySchema as MS}from"@octocodeai/octocode-core/schemas";var NS={entryPageNumber:q.default(1),matchStringContextLines:v(0,50).default(3),charLength:v(1,5e4).optional(),page:q.default(1),detailed:mp.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},gp=mp.object({...MS.shape,...NS}),Zo=gp.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.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".'})}),hp=X(gp,{maxQueries:5});import{promises as In}from"fs";import{join as Zs,basename as qo,dirname as YS,resolve as xp,sep as XS}from"node:path";import{securityRegistry as JS}from"@octocodeai/octocode-engine/registry";import yp from"path";import{pathValidator as DS}from"@octocodeai/octocode-engine/pathValidator";function ve(e,t){if(!e.path?.trim()){let s=De.pathValidationFailed("","path is required");return{isValid:!1,errorResult:L(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||ae().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=yp.isAbsolute(r)?r:yp.resolve(n,r),i=DS.validate(o);if(!i.isValid){let s=De.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:L(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function _M(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:De.outputTooLarge(e,r).errorCode,hints:[`Found ${e} ${o}${e===1?"":"s"} - exceeds safe limit of ${r}`,"Use charLength to paginate through results",i?"Detailed results increase size - consider using charLength for pagination":"Consider using charLength to paginate large result sets"]}:{shouldBlock:!1}}import{validateCommand as HS}from"@octocodeai/octocode-engine/commandValidator";async function On(e,t=[],n={}){let r=HS(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Bo(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024,tolerateOutputLimit:u=!1}=n,l=await Xt(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(l.outputLimitExceeded&&u)return{success:!0,code:l.exitCode,stdout:l.stdout,stderr:l.stderr,truncated:!0};if(l.error)throw l.error;return{success:l.success,code:l.exitCode,stdout:l.stdout,stderr:l.stderr}}var Ks=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],Ys=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],Xs=[".dmg",".rar",".cpgz"],Rp=[".aar",".yaa"];function Ze(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function GS(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},u={command:"bsdtar",args:o},l={command:"7z",args:i},d={command:"7zz",args:i},m={command:"aa",args:s};return Ze(Rp,e)?[m]:Ze(Xs,e)?[l,d,u,c,a]:Ze(Ys,e)?[u,l,d,c,a]:Ze(Ks,e)?[a,c,u,l,d]:[c,a,u,l,d]}function US(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return Ze(Xs,e)?[s,a,o,r,n]:Ze(Ys,e)?[o,s,a,r,n]:Ze(Ks,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function Js(e){let t=[];for(let n of e){let r=await On(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function BS(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
42
+ `)}function Zk(e,t,n,r){let o=Array.isArray(e.fileChanges)?e.fileChanges:[],i=n.patches.files,s=i&&i.length>0?o.filter(f=>i.includes(pa(f))):o,a=ju(t),c=a?s.filter(f=>fa(pa(f),a)||fa(f.patch,a)):s,{items:l,pagination:u}=$u(c,t.filePage??t.page??1,t.itemsPerPage??20),d=n.patches.mode!=="none",p=l.map(f=>{let m=qk(f,!1);if(!d||typeof f.patch!="string")return m;let g=r&&!a?Xk(f.patch):f.patch,b=ga(g,t.charOffset??0,t.charLength??12e3);return{...m,patch:b?.content??"",diff:jo(b?.content),...b?{patchPagination:b.pagination}:{}}});return n.changedFiles||n.patches.mode!=="none"?{changedFiles:p,filePagination:u}:o.length===0?{}:{filePathsPreview:o.slice(0,20).map(pa).filter(Boolean),filePathsPagination:{totalFiles:o.length,filesPerPage:20,hasMore:o.length>20,...o.length>20?{nextFilePage:2}:{}}}}function oi(e){return typeof e=="object"&&e!==null}function Uu(e){if(oi(e)&&!(typeof e.currentPage!="number"||typeof e.totalPages!="number"||typeof e.itemsPerPage!="number"||typeof e.totalItems!="number"||typeof e.hasMore!="boolean"))return e}function qu(e){if(oi(e)&&!(typeof e.charOffset!="number"||typeof e.charLength!="number"||typeof e.totalChars!="number"||typeof e.hasMore!="boolean"))return e}function eO(e){return{...e.changedFiles?{changedFiles:!0}:{},...e.patches.mode!=="none"?{patches:e.patches}:{}}}function tO(e){let t=e.changedFiles;if(Array.isArray(t))for(let n of t){if(!oi(n))continue;let r=qu(n.patchPagination);if(r?.hasMore)return r}}function nO(e){let t=e.comments;if(Array.isArray(t))for(let n of t){if(!oi(n))continue;let r=qu(n.bodyPagination);if(r?.hasMore)return r}}function rO(e,t,n,r){let o={},i=qu(e.bodyPagination),s=Uu(e.filePagination),a=Uu(e.commentPagination),c=Uu(e.commitPagination),l=tO(e),u=nO(e),d=eO(n);i&&(o.body={...i,nextQuery:vy(t,r,{body:!0},i)}),s&&(o.changedFiles={...s,nextQuery:Qu(t,r,d,"filePage",s)}),a&&n.comments&&(o.comments={...a,nextQuery:Qu(t,r,{comments:n.comments},"commentPage",a)}),u?.hasMore&&u.nextCharOffset!==void 0&&n.comments&&(o.commentBody={...u,nextQuery:ma(t,r,{content:{comments:n.comments},...t.commentPage!==void 0?{commentPage:t.commentPage}:{},commentBodyOffset:u.nextCharOffset,charLength:t.charLength})}),c&&n.commits&&(o.commits={...c,nextQuery:Qu(t,r,{commits:n.commits},"commitPage",c)}),l&&n.patches.mode!=="none"&&(o.patches={...l,nextQuery:vy(t,r,{patches:n.patches},l,{filePage:t.filePage??t.page})});let p=e.filePathsPagination;return oi(p)&&(o.filePaths={...p,hasMore:p.hasMore===!0,nextQuery:p.hasMore===!0?ma(t,r,{content:{changedFiles:!0},filePage:p.nextFilePage}):void 0}),Object.keys(o).length>0?o:void 0}function oO(e){delete e.bodyPagination,delete e.filePagination,delete e.commentPagination,delete e.commitPagination,delete e.filePathsPagination}function _y(e,t,n,r,o){let i=Number(e.number),s=typeof e.body=="string"?e.body:void 0,a=s&&r?Jk(s):s,c=n.body?ga(a,t.charOffset??0,t.charLength??12e3):void 0,l=n.body||n.changedFiles||n.patches.mode!=="none"||!!n.comments||n.reviews||!!n.commits,u=o!==void 0?o:l,p=t.prNumber!==void 0||t.verbose===!0,m={...{number:e.number,title:e.title,...e.url?{url:e.url}:{},state:e.state,...e.draft?{draft:e.draft}:{},author:e.author,...Array.isArray(e.assignees)&&e.assignees.length?{assignees:e.assignees}:{},...Array.isArray(e.labels)&&e.labels.length?{labels:e.labels}:{},targetBranch:e.targetBranch,...p?{sourceBranch:e.sourceBranch,...e.sourceSha?{sourceSha:e.sourceSha}:{}}:{},createdAt:e.createdAt,...p?{updatedAt:e.updatedAt}:{},...p||!e.mergedAt?{closedAt:e.closedAt}:{},mergedAt:e.mergedAt,...e.commentsCount?{commentsCount:e.commentsCount}:{},...e.changedFilesCount?{changedFilesCount:e.changedFilesCount}:{},...e.additions?{additions:e.additions}:{},...e.deletions?{deletions:e.deletions}:{},...p&&!c?{bodyPreview:Ay(typeof e.body=="string"?e.body:void 0)}:{},...u?{next:$k(t,i,n)}:{}},...n.body?c?{body:c.content,bodyPagination:c.pagination}:{bodyEmpty:!0}:{},...Zk(e,t,n,r),...Wk(e,t,n),...Kk(e,t,n),...Yk(e,t,n),...e.reviewSummary?{reviewSummary:e.reviewSummary}:{},...Array.isArray(e.sanitizationWarnings)&&e.sanitizationWarnings.length>0?{sanitizationWarnings:e.sanitizationWarnings}:{}},g=rO(m,t,n,i);return oO(m),g&&(m.contentPagination=g),m}var Vu=y(()=>{"use strict";me();$o()});import{z as Ln}from"zod";import{GitHubPullRequestSearchQuerySchema as Iy}from"@octocodeai/octocode-core/schemas";import{GitHubSearchPullRequestsOutputSchema as iO}from"@octocodeai/octocode-core/schemas/outputs";var Fy,sO,Er,ha,k1,ii=y(()=>{"use strict";me();Be();tt();Gt();Fy={perPage:G(1,100).optional().default(30),prNumber:G(1,1e9).optional(),limit:G(1,100).optional().default(30),page:ae.default(1),filePage:ae.optional(),commentPage:ae.optional(),commitPage:ae.optional(),itemsPerPage:G(1,100).optional().default(20),charOffset:G(0,1e8).optional(),commentBodyOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional()},sO=he(Iy,Fy),Er=ue(Iy,Fy),ha=ie(sO),k1=iO.extend({results:Ln.array(Ln.object({id:Ln.string().optional(),status:Ln.string().optional(),data:Ln.object({pull_requests:Ln.array(Ln.object({}).passthrough()).optional()}).passthrough().optional()}).passthrough()).optional(),...Qe})});async function My(e){let{queries:t,authInfo:n}=e,r=at(n);return se(t,async(o,i)=>{try{let s=Ue(Er,o);if(s.ok===!1)return s.error;if(s.data.type==="commits"){let O=s.data;if(!O.owner||!O.repo)return M("owner and repo are required for commits mode.",o);let w=O.path,N=w&&!w.endsWith("/")?"file":"repo";if(N==="file"&&!w)return M("path is required when querying a specific file in commits mode.",o);let I=await gh({type:N,owner:O.owner,repo:O.repo,path:w,branch:O.branch,since:O.since,until:O.until,author:O.author,page:Number(O.page)||1,perPage:Number(O.perPage)||30,filePage:typeof O.filePage=="number"?O.filePage:void 0,itemsPerPage:typeof O.itemsPerPage=="number"?O.itemsPerPage:void 0,includeDiff:!!O.includeDiff,charOffset:typeof O.charOffset=="number"?O.charOffset:void 0,charLength:typeof O.charLength=="number"?O.charLength:void 0},n);if(On(I))return M(I,o,{toolName:A.GITHUB_SEARCH_PULL_REQUESTS});let{commits:v}=I.data,B=v.length>0;return Fe(o,I.data,B,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:I.rawResponseChars})}let a=r(),c={...s.data},l=Oy(c),u=c.prNumber!==void 0;if(u||(c.content=void 0,c.reviewMode=void 0),!(c.keywordsToSearch?.length||c.owner||c.repo||c.author||c.assignee||c.prNumber&&c.owner&&c.repo))return M("At least one valid search parameter, filter, or PR number is required.",o);let p=await tn(c,()=>a.provider.searchPullRequests(my(c)));if(p.ok===!1)return p.result;let f=u?l.changedFiles||l.patches.mode!=="none":!1,{pullRequests:m,resultData:g}=gy(p.response.data,{includeFileChanges:f});c.prNumber!==void 0&&delete g.pagination;let b=!u&&(!!o.content||!!o.reviewMode),C={...l,body:!1,changedFiles:!1,patches:{mode:"none"},comments:!1,commits:!1},S=c.minify==="standard",T=u,L=m.map(O=>_y(O,c,b?C:l,S,T));g.pull_requests=L,!u&&c.concise===!0&&(g.pull_requests=L.map(O=>{let w=O;return`#${w.number} ${w.title}`}));let k=L.length>0;return Fe(c,g,k,A.GITHUB_SEARCH_PULL_REQUESTS,{rawResponse:p.response.rawResponseChars})}catch(s){return Me(s,o,void 0,A.GITHUB_SEARCH_PULL_REQUESTS)}},{toolName:A.GITHUB_SEARCH_PULL_REQUESTS,keysPriority:["pull_requests","pagination","total_count","error"]},e)}var Wu=y(()=>{"use strict";ii();fe();je();De();An();nn();Bu();Vu();su();Yo()});function Dy(e,t){if(!e&&!t)return 0;if(!e)return 1;if(!t)return-1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)&&Number.isNaN(r)?0:Number.isNaN(n)?1:Number.isNaN(r)?-1:r-n}var Ku=y(()=>{"use strict"});function aO(e){let t=e,n={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0,url:t.url,updatedAt:t.updatedAt};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function j1(e){let t=e,r=[`${t.owner?`${t.owner}/`:""}${t.repo}`];if(typeof t.stars=="number"&&r.push(`${t.stars} stars`),typeof t.forksCount=="number"&&t.forksCount>0&&r.push(`${t.forksCount} forks`),typeof t.openIssuesCount=="number"&&t.openIssuesCount>0&&r.push(`${t.openIssuesCount} issues`),t.language&&r.push(t.language),t.license&&r.push(t.license),t.pushedAt&&r.push(t.pushedAt.slice(0,10)),t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"&&r.push(`@${t.defaultBranch}`),t.visibility&&t.visibility!=="public"&&r.push(t.visibility),Array.isArray(t.topics)&&t.topics.length>0&&r.push(`#${t.topics.slice(0,4).join(",")}`),t.description&&t.description!=="No description"){let o=t.description.replace(/\s+/g," ").trim();r.push(o.length>100?`${o.slice(0,99)}...`:o)}return r.join(" | ")}function cO(e,t){let n=t.concise===!0;return{data:{pagination:e.pagination,repositories:n?e.repositories.map(r=>`${r.owner?`${r.owner}/`:""}${r.repo}`):e.repositories.map(aO)}}}function Hy(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function zy(e){return!!(e.keywords&&e.keywords.length>0)}function lO(e){return!!(zy(e)||Hy(e)||e.owner||e.language||e.stars||e.created||e.updated||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function Ny(e,t){return e?`${e} (${t==="topics"?"topics-based search":"keywords-based search"})`:`${t.charAt(0).toUpperCase()+t.slice(1)}-based repository search`}function uO(e){let t=Hy(e),n=zy(e);if(t&&n){let{topicsToSearch:r,keywords:o,...i}=e;return[{label:"topics",query:{...i,reasoning:Ny(e.reasoning,"topics"),topicsToSearch:r}},{label:"keywords",query:{...i,reasoning:Ny(e.reasoning,"keywords"),keywords:o}}]}return[{label:"combined",query:e}]}function dO(e){let t=new Map;for(let n of e){let r=`${n.owner}/${n.repo}`;t.has(r)||t.set(r,n)}return[...t.values()]}function pO(e,t){return[...e].sort((n,r)=>{let o=fO(n,r,t.sort);if(o!==0)return o;let i=Gy(r,t)-Gy(n,t);if(i!==0)return i;let s=(r.stars??0)-(n.stars??0);return s!==0?s:Yu(n).localeCompare(Yu(r))})}function fO(e,t,n){switch(n){case"stars":return(t.stars??0)-(e.stars??0);case"forks":return(t.forksCount??0)-(e.forksCount??0);case"help-wanted-issues":return(t.openIssuesCount??0)-(e.openIssuesCount??0);case"updated":return Dy(e.updatedAt,t.updatedAt);case"best-match":case void 0:return 0;default:return 0}}function Gy(e,t){let n=mO(t),r=Yu(e).toLowerCase(),o=e.repo.toLowerCase(),i=(e.description??"").toLowerCase(),s=(e.topics??[]).map(u=>u.toLowerCase()),a=e.language?.toLowerCase(),c=t.language?.toLowerCase();return n.reduce((u,d)=>o===d||r===d?u+80:o.includes(d)||r.includes(d)?u+40:s.includes(d)?u+35:i.includes(d)?u+10:u,0)+(c&&a===c?20:0)}function mO(e){let t=e.keywords??[],n=e.topicsToSearch??[];return[...t,...n].map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)}function Yu(e){return`${e.owner}/${e.repo}`}function gO(e){return{currentPage:e.currentPage,totalPages:e.totalPages,perPage:e.entriesPerPage||10,totalMatches:e.totalMatches||0,hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function hO(e){let t=e.map(n=>n.response.data.pagination).filter(n=>!!n);if(t.length!==0)return{currentPage:t[0].currentPage,totalPages:Math.max(...t.map(n=>n.totalPages)),hasMore:t.some(n=>n.hasMore),entriesPerPage:t[0].entriesPerPage,totalMatches:t.reduce((n,r)=>n+(r.totalMatches??0),0),reachableTotalMatches:t.reduce((n,r)=>n+(r.reachableTotalMatches??r.totalMatches??0),0),totalMatchesKind:t.some(n=>n.totalMatchesKind==="lowerBound")?"lowerBound":t.some(n=>n.totalMatchesKind==="reported")?"reported":"exact",totalMatchesCapped:t.some(n=>n.totalMatchesCapped===!0)}}function yO(e){return e.reduce((t,n)=>t+(n.response.rawResponseChars??U(n.response.data??n.response)),0)}async function By(e){let{queries:t,authInfo:n}=e,r=at(n);return se(t,async(o,i)=>{try{if(!lO(o))return M("At least one repository search term or filter is required.",o);let s=r(),a=uO(o),{successes:c,failures:l}=await ty(a.map(k=>({meta:{label:k.label,query:k.query},operation:()=>s.provider.searchRepos(py(k.query))}))),u=c.map(k=>({label:k.meta.label,query:k.meta.query,response:k.response})),d=l.map(k=>({label:k.meta.label,query:k.meta.query,response:k.response}));if(u.length===0){let k=d[0];return k?Xs(k.response,o):Me(new Error("Repository search produced no provider results"),o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}let p=o.limit,f=pO(dO(u.flatMap(k=>fy(k.response.data.repositories))),o),m=p!=null?f.slice(0,p):f,g=u.length===1?u[0]:void 0,C=u.length>1?hO(u):g?.response.data.pagination,S=C?gO(C):void 0,T=m.length>0,L=cO({repositories:m,pagination:S},o);return Fe(o,L.data,T,A.GITHUB_SEARCH_REPOSITORIES,{rawResponse:yO([...u,...d])})}catch(s){return Me(s,o,void 0,A.GITHUB_SEARCH_REPOSITORIES)}},{toolName:A.GITHUB_SEARCH_REPOSITORIES,keysPriority:["repositories","pagination","error"]},e)}var Xu=y(()=>{"use strict";fe();je();Ku();De();An();nn();oe()});import{z as W}from"zod";import{GitHubReposSearchSingleQuerySchema as Qy}from"@octocodeai/octocode-core/schemas";var Uy,ya,ba,bO,RO,SO,nq,Ra=y(()=>{"use strict";me();Be();tt();Gt();Uy={limit:G(1,100).optional(),page:ae.default(1)},ya=ue(Qy,Uy),ba=ie(he(Qy,Uy)),bO=W.object({owner:W.string(),repo:W.string(),stars:W.number().optional(),forks:W.number().optional(),openIssuesCount:W.number().optional(),language:W.string().optional(),license:W.string().optional(),description:W.string().optional(),homepage:W.string().optional(),pushedAt:W.string().optional(),createdAt:W.string().optional(),defaultBranch:W.string().optional(),topics:W.array(W.string()).optional(),visibility:W.string().optional(),url:W.string().optional(),updatedAt:W.string().optional()}),RO=W.object({currentPage:W.number(),totalPages:W.number(),hasMore:W.boolean(),perPage:W.number().optional(),totalMatches:W.number().optional(),reportedTotalMatches:W.number().optional(),reachableTotalMatches:W.number().optional(),totalMatchesKind:W.enum(["exact","reported","lowerBound"]).optional(),totalMatchesCapped:W.boolean().optional(),nextPage:W.number().optional()}).optional(),SO=W.object({repositories:W.array(W.union([W.string(),bO])).optional(),pagination:RO}).passthrough(),nq=W.object({results:W.array(W.object({id:W.string().optional(),status:W.string().optional(),data:SO.optional()}).passthrough()).optional()}).extend(Qe)});function CO(e,t){let n=e.error,r=typeof n=="object"&&n!==null?n:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof n=="string"?n:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{}}}function PO(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.split("/").pop()??n;if(n!==""&&n!=="."&&Ao(o))continue;let i=r.files.filter(a=>!gr(a)),s=r.folders.filter(a=>!Ao(a));(i.length>0||s.length>0)&&(t[n]={files:i,folders:s})}return t}async function jy(e){let{queries:t,authInfo:n}=e,r=at(n);return se(t,async(o,i)=>{try{let s=r(),a=`${o.owner}/${o.repo}`,c=o.branch??await s.provider.resolveDefaultBranch(a),l=await tn(o,()=>s.provider.getRepoStructure(by(o,c)));if(l.ok===!1)return CO(l.result,o);let u=PO(l.response.data.structure),d=Object.keys(u).length>0,p=Ry(l.response.data,o,u,c);return Fe(o,p,d,A.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:l.response.rawResponseChars})}catch(s){return Me(s,o,"Failed to explore repository structure",A.GITHUB_VIEW_REPO_STRUCTURE)}},{toolName:A.GITHUB_VIEW_REPO_STRUCTURE,keysPriority:["resolvedBranch","branchFallback","summary","pagination","structure","error"]},e)}var Ju=y(()=>{"use strict";fe();je();hr();De();An();nn()});import{GitHubViewRepoStructureQuerySchema as $y}from"@octocodeai/octocode-core/schemas";import{GitHubViewRepoStructureOutputSchema as xO}from"@octocodeai/octocode-core/schemas/outputs";var qy,Sa,Ca,bq,Pa=y(()=>{"use strict";me();me();Be();tt();Gt();qy={maxDepth:G(0,20).optional(),page:ae.default(1),itemsPerPage:G(1,200).optional()},Sa=ue($y,qy),Ca=ie(he($y,qy)),bq=xO.extend(Qe)});import{z as Vy}from"zod";import{LocalBinaryInspectQuerySchema as wO}from"@octocodeai/octocode-core/schemas";var EO,Wy,Tr,xa,si=y(()=>{"use strict";Be();EO={entryPageNumber:ae.default(1).describe("list mode: 1-based page over archive entries when an archive has many files."),matchStringContextLines:G(0,50).default(3).describe("Lines of context to keep around each matchString hit (strings/decompress/extract)."),charLength:G(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:ae.default(1).describe("1-based page for paginated entry/content listings."),detailed:Vy.boolean().optional().describe("inspect: include full symbols/imports/exports/sections arrays.")},Wy=Vy.object({...wO.shape,...EO}),Tr=Wy.strict().superRefine((e,t)=>{e.mode==="extract"&&!e.archiveFile&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile is required for mode="extract" \u2014 run mode="list" first to get exact entry names'}),e.archiveFile?.startsWith("-")&&t.addIssue({code:"custom",path:["archiveFile"],message:'archiveFile must not start with "-" (prevents flag injection into backend CLIs)'});let n=[".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst",".zip",".jar",".war",".apk",".7z"];e.mode==="decompress"&&n.some(r=>e.path.toLowerCase().endsWith(r))&&t.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".'})}),xa=ie(Wy,{maxQueries:5})});import Ky from"path";import{pathValidator as TO}from"@octocodeai/octocode-engine/pathValidator";function Ke(e,t){if(!e.path?.trim()){let s=Xe.pathValidationFailed("","path is required");return{isValid:!1,errorResult:M(s,e,{toolName:t})}}let n=process.env.WORKSPACE_ROOT?.trim()||ge().local.workspaceRoot||process.cwd(),r=e.path.replace(/^file:\/\//,""),o=Ky.isAbsolute(r)?r:Ky.resolve(n,r),i=TO.validate(o);if(!i.isValid){let s=Xe.pathValidationFailed(e.path,i.error);return{isValid:!1,errorResult:M(s,e,{toolName:t,extra:{cwd:n,resolvedPath:o}})}}return{isValid:!0,sanitizedPath:i.sanitizedPath??o}}function vq(e,t,n={}){let{threshold:r=100,itemType:o="item",detailed:i=!1}=n;return t?{shouldBlock:!1}:e>r?{shouldBlock:!0,errorCode:Xe.outputTooLarge(e,r).errorCode,hints:[`Found ${e} ${o}${e===1?"":"s"} - exceeds safe limit of ${r}`,"Use charLength to paginate through results",i?"Detailed results increase size - consider using charLength for pagination":"Consider using charLength to paginate large result sets"]}:{shouldBlock:!1}}var Et=y(()=>{"use strict";no();Ys();_e()});import{validateCommand as kO}from"@octocodeai/octocode-engine/commandValidator";async function kr(e,t=[],n={}){let r=kO(e,t);if(!r.isValid)throw new Error(`Command validation failed: ${r.error||"Command not allowed"}`);let o=Zs(t);if(!o.valid)throw new Error(`Argument validation failed: ${o.error||"Invalid arguments"}`);let{timeout:i=3e4,cwd:s,env:a,maxOutputSize:c=10*1024*1024,tolerateOutputLimit:l=!1}=n,u=await vn(e,t,{timeout:i,cwd:s,env:a,maxOutputSize:c});if(u.outputLimitExceeded&&l)return{success:!0,code:u.exitCode,stdout:u.stdout,stderr:u.stderr,truncated:!0};if(u.error)throw u.error;return{success:u.success,code:u.exitCode,stdout:u.stdout,stderr:u.stderr}}var wa=y(()=>{"use strict";ei()});function bt(e,t){let n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function OO(e,t){let n=t?["-tvf",e]:["-tf",e],r=t?["-l",e]:["-Z","-1",e],o=n,i=["l","-ba","-bd",e],s=t?["list","-i",e,"-v"]:["list","-i",e],a={command:"tar",args:n},c={command:"unzip",args:r},l={command:"bsdtar",args:o},u={command:"7z",args:i},d={command:"7zz",args:i},p={command:"aa",args:s};return bt(Yy,e)?[p]:bt(td,e)?[u,d,l,c,a]:bt(ed,e)?[l,u,d,c,a]:bt(Zu,e)?[a,c,l,u,d]:[c,a,l,u,d]}function vO(e,t){let n={command:"tar",args:["-xOf",e,"--",t]},r={command:"unzip",args:["-p",e,t]},o={command:"bsdtar",args:["-xOf",e,"--",t]},i=["e","-so","-bd","--",e,t],s={command:"7z",args:i},a={command:"7zz",args:i};return bt(td,e)?[s,a,o,r,n]:bt(ed,e)?[o,s,a,r,n]:bt(Zu,e)?[n,r,o,s,a]:[r,n,o,s,a]}async function nd(e){let t=[];for(let n of e){let r=await kr(n.command,n.args);if(!r.success){if(r.stderr.toLowerCase().includes("not found")||r.stderr.toLowerCase().includes("no such file")||r.code===127){t.push(n.command);continue}return{success:!1,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!0,stdout:r.stdout,stderr:r.stderr,commandUsed:n.command,missingCommands:t.length?t:void 0}}return{success:!1,stdout:"",stderr:"All backends failed or were not found",missingCommands:t}}function AO(e,t){return t!=="7z"&&t!=="7zz"?e:e.split(`
43
43
  `).map(n=>{if(!n.trim())return"";let r=n.match(/^.+\s{2,}(\S.*)$/);return r?r[1].trim():n.trim()}).filter(Boolean).join(`
44
- `)}async function bp(e,t){let n=await Js(GS(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?BS(n.stdout,n.commandUsed):n.stdout).split(`
45
- `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function Sp(e,t){return Js(US(e,t))}function zS(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return Ze(Rp,e)?[c]:Ze(Xs,e)?[s,a,o,n,r]:Ze(Ys,e)?[o,s,a,n,r]:Ze(Ks,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Cp(e,t){return Js(zS(e,t))}var QS={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},jS=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],$S={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"};function VS(e){let t=e.toLowerCase();for(let{ext:n,format:r}of jS)if(t.endsWith(n))return r}async function WS(e){let t=await On("file",["--mime-type","-b",e]);if(t.success)return $S[t.stdout.trim().toLowerCase()]}async function KS(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await On(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await On(r.command,r.args)).stderr,commandUsed:r.command}}async function Pp(e,t){let n;if(t!=="auto"?n=t:n=VS(e)??await WS(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=QS[n],o=await KS(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}function Ep(e){try{return{success:!0,info:O.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function Tp(e,t,n,r=0){try{let o=O.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var ZS=S.LOCAL_BINARY_INSPECT;function wp(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function qS(e){return Zs(W.unzip,`${qo(e)}-${wp()}`)}function eC(e,t){return Zs(W.binary,`${qo(e)}-${t}-${wp()}`)}function tC(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function qs(e,t,n,r){let o=xp(eC(e,t)),i=xp(Zs(o,tC(n)));if(!i.startsWith(o+XS)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await In.mkdir(YS(i),{recursive:!0}),await In.writeFile(i,r,"utf-8"),i}var nC=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],_p=!1;function rC(){if(!_p){try{JS.addAllowedCommands(nC)}catch{}_p=!0}}var oC=1e3,iC=8;function Ap(e,t,n){let r=O.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
46
- `):null}function ea(e,t,n,r){let s=mt(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function sC(e,t){let n=Ep(e);if(!n.success||!n.info)return L(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function aC(e,t){let n=t.verbose??!1,r=await bp(e,n);if(!r.success)return L(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??oC,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,u=a?s.slice((c-1)*a,c*a):s,l=a?Math.ceil(s.length/a):1,d=a?c<l:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:u,...a&&{pagination:{currentPage:c,totalPages:l,hasMore:d,entriesPerPage:a,totalEntries:s.length}}}}async function cC(e,t){let n=t.archiveFile,r=await Sp(e,n);if(!r.success)return L(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return L("Entry is empty",t);let i=await qs(e,"extract",n,o);if(t.matchString){let c=Ap(o,t.matchString,t.matchStringContextLines??3);if(!c)return L(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=Ce(),a=ea(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,contentLength:o.length,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function uC(e,t){let n=await Pp(e,t.format??"auto");if(!n.success)return L(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return L("Decompressed file is empty",t);let o=await qs(e,"decompress",`${qo(e)}.decompressed.txt`,r);if(t.matchString){let a=Ap(r,t.matchString,t.matchStringContextLines??3);if(!a)return L(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=Ce(),s=ea(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,contentLength:r.length,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function lC(e,t){let n=t.minLength??iC,r=t.includeOffsets??!1,o=t.scanOffset??0,i=Tp(e,n,r,o);if(!i.success)return L(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
47
- `),a=s?await qs(e,"strings",`${qo(e)}.strings.txt`,s):void 0,c=Ce(),u=ea(s,t.charOffset,t.charLength,c);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},contentLength:s.length,totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function dC(e,t){try{await In.stat(e)}catch{return L(`File not found: ${e}`,t)}let n=qS(e);await In.mkdir(n,{recursive:!0});let r=await Cp(e,n);if(!r.success)return L(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await In.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function Lp(e){rC();let t=ve(e,ZS);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await In.stat(n)).isFile())return L(`Path is not a regular file: ${n}`,e)}catch{return L(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return sC(n,e);case"list":return aC(n,e);case"extract":return cC(n,e);case"decompress":return uC(n,e);case"strings":return lC(n,e);case"unpack":return dC(n,e);default:return L(`Unknown mode: ${String(e.mode)}`,e)}}async function Op(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Le(Zo,n);if(r.ok===!1)return r.error;let o=await Lp(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return U(o,s),o}}),{toolName:S.LOCAL_BINARY_INSPECT},e)}import{open as pC,readFile as fC,stat as mC}from"fs/promises";import{ContentSanitizer as gC}from"@octocodeai/octocode-engine/contentSanitizer";var oN={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},st={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500};function kp(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function Ip(e,t,n){return{...e,...kp(t,n)}}function hC(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function yC(e,t){try{return{fileStats:await mC(t)}}catch(n){let r=De.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:L(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function RC(e,t){return t>st.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function bC(e,t,n){let r=De.fileTooLarge(e.path,n,st.LARGE_FILE_THRESHOLD_KB);return L(r,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function SC(e,t){let n=De.binaryFileUnsupported(e.path);return L(n,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function CC(e){let n=Buffer.alloc(8192),r;try{r=await pC(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let u=i[c];if(u===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let l=u===9||u===10||u===13;u<32&&!l&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(Tu("binary sample handle close",void 0))}}async function PC(e,t){try{return{content:await fC(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?De.fileAccessFailed(e.path,r):De.fileReadFailed(e.path,r);return{errorResult:L(i,e,{toolName:S.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function EC(e,t){return{status:"empty",errorCode:H.NO_MATCHES,totalLines:t}}function TC(e,t,n){let r=xo(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:EC(e,n)};let o=r.lines.join(`
48
- `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,u,l,d;if(r.matchRanges.length>0){let m=r.matchRanges[0],p=r.matchRanges[r.matchRanges.length-1];m&&p&&(u=m.start,l=p.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:u,actualEndLine:l,matchRanges:d,warnings:[c]}}function xC(e){return e.startLine!==void 0&&e.endLine!==void 0}function _C(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:H.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:H.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
49
- `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function wC(e,t,n){let r=t.split(`
50
- `),o=Wt(t);return e.matchString?TC(e,r,o):xC(e)?_C(e,r,o):{resultContent:t,isPartial:!1}}function AC(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),u=i?O.applyContentViewMinification(t.resultContent,c):t.resultContent,l=e.charLength,d=e.charOffset??0,m=l,p=!1,f=d;m===void 0&&u.length>o&&(m=o,p=!0,a.push(`Auto-paginated: Content (${u.length} chars) exceeds ${o} char limit`));let g="char-limit",h=m;if(m!==void 0){let C=To(u,f,m,c);g=C.chunkMode,h=C.length}let R=mt(u,f,h,m!==void 0?{pageSize:m}:void 0),b=t.isPartial||R.hasMore,P;if(R.hasMore&&g==="char-limit"&&Sr(R.paginatedContent)){let C=R.charOffset+R.charLength;P=Cr(u,C,c)}let x=R.hasMore&&R.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:R.nextCharOffset,charLength:m??R.charLength,minify:e.minify}}}:void 0;return{path:c,content:R.paginatedContent,...s!=="standard"&&{contentView:s},...b&&{isPartial:b},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...(m!==void 0||d>0||p)&&{pagination:{...br(R),chunkMode:g,...P!==void 0&&{nextBlockChar:P}}},...x?{next:x}:{},...a.length>0&&{warnings:a}}}function LC(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function vp(e){let t=Ce();try{let n=ve(e,S.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=hC(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await yC(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,u=c/1024;if(await CC(o))return U(SC(e,o),c);if(RC(e,u))return U(bC(e,o,u),c);let{content:l,errorResult:d}=await PC(e,o);if(d||l===void 0)return d;let m=gC.sanitizeContent(l,i),p=m.content,f=p.length,g=Buffer.byteLength(p,"utf-8"),h=m.hasSecrets?`Secrets detected and redacted: ${m.secretsDetected.join(", ")}`:void 0,R=e.minify,b=R==="standard"||R==="symbols",P=b?"standard":"none",x;if(R==="symbols"){let w=O.extractSignatures(p,i);if(w===null&&(x=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`),w!==null){let A=Wt(p),Q=O.applyContentViewMinification(w,i);return U({path:e.path,content:Q,contentView:"symbols",isSkeleton:!0,totalLines:A,...kp(f,g),...h?{warnings:[h]}:{}},f)}}let C=Wt(p),_=wC(e,p,t),I=w=>{let A=[...x?[x]:[],...h?[h]:[]];if(A.length===0)return w;let Q=w.warnings??[];return{...w,warnings:[...Q,...A]}};if(_.earlyResult){let w=_.earlyResult.content,A=b&&typeof w=="string"?{..._.earlyResult,content:O.applyContentViewMinification(w,i)}:_.earlyResult;return U(Ip(I(ta(LC(A,P),e,C)),f,g),f)}let j=AC(e,_,s,C,t,b,P);return U(Ip(I(ta(j,e,C)),f,g),f)}catch(n){return L(n,e,{toolName:S.LOCAL_FETCH_CONTENT})}}function ta(e,t,n){return e}import{z as OC}from"zod";import{FetchContentQuerySchema as Fp}from"@octocodeai/octocode-core/schemas";var IC=OC.enum(["none","standard","symbols"]).optional().default("standard"),Mp={startLine:Ln,endLine:Ln,contextLines:An.default(5),charOffset:v(0,1e8).optional(),charLength:v(1,5e4).optional(),minify:IC},kC=ce(Fp,Mp),ei=re(Fp,Mp),Np=X(kC,{maxQueries:5});async function Dp(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Le(ei,n);return r.ok===!1?r.error:await vp(r.data)}}),{toolName:S.LOCAL_FETCH_CONTENT},e)}import{z as vC}from"zod";import{FindFilesQuerySchema as FC}from"@octocodeai/octocode-core/schemas";var Hp={maxDepth:v(0,100).optional(),minDepth:v(0,100).optional(),limit:v(1,1e4).optional(),page:q.default(1),itemsPerPage:v(1,50).optional()},Gp=vC.object(Object.fromEntries(Object.entries(FC.shape).filter(([e])=>e!=="regexType")));function MC(e,t){e.minDepth!==void 0&&e.maxDepth!==void 0&&e.minDepth>e.maxDepth&&t.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var NC=ce(Gp,Hp),ti=re(Gp,Hp).superRefine(MC),Up=X(NC,{maxQueries:5});function kn(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function Ar(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var DC=[];function HC(e,t){let n=t??DC,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Bp(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=ve(e,S.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:HC(i.path,i.excludeDir)},a=QC(s),c=e.limit??1e4,u=O.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:c}),l=u.totalDiscovered,d=u.wasCapped,m=u.entries.map(A=>GC(A,r)),p=e.sortBy||"modified";UC(m,p,r);let f=BC(m,t,n),g=f.length,h=e.itemsPerPage||20,R=e.page||1,b=Math.max(1,Math.ceil(g/h)),P=(R-1)*h,x=Math.min(P+h,g),_=f.slice(P,x),I=[...u.warnings,...u.skipped>0?[`${u.skipped} entr${u.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],j=[...a,...I],w={...g===0?{status:"empty"}:{},path:i.path,files:_,pagination:{currentPage:R,totalPages:b,filesPerPage:h,totalFiles:g,hasMore:R<b,...R<b?{nextPage:R+1}:{},...d?{totalFilesFound:l}:{}},...j.length>0&&{warnings:j}};return U(zp(w,e,{totalFiles:g}),u.entries.reduce((A,Q)=>A+Q.path.length,0))}catch(o){return L(o,e,{toolName:S.LOCAL_FIND_FILES})}}function GC(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function zp(e,t,n){return e}function UC(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function BC(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=kn(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}var zC=/^\d+[hdwm]$/;function QC(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!zC.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}async function Qp(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Le(ti,n);return r.ok===!1?r.error:await Bp(r.data)}}),{toolName:S.LOCAL_FIND_FILES},e)}import{z as na}from"zod";import{RipgrepQuerySchema as jp}from"@octocodeai/octocode-core/schemas";var jC=["semanticRanking"],$p={contextLines:An,matchContentLength:v(1,1e5).optional().default(500),maxMatchesPerFile:v(1,1e5).optional(),maxFiles:v(1,1e5).optional(),matchPage:q.optional(),itemsPerPage:v(1,1e3).optional(),page:q.default(1),unique:na.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:na.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},$C={...$p,semanticRanking:na.never().optional()},VC=ce(jp,$C),WC=re(jp,$p,{strict:!0,omit:jC}),vn=WC.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),Vp=X(VC,{maxQueries:5});import{validateRipgrepQuery as FP}from"@octocodeai/octocode-core/schemas/runtime";var Wp=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],ee={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},KC=2e3,YC=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,Kp={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},Lr={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...Kp},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...Kp},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},XC=/^\s*#{1,6}\s/,oa=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,JC=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,ZC=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,qC=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,eP=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,tP=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,nP=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,rP=new Set(["typescript","javascript","rust","python","go","java","scala"]),Xp=/\.([a-z0-9]+)$/i;function ia(e){return Xp.exec(e)?.[1]?.toLowerCase()??""}function oP(e){let t=ia(e);if(!t)return!1;for(let n of rP)if(Lr[n].extensions.includes(t))return!0;return!1}function iP(e,t,n){if(n&&n!=="auto")return Lr[n];let r=ia(e),o=(t??"").toLowerCase();for(let i of Wp){let s=Lr[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of Wp){let s=Lr[i];if(i!=="generic"&&s.extensions.includes(r))return s}return Lr.generic}function Jp(e){return JC.test(e)?"generated":qC.test(e)?"fixture":ZC.test(e)?"test":tP.test(e)?"config":eP.test(e)?"docs":!oa.test(e)&&(nP.test(e)||oP(e))?"source":"unknown"}function sP(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function aP(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function cP(e,t,n,r,o){if(!e||e.length===0)return 0;let i=bP(n.keyword),s=0,a="";for(let c of e){let u=c.value??"";if(!u)continue;let l=SP(u,r,n.caseSensitive),d=0,m=[];r&&i&&(new RegExp(`(^|[^\\w$])${qp(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(l)?(d+=ee.exactWholeWord,m.push("whole-word match")):!n.caseSensitive&&l.toLowerCase().includes(r.toLowerCase())?(d+=ee.exactCaseInsensitive,m.push("case-insensitive match")):l.includes(r)&&(d+=ee.substring,m.push("substring match")));let p=c.kind;if(p)d+=uP(p,m);else{let f=CP(l,r,t.id,n.caseSensitive);f!=="code"?(d+=ee.commentOrStringPenalty,m.push(f==="comment"?"comment match (weak)":"string literal (weak)")):(ra(t.declaration,l)&&(d+=ee.declarationLine,m.push("declaration line")),ra(t.export,l)&&(d+=ee.exportLine,m.push("export/public line")),ra(t.import,l)&&(d+=ee.importLine,m.push("import line")),t.id==="markdown"&&XC.test(l)&&(d+=ee.headingLine,m.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&lP(l,r)&&(d+=ee.configKeyLine,m.push("config key match")))}d>s&&(s=d,a=m.join(", "))}return a&&o.push(a),s}function uP(e,t){switch(e){case"declaration":return t.push("AST: declaration"),ee.declarationLine;case"export":return t.push("AST: export/public"),ee.exportLine;case"configKey":return t.push("AST: config key"),ee.configKeyLine;case"heading":return t.push("AST: heading"),ee.headingLine;case"import":return t.push("AST: import"),ee.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),ee.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function lP(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function dP(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),u=n.toLowerCase();c.split("/").some(l=>l.replace(Xp,"").includes(u))&&(s+=ee.pathSegmentToken,i.push("query token in path"))}let a=ia(e);return r.extensions.includes(a)&&t.langType&&(s+=ee.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=ee.sourceDir,i.push("source file")),s}function pP(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),ee.lowSignalPathPenalty):0}function fP(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*ee.matchCountScale,r=Math.min(n,ee.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function mP(e,t){let n=aP(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>gP(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function gP(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${qp(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function hP(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let u=Math.log2((t.candidateCount+1)/(c+1)),l=Math.min(u*ee.rareQueryTokenScale,ee.rareQueryTokenCap);l>i&&(i=l,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function yP(e,t,n){let r=iP(e.path,t.langType,t.profileOverride),o=Jp(e.path),i=sP(t.keyword),s=[],a=0;return a+=cP(e.matches,r,t,i,s),a+=dP(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=ee.pathUnderQuery,s.push("under requested subtree")),a+=pP(o,t,s),oa.test(e.path)&&!t.explicitLowSignal&&(a+=ee.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=fP(e.matchCount??0,s),a+=hP(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Zp(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Yp),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,m)=>d.path.localeCompare(m.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??KC,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Yp);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=mP(i,n),u=i.map(d=>{try{return{file:d,s:yP(d,n,c)}}catch{return{file:d,s:RP()}}});u.sort((d,m)=>{if(m.s.score!==d.s.score)return m.s.score-d.s.score;let p=(m.file.matchCount??0)-(d.file.matchCount??0);return p!==0?p:d.file.path.localeCompare(m.file.path)});let l={files:[...u.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(l.debug=new Map(u.map(d=>[d.file.path,d.s]))),l}function RP(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Yp(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function ra(e,t){for(let n of e)if(n.test(t))return!0;return!1}function qp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bP(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function SP(e,t,n){if(e.indexOf(`
44
+ `)}async function Xy(e,t){let n=await nd(OO(e,t));if(!n.success)return n;let o=(!t&&n.commandUsed?AO(n.stdout,n.commandUsed):n.stdout).split(`
45
+ `).map(i=>i.trim()).filter(Boolean);return{...n,entries:o}}async function Jy(e,t){return nd(vO(e,t))}function LO(e,t){let n={command:"tar",args:["-xf",e,"-C",t]},r={command:"unzip",args:["-o","-q",e,"-d",t]},o={command:"bsdtar",args:["-xf",e,"-C",t]},i=["x",`-o${t}`,"-y","-bd","--",e],s={command:"7z",args:i},a={command:"7zz",args:i},c={command:"aa",args:["extract","-i",e,"-d",t]};return bt(Yy,e)?[c]:bt(td,e)?[s,a,o,n,r]:bt(ed,e)?[o,s,a,n,r]:bt(Zu,e)?[n,o,s,a,r]:[r,n,o,s,a]}async function Zy(e,t){return nd(LO(e,t))}var Zu,ed,td,Yy,eb=y(()=>{"use strict";wa();Zu=[".tar",".tar.gz",".tgz",".tar.bz2",".tbz2",".tbz",".tar.xz",".txz",".tar.zst",".tzst"],ed=[".7z",".iso",".cab",".cpio",".xar",".pkg",".ar",".deb",".lha",".lzh"],td=[".dmg",".rar",".cpgz"],Yy=[".aar",".yaa"]});function MO(e){let t=e.toLowerCase();for(let{ext:n,format:r}of IO)if(t.endsWith(n))return r}async function DO(e){let t=await kr("file",["--mime-type","-b",e]);if(t.success)return FO[t.stdout.trim().toLowerCase()]}async function NO(e,t){let n=[{command:e.command,args:e.args(t)},...e.fallback?[{command:e.fallback.command,args:e.fallback.args(t)}]:[]];for(let i of n){let s=await kr(i.command,i.args);if(s.success)return{success:!0,stdout:s.stdout,stderr:s.stderr,commandUsed:i.command}}let r=n[n.length-1];return{success:!1,stdout:"",stderr:(await kr(r.command,r.args)).stderr,commandUsed:r.command}}async function tb(e,t){let n;if(t!=="auto"?n=t:n=MO(e)??await DO(e),!n)return{success:!1,error:"Could not detect compression format from extension or mime-type. Set format: gzip|bzip2|xz|lzma|zstd|lz4|brotli|lzfse explicitly."};let r=_O[n],o=await NO(r,e);return o.success?{success:!0,format:n,backend:o.commandUsed,content:o.stdout}:{success:!1,format:n,backend:o.commandUsed,error:o.stderr||`${o.commandUsed} failed`}}var _O,IO,FO,nb=y(()=>{"use strict";wa();_O={gzip:{command:"zcat",args:e=>[e],fallback:{command:"gunzip",args:e=>["-c",e]}},bzip2:{command:"bzcat",args:e=>[e]},xz:{command:"xzcat",args:e=>[e]},lzma:{command:"xzcat",args:e=>["--format=lzma",e]},zstd:{command:"zstdcat",args:e=>[e],fallback:{command:"zstd",args:e=>["-dcq",e]}},lz4:{command:"lz4cat",args:e=>[e]},brotli:{command:"brotli",args:e=>["-dc",e]},lzfse:{command:"lzfse",args:e=>["-decode","-i",e,"-o","/dev/stdout"]}},IO=[{ext:".gz",format:"gzip"},{ext:".bz2",format:"bzip2"},{ext:".xz",format:"xz"},{ext:".lzma",format:"lzma"},{ext:".zst",format:"zstd"},{ext:".zstd",format:"zstd"},{ext:".lz4",format:"lz4"},{ext:".br",format:"brotli"},{ext:".lzfse",format:"lzfse"}],FO={"application/gzip":"gzip","application/x-gzip":"gzip","application/x-bzip2":"bzip2","application/x-bzip":"bzip2","application/x-xz":"xz","application/x-lzma":"lzma","application/zstd":"zstd","application/x-zstd":"zstd","application/x-lz4":"lz4","application/x-brotli":"brotli","application/x-lzfse":"lzfse"}});function rb(e){try{return{success:!0,info:F.inspectBinaryNative(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}function ob(e,t,n,r=0){try{let o=F.extractBinaryStringsNative(e,t,n,r);return{success:!0,strings:o.strings,totalFound:o.totalFound,truncated:o.truncated,nextScanOffset:o.nextScanOffset}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}var ib=y(()=>{"use strict";be()});import{promises as Or}from"fs";import{join as rd,basename as Ea,dirname as GO,resolve as sb,sep as HO}from"node:path";import{securityRegistry as zO}from"@octocodeai/octocode-engine/registry";function cb(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function UO(e){return rd(ne.unzip,`${Ea(e)}-${cb()}`)}function jO(e,t){return rd(ne.binary,`${Ea(e)}-${t}-${cb()}`)}function $O(e){return e.replace(/\\/g,"/").split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")||"content.txt"}async function od(e,t,n,r){let o=sb(jO(e,t)),i=sb(rd(o,$O(n)));if(!i.startsWith(o+HO)&&i!==o)throw new Error("Derived binary output path escaped its tmp directory.");return await Or.mkdir(GO(i),{recursive:!0}),await Or.writeFile(i,r,"utf-8"),i}function VO(){if(!ab){try{zO.addAllowedCommands(qO)}catch{}ab=!0}}function id(e,t,n){let r=F.extractMatchingLines(e,t,{isRegex:!0,caseSensitive:!1,contextLines:n});return r.lines.length>0?r.lines.join(`
46
+ `):null}function sd(e,t,n,r){let s=Sr(e,t??0,n??r),a=s.hasMore||s.totalPages>1?{currentPage:s.currentPage,totalPages:s.totalPages,hasMore:s.hasMore,charOffset:s.charOffset,charLength:s.charLength,totalChars:s.totalChars,...s.hasMore&&s.nextCharOffset!==void 0?{nextCharOffset:s.nextCharOffset}:{}}:void 0;return{content:s.paginatedContent,isPartial:s.hasMore,pagination:a}}function YO(e,t){let n=rb(e);if(!n.success||!n.info)return M(n.error??"inspect failed",t);let r=n.info,o=t.detailed??!1;return{status:"success",mode:"inspect",path:e,format:r.format,description:r.description,magicBytes:r.magicHex,...r.arch?{arch:r.arch}:{},...r.bits?{bits:r.bits}:{},...r.endianness?{endianness:r.endianness}:{},...r.stripped!==void 0?{stripped:r.stripped}:{},...r.entry?{entry:r.entry}:{},symbolCount:r.symbolCount,importCount:r.importCount,exportCount:r.exportCount,...o&&r.symbols.length?{symbols:r.symbols}:{},...o&&r.imports.length?{imports:r.imports}:{},...o&&r.exports.length?{exports:r.exports}:{},...o&&r.sections.length?{sections:r.sections}:{},...r.libraries.length?{libraries:r.libraries}:{},...o?{detailed:!0}:{},...r.truncated?{truncated:!0}:{},...r.notes.length?{warnings:r.notes}:{}}}async function XO(e,t){let n=t.verbose??!1,r=await Xy(e,n);if(!r.success)return M(r.stderr||"All archive backends failed",t);let o=r.entries??[],i=Math.min(t.maxEntries??WO,o.length),s=o.slice(0,i),a=t.entriesPerPage,c=t.entryPageNumber??1,l=a?s.slice((c-1)*a,c*a):s,u=a?Math.ceil(s.length/a):1,d=a?c<u:!1;return{status:"success",mode:"list",path:e,backend:r.commandUsed,totalEntries:o.length,entries:l,...a&&{pagination:{currentPage:c,totalPages:u,hasMore:d,entriesPerPage:a}}}}async function JO(e,t){let n=t.archiveFile,r=await Jy(e,n);if(!r.success)return M(r.stderr||"Extraction failed",t);let o=r.stdout;if(!o)return M("Entry is empty",t);let i=await od(e,"extract",n,o);if(t.matchString){let c=id(o,t.matchString,t.matchStringContextLines??3);if(!c)return M(`No lines match "${t.matchString}" in the extracted entry`,t);o=c}let s=et(),a=sd(o,t.charOffset,t.charLength,s);return{status:"success",mode:"extract",path:e,archiveFile:n,backend:r.commandUsed,localPath:i,content:a.content,isPartial:a.isPartial,...a.pagination?{pagination:a.pagination}:{}}}async function ZO(e,t){let n=await tb(e,t.format??"auto");if(!n.success)return M(n.error??"Decompression failed",t);let r=n.content??"";if(!r)return M("Decompressed file is empty",t);let o=await od(e,"decompress",`${Ea(e)}.decompressed.txt`,r);if(t.matchString){let a=id(r,t.matchString,t.matchStringContextLines??3);if(!a)return M(`No lines match "${t.matchString}" in the decompressed content`,t);r=a}let i=et(),s=sd(r,t.charOffset,t.charLength,i);return{status:"success",mode:"decompress",path:e,format:n.format,backend:n.backend,localPath:o,content:s.content,isPartial:s.isPartial,...s.pagination?{pagination:s.pagination}:{}}}async function ev(e,t){let n=t.minLength??KO,r=t.includeOffsets??!1,o=t.scanOffset??0,i=ob(e,n,r,o);if(!i.success)return M(i.error??"strings extraction failed",t);let s=(i.strings??[]).join(`
47
+ `),a=s?await od(e,"strings",`${Ea(e)}.strings.txt`,s):void 0;if(t.matchString){let d=id(s,t.matchString,t.matchStringContextLines??3);if(!d)return M(`No lines match "${t.matchString}" in extracted strings`,t);s=d}let l=!!a&&t.charOffset===void 0&&t.charLength===void 0&&!t.matchString?Math.min(QO,et()):et(),u=sd(s,t.charOffset,t.charLength,l);return{status:"success",mode:"strings",path:e,content:u.content,...a?{localPath:a}:{},totalFound:i.totalFound??0,isPartial:u.isPartial,...u.pagination?{pagination:u.pagination}:{},scanOffset:o,...i.nextScanOffset!==void 0?{nextScanOffset:i.nextScanOffset}:{}}}async function tv(e,t){try{await Or.stat(e)}catch{return M(`File not found: ${e}`,t)}let n=UO(e);await Or.mkdir(n,{recursive:!0});let r=await Zy(e,n);if(!r.success)return M(`Unpack failed: ${r.stderr||"no backend could extract this archive"}`,t);let o=0;try{o=(await Or.readdir(n)).length}catch{}return{status:"success",mode:"unpack",path:e,localPath:n,cached:!1,topLevelEntries:o}}async function lb(e){VO();let t=Ke(e,BO);if(!t.isValid)return t.errorResult;let n=t.sanitizedPath;try{if(!(await Or.stat(n)).isFile())return M(`Path is not a regular file: ${n}`,e)}catch{return M(`File not found: ${n}`,e)}switch(e.mode){case"inspect":return YO(n,e);case"list":return XO(n,e);case"extract":return JO(n,e);case"decompress":return ZO(n,e);case"strings":return ev(n,e);case"unpack":return tv(n,e);default:return M(`Unknown mode: ${String(e.mode)}`,e)}}var BO,QO,qO,ab,WO,KO,ub=y(()=>{"use strict";fe();hn();Et();be();zo();br();eb();nb();ib();BO=A.LOCAL_BINARY_INSPECT,QO=4e3;qO=["file","unzip","tar","bsdtar","7z","7zz","aa","zcat","gunzip","bzcat","xzcat","zstdcat","zstd","lz4cat","brotli","lzfse"],ab=!1;WO=1e3,KO=8});async function db(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_BINARY_INSPECT,query:n,contextMessage:"localBinaryInspect execution failed",execute:async()=>{let r=Ue(Tr,n);if(r.ok===!1)return r.error;let o=await lb(r.data),i=o,s=typeof i.content=="string"?i.content.length:typeof i.strings=="object"&&i.strings!==null?JSON.stringify(i.strings).length:0;return $(o,s),o}}),{toolName:A.LOCAL_BINARY_INSPECT},e)}var ad=y(()=>{"use strict";si();fe();je();De();oe();Ht();ub()});var aV,Tt,vr=y(()=>{"use strict";aV={COMMAND_TIMEOUT:3e4,MAX_OUTPUT_SIZE:10485760,MAX_RESULTS:100,CONTEXT_LINES:5},Tt={MCP_MAX_TOKENS:25e3,CHARS_PER_TOKEN:4,MAX_FETCH_CONTENT_CHARS:5e4,MAX_OUTPUT_SIZE_BYTES:10*1024*1024,LARGE_FILE_THRESHOLD_KB:100,MAX_ENTRIES_BEFORE_PAGINATION:100,MAX_FILES_DEFAULT:1e3,DEFAULT_ENTRIES_PER_PAGE:100,MAX_ENTRIES_PER_PAGE:200,MAX_LIST_ITEMS_DETAILED:100,MAX_LIST_ITEMS_SIMPLE:200,MAX_ARCHIVE_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_PER_PAGE:100,MAX_DIR_ENTRIES_TREE:1e3,DEFAULT_EXEC_TIMEOUT_MS:3e4,DEFAULT_MAX_MATCHES_PER_FILE:3,DEFAULT_CONTEXT_LINES:5,DEFAULT_MATCH_CONTENT_LENGTH:500,MAX_MATCH_CONTENT_LENGTH:800,DEFAULT_MATCHES_PER_PAGE:10,MAX_MATCHES_PER_PAGE:100,DEFAULT_FILES_PER_PAGE:20,MAX_FILES_PER_PAGE:50,MAX_RIPGREP_DIRECTORY_SIZE_MB:100,MAX_FILE_COUNT_FOR_SEARCH:1e3,ESTIMATED_AVG_FILE_SIZE_BYTES:50*1024,LARGE_RESULT_BYTES_HINT:1.5*1024*1024,BINARY_MAX_BYTES:10*1024,BINARY_DEFAULT_HEX_LINES:20,BINARY_DEFAULT_MIN_STRING_LENGTH:6,MAX_ARCHIVE_FILES:1e3,DEFAULT_ARCHIVE_MAX_FILES:200,GLOBAL_MEMORY_LIMIT_BYTES:100*1024*1024,PER_OPERATION_MEMORY_LIMIT_BYTES:10*1024*1024,MEMORY_RESERVATION_TIMEOUT_MS:300*1e3,TOKEN_CRITICAL_THRESHOLD:5e4,TOKEN_HIGH_THRESHOLD:25e3,TOKEN_MODERATE_THRESHOLD:1e4,TOKEN_NOTICE_THRESHOLD:2500}});function lV(e){return t=>{}}function pb(e,t){return n=>t}var cd=y(()=>{"use strict"});import{open as nv,readFile as rv,stat as ov}from"fs/promises";import{ContentSanitizer as iv}from"@octocodeai/octocode-engine/contentSanitizer";function ld(e,t){let n=Math.abs(t-e);return n>=50&&n/e>=.02?{sourceChars:e,sourceBytes:t}:{sourceChars:e}}function fb(e,t,n){return{...e,...ld(t,n)}}function sv(e){let t=e.fullContent===!0,n=e.matchString!==void 0,r=e.startLine!==void 0||e.endLine!==void 0;if(t&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(t&&r)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&r)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let o=e.startLine!==void 0,i=e.endLine!==void 0;return o&&!i?{status:"error",error:`startLine=${e.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!o?{status:"error",error:`endLine=${e.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function av(e,t){try{return{fileStats:await ov(t)}}catch(n){let r=Xe.fileAccessFailed(e.path,n instanceof Error?n:void 0);return{errorResult:M(r,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function cv(e,t){return t>Tt.LARGE_FILE_THRESHOLD_KB&&!e.matchString&&!e.startLine&&!e.fullContent}function lv(e,t,n){let r=Xe.fileTooLarge(e.path,n,Tt.LARGE_FILE_THRESHOLD_KB);return M(r,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}function uv(e,t){let n=Xe.binaryFileUnsupported(e.path);return M(n,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}async function dv(e){let n=Buffer.alloc(8192),r;try{r=await nv(e,"r");let{bytesRead:o}=await r.read(n,0,8192,0);if(o===0)return!1;let i=n.subarray(0,o);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return!0}let s=0,a=0,c=0;for(;c<i.length;){let l=i[c];if(l===27&&c+1<i.length&&i[c+1]===91){for(c+=2;c<i.length&&(i[c]<64||i[c]>126);)c+=1;c+=1;continue}s+=1;let u=l===9||l===10||l===13;l<32&&!u&&(a+=1),c+=1}return s>0&&a/s>.05}catch{return!1}finally{await r?.close().catch(pb("binary sample handle close",void 0))}}async function pv(e,t){try{return{content:await rv(t,"utf-8")}}catch(n){let r=n instanceof Error?n:void 0,i=r?.code==="EISDIR"?Xe.fileAccessFailed(e.path,r):Xe.fileReadFailed(e.path,r);return{errorResult:M(i,e,{toolName:A.LOCAL_FETCH_CONTENT,extra:{resolvedPath:t}})}}}function fv(e,t){return{status:"empty",errorCode:Q.NO_MATCHES,totalLines:t}}function mv(e,t,n){let r=_s(t,e.matchString,e.contextLines??5,e.matchStringIsRegex??!1,e.matchStringCaseSensitive??!1);if(r.lines.length===0)return{isPartial:!1,earlyResult:fv(e,n)};let o=r.lines.join(`
48
+ `),i=e.contextLines??5,s=r.matchingLines.slice(0,10).join(", "),a=r.matchingLines.length>10?` (+${r.matchingLines.length-10} more)`:"",c=`Found ${r.matchCount} occurrence${r.matchCount===1?"":"s"} of "${e.matchString}" on line${r.matchingLines.length===1?"":"s"} ${s}${a} \u2014 all shown as ${r.matchRanges.length} slice${r.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,l,u,d;if(r.matchRanges.length>0){let p=r.matchRanges[0],f=r.matchRanges[r.matchRanges.length-1];p&&f&&(l=p.start,u=f.end,r.matchRanges.length>1&&(d=r.matchRanges))}return{resultContent:o,isPartial:!0,actualStartLine:l,actualEndLine:u,matchRanges:d,warnings:[c]}}function gv(e){return e.startLine!==void 0&&e.endLine!==void 0}function hv(e,t,n){let r=e.startLine,o=e.endLine,i=Math.max(1,r),s=Math.min(o,n);if(o<r)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:Q.NO_MATCHES,warnings:[`startLine ${r} is greater than endLine ${o} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:Q.NO_MATCHES,warnings:[`Requested startLine ${r} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let a=[];return o>n&&a.push(`Requested endLine ${o} adjusted to ${n} (file end)`),{resultContent:t.slice(i-1,s).join(`
49
+ `),isPartial:!0,actualStartLine:i,actualEndLine:s,warnings:a}}function yv(e,t,n){let r=t.split(`
50
+ `),o=Dt(t);return e.matchString?mv(e,r,o):gv(e)?hv(e,r,o):{resultContent:t,isPartial:!1}}function bv(e,t,n,r,o,i=!0,s=i?"standard":"none"){if(!t.resultContent||t.resultContent.trim().length===0)return{status:"empty",totalLines:r};let a=[...t.warnings??[]],c=String(e.path),l=i?F.applyContentViewMinification(t.resultContent,c):t.resultContent,u=e.charLength,d=e.charOffset??0,p=u,f=!1,m=d;p===void 0&&!e.fullContent&&l.length>o&&(p=o,f=!0,a.push(`Auto-paginated: Content (${l.length} chars) exceeds ${o} char limit`));let g="char-limit",b=p;if(p!==void 0){let k=As(l,m,p,c);g=k.chunkMode,b=k.length}let C=Sr(l,m,b,p!==void 0?{pageSize:p}:void 0),S=t.isPartial||C.hasMore,T;if(C.hasMore&&g==="char-limit"&&Bo(C.paginatedContent)){let k=C.charOffset+C.charLength;T=Qo(l,k,c)}let L=C.hasMore&&C.nextCharOffset!==void 0?{continueChars:{tool:"localGetFileContent",query:{path:c,charOffset:C.nextCharOffset,charLength:p??C.charLength,minify:e.minify}}}:void 0;return{path:c,content:C.paginatedContent,...s!=="standard"&&{contentView:s},...S&&{isPartial:S},totalLines:r,...t.actualStartLine!==void 0&&t.actualEndLine!==void 0&&{startLine:t.actualStartLine,endLine:t.actualEndLine,...t.matchRanges!==void 0&&{matchRanges:t.matchRanges}},...n.mtime&&{modified:n.mtime.toISOString()},...(p!==void 0||d>0||f)&&{pagination:{...Dg(C),chunkMode:g,...T!==void 0&&{nextBlockChar:T}}},...L?{next:L}:{},...a.length>0&&{warnings:a}}}function Rv(e,t,n=!1){return typeof e.content!="string"?e:{...e,contentView:t,...n?{isSkeleton:!0}:{}}}async function Ta(e){let t=et();try{let n=Ke(e,A.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let r=sv(e);if(r)return r;let o=n.sanitizedPath,i=String(e.path),{fileStats:s,errorResult:a}=await av(e,o);if(a||!s)return a;let c=typeof s.size=="bigint"?Number(s.size):s.size,l=c/1024;if(await dv(o))return $(uv(e,o),c);if(cv(e,l))return $(lv(e,o,l),c);let{content:u,errorResult:d}=await pv(e,o);if(d||u===void 0)return d;let p=iv.sanitizeContent(u,i),f=p.content,m=f.length,g=Buffer.byteLength(f,"utf-8"),b=p.hasSecrets?`Secrets detected and redacted: ${p.secretsDetected.join(", ")}`:void 0,C=e.minify,S=C==="standard"||C==="symbols",T=S?"standard":"none",L;if(C==="symbols"){let I=F.extractSignatures(f,i);if(I===null){let v=Fs(f,i);if(v!==null)return $({path:e.path,content:v,contentView:"symbols",isSkeleton:!0,totalLines:Dt(f),...ld(m,g),...b?{warnings:[b]}:{}},m);L=`minify:"symbols" is not supported for this file type (${i.split(".").pop()??"unknown"}) \u2014 falling back to standard content view.`}if(I!==null){let v=Dt(f),B=F.applyContentViewMinification(I,i);return $({path:e.path,content:B,contentView:"symbols",isSkeleton:!0,totalLines:v,...ld(m,g),...b?{warnings:[b]}:{}},m)}}let k=Dt(f),O=yv(e,f,t),w=I=>{let v=[...L?[L]:[],...b?[b]:[]];if(v.length===0)return I;let B=I.warnings??[];return{...I,warnings:[...B,...v]}};if(O.earlyResult){let I=O.earlyResult.content,v=S&&typeof I=="string"?{...O.earlyResult,content:F.applyContentViewMinification(I,i)}:O.earlyResult;return $(fb(w(ud(Rv(v,T),e,k)),m,g),m)}let N=bv(e,O,s,k,t,S,T);return $(fb(w(ud(N,e,k)),m,g),m)}catch(n){return M(n,e,{toolName:A.LOCAL_FETCH_CONTENT})}}function ud(e,t,n){return e}var ai=y(()=>{"use strict";Is();be();zo();Ls();vr();Rr();br();fe();Et();no();mn();cd();oe();Ms()});import{z as Sv}from"zod";import{FetchContentQuerySchema as mb}from"@octocodeai/octocode-core/schemas";var Cv,gb,Pv,Ar,ka,ci=y(()=>{"use strict";me();Be();tt();Cv=Sv.enum(["none","standard","symbols"]).optional().default("standard"),gb={startLine:xr,endLine:xr,contextLines:Pr.default(5),charOffset:G(0,1e8).optional(),charLength:G(1,5e4).optional(),minify:Cv},Pv=he(mb,gb),Ar=ue(mb,gb),ka=ie(Pv,{maxQueries:5})});async function hb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let r=Ue(Ar,n);return r.ok===!1?r.error:await Ta(r.data)}}),{toolName:A.LOCAL_FETCH_CONTENT},e)}var dd=y(()=>{"use strict";fe();je();ai();ci();De();Ht();ai()});import{z as xv}from"zod";import{FindFilesQuerySchema as wv}from"@octocodeai/octocode-core/schemas";function Ev(e,t){e.minDepth!==void 0&&e.maxDepth!==void 0&&e.minDepth>e.maxDepth&&t.addIssue({code:"custom",message:"minDepth must be less than or equal to maxDepth.",path:["minDepth"]})}var yb,bb,Tv,Lr,Oa,li=y(()=>{"use strict";me();Be();tt();yb={maxDepth:G(0,100).optional(),minDepth:G(0,100).optional(),limit:G(1,1e4).optional(),page:ae.default(1),itemsPerPage:G(1,50).optional()},bb=xv.object(Object.fromEntries(Object.entries(wv.shape).filter(([e])=>e!=="regexType")));Tv=he(bb,yb),Lr=ue(bb,yb).superRefine(Ev),Oa=ie(Tv,{maxQueries:5})});function _r(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function ui(e){let t=e.trim();if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(n&&n[1]&&n[2]){let s=parseFloat(n[1]);switch(n[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let r=t.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!r||!r[1]||!r[2])throw new Error(`Invalid size format: ${e}`);let o=parseFloat(r[1]);switch(r[2].toUpperCase()){case"K":return Math.round(o*1024);case"M":return Math.round(o*1024*1024);case"G":return Math.round(o*1024*1024*1024);default:return Math.round(o*1024*1024*1024*1024)}}var di=y(()=>{"use strict"});function Ov(e,t){let n=t??kv,r=new Set(e.split("/").filter(Boolean));return n.filter(o=>!r.has(o))}async function Ir(e){let t=e.details??!1,n=e.showFileLastModified??!1,r=n||(e.sortBy||"modified")==="modified";try{let o=Ke(e,A.LOCAL_FIND_FILES);if(!o.isValid)return o.errorResult;let i={...e,path:o.sanitizedPath},s={...i,excludeDir:Ov(i.path,i.excludeDir)},a=Iv(s),c=e.limit??1e4,l=F.queryFileSystem({path:s.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:s.maxDepth,minDepth:s.minDepth,names:s.names,pathPattern:s.pathPattern,regex:s.regex,entryType:s.entryType,empty:s.empty,modifiedWithin:s.modifiedWithin,modifiedBefore:s.modifiedBefore,accessedWithin:s.accessedWithin,sizeGreater:s.sizeGreater,sizeLess:s.sizeLess,permissions:s.permissions,executable:s.executable,readable:s.readable,writable:s.writable,excludeDir:s.excludeDir,limit:1e4}),u=l.totalDiscovered,d=l.wasCapped,p=l.entries.map(B=>vv(B,r)),f=e.sortBy||"modified";Av(p,f,r);let m=p.slice(0,c),g=Lv(m,t,n),b=g.length,C=e.itemsPerPage||20,S=e.page||1,T=Math.max(1,Math.ceil(b/C)),L=(S-1)*C,k=Math.min(L+C,b),w=g.slice(L,k),N=[...l.warnings,...l.skipped>0?[`${l.skipped} entr${l.skipped===1?"y":"ies"} skipped during filesystem traversal`]:[]],I=[...a,...N],v={...b===0?{status:"empty"}:{},path:i.path,files:w,pagination:{currentPage:S,totalPages:T,filesPerPage:C,totalFiles:b,hasMore:S<T,...S<T?{nextPage:S+1}:{},...d||u>b?{totalFilesFound:u}:{}},...I.length>0&&{warnings:I}};return $(Rb(v,e,{totalFiles:b}),l.entries.reduce((B,z)=>B+z.path.length,0))}catch(o){return M(o,e,{toolName:A.LOCAL_FIND_FILES})}}function vv(e,t){let n={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return t&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),n}function Rb(e,t,n){return e}function Av(e,t,n){e.sort((r,o)=>{switch(t){case"size":return(o.size??0)-(r.size??0);case"name":return(r.path.split("/").pop()||"").localeCompare(o.path.split("/").pop()||"");case"path":return r.path.localeCompare(o.path);default:return n&&r.modified&&o.modified?new Date(o.modified).getTime()-new Date(r.modified).getTime():r.path.localeCompare(o.path)}})}function Lv(e,t,n){return e.map(r=>{let o={path:r.path,type:r.type};return r.size!==void 0&&r.type!=="directory"&&(o.sizeFormatted=_r(r.size)),t&&r.permissions&&(o.permissions=r.permissions),r.modified&&(o.modified=r.modified),o})}function Iv(e){let t=[],n=[{key:"modifiedBefore",value:e.modifiedBefore},{key:"modifiedWithin",value:e.modifiedWithin},{key:"accessedWithin",value:e.accessedWithin}];for(let{key:r,value:o}of n)o&&!_v.test(o)&&t.push(`${r}="${o}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`);return t}var kv,_v,pi=y(()=>{"use strict";Et();di();be();fe();me();oe();kv=[];_v=/^\d+[hdwm]$/});async function Sb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_FIND_FILES,query:n,contextMessage:"localFindFiles execution failed",execute:async()=>{let r=Ue(Lr,n);return r.ok===!1?r.error:await Ir(r.data)}}),{toolName:A.LOCAL_FIND_FILES},e)}var pd=y(()=>{"use strict";li();fe();je();pi();De();Ht();pi()});import{z as Fr}from"zod";import{RipgrepQuerySchema as Cb}from"@octocodeai/octocode-core/schemas";var Fv,Mv,Pb,Dv,Nv,Gv,rn,va,Mr=y(()=>{"use strict";me();Be();tt();Fv=["paginated","discovery","detailed","structural"],Mv=["semanticRanking"],Pb={mode:Fr.enum(Fv).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:Fr.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:Fr.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:Pr,matchContentLength:G(1,1e5).optional().default(500),maxMatchesPerFile:G(1,1e5).optional(),maxFiles:G(1,1e5).optional(),matchPage:ae.optional(),itemsPerPage:G(1,1e3).optional(),page:ae.default(1),unique:Fr.boolean().optional().describe("With onlyMatching, return each matched value once per file."),countUnique:Fr.boolean().optional().describe("With onlyMatching, return each matched value once per file with its frequency.")},Dv={...Pb,semanticRanking:Fr.never().optional()},Nv=he(Cb,Dv),Gv=ue(Cb,Pb,{strict:!0,omit:Mv}),rn=Gv.superRefine((e,t)=>{let n=e;if(n.caseSensitive&&n.caseInsensitive&&t.addIssue({code:"custom",message:"caseSensitive and caseInsensitive are mutually exclusive.",path:["caseSensitive"]}),n.fixedString&&n.perlRegex&&t.addIssue({code:"custom",message:"fixedString and perlRegex are mutually exclusive.",path:["fixedString"]}),n.filesOnly&&n.filesWithoutMatch&&t.addIssue({code:"custom",message:"filesOnly and filesWithoutMatch are mutually exclusive.",path:["filesOnly"]}),n.countLinesPerFile&&n.countMatchesPerFile&&t.addIssue({code:"custom",message:"countLinesPerFile and countMatchesPerFile are mutually exclusive.",path:["countLinesPerFile"]}),n.multilineDotall&&!n.multiline&&t.addIssue({code:"custom",message:"multilineDotall requires multiline=true.",path:["multilineDotall"]}),n.mode==="structural"){for(let r of["unique","countUnique"])n[r]&&t.addIssue({code:"custom",message:`\`${r}\` is not valid with mode:"structural".`,path:[r]});return}n.unique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"unique requires onlyMatching:true.",path:["unique"]}),n.countUnique&&!n.onlyMatching&&t.addIssue({code:"custom",message:"countUnique requires onlyMatching:true.",path:["countUnique"]})}),va=ie(Nv,{maxQueries:5})});function gd(e){return Tb.exec(e)?.[1]?.toLowerCase()??""}function Kv(e){let t=gd(e);if(!t)return!1;for(let n of Wv)if(fi[n].extensions.includes(t))return!0;return!1}function Yv(e,t,n){if(n&&n!=="auto")return fi[n];let r=gd(e),o=(t??"").toLowerCase();for(let i of xb){let s=fi[i];if(i!=="generic"&&o&&(i===o||s.extensions.includes(o)))return s}for(let i of xb){let s=fi[i];if(i!=="generic"&&s.extensions.includes(r))return s}return fi.generic}function kb(e){return Qv.test(e)?"generated":jv.test(e)?"fixture":Uv.test(e)?"test":qv.test(e)?"config":$v.test(e)?"docs":!md.test(e)&&(Vv.test(e)||Kv(e))?"source":"unknown"}function Xv(e){if(!e)return;let t=/[A-Za-z_$][\w$]*/.exec(e);return t?t[0]:void 0}function Jv(e,t){if(!e)return[];let n=new Set,r=[];for(let o of e.matchAll(/[A-Za-z_$][\w$]*/g)){let i=o[0],s=t?i:i.toLowerCase();n.has(s)||(n.add(s),r.push(i))}return r}function Zv(e,t,n,r,o){if(!e||e.length===0)return 0;let i=uA(n.keyword),s=0,a="";for(let c of e){let l=c.value??"";if(!l)continue;let u=dA(l,r,n.caseSensitive),d=0,p=[];r&&i&&(new RegExp(`(^|[^\\w$])${vb(r)}([^\\w$]|$)`,n.caseSensitive?"":"i").test(u)?(d+=ce.exactWholeWord,p.push("whole-word match")):!n.caseSensitive&&u.toLowerCase().includes(r.toLowerCase())?(d+=ce.exactCaseInsensitive,p.push("case-insensitive match")):u.includes(r)&&(d+=ce.substring,p.push("substring match")));let f=c.kind;if(f)d+=eA(f,p);else{let m=pA(u,r,t.id,n.caseSensitive);m!=="code"?(d+=ce.commentOrStringPenalty,p.push(m==="comment"?"comment match (weak)":"string literal (weak)")):(fd(t.declaration,u)&&(d+=ce.declarationLine,p.push("declaration line")),fd(t.export,u)&&(d+=ce.exportLine,p.push("export/public line")),fd(t.import,u)&&(d+=ce.importLine,p.push("import line")),t.id==="markdown"&&Bv.test(u)&&(d+=ce.headingLine,p.push("markdown heading")),(t.id==="json"||t.id==="yaml")&&tA(u,r)&&(d+=ce.configKeyLine,p.push("config key match")))}d>s&&(s=d,a=p.join(", "))}return a&&o.push(a),s}function eA(e,t){switch(e){case"declaration":return t.push("AST: declaration"),ce.declarationLine;case"export":return t.push("AST: export/public"),ce.exportLine;case"configKey":return t.push("AST: config key"),ce.configKeyLine;case"heading":return t.push("AST: heading"),ce.headingLine;case"import":return t.push("AST: import"),ce.importLine;case"comment":case"string":return t.push(`AST: ${e} (weak)`),ce.commentOrStringPenalty;case"callsite":return t.push("AST: callsite"),1;default:return 0}}function tA(e,t){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n);return t?r.includes(t):/["'\w]/.test(r)}function nA(e,t,n,r,o,i){let s=0;if(n){let c=e.toLowerCase(),l=n.toLowerCase();c.split("/").some(u=>u.replace(Tb,"").includes(l))&&(s+=ce.pathSegmentToken,i.push("query token in path"))}let a=gd(e);return r.extensions.includes(a)&&t.langType&&(s+=ce.extMatchesLangType,i.push("extension matches langType")),o==="source"&&(s+=ce.sourceDir,i.push("source file")),s}function rA(e,t,n){return t.explicitLowSignal?0:e==="generated"||e==="fixture"?(n.push(`${e} file (penalized)`),ce.lowSignalPathPenalty):0}function oA(e,t){if(e<=0)return 0;let n=Math.log2(e+1)*ce.matchCountScale,r=Math.min(n,ce.matchCountCap);return e>1&&t.push(`match count saturated (${e})`),r}function iA(e,t){let n=Jv(t.keyword,t.caseSensitive);if(n.length<2||e.length<2)return;let r=new Map,o=new Map;for(let i of e){let s=n.filter(a=>sA(i,a,t.caseSensitive));if(s.length!==0){r.set(i.path,s);for(let a of s)o.set(a,(o.get(a)??0)+1)}}if(r.size!==0)return{candidateCount:e.length,fileTokens:r,documentFrequency:o}}function sA(e,t,n){let r=n?"":"i",o=new RegExp(`(^|[^\\w$])${vb(t)}([^\\w$]|$)`,r);for(let i of e.matches??[])if(o.test(i.value??""))return!0;return o.test(e.path)}function aA(e,t,n){if(!t)return 0;let r=t.fileTokens.get(e.path);if(!r?.length)return 0;let o="",i=0,s=0;for(let a of r){let c=t.documentFrequency.get(a)??t.candidateCount;if(c>t.candidateCount/2)continue;let l=Math.log2((t.candidateCount+1)/(c+1)),u=Math.min(l*ce.rareQueryTokenScale,ce.rareQueryTokenCap);u>i&&(i=u,o=a,s=c)}return i<=0?0:(n.push(`rare query token: ${o} (${s}/${t.candidateCount} files)`),i)}function cA(e,t,n){let r=Yv(e.path,t.langType,t.profileOverride),o=kb(e.path),i=Xv(t.keyword),s=[],a=0;return a+=Zv(e.matches,r,t,i,s),a+=nA(e.path,t,i,r,o,s),t.queryPath&&e.path.startsWith(t.queryPath.replace(/\/+$/,"")+"/")&&(a+=ce.pathUnderQuery,s.push("under requested subtree")),a+=rA(o,t,s),md.test(e.path)&&!t.explicitLowSignal&&(a+=ce.lowSignalPathPenalty,s.push("low-signal path (penalized)")),a+=oA(e.matchCount??0,s),a+=aA(e,n,s),{score:Math.round(a*100)/100,profile:r.id,pathRole:o,reasons:s}}function Ob(e,t,n,r={}){if(t==="matchCount")return{files:[...e].sort(Eb),cappedCandidates:0};if(t==="path")return{files:[...e].sort((d,p)=>d.path.localeCompare(p.path)),cappedCandidates:0};if(t==="created"||t==="modified"||t==="accessed")return{files:[...e],cappedCandidates:0};let o=r.candidateCap??Hv,i=e,s=[],a=0;if(e.length>o){let d=[...e].sort(Eb);i=d.slice(0,o),s=d.slice(o),a=s.length}let c=iA(i,n),l=i.map(d=>{try{return{file:d,s:cA(d,n,c)}}catch{return{file:d,s:lA()}}});l.sort((d,p)=>{if(p.s.score!==d.s.score)return p.s.score-d.s.score;let f=(p.file.matchCount??0)-(d.file.matchCount??0);return f!==0?f:d.file.path.localeCompare(p.file.path)});let u={files:[...l.map(d=>d.file),...s],cappedCandidates:a};return r.debug&&(u.debug=new Map(l.map(d=>[d.file.path,d.s]))),u}function lA(){return{score:0,profile:"generic",pathRole:"unknown",reasons:["ranking unavailable for this file"]}}function Eb(e,t){let n=(t.matchCount??0)-(e.matchCount??0);return n!==0?n:e.path.localeCompare(t.path)}function fd(e,t){for(let n of e)if(n.test(t))return!0;return!1}function vb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uA(e){return!!e&&/^[A-Za-z_$][\w$]*$/.test(e.trim())}function dA(e,t,n){if(e.indexOf(`
51
51
  `)<0)return e;let o=e.split(`
52
- `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function CP(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(YC.test(e))return"comment";let o=PP(e,t,r);if(o<0)return"code";let i=EP(e);return i>=0&&o>i?"comment":TP(e,o)?"string":"code"}function PP(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function EP(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function TP(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function ef(e){if(!e)return!1;if(oa.test(e))return!0;let t=Jp(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var tf=8,xP=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),_P=/^[A-Za-z_$][A-Za-z0-9_$]*$/;async function ri(e,t,n,r,o){let i=t.sort??"relevance",s;try{s=Zp(e,i,IP(t),{debug:!!t.debugRanking})}catch{s={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let a=s.files,c=s.debug,u=a,l=!1;t.maxFiles&&a.length>t.maxFiles&&(u=a.slice(0,t.maxFiles),l=!0);let d=u.length,m=!!(t.filesOnly||t.filesWithoutMatch),p=!!(t.countLinesPerFile||t.countMatchesPerFile),f=m||p,g=u.reduce(($,D)=>$+(D.matchCount??0),0),h=f?o?.matchCount??g:g,R=t,b=R.itemsPerPage||st.DEFAULT_FILES_PER_PAGE,P=R.page||1,x=Math.ceil(d/b),C=(P-1)*b,_=Math.min(C+b,d),I=u.slice(C,_),j=R.maxMatchesPerFile||st.DEFAULT_MATCHES_PER_PAGE,w=I.map($=>{let D=$.matches?.length??0,Re=Math.ceil(D/j),ue=Math.max(1,R.matchPage||1),at=(ue-1)*j,en=Math.min(at+j,D),V=f?void 0:$.matches?.slice(at,en),qe=c?.get($.path);return{path:$.path,...m?{}:{matchCount:p?$.matchCount||1:D},...V!==void 0&&{matches:V},...qe?{ranking:{score:qe.score,profile:qe.profile,pathRole:qe.pathRole,reasons:qe.reasons}}:{},pagination:!f&&D>j?{currentPage:ue,totalPages:Re,matchesPerPage:j,totalMatches:D,hasMore:ue<Re,...ue<Re?{nextMatchPage:ue+1}:{}}:void 0}}),A=w.filter($=>$.pagination?.hasMore),Q=wP(w,t,n,{isFileListMode:f,currentPage:P,totalFilePages:x,matchPage:R.matchPage||1,matchesPerPage:j,hasFileWithMoreMatches:A.length>0}),se={searchEngine:n,...o?{stats:o}:{},files:w,pagination:{currentPage:P,totalPages:x,filesPerPage:b,totalFiles:d,...m?{}:{totalMatches:h},hasMore:P<x,...P<x?{nextPage:P+1}:{},...l?{totalFilesFound:a.length}:{}},...r.length>0?{warnings:r}:{},...Object.keys(Q).length>0?{next:Q}:{}};return nf(se,t,{totalMatches:h,totalFiles:d})}function nf(e,t,n){return e}function wP(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=AP(i);s.fetchExact={tool:"localGetFileContent",query:ni({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:ni({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=LP(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:ni({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:ni({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function AP(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-tf),endLine:n+tf}}function LP(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return OP(e?.metavars);if(!t.matchWindow)return t.onlyMatching?sa(e?.value):sa(t.keywords)}}function OP(e){if(e)for(let t of Object.values(e))for(let n of t){let r=sa(n);if(r)return r}}function sa(e){if(typeof e!="string")return;let t=e.trim();if(_P.test(t)&&!xP.has(t))return t}function ni(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function IP(e){let t=e.rankingProfile,n=!!(e.include?.length||ef(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}function rf(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=O.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&kP(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&vP(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function kP(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function vP(e){return/\(\?[=!<]/.test(e)}function MP(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function NP(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:MP(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function DP(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function of(e){let t=[],n=FP(e);if(!n.isValid)return L(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=vn.safeParse(e);if(!r.success){let g=r.error.issues.map(h=>h.message);return L(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return L(new Error("Path is required for search"),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:t}});let s=ve(o,S.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=rf({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return L(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:S.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let u=[...c.warnings],l;try{l=await O.searchRipgrep(NP(a))}catch(g){return L(g instanceof Error?g:new Error(String(g)),o,{toolName:S.LOCAL_RIPGREP})}let d=l.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(h=>{let R={line:h.line,column:h.column,value:h.value};return h.count!==void 0&&(R.count=h.count),h.kind!==void 0&&(R.kind=h.kind),h.scoreHint!==void 0&&(R.scoreHint=h.scoreHint),R})})),m=DP(d),p={matchCount:l.stats.matchCount,matchedLines:l.stats.matchedLines,filesMatched:l.stats.filesMatched,filesSearched:l.stats.filesSearched,bytesSearched:l.stats.bytesSearched??void 0,searchTime:l.stats.searchTime};if(d.length===0)return U({status:"empty",searchEngine:"rg",stats:p,warnings:[...t,...u]},m);!a.filesOnly&&m>st.LARGE_RESULT_BYTES_HINT&&u.push(`Result payload is large (~${Math.round(m/1024)}KB).`);let f=await ri(d,o,"rg",[...t,...u],p);return U(f,m)}var HP=[],GP=2e3,UP=1e6,BP="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`.",zP={ts:["ts","tsx","mts","cts"],typescript:["ts","tsx","mts","cts"],tsx:["tsx"],js:["js","jsx","mjs","cjs"],javascript:["js","jsx","mjs","cjs"],jsx:["jsx"],py:["py","pyi"],python:["py","pyi"],go:["go"],rs:["rs"],rust:["rs"],java:["java"],c:["c","h"],cpp:["cpp","hpp","cc","cxx","hh","hxx"],"c++":["cpp","hpp","cc","cxx","hh","hxx"],cs:["cs"],csharp:["cs"],sh:["sh","bash","zsh"],bash:["sh","bash","zsh"],shell:["sh","bash","zsh"],html:["html","htm"],css:["css"],scss:["scss"],less:["less"],scala:["scala","sc","sbt"],json:["json","jsonc"],yaml:["yaml","yml"],yml:["yaml","yml"],toml:["toml"]};function QP(e){if(!e)return;let t=e.trim().toLowerCase();return(zP[t]??[t.replace(/^[.*]+/,"")]).filter(Boolean).map(r=>`*.${r}`)}async function sf(e){let t=ve(e,S.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=O.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,include:e.include?.length?e.include:QP(e.langType),excludeDir:e.excludeDir?.length?e.excludeDir:HP,maxFiles:e.maxFiles??GP,maxFileBytes:UP})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return L(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:S.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.split(`
53
- `,1)[0],column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={matchCount:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&i.push(BP),await ri(r,e,"structural",i,o)}function jP(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function af(e){let t=jP(e);if(t.mode==="structural")return await sf(t);t.contextLines===void 0&&(t.contextLines=2);try{return await of(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:H.OUTPUT_TOO_LARGE}:L(n,t,{toolName:S.LOCAL_RIPGREP})}}async function cf(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Le(vn,n);return r.ok===!1?r.error:await af(r.data)}}),{toolName:S.LOCAL_RIPGREP},e)}import{ViewStructureQuerySchema as uf}from"@octocodeai/octocode-core/schemas";var lf={maxDepth:v(0,20).optional(),limit:v(1,1e4).optional(),page:q.default(1),itemsPerPage:v(1,50).optional()},$P=ce(uf,lf),oi=re(uf,lf),df=X($P,{maxQueries:5});var VP=new Set(["+","*","?"]),WP=1e3;function KP(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function pf(e,t){let n=e[t];return n===void 0?!1:VP.has(n)||n==="{"&&JP(e,t)}function YP(e,t,n){let r=n.pop()??!1,o=pf(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?ff(e,t+1):t+1})}function XP(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:ff(e,t)})}function aa(e){if(e.length>WP)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=KP(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=YP(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(pf(e,r)){let i=XP(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function JP(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function ff(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function XD(e,t){let n=aa(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}function mf(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!aa(s).safe)return n=n.filter(u=>(u.name.includes("/")?u.name.split("/").pop():u.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(u=>{let l=u.name.includes("/")?u.name.split("/").pop():u.name;return c.test(l)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function gf(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function hf(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}function ca(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+Ar(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${kn(r)})`}function ua(e,t){let n=e.length,r=t.itemsPerPage||st.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function ZP(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function la(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}async function yf(e){try{let t=ve(e,S.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return qP(e,t.sanitizedPath,n)}catch(t){let n=De.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function qP(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=tE(e),s=r&&e.limit&&!eE(e,i)?e.limit*2:1e4,a;try{a=O.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:nE(e),limit:s})}catch(P){return iE(P,e,t)}let c=a.entries.map(P=>rE(P,n,e.details??!1)),u=mf(c,e),l=e.sortBy??"name";u=u.sort((P,x)=>{let C=0;switch(l){case"size":{let _=P.sizeBytes??(P.size?Ar(P.size):0),I=x.sizeBytes??(x.size?Ar(x.size):0);C=_-I;break}case"time":n&&P.modified&&x.modified?C=P.modified.localeCompare(x.modified):C=P.name.localeCompare(x.name);break;case"extension":C=(P.extension||"").localeCompare(x.extension||"");break;default:C=P.name.localeCompare(x.name);break}return e.reverse?-C:C}),e.limit&&(u=u.slice(0,e.limit));let d=u.length,{paginatedEntries:m,pagination:p}=ua(u,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:m.map(P=>({...hf(P),path:P.path??`${t.replace(/\/$/,"")}/${P.name}`}))}:{path:t,...gf(m)},h=[...a.warnings,...la({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],R=d===0,b=ca(u);return U(Rf({...R?{status:"empty"}:{},...g,summary:b,...p.hasMore||p.totalPages>1?{pagination:p}:{},...h.length>0&&{warnings:h}},e),a.entries.reduce((P,x)=>P+x.path.length,0))}function eE(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function tE(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function nE(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function rE(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:kn(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=oE(e.permissions)),o}function oE(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function iE(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=De.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return L(a,t,{toolName:S.LOCAL_VIEW_STRUCTURE})}function Rf(e,t){return e}async function bf(e){let{queries:t}=e;return J(t||[],async n=>ke({toolName:S.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Le(oi,n);return r.ok===!1?r.error:await yf(r.data)}}),{toolName:S.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}import fE from"node:path";import{acquirePooledClient as wf,isLanguageServerAvailable as Af}from"@octocodeai/octocode-engine/lsp/manager";import{resolveImportAliasDefinitions as mE}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Lf}from"@octocodeai/octocode-engine/lsp/workspaceRoot";import{safeReadFile as sE}from"@octocodeai/octocode-engine/lsp/validation";var Sf={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0};function Or(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Cf(e,t,n){if(t<=0)return e;let r=await sE(e.uri);if(!r)return e;let o=Rr(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((u,l)=>{let d=s+l+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${u}`}).join(`
54
- `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function aE(e,t){return Promise.all(e.map(async n=>({...n,from:await Cf(n.from,t,n.fromRanges)})))}async function cE(e,t){return Promise.all(e.map(async n=>({...n,to:await Cf(n.to,t)})))}async function da(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Sf};try{let i=await e.getIncomingCalls(t),s=o>0?await aE(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let u=Or(c.from);return r.has(u)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(u),da(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,u)=>c+u.cycleCount,0),failedRequestCount:a.reduce((c,u)=>c+u.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function pa(e,t,n,r,o){if(n<=0||!e)return{calls:[],...Sf};try{let i=await e.getOutgoingCalls(t),s=o>0?await cE(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let u=Or(c.to);return r.has(u)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(u),pa(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,u)=>c+u.cycleCount,0),failedRequestCount:a.reduce((c,u)=>c+u.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}import{readFile as uE}from"node:fs/promises";import{SymbolResolver as lE,SymbolResolutionError as dE}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as Pf}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function fa(e,t){let n=e.uri,r=ve({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{return{ok:!0,value:{uri:o,absolutePath:o,content:await uE(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:Pf.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function Ef(e,t){let n=await fa(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new lE({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),u=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:pE(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u}}}}}catch(o){if(o instanceof dE)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:Pf.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function pE(e){return{start:e,end:{line:e.line,character:e.character}}}var ma;function Of(e){return ma||(ma=new Set(O.getSupportedJsTsExtensions().map(t=>`.${t}`))),ma.has(fE.extname(e).toLowerCase())}function gE(e,t){if(!Of(e))return null;try{let n=O.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}var hE=40,If=40,yE=10,RE=8;async function ya(e){return J(e.queries||[],async t=>ke({toolName:Ie,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await AE(t);return bE(SE(t,n))}}),{toolName:Ie,minQueryTimeoutMs:3e4},e)}function bE(e){return U(e,N(e))}function SE(e,t){return e.format!=="compact"||!CE(t)?t:PE(t)}function CE(e){return Zt(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Zt(e.payload)}function PE(e){return{...e,format:"compact",payload:EE(e.payload)}}function EE(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(Tf)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(xE)}:{locations:(e.locations??[]).map(Tf)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:kf(e.root)}:{},direction:e.direction,calls:e.calls.map(_E),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(TE)};case"hover":case"empty":return e}}function TE(e){if(!Zt(e))return String(e);let t=Fe(e,"line"),n=Fe(e,"character"),r=Fe(e,"endLine"),o=yt(e,"kind"),i=yt(e,"name"),s=Fe(e,"childCount"),a=yt(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function Tf(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Ff(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function xE(e){if(!Zt(e))return String(e);let t=yt(e,"uri"),n=Fe(e,"firstLine"),r=Fe(e,"firstCharacter"),o=Fe(e,"count"),i=vf(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function _E(e){if(!Zt(e))return String(e);let t=yt(e,"direction"),n=kf(e.item),r=vf(e,"ranges").map(wE).join(","),o=Fe(e,"rangeCount"),i=Fe(e,"rangeSampleCount"),s=yt(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${Ff(s,180)}`:""].filter(Boolean).join(" ")}function kf(e){if(!Zt(e))return String(e);let t=yt(e,"name"),n=yt(e,"kind"),r=yt(e,"uri"),o=Fe(e,"line"),i=Fe(e,"endLine"),s=Fe(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function wE(e){return Zt(e)?`${Fe(e,"line")}:${Fe(e,"character")}`:String(e)}function Zt(e){return typeof e=="object"&&e!==null}function yt(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Fe(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function vf(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ff(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function AE(e){if(e.type==="documentSymbols")return LE(e);let t=await Ef(e,Ie);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return BE(e,i)}let n=e.workspaceRoot??await Lf(t.value.uri);if(!await Af(t.value.uri,n)){if(e.type==="references"){let i=IE(e,t.value);if(i)return i}return ht(e.type,t.value,"Language server unavailable")}let o=await wf(n,t.value.uri);if(!o)return ht(e.type,t.value,"Language server unavailable");switch(e.type){case"definition":return o.hasCapability("definitionProvider")?ga(e,t.value,"definition","definitionProvider",await mE({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):ht(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?ga(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ht(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?ga(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ht(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?Mf(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):ht(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?kE(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):ht(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?vE(e,t.value,o):ht(e.type,t.value,"callHierarchyProvider unsupported",!0)}}async function LE(e){let t=await fa(e,Ie);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Lf(t.value.uri),r=await Af(t.value.uri,n),o=r?await wf(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a;if(i&&o){let h=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(h)?h:[],a="lsp"}else{let h=gE(t.value.uri,t.value.content);h&&(s=h,a="native")}let c=a!==void 0,u=FE(s),l=DE(s),{pageItems:d,pagination:m}=ii(u,e.page??1,e.itemsPerPage??hE),p=HE(u,h=>h.kind),g=c?void 0:{category:r?"unsupportedOperation":"serverUnavailable",reason:(c?void 0:r?"documentSymbolProvider unsupported":"Language server unavailable; native outline supports JS/TS only")??"document symbols unavailable"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:d.length,topLevelSymbols:l,kinds:p},payload:{kind:"documentSymbols",symbols:d,...g?{empty:g}:{}},pagination:m}}function ga(e,t,n,r,o){let i=o.length>0,s=o.map(Xi),{pageItems:a,pagination:c}=ii(s,e.page??1,e.itemsPerPage??If);return{type:e.type,uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}var OE={kind:"lsp"};function Mf(e,t,n,r=OE){let o=r.kind==="native",i=n.map(d=>{let m=d.uri===t.uri&&d.range.start.line===t.resolvedSymbol.position.line&&d.range.start.character===t.resolvedSymbol.position.character;return{...d,...m?{isDefinition:!0}:{}}}),s=e.groupByFile?zE(i):void 0,a=s??i.map(Xi),{pageItems:c,pagination:u}=ii(a,e.page??1,e.itemsPerPage??If),l=i.length===0?{category:"noReferences",reason:o?"no in-file references found":"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:o?{serverAvailable:!1,source:"native"}:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...s?{byFile:c}:{locations:c},totalReferences:i.length,totalFiles:new Set(i.map(d=>d.uri)).size,...l?{empty:l}:{}},pagination:u,...l&&o?{warnings:["source: native (oxc) \u2014 same-file references only; install a language server for cross-file references."]}:{}}}function IE(e,t){if(!Of(t.uri))return null;let n;try{let i=O.findInFileReferences(t.content,t.uri,t.resolvedSymbol.position.line,t.resolvedSymbol.position.character);if(!i)return null;let s=JSON.parse(i);if(!Array.isArray(s))return null;n=s}catch{return null}let r=t.content.split(`
55
- `),o=n.map(i=>({uri:t.uri,range:i,content:(r[i.start.line]??"").trim()}));return Mf(e,t,o,{kind:"native",scope:"file"})}async function kE(e,t,n){let r=QE(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function vE(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return ht(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await da(n,o,i,new Set([Or(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await pa(n,o,i,new Set([Or(o)]),e.contextLines??0):s,u=b=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(b.to.uri),l=c.calls.filter(u).length,d=c.calls.filter(b=>!u(b)),m=[...a.calls.map(b=>({direction:"incoming",...b})),...d.map(b=>({direction:"outgoing",...b}))],p=m.map(b=>b.direction==="incoming"?GE(b,e.contextLines??0):UE(b,e.contextLines??0)),{pageItems:f,pagination:g}=ii(p,e.page??1,e.itemsPerPage??yE),h=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",R=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Ra(o),direction:h,calls:f,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:R,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...l>0&&{stdlibCallsExcluded:l}},...m.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}function ii(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function FE(e){let t=[];for(let n of e)Nf(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function Nf(e,t,n){if(!e||typeof e!="object")return;let r=e,o=NE(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:ha(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&ME.has(ha(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)Nf(s,t,i)}}var ME=new Set(["file","module","namespace","package","class","enum","interface","struct"]);function NE(e){if(xf(e.range))return e.range;let t=e.location;return t&&xf(t.range)?t.range:void 0}function xf(e){if(!e||typeof e!="object")return!1;let t=e;return _f(t.start)&&_f(t.end)}function _f(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function DE(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function HE(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function GE(e,t){let n=Df(e.fromRanges);return{direction:"incoming",item:Ra(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Hf(e.from,t)}}function UE(e,t){let n=Df(e.fromRanges);return{direction:"outgoing",item:Ra(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...Hf(e.to,t)}}function Ra(e){return{name:e.name,kind:ha(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function Df(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=RE))break}return n}function Hf(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function ha(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function Gf(e,t){return/unavailable/i.test(t)?"serverUnavailable":/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function BE(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Gf(e.type,t),reason:t}}}function ht(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:bn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Gf(e,n),reason:n}}}function zE(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function QE(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>jE(r)).join(`
56
- `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function jE(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}import{z as y}from"zod";import{LspGetSemanticsQuerySchema as zf}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as $E}from"@octocodeai/octocode-core/schemas/outputs";var VE=v(1,1e9),WE=v(0,1e5).optional(),KE=["structured","compact"],Qf={type:y.enum(mu).default("definition"),symbolName:y.string().min(1).optional(),lineHint:VE.optional(),orderHint:WE,depth:v(0,20).optional(),includeDeclaration:y.boolean().optional().default(!0),page:q,itemsPerPage:v(1,100).optional(),contextLines:v(0,100).optional(),format:y.enum(KE).optional().default("structured")},YE=ce(zf,Qf),Sa=re(zf,Qf),XE=Sa,Ca=X(YE,{maxQueries:5}),Uf=y.object({line:y.number(),character:y.number()}),JE=y.object({start:Uf,end:Uf}),ZE=y.object({startLine:y.number(),endLine:y.number()}),si=y.object({uri:y.string(),content:y.string().optional(),displayRange:ZE.optional(),isDefinition:y.boolean().optional()}),ai=y.string(),qE=y.object({name:y.string(),uri:y.string(),foundAtLine:y.number(),orderHint:y.number().optional()}),eT=y.object({serverAvailable:y.boolean().optional(),provider:y.string().optional(),source:y.string().optional()}),jf=y.enum(["serverUnavailable","unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls"]),ba=y.object({category:jf,reason:y.string()}),tT=y.object({currentPage:y.number(),totalPages:y.number(),totalResults:y.number(),hasMore:y.boolean(),itemsPerPage:y.number(),nextPage:y.number().optional()}),nT=y.object({name:y.string(),kind:y.string(),line:y.number(),character:y.number(),endLine:y.number(),childCount:y.number(),containerName:y.string().optional()}),rT=y.string(),$f=y.object({name:y.string(),kind:y.string(),uri:y.string(),line:y.number(),endLine:y.number(),selectionLine:y.number().optional()}),oT=y.string(),iT=y.object({direction:y.enum(["incoming","outgoing"]),item:$f,ranges:y.array(y.object({line:y.number(),character:y.number()})),rangeCount:y.number(),rangeSampleCount:y.number(),contentPreview:y.string().optional()}),sT=y.string(),aT=y.object({complete:y.boolean(),truncatedByDepth:y.boolean(),cycleCount:y.number(),failedRequestCount:y.number(),dynamicCallsExcluded:y.literal(!0),stdlibCallsExcluded:y.number().optional()}),cT=y.object({uri:y.string(),count:y.number(),firstLine:y.number(),firstCharacter:y.number(),lines:y.array(y.number()),hasDefinition:y.boolean().optional()}),uT=y.string(),lT=y.discriminatedUnion("kind",[y.object({kind:y.literal("definition"),locations:y.array(y.union([si,ai]))}),y.object({kind:y.literal("typeDefinition"),locations:y.array(y.union([si,ai]))}),y.object({kind:y.literal("implementation"),locations:y.array(y.union([si,ai]))}),y.object({kind:y.literal("references"),locations:y.array(y.union([si,ai])).optional(),byFile:y.array(y.union([cT,uT])).optional(),totalReferences:y.number(),totalFiles:y.number(),empty:ba.optional()}),...["callers","callees","callHierarchy"].map(e=>y.object({kind:y.literal(e),root:y.union([$f,oT]).optional(),direction:y.enum(["incoming","outgoing","both"]),calls:y.array(y.union([iT,sT])),incomingCalls:y.number(),outgoingCalls:y.number(),completeness:aT,empty:ba.optional()})),y.object({kind:y.literal("hover"),markdown:y.string().optional(),text:y.string().optional(),range:JE.optional()}),y.object({kind:y.literal("documentSymbols"),symbols:y.array(y.union([nT,rT])),totalSymbols:y.number().optional(),topLevelSymbols:y.number().optional(),empty:ba.optional()}),y.object({kind:y.literal("empty"),category:jf,reason:y.string()})]),Bf=y.object({type:y.string(),uri:y.string(),format:y.enum(["structured","compact"]).optional(),resolvedSymbol:qE.optional(),lsp:eT,payload:lT,pagination:tT.optional(),summary:y.record(y.string(),y.unknown()).optional(),warnings:y.array(y.string()).optional()}),dT=y.object({base:y.string().optional(),shared:y.record(y.string(),y.union([y.string(),y.number(),y.boolean()])).optional(),results:y.array(y.union([y.object({id:y.string().min(1),status:y.literal("empty"),data:Bf}),y.object({id:y.string().min(1),status:y.literal("error"),data:$E}),y.object({id:y.string().min(1),data:Bf})]))});import{existsSync as Vf}from"fs";import{delimiter as pT,dirname as fT,join as Wf}from"path";function Kf(){return process.platform==="win32"?"npm.cmd":"npm"}function mT(){let e=fT(process.execPath);return Wf(e,Kf())}function gT(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function hT(){let e=(process.env.PATH??"").split(pT).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...gT()])]}function Yf(){let e=mT();if(Vf(e))return{command:process.execPath,argsPrefix:[e]};let t=Kf();for(let n of hT()){let r=Wf(n,t);if(Vf(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}var yT=["view","search","ping","config","whoami"],RT=[..._r,...Jl];async function eG(e=1e4){let t=Yf();return Zl(t.command,[...t.argsPrefix,"--version"],e)}async function Ir(e,t,n={}){if(!yT.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Bo(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=Yf(),c=await Xt(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:RT});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var nG=5;var Fn=new Map,Ea=5,kr=3e4;function vr(e){try{return new URL(e).host||e}catch{return e}}var Pa=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}};function Xf(e,t=Date.now()){let n=Fn.get(vr(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<kr)throw new Pa(vr(e),kr-r);n.state="half-open"}}function Ta(e){let t=Fn.get(vr(e));t&&(t.failures=0,t.state="closed")}function Jf(e,t=Date.now()){let n=vr(e),r=Fn.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=Ea&&(r.state="open",r.openedAt=t)),Fn.set(n,r)}function rG(){Fn.clear(),Ea=5,kr=3e4}function oG(e){typeof e.failureThreshold=="number"&&(Ea=e.failureThreshold),typeof e.cooldownMs=="number"&&(kr=e.cooldownMs)}function Zf(e,t=Date.now()){let n=Fn.get(vr(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<kr:!1}var bT=6e4;function qf(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function ST(e,t,n,r){e&&Lt({limit_type:"primary",retry_after_seconds:qf(r),api_method:t,api_url:n,provider:e}).catch(xe("fetch rate-limit session logging"))}function CT(e,t,n,r,o){e.body?.cancel?.().catch(xe("response body cancellation")),M("fetchWithRetries",St.FETCH_HTTP_ERROR.code).catch(xe("fetch retry session logging"));let i=new Error(St.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&gu(r),e.status===429&&ST(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function PT(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=qf(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function vt(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=bT,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:u,packageRegistry:l}=t,d=e;if(a){let h=e.includes("?")?"&":"?";d=`${e}${h}version=${encodeURIComponent(ft)}`}let m={"User-Agent":`Octocode-MCP/${ft}`,...i},p=globalThis.fetch;if(!p)throw M("fetchWithRetries",St.FETCH_NOT_AVAILABLE.code).catch(xe("fetch retry session logging")),new Error(St.FETCH_NOT_AVAILABLE.message);Xf(d);let f,g=n+1;for(let h=1;h<=g;h++){if(c?.aborted)throw new Error("Request aborted");try{let R=await p(d,{method:s,headers:m,signal:c});if(!R.ok)throw CT(R,s,d,l,u);if(R.status===204)return Ta(d),null;let b=await R.json();return Ta(d),b}catch(R){let b=R;if(c?.aborted||R instanceof Error&&R.name==="AbortError")throw new Error("Request aborted");if(b&&b.retryable===!1)throw R;if(f=R instanceof Error?R:new Error(String(R)),h===g)break;let P=PT(h,r,o,b);await new Promise(x=>setTimeout(x,P))}}throw Jf(d),await M("fetchWithRetries",St.FETCH_FAILED_AFTER_RETRIES.code),new Error(St.FETCH_FAILED_AFTER_RETRIES.message(g,f?.message||""))}import{z as T}from"zod";var ci=T.looseObject({name:T.string(),version:T.string(),repository:T.union([T.string(),T.object({url:T.string().optional(),type:T.string().optional(),directory:T.string().optional()})]).optional(),main:T.string().optional(),module:T.string().optional(),type:T.string().optional(),exports:T.unknown().optional(),types:T.string().optional(),typings:T.string().optional(),description:T.string().optional(),keywords:T.array(T.string()).optional(),license:T.union([T.string(),T.object({type:T.string().optional()})]).optional(),homepage:T.string().optional(),author:T.union([T.string(),T.object({name:T.string().optional(),email:T.string().optional(),url:T.string().optional()})]).optional(),maintainers:T.array(T.object({name:T.string().optional(),email:T.string().optional()})).optional(),engines:T.record(T.string(),T.string()).optional(),dependencies:T.record(T.string(),T.string()).optional(),devDependencies:T.record(T.string(),T.string()).optional(),peerDependencies:T.record(T.string(),T.string()).optional(),time:T.record(T.string(),T.string().optional()).optional()}),ET=T.looseObject({package:T.looseObject({name:T.string().nullish(),version:T.string().nullish(),description:T.string().nullish(),links:T.looseObject({npm:T.string().nullish(),homepage:T.string().nullish(),repository:T.string().nullish()}).nullish()}),score:T.looseObject({final:T.number().nullish(),detail:T.looseObject({quality:T.number().nullish(),popularity:T.number().nullish(),maintenance:T.number().nullish()}).nullish()}).nullish()}),em=T.looseObject({objects:T.array(ET),total:T.union([T.number(),T.string()]).optional()}),tm=T.union([T.string(),T.boolean(),T.number(),T.null(),T.record(T.string(),T.unknown())]);var ui="https://registry.npmjs.org",TT=3e3,Fr=null;async function xa(){if(Fr)return Fr;try{let e=await Ir("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return Fr=t,t}}catch{}return Fr=ui,ui}function SG(){Fr=null}async function CG(){try{let e=await xa(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}function qt(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}var xT="https://api.npmjs.org/downloads/point/last-week";function Ue(e){return e===void 0?0:N(e)}async function am(e){try{let t=`${xT}/${encodeURIComponent(e)}`,n=await vt(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:Ue(n)}}catch{return{rawResponseChars:0}}}function li(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function cm(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function _T(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function wT(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function nm(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function rm(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function AT(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function _a(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=qt(e.repository):(e.repository.url&&(r=qt(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:AT(e),...o?{repositoryDirectory:o}:{},...nm(e.exports)?{exports:nm(e.exports)}:{},...rm(e.bin,e.name)?{bin:rm(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function LT(e){return typeof e.links?.repository=="string"?qt(e.links.repository):typeof e.repository=="string"?qt(e.repository):typeof e.repository?.url=="string"?qt(e.repository.url):null}function OT(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:LT(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function um(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function lm(e){try{let t=await xa(),n=um(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await vt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=Ue(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await vt(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:Ue(i)}}catch{return{rawResponseChars:0}}}async function wa(e,t,n){let[r,o]=await Promise.all([am(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):lm(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function di(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function IT(e,t){try{let n=await Ir("view",[e,"--json"],{timeout:TT});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...di(c)?{}:{errorDetail:c},rawResponseChars:Ue(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=Ue(o),s=ci.safeParse(o);return s.success?{pkg:_a(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...di(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function kT(e,t){try{let n=await xa(),r=um(e),o=`${n}/${r}/latest`,i;try{i=await vt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(u){let l=u instanceof Error?u.message:String(u);return l.includes("404")||l.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:l,rawResponseChars:0}}let s=Ue(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=ci.safeParse(i);return a.success?{pkg:_a(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...di(r)?{}:{errorDetail:r},rawResponseChars:0}}}function vT(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function dm(e,t){let n=0,r;for(let o of vT(e)){let i;try{i=await vt(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let u=c instanceof Error?c.message:String(c);di(u)||(r=u);continue}if(n+=Ue(i),!i||typeof i!="object")continue;let s=ci.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:_a(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Aa(e,t=!1){let[n,r]=await Promise.allSettled([IT(e,t),kT(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?wa(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function FT(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Aa(e,t);if(!r){if(o){let s=cm(o);if(s&&n){let a=await dm(e,t);if(a.pkg){let c=await wa(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function MT(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ir("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:Ue(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=Ue(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let l=[...a].sort((f,g)=>{let h=f?.score?.final??0;return(g?.score?.final??0)-h}).slice(r,r+t),d=await Promise.all(l.map(async f=>{if(!f||typeof f!="object")return null;let g=f;if(!g.name)return null;if(n){let h=await Aa(g.name,!0);if(h.pkg)return h}return{pkg:OT(g),rawResponseChars:0}})),m=d.map(f=>f?.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+(g?.rawResponseChars??0),0);return{packages:m,totalFound:a.length,rawResponseChars:c+p}}async function NT(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${ui}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await vt(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(f){return{error:`NPM registry search failed: ${f instanceof Error?f.message:String(f)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=Ue(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=em.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let l=[...c.data.objects].sort((f,g)=>{let h=f.score?.final??0;return(g.score?.final??0)-h}).map(f=>f.package).filter(f=>typeof f.name=="string"&&f.name.length>0).slice(0,t),d=await Promise.all(l.map(async f=>{if(n){let g=await Aa(f.name,!0);if(g.pkg)return g}return{pkg:{name:f.name,npmUrl:(f.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(f.name)}`,repoUrl:f.links?.repository&&typeof f.links.repository=="string"?qt(f.links.repository):null,version:f.version??"unknown",source:"registry",...f.description?{description:f.description}:{},...f.links?.homepage?{homepage:f.links.homepage}:{}},rawResponseChars:0}})),m=d.map(f=>f.pkg).filter(f=>!!f),p=d.reduce((f,g)=>f+g.rawResponseChars,0);return{packages:m,totalFound:wT(c.data.total,m.length),rawResponseChars:a+p}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function om(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await vt(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:Ue(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:Ue(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?qt(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:Ue(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function im(e,t,n,r=0){try{let o=await MT(e,t,n,r);if(!("error"in o))return o}catch{}return NT(e,t,n,r)}async function sm(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):am(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):lm(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function pm(e,t,n,r=0){let o=_e("npm-search",{name:e,limit:t,metadata:n,from:r});return we(o,async()=>{if(Zf(ui)){if(r===0&&t===1&&li(e)){let l=await dm(e,n);if(l.pkg){let d=await wa(e,l.pkg,l.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let u=await om(e,t);return!("error"in u)&&u.packages.length>0?u:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&li(e)){let u=await FT(e,n,t===1);if("error"in u){if(!cm(u.error))return u}else if(u.packages.length>0||t===1)return u}let s=await im(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return sm(s);let a=_T(e);if(a!==e){let u=await im(a,t,n,r);if(!("error"in u)&&u.packages.length>0)return sm(u)}let c=await om(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function DT(e){try{let t=await Ir("view",[e,"deprecated","--json"]);if(t.error||t.exitCode!==0)return null;let n=t.stdout.trim();if(!n||n==="undefined"||n==="")return{deprecated:!1};try{let r=JSON.parse(n),o=tm.safeParse(r),i=o.success?o.data:n;return{deprecated:!0,message:typeof i=="string"?i:"This package is deprecated"}}catch{return{deprecated:!0,message:n}}}catch{return null}}async function fm(e){let t=li(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return pm(e.name,n,!0,r)}function HT(e){return"error"in e}function pi(e){return"npmUrl"in e}function GT(e){return pi(e)&&e.path?e.path:e.name}function UT(e){return pi(e)?e.repoUrl:e.repository}function BT(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function zT(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function QT(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function jT(e,t){let n=QT(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function $T(e){let t=GT(e),n=zT(UT(e)),r={name:t};pi(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=BT(pi(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=jT(n,o);return i&&(r.next=i),r}function VT(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=Math.max(1,Math.ceil(t/i)),a=o<s;return{currentPage:o,totalPages:s,perPage:i,totalFound:t,returned:n,hasMore:a,...a?{nextPage:o+1}:{}}}async function mm(e){return J(e.queries,async t=>{try{if(!t.packageName)return L("Package name is required for package search",t);let n=await fm({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(HT(n))return L(n.error,t,{rawResponse:n});let r=n.packages,o=r.map($T),i=o.length>0,s=r.length>1||n.totalFound>1,a=VT(t,n.totalFound,o.length,s);return Pe(t,{packages:o,pagination:a},i,S.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return L(n,t,{toolName:S.PACKAGE_SEARCH})}},{toolName:S.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}import{z as Y}from"zod";import{NpmPackageQuerySchema as gm}from"@octocodeai/octocode-core/schemas";var hm={page:q,mode:Y.enum(["lean","full"]).optional()},ym=re(gm,hm),Rm=X(ce(gm,hm,{strict:!0}),{maxQueries:5}),MG=Y.object({results:Y.array(Y.looseObject({id:Y.string(),data:Y.looseObject({packages:Y.array(Y.object({name:Y.string(),version:Y.string().optional(),description:Y.string().optional(),license:Y.string().optional(),downloads:Y.number().optional(),repository:Y.string().optional(),repositoryDirectory:Y.string().optional(),next:Y.record(Y.string(),Y.unknown()).optional()}).passthrough()).optional(),pagination:Y.object({currentPage:Y.number(),totalPages:Y.number(),perPage:Y.number(),totalFound:Y.number(),returned:Y.number(),hasMore:Y.boolean(),nextPage:Y.number().optional()}).optional()}).optional(),status:Y.string().optional()})).optional()}).extend(Ae);var La={hasTool(e){return ds(e)},getDescription(e){return ls[e]??""},getToolName(e){return S[e]??String(e)}};var bm=(e,t=La)=>t.getDescription(e);function WT(e,t){return t.getToolName(e)}function We(e,t,n){let r=WT(t,e);return{...n,name:r,description:bm(r,e)}}function KT(e=La){let t=We(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:zd,inputSchema:Qd,executionFn:Gd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=We(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:jo,inputSchema:Pd,executionFn:Dd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=We(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:pp,inputSchema:fp,executionFn:up,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=We(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ap,inputSchema:cp,executionFn:op,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=We(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Jo,inputSchema:Jd,executionFn:Zd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=We(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ym,inputSchema:Rm,executionFn:mm,security:"remote",requiresServerRuntime:!0}}),a=We(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:Bs,inputSchema:bd,executionFn:gd,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=We(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:vn,inputSchema:Vp,executionFn:cf,security:"basic"}}),u=We(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:oi,inputSchema:df,executionFn:bf,security:"basic"}}),l=We(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:ti,inputSchema:Up,executionFn:Qp,security:"basic"}}),d=We(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:ei,inputSchema:Np,executionFn:Dp,security:"basic"}}),m={name:Ie,description:bm(Ie,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:Sa,inputSchema:Ca,executionFn:ya,security:"basic",requiresServerRuntime:!0}},p=We(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Zo,inputSchema:hp,executionFn:Op,security:"basic"}});return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:u,LOCAL_FIND_FILES:l,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:m,LOCAL_BINARY_INSPECT:p,ALL_TOOLS:[t,n,r,o,i,s,a,c,u,l,d,m,p]}}var Me=KT(),fU=Me.GITHUB_SEARCH_CODE,mU=Me.GITHUB_FETCH_CONTENT,gU=Me.GITHUB_VIEW_REPO_STRUCTURE,hU=Me.GITHUB_SEARCH_REPOSITORIES,yU=Me.GITHUB_SEARCH_PULL_REQUESTS,RU=Me.PACKAGE_SEARCH,bU=Me.GITHUB_CLONE_REPO,SU=Me.LOCAL_RIPGREP,CU=Me.LOCAL_VIEW_STRUCTURE,PU=Me.LOCAL_FIND_FILES,EU=Me.LOCAL_FETCH_CONTENT,TU=Me.LSP_GET_SEMANTIC_CONTENT,xU=Me.LOCAL_BINARY_INSPECT,Sm=Me.ALL_TOOLS;import{completeMetadata as YT}from"@octocodeai/octocode-core";var Mr=null;function Cm(){return Mr||(Mr=YT),Mr}async function AU(){return Cm()}async function LU(){Cm()}function OU(){return Mr}function IU(){Mr=null}import{z as Fa}from"zod";import{ContentSanitizer as XT}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as Pm}from"@octocodeai/octocode-engine/mask";function Oa(e){let t=e;if(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let r=XT.sanitizeContent(n.text),o=r.hasSecrets?Pm(r.content):Pm(n.text);return{...n,text:o}}catch{return n}return n})}),t.structuredContent)try{t={...t,structuredContent:ot(t.structuredContent)}}catch{}return t}var JT="TOOL_CALLBACK_EXCEPTION";function Ia(e,t){let n=ZT(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
57
- message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:JT,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Oa(r)}catch{return r}}function ZT(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:qT(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function qT(e){try{return JSON.stringify(e)}catch{return}}import{releaseAllPooledClients as ex}from"@octocodeai/octocode-engine/lsp/manager";var Em=["GitHub","Local","LSP","Package","Other"],Tm=new Map([ge.GITHUB_SEARCH_CODE,ge.GITHUB_SEARCH_REPOSITORIES,ge.GITHUB_SEARCH_PULL_REQUESTS,ge.GITHUB_FETCH_CONTENT,ge.GITHUB_VIEW_REPO_STRUCTURE,ge.GITHUB_CLONE_REPO,ge.LOCAL_RIPGREP,ge.LOCAL_FIND_FILES,ge.LOCAL_FETCH_CONTENT,ge.LOCAL_VIEW_STRUCTURE,Ie,ge.PACKAGE_SEARCH].map((e,t)=>[e,t])),Rt=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},ka=null,va=null,tx=["id","mainResearchGoal","researchGoal","reasoning"],Da=new Set([...tx]),nx=["id","researchGoal","reasoning"],xm=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}];function rx(e){return async t=>e(t)}function ox(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:rx(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}var _m=Sm.map(ox),WU=_m.map(Om);function wm(e){let t=Ha(e);return t?Om(t):void 0}function fi(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")?"Local":e.startsWith("lsp")?"LSP":e===ge.PACKAGE_SEARCH?"Package":"Other"}function KU(e){return[...e].sort((t,n)=>{let r=Em.indexOf(fi(t)),o=Em.indexOf(fi(n));if(r!==o)return r-o;let i=Tm.get(t)??Number.MAX_SAFE_INTEGER,s=Tm.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function YU(e){let t=wm(e);if(!t)return"{}";try{return JSON.stringify(Fa.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(Fa.toJSONSchema(t.schema),null,2)}}function XU(e){return JSON.stringify(e??{},null,2)}function JU(e){let t=fi(e),n=[...nx];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function ZU(){return xm.map(e=>({...e}))}function qU(){return JSON.stringify(Object.fromEntries(xm.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function eB(e,t){return t?.tools?.[e]?.description??e}function Am(e){let t=wm(e);if(!t)return[];let n=Fa.toJSONSchema(t.schema);if(!Nr(n))return[];let r=Ft(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!Da.has(i)&&!Na(r[i])):[]);return Ma(r,o)}function tB(e){let t=Am(e),n=t.filter(i=>i.required),r=n.length>0?n:t.slice(0,4),o={};for(let i of r)o[i.name]=px(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Ie&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function nB(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new Rt("Tool input must be valid JSON.")}return ix(e,r,n)}function ix(e,t,n={}){let r=ax(e,t,n),o=Ha(e);if(!o)throw new Rt(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new Rt("Tool input does not match the expected schema.",sx(i.error));return i.data}function sx(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function ax(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(Ft(t)&&Array.isArray(t.queries))r=t.queries;else if(Ft(t))r=[t];else throw new Rt('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new Rt("At least one query is required.");let o=Ft(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="queries")):{},i=!1,s={...n,onUnknownFields:(c,u)=>{i=!0,n.onUnknownFields?.(c,u)}},a=r.map((c,u)=>cx(e,u,lx(e,c,u,s),{sourceLabel:n.sourceLabel}));if(i&&n.onUnknownFields!==void 0)throw new Rt("Tool input contains unknown fields. See warnings above for details.");return{...o,queries:a}}function cx(e,t,n,r){let o={...n},i=fi(e),s=r.sourceLabel??"direct tool execution",a=ux(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function ux(e,t){return`Execute ${e} via ${t}`}function lx(e,t,n,r={}){if(!Ft(t))throw new Rt("Tool input must be a JSON object or an array of objects.");let o=new Set([...Am(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...Da]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}return s.length>0&&o.size>0&&r.onUnknownFields?.(s,n),i}function dx(e){let t=[],n=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return n!==void 0&&r!==void 0?t.push(`${n}-${r}`):n!==void 0?t.push(`>=${n}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function Lm(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let t=Nr(e.items)?e.items:void 0;return`array<${t?Lm(t):"value"}>`}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function Ma(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&Da.has(o))continue;let s=Nr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:Lm(s),constraints:dx(s),description:typeof s.description=="string"?s.description:void 0}),Ft(s.properties)){let u=new Set(Array.isArray(s.required)?s.required.filter(l=>typeof l=="string"?!Na(s.properties?.[l]):!1):[]);r.push(...Ma(s.properties,u,a))}let c=s.type==="array"&&Nr(s.items)?s.items:void 0;if(c&&Ft(c.properties)){let u=new Set(Array.isArray(c.required)?c.required.filter(l=>typeof l=="string"?!Na(c.properties?.[l]):!1):[]);r.push(...Ma(c.properties,u,a))}}return r}function px(e,t){if(t.startsWith("array<"))return[e];if(t==="integer"||t==="number")return 1;if(t==="boolean")return!0;if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;switch(e){case"path":return".";case"owner":return"bgauryy";case"repo":return"octocode";case"name":case"packageName":return"react";default:return e}}function Ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nr(e){return Ft(e)}function Na(e){return Nr(e)&&"default"in e}async function rB(e,t){let n=Ha(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=fx(n,t);return await mx(n),gx(n),await hx(n,r)}catch(r){return Ia(n.name,r)}finally{e===Ie&&await ex()}}function Om(e){return{name:e.name,schema:e.schema,inputSchema:e.inputSchema}}function Ha(e){return _m.find(t=>t.name===e)}function fx(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function mx(e){e.requiresServerRuntime&&(ka||(ka=du()),await ka),e.requiresProviders&&(va||(va=Yl().then(()=>{})),await va)}function gx(e){if(!e.isLocal&&!e.isClone)return;let t=ae();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}if(e.isClone&&!(t.local.enabled&&t.local.enableClone)){let n=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true and ENABLE_LOCAL=true to use it.`);throw n.code="cloneDisabled",n}}async function hx(e,t){try{let n=e.security==="remote"?await yx(e,t):await Rx(e,t);return Oa(n)}catch(n){return Ia(e.name,n)}}async function yx(e,t){return Qa(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function Rx(e,t){return ja(e.execute,e.name)(t)}function sB(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function aB(){try{return ae().local.enabled}catch{return!1}}function cB(){try{if(!ae().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}function pB(e,t){let n=Ce(),r=t.maxOutputChars??n,o=t.recommendedCharLength??n,i=[];if(t.charLength!==void 0||t.charOffset!==void 0){let s=t.charLength??o,a=t.charOffset??0,c=mt(e,a,s),u=br(c);return{content:c.paginatedContent,wasLimited:!0,pagination:u,warnings:i,paginationHints:Im(u)}}if(e.length>r){i.push(`Auto-paginated: Output (${e.length} chars) exceeds ${r} char limit. Use charOffset/charLength to navigate.`);let s=mt(e,0,o),a=br(s);return{content:s.paginatedContent,wasLimited:!0,pagination:a,warnings:i,paginationHints:Im(a)}}return{content:e,wasLimited:!1,warnings:i,paginationHints:[]}}function Im(e){let t=[];if(e.hasMore){let n=(e.charOffset??0)+(e.charLength??0),r=(e.charOffset??0)+1,o=n;t.push(`Page ${e.currentPage}/${e.totalPages} (chars ${r}-${o} of ${e.totalChars}). Next: charOffset=${n}`)}return t}function gB(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=O.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={matchCount:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}import{z as F}from"zod";var mi=F.object({text:F.string()}),bx=F.object({match:F.object({text:F.string()}).optional(),start:F.number(),end:F.number()}),Sx=F.object({type:F.literal("match"),data:F.object({path:mi,lines:F.object({text:F.string()}),line_number:F.number(),absolute_offset:F.number(),submatches:F.array(bx)})}),Cx=F.object({type:F.literal("context"),data:F.object({path:mi,lines:F.object({text:F.string()}),line_number:F.number(),absolute_offset:F.number()})}),Px=F.object({type:F.literal("begin"),data:F.object({path:mi})}),Ex=F.object({type:F.literal("end"),data:F.object({path:mi,stats:F.object({elapsed:F.object({human:F.string()}),searches:F.number(),searches_with_match:F.number()}).optional()})}),Tx=F.object({type:F.literal("summary"),data:F.object({elapsed_total:F.object({human:F.string()}),stats:F.object({elapsed:F.object({human:F.string()}),searches:F.number(),searches_with_match:F.number(),bytes_searched:F.number(),bytes_printed:F.number(),matched_lines:F.number(),matches:F.number()})})}),RB=F.discriminatedUnion("type",[Sx,Cx,Px,Ex,Tx]);var xx=1e5,Ga=new Set(["hints","warnings","pagination","outputPagination"]);function km(){return Math.min(Math.max(Ce(),1),xx)}function vm(e,t=km()){return{offset:e.offset??0,length:Math.max(e.length??t,1),explicit:e.offset!==void 0||e.length!==void 0}}function ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Ne(e){return JSON.stringify(e)}function Fm(e,t,n,r){let o=Math.max(r,1),i=Math.max(n,0),s=Math.max(1,Math.ceil(i/o)),a=i===0?0:Math.max(i-1,0),c=Math.min(Math.max(e,0),a),u=i===0?1:Math.min(s,Math.floor(c/o)+1),l=e+t<i;return{currentPage:u,totalPages:l?Math.max(s,u+1):u,hasMore:l,charOffset:e,charLength:t,totalChars:i}}function _x(e,t){let n={...e};delete n.outputPagination;for(let s of t)s.kind==="array"&&Array.isArray(n[s.field])&&(n[s.field]=[]),s.kind==="record"&&ye(n[s.field])&&(n[s.field]={});let r=Ne(n).length,o=[],i=r;for(let s of t){let a=e[s.field];if(s.kind==="array"&&Array.isArray(a)&&a.length>0){let c=!0;for(let u of a){let l=Ne(u),d=`${c?"":","}${l}`.length;o.push({field:s.field,kind:"array",value:u,start:i,end:i+d,itemPaginator:s.itemPaginator}),i+=d,c=!1}continue}if(s.kind==="record"&&ye(a)){let c=!0;for(let[u,l]of Object.entries(a)){let d=Ne(l),m=`${c?"":","}${Ne(u)}:${d}`.length;o.push({field:s.field,kind:"record",key:u,value:l,start:i,end:i+m,itemPaginator:s.itemPaginator}),i+=m,c=!1}}}return{baseObject:n,baseChars:r,segments:o,totalChars:i}}function wx(e,t){let n={...e};for(let r of t){if(r.kind==="array"){let i=Array.isArray(n[r.field])?[...n[r.field]]:[];i.push(r.value),n[r.field]=i;continue}let o=ye(n[r.field])?{...n[r.field]}:{};r.key!==void 0&&(o[r.key]=r.value),n[r.field]=o}return n}function Ax(e,t,n,r){let o=n.findIndex(c=>c.end>r.offset);if(o===-1)return{selectedSegments:[],actualOffset:r.offset,pageEnd:r.offset};let i=[],s,a=0;for(let c=o;c<n.length;c+=1){let u=n[c],l=c===o?Math.max(0,r.offset-u.start):0,d=s===void 0?0:a-s,m=Math.max(r.length-d,1),p=u.end-u.start;if(l===0&&p<=m){s===void 0&&(s=r.offset<e?0:u.start),i.push(u),a=u.end;continue}if(u.itemPaginator){let f=u.itemPaginator(u.value,{offset:l,length:m,explicit:!0});if(f){s===void 0&&(s=r.offset<e?0:u.start+f.actualOffset),i.push({...u,value:f.value}),a=u.start+f.pageEnd;let g=f.pageEnd>=f.totalChars,h=a-s<r.length;if(g&&h)continue;break}}s===void 0&&(s=r.offset<e?0:u.start),i.push(u),a=u.end;break}return s===void 0&&(s=r.offset<e?0:Math.min(r.offset,t),a=Math.min(t,Math.max(e,s))),{selectedSegments:i,actualOffset:s,pageEnd:a}}function Ua(e,t,n,r,o=!0){return!o||!e.explicit&&t<=e.length?{value:n,actualOffset:0,pageEnd:t,totalChars:t,paginated:!1}:e.offset>=t?{value:r,actualOffset:e.offset,pageEnd:e.offset,totalChars:t,paginated:!0}:null}function Ke(e,t,n){let r=Ne(e).length;if(n.length===0)return{value:e,actualOffset:0,pageEnd:r,totalChars:r,paginated:!1};let{baseObject:o,baseChars:i,segments:s,totalChars:a}=_x(e,n),c=Ua(t,a,e,o,s.length>0);if(c)return c;let u=Ax(i,a,s,t);return{value:wx(o,u.selectedSegments),actualOffset:u.actualOffset,pageEnd:u.pageEnd,totalChars:a,paginated:!0}}function Ba(e,t){let n=Array.from(e),r=n.map(f=>Math.max(JSON.stringify(f).length-2,0)),i=2+r.reduce((f,g)=>f+g,0),s=Ua(t,i,e,"");if(s)return s;let a=0,c=0;if(t.offset>1){let f=1,g=!1;for(let h=0;h<r.length;h+=1){let R=r[h];if(f+R>t.offset){a=h,c=f,g=!0;break}f+=R}if(!g)return{value:"",actualOffset:t.offset,pageEnd:t.offset,totalChars:i,paginated:!0}}let u=Math.max(1,t.length-(a===0?1:0)-1),l=0,d=a;for(;d<n.length;){let f=r[d];if(l+f>u&&d>a||(l+=f,d+=1,l>=u))break}d===a&&d<n.length&&(l+=r[d],d+=1);let m=a===0?0:c,p=l+(a===0?1:0)+(d===n.length?1:0);return{value:n.slice(a,d).join(""),actualOffset:m,pageEnd:Math.min(i,m+Math.max(p,1)),totalChars:i,paginated:!0}}function Mm(e,t,n,r,o){let i={...e,[t]:r};delete i.outputPagination;let s=Math.max(Ne(i).length-2,0),a=o(e[t],{offset:n.offset<=s?0:n.offset-s,length:n.offset<=s?Math.max(1,n.length-s):n.length,explicit:!0}),c=s+a.totalChars,u=Ua(n,c,e,i);return u||{value:{...i,[t]:a.value},actualOffset:n.offset<=s?0:s+a.actualOffset,pageEnd:s+a.pageEnd,totalChars:c,paginated:!0}}function gi(e,t,n){return typeof e[t]!="string"?null:Mm(e,t,n,"",(r,o)=>Ba(r,o))}function Lx(e,t,n){return ye(e[t])?Mm(e,t,n,{},(r,o)=>za(r,o)):null}function Ox(e,t){return typeof e=="string"?Ba(e,t):ye(e)?za(e,t):null}function za(e,t){let n=[];for(let[i,s]of Object.entries(e))Ga.has(i)||Array.isArray(s)&&s.length>0&&n.push({field:i,kind:"array",itemPaginator:Ox});let r=Ke(e,t,n);if(r.paginated)return r;for(let[i,s]of Object.entries(e)){if(Ga.has(i)||typeof s!="string")continue;let a=gi(e,i,t);if(a?.paginated)return a}for(let[i,s]of Object.entries(e)){if(Ga.has(i)||!ye(s))continue;let a=Lx(e,i,t);if(a?.paginated)return a}let o=Ne(e).length;return{value:e,actualOffset:0,pageEnd:o,totalChars:o,paginated:!1}}function Ix(e,t){return ye(e)?Ke(e,t,[{field:"text_matches",kind:"array",itemPaginator:(n,r)=>typeof n=="string"?Ba(n,r):ye(n)?gi(n,"value",r):null}]):null}function kx(e,t){return!ye(e)||Ne(e).length<=km()?null:Ke(e,t,[{field:"fileChanges",kind:"array",itemPaginator:(n,r)=>ye(n)?gi(n,"patch",r):null}])}function vx(e,t){return ye(e)?gi(e,"value",t):null}function Fx(e,t){return ye(e)?Ke(e,t,[{field:"matches",kind:"array",itemPaginator:vx}]):null}function Nm(e,t,n){let r;switch(e){case S.GITHUB_SEARCH_CODE:r=Ke(t,n,[{field:"files",kind:"array",itemPaginator:Ix}]);break;case S.GITHUB_SEARCH_REPOSITORIES:r=Ke(t,n,[{field:"repositories",kind:"array"},{field:"repositoryDetails",kind:"array"}]);break;case S.GITHUB_VIEW_REPO_STRUCTURE:r=Ke(t,n,[{field:"structure",kind:"record"}]);break;case S.PACKAGE_SEARCH:r=Ke(t,n,[{field:"packages",kind:"array"}]);break;case S.LOCAL_RIPGREP:r=Ke(t,n,[{field:"files",kind:"array",itemPaginator:Fx}]);break;case S.LOCAL_VIEW_STRUCTURE:r=Ke(t,n,[{field:"entries",kind:"array"}]);break;case S.GITHUB_SEARCH_PULL_REQUESTS:r=Ke(t,n,[{field:"pull_requests",kind:"array",itemPaginator:kx}]);break;case S.LOCAL_FIND_FILES:{let o=Ne(t).length;return{value:t,actualOffset:0,pageEnd:o,totalChars:o,paginated:!1}}case S.GITHUB_FETCH_CONTENT:case S.LOCAL_FETCH_CONTENT:return{value:t,actualOffset:0,pageEnd:Ne(t).length,totalChars:Ne(t).length,paginated:!1};default:r={value:t,actualOffset:0,pageEnd:Ne(t).length,totalChars:Ne(t).length,paginated:!1};break}return r.paginated?r:za(t,n)}function Mx(e,t,n){if(!ye(e)||!ye(e.data)||e.status!==void 0)return null;let r={...e,data:{}},o=Math.max(Ne(r).length-2,0),i=Nm(n,e.data,{offset:t.offset<=o?0:t.offset-o,length:t.offset<=o?Math.max(1,t.length-o):t.length,explicit:!0}),s=o+i.totalChars;if(!i.paginated&&(!t.explicit||s<=t.length))return{value:e,actualOffset:0,pageEnd:s,totalChars:s,paginated:!1};if(t.offset>=s)return{value:r,actualOffset:t.offset,pageEnd:t.offset,totalChars:s,paginated:!0};let a=Fm(i.actualOffset,Math.max(0,i.pageEnd-i.actualOffset),i.totalChars,t.length),c=i.paginated&&ye(i.value)?{...i.value,outputPagination:a,...n===S.LOCAL_FIND_FILES&&{charPagination:a}}:i.value;return{value:{...e,data:c},actualOffset:t.offset<=o?0:o+i.actualOffset,pageEnd:o+i.pageEnd,totalChars:s,paginated:!0}}function PB(e,t,n){if(!ye(e.data)||e.status!==void 0)return e;let r=vm({offset:typeof t.charOffset=="number"?t.charOffset:void 0,length:typeof t.charLength=="number"?t.charLength:void 0});if(!r.explicit)return e;let o=Nm(n,e.data,r);if(!o.paginated)return e;let i=Fm(o.actualOffset,Math.max(0,o.pageEnd-o.actualOffset),o.totalChars,r.length),s={...o.value,outputPagination:i};return{...e,data:s}}function EB(e,t,n){let r=vm(t,tl(e.results.length));if(!r.explicit&&e.results.length>0&&e.results.every(i=>ye(i?.data)&&i.data.outputPagination!==void 0))return e;let o=Ke({results:e.results},r,[{field:"results",kind:"array",itemPaginator:(i,s)=>Mx(i,s,n)}]);return o.paginated?{results:Array.isArray(o.value.results)?o.value.results:[]}:e}import{securityRegistry as RQ,ContentSanitizer as bQ}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as CQ}from"@octocodeai/octocode-engine/mask";import{configureSecurity as EQ}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as kQ}from"@octocodeai/octocode-core";import{z as FQ}from"zod";export{zx as ALL_ERROR_CODES,Sm as ALL_TOOLS,Wh as BASE_SCHEMA,$a as BaseCommandBuilder,bd as BulkCloneRepoLocalSchema,Ca as BulkLspGetSemanticsQuerySchema,hi as CONFIG_ERRORS,Xc as CONFIG_FILE_NAME,er as CONFIG_FILE_PATH,Xn as CONFIG_SCHEMA_VERSION,Uo as CORE_ALLOWED_ENV_VARS,Ye as CREDENTIALS_FILE,Pa as CircuitOpenError,Bs as CloneRepoQueryLocalSchema,Fo as ContentBuilder,bQ as ContentSanitizer,oN as DEFAULTS,nG as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,co as DEFAULT_CONFIG,Jn as DEFAULT_GITHUB_CONFIG,At as DEFAULT_LOCAL_CONFIG,qn as DEFAULT_LSP_CONFIG,Ja as DEFAULT_MATCH_SNIPPET_CHARS,ln as DEFAULT_NETWORK_CONFIG,pt as DEFAULT_OUTPUT_CONFIG,Zn as DEFAULT_TELEMETRY_CONFIG,Bt as DEFAULT_TOOLS_CONFIG,La as DEFAULT_TOOL_METADATA_GATEWAY,ls as DESCRIPTIONS,Uy as DIFF_PREVIEW_MAX_LINES,Em as DIRECT_TOOL_CATEGORIES,WU as DIRECT_TOOL_DEFINITIONS,Rt as DirectToolInputError,an as ENV_TOKEN_VARS,G as ERROR_CODES,le as ERROR_MESSAGES,St as FETCH_ERRORS,Oe as FILE_OPERATION_ERRORS,Pd as FileContentBulkQueryLocalSchema,bb as FileContentQueryBaseLocalSchema,jo as FileContentQueryLocalSchema,bU as GITHUB_CLONE_REPO,mU as GITHUB_FETCH_CONTENT,Xa as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,fU as GITHUB_SEARCH_CODE,Be as GITHUB_SEARCH_DEFAULT_LIMIT,pe as GITHUB_SEARCH_MAX_LIMIT,Gx as GITHUB_SEARCH_MAX_PAGES,yU as GITHUB_SEARCH_PULL_REQUESTS,hU as GITHUB_SEARCH_REPOSITORIES,Kt as GITHUB_STRUCTURE_DEFAULTS,Ux as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,Va as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,gU as GITHUB_VIEW_REPO_STRUCTURE,h0 as GitHubCloneRepoOutputLocalSchema,Qd as GitHubCodeSearchBulkQueryLocalSchema,lF as GitHubCodeSearchOutputLocalSchema,zd as GitHubCodeSearchQueryLocalSchema,T0 as GitHubFetchContentOutputLocalSchema,vo as GitHubProvider,Jd as GitHubPullRequestSearchBulkQueryLocalSchema,Jo as GitHubPullRequestSearchQueryLocalSchema,cp as GitHubReposSearchBulkQueryLocalSchema,ap as GitHubReposSearchSingleQueryLocalSchema,TF as GitHubSearchPullRequestsOutputLocalSchema,qF as GitHubSearchRepositoriesOutputLocalSchema,fp as GitHubViewRepoStructureBulkQueryLocalSchema,gM as GitHubViewRepoStructureOutputLocalSchema,pp as GitHubViewRepoStructureQueryLocalSchema,ut as HOME,gL as IGNORED_FILE_EXTENSIONS,hL as IGNORED_FILE_NAMES,yL as IGNORED_FOLDER_NAMES,rt as KEY_FILE,xU as LOCAL_BINARY_INSPECT,Ka as LOCAL_DEFAULT_FILES_PER_PAGE,EU as LOCAL_FETCH_CONTENT,PU as LOCAL_FIND_FILES,nn as LOCAL_MAX_DEPTH,Hr as LOCAL_MAX_FILES_PER_PAGE,tn as LOCAL_MAX_LIMIT,SU as LOCAL_RIPGREP,H as LOCAL_TOOL_ERROR_CODES,Za as LOCAL_TOOL_ERROR_REGISTRY,CU as LOCAL_VIEW_STRUCTURE,TU as LSP_GET_SEMANTIC_CONTENT,Ie as LSP_GET_SEMANTIC_CONTENT_TOOL_NAME,hp as LocalBinaryInspectBulkQuerySchema,Zo as LocalBinaryInspectQuerySchema,Np as LocalFetchContentBulkQuerySchema,ei as LocalFetchContentQuerySchema,Up as LocalFindFilesBulkQuerySchema,ti as LocalFindFilesQuerySchema,Vp as LocalRipgrepBulkQuerySchema,vn as LocalRipgrepQuerySchema,Qm as LocalToolErrorCategory,df as LocalViewStructureBulkQuerySchema,oi as LocalViewStructureQuerySchema,dT as LspGetSemanticsOutputSchema,Sa as LspGetSemanticsQueryDisplaySchema,XE as LspGetSemanticsQuerySchema,fh as MAX_BRANCH_CACHE_SIZE,rn as MAX_CHAR_LENGTH,Ya as MAX_CONTEXT_LINES,el as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Py as MAX_DIRECTORY_FILES,Ur as MAX_MATCH_CONTENT_LENGTH,hn as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,Gr as MAX_PAGE_NUMBER,mn as MAX_RETRIES,pn as MAX_TIMEOUT,Ey as MAX_TOTAL_SIZE,gn as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,fn as MIN_RETRIES,dn as MIN_TIMEOUT,ns as NETWORK_ERROR_PATTERNS,tm as NpmDeprecationOutputSchema,em as NpmRegistrySearchSchema,Rm as NpmSearchBulkQueryLocalSchema,MG as NpmSearchOutputLocalSchema,ym as NpmSearchQueryLocalSchema,ci as NpmViewResultSchema,Ci as OCTOCODE_DIR,be as OCTOCODE_HOME,uo as OctocodeConfigSchema,ch as OctokitWithThrottling,RU as PACKAGE_SEARCH,Ct as PROMISE_ERRORS,Bl as PROVIDER_CAPABILITIES,Jl as PROXY_ENV_VARS,Mt as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,Wa as PR_CONTENT_MAX_ITEMS_PER_PAGE,Us as ProviderInitializationError,rv as QuickResult,Ro as RATE_LIMIT_CONFIG,rs as RATE_LIMIT_PATTERNS,et as REPOSITORY_ERRORS,st as RESOURCE_LIMITS,RB as RipgrepJsonMessageSchema,oe as SEARCH_ERRORS,mu as SEMANTIC_CONTENT_TYPES,wv as SENSITIVE_ENV_VARS,xt as SESSION_FILE,zm as STARTUP_ERRORS,ge as STATIC_TOOL_NAMES,_t as STATS_FILE,Eu as STATUS_TO_ERROR_CODE,Mo as StatusEmoji,LR as StatusEmojis,_r as TOOLING_ALLOWED_ENV_VARS,Br as TOOL_ERRORS,Bm as TOOL_METADATA_ERRORS,S as TOOL_NAMES,Te as ToolError,De as ToolErrors,bt as VALIDATION_ERRORS,Vi as _getCacheState,tc as _getLogHandler,_T as _packageNameToSearchKeywords,$i as _resetConfigCache,IU as _resetMetadataState,SG as _resetNpmRegistryUrlCache,Yc as _resetSessionState,bA as _resetTokenResolvers,RA as _setTokenResolvers,EB as applyBulkResponsePagination,sl as applyContentPagination,mf as applyEntryFilters,Kb as applyExactMatchRanking,pB as applyOutputSizeLimit,mt as applyPagination,wo as applyPartialContentFilter,PB as applyQueryOutputPagination,Nl as applyStructurePagination,Xf as assertCircuitAvailable,U as attachRawResponseChars,OO as buildBlockBoundaryHint,Ms as buildChildProcessEnv,wu as buildCodeSearchQuery,Pr as buildDiffPreview,tB as buildDirectToolExampleQuery,ZP as buildEntryPaginationHints,Hd as buildGhSearchCodeFinalizer,Nd as buildGithubFetchContentFinalizer,A0 as buildPaginationHints,Lu as buildPullRequestSearchQuery,Au as buildRepoSearchQuery,ri as buildSearchResult,Ia as buildToolErrorResult,la as buildWalkWarnings,vy as byteSlice,Eo as byteToCharIndex,nl as charToByteIndex,_M as checkLargeOutputSafety,eG as checkNpmAvailability,DT as checkNpmDeprecation,CG as checkNpmRegistryReachable,aa as checkRegexSafety,v as clampedInt,SA as cleanup,aL as clearAllCache,uL as clearLSPToolCache,cL as clearLocalToolCache,VA as clearOctokitInstances,Yk as clearProviderCache,lL as clearRemoteAPICache,td as cloneRepo,$o as collectFlatErrors,KR as commonDirPrefix,Xi as compactLocation,bn as compactResolvedSymbol,qd as compareIsoDateDescending,kQ as completeMetadata,nb as computeQueryTimeout,lo as configExists,oG as configureCircuitBreaker,EQ as configureSecurity,An as contextLinesField,EO as convertByteMatchToChar,Wt as countLines,N as countSerializedChars,Cs as createBasePRTransformation,gr as createCacheMeta,Or as createCallItemKey,L as createErrorResult,gt as createGitHubProviderError,ko as createGitHubProviderErrorFromResult,$e as createLazyProviderContext,tt as createLogger,br as createPaginationInfo,lb as createProviderExecutionContext,X as createRelaxedBulkQuerySchema,xr as createResponseFormat,nv as createResult,No as createRoleBasedResult,XD as createSafeRegExp,Pe as createSuccessResult,$r as decrypt,Pc as deleteCredentials,Kc as deleteSession,sB as detectEnvironment,jr as encrypt,Jm as ensureBinary,uc as ensureClone,hr as ensureCloneParentDir,Bn as ensureHome,Ym as ensureLogs,Pt as ensureOctocodeDir,Km as ensureRepos,zn as ensureTmp,Xm as ensureTree,Zm as ensureUnzip,Co as evictExpiredClones,dr as evictExpiredTrees,J as executeBulkOperation,gd as executeCloneRepo,rB as executeDirectTool,Dp as executeFetchContent,Qp as executeFindFiles,Op as executeInspectBinary,ya as executeLspGetSemantics,Ir as executeNpmCommand,kt as executeProviderOperation,md as executeProviderOperations,cf as executeRipgrepSearch,of as executeRipgrepSearchInternal,bf as executeViewStructure,od as executeWithErrorIsolation,ke as executeWithToolBoundary,up as exploreMultipleRepositoryStructures,xo as extractMatchingLines,Tu as fallbackOnBestEffortFailure,vp as fetchContent,Zu as fetchDirectoryContents,As as fetchDirectoryContentsRecursivelyAPI,qu as fetchFileContentToDisk,al as fetchFileTimestamp,ul as fetchGitHubFileContentAPI,SI as fetchGitHubPullRequestByNumberAPI,xs as fetchGitHubPullRequestByNumberAPIInternal,kl as fetchHistory,Dd as fetchMultipleGitHubFileContents,So as fetchRawGitHubFileContent,vt as fetchWithRetries,ll as filterPatch,vS as filterStructure,ta as finalizeFetchContentResult,zp as finalizeFindFilesResult,nf as finalizeRipgrepResult,Rf as finalizeViewStructureResult,wm as findDirectToolDefinition,Bp as findFiles,Cr as findNextBlockBoundary,zc as flushSession,Qc as flushSessionSync,Zg as formatBytes,ov as formatCallToolResultForOutput,XU as formatDirectToolMetadataSchemaText,qU as formatDirectToolOutputSchemaText,YU as formatDirectToolSchemaText,sx as formatDirectToolValidationIssues,kn as formatFileSize,Vo as formatFinalizedResponse,Er as formatPRForResponse,BF as formatRepoLine,da as gatherIncomingCallsRecursive,pa as gatherOutgoingCallsRecursive,_e as generateCacheKey,ZI as generatePaginationHints,Oo as generateStructurePaginationHints,ir as getActiveProvider,Yi as getActiveProviderConfig,zr as getAppDataPath,ac as getArchitecture,tl as getBulkDefaultCharLength,rl as getByteLength,dL as getCacheStats,my as getCacheTTL,fs as getCloneBaseDir,$u as getCloneDir,go as getConfig,qc as getConfigPath,ae as getConfigSync,lu as getConfigValue,Ut as getCredentials,wc as getCredentialsFilePath,Yr as getCredentialsSync,cc as getDefaultOctocodeHome,bm as getDescription,JU as getDirectToolAutoFilledFields,fi as getDirectToolCategory,eB as getDirectToolDescription,Am as getDirectToolDisplayFields,ZU as getDirectToolOutputFields,or as getDirectorySizeBytes,Ti as getEnvTokenSource,ku as getExtension,$l as getFileContent,Wr as getGhCliToken,pu as getGitHubToken,ic as getLocalAppDataPath,cB as getLspEnvironmentHint,gy as getMaxCacheSizeBytes,hy as getMaxCloneCount,OU as getMetadataOrNull,xa as getNpmRegistryUrl,zt as getOctocodeDir,ie as getOctokit,to as getOrCreateSession,Ce as getOutputCharLimit,Ah as getOwnerQualifier,sc as getPlatformName,Os as getProvider,ne as getRawResponseChars,ws as getRecursiveFetchFailureCount,Wl as getRepoStructure,sO as getReposBaseDir,ho as getServerConfig,jc as getSessionId,Sn as getSessionManager,Ac as getToken,Vr as getTokenFromEnv,EA as getTokenSource,Lc as getTokenSync,Oi as getTokenWithRefresh,ju as getTreeBaseDir,ms as getTreeDir,Ee as handleCatchError,Z as handleGitHubAPIError,Go as handleProviderError,xc as hasCredentials,_c as hasCredentialsSync,xi as hasEnvToken,pF as hasExpensiveContentRequest,ad as hoistSharedFields,xe as ignoreBestEffortFailure,ro as incrementErrors,so as incrementGitHubCacheHits,ao as incrementGitHubCacheRateLimits,Vc as incrementPackageRegistryFailures,$c as incrementRateLimitByProvider,oo as incrementRateLimits,no as incrementToolCalls,io as incrementToolCharSavings,LP as inferLspSymbolName,du as initialize,Yl as initializeProviders,vA as initializeSession,LU as initializeToolMetadata,yn as invalidateConfigCache,Gn as invalidateCredentialsCache,Sv as invokeCallbackSafely,mr as isCacheHit,Vu as isCacheValid,Zf as isCircuitOpen,PA as isCloneEnabled,li as isExactPackageName,Yt as isGitHubAPIError,aR as isGitHubAPISuccess,bi as isLinux,CA as isLocalEnabled,Ji as isLocalTool,fu as isLoggingEnabled,Un as isMac,Sr as isMidBlockCut,$t as isNoResultsSearchError,cb as isProviderError,zo as isProviderSuccess,Dn as isRefreshTokenExpired,cR as isRepository,ct as isTokenExpired,yi as isToolError,ds as isToolInMetadata,Nt as isWindows,Ln as lineNumberField,Ec as listStoredHosts,Tc as listStoredHostsSync,Zc as loadConfig,tr as loadConfigSync,AU as loadToolContent,gu as logPackageRegistryFailure,NA as logPromptCall,Lt as logRateLimit,M as logSessionError,FA as logSessionInit,MA as logToolCall,_d as mapCodeSearchProviderResult,Td as mapCodeSearchToolQuery,kd as mapFileContentProviderResult,Id as mapFileContentToolQuery,Od as mapPullRequestProviderResultData,Ld as mapPullRequestToolQuery,Ad as mapRepoSearchProviderRepositories,wd as mapRepoSearchToolQuery,Fd as mapRepoStructureProviderResult,vd as mapRepoStructureToolQuery,CQ as maskSensitiveData,Tr as normalizeOwnerRepo,jd as normalizePullRequestContentRequest,bo as normalizeResponseHeaders,ua as paginateEntries,k0 as paginateGroupsCharWindow,Ar as parseFileSize,de as parseGitHubProjectId,Bi as parseLoggingEnv,gB as parseRipgrepJson,W as paths,rf as preflightValidateRipgrepPattern,ix as prepareDirectToolInput,nB as prepareDirectToolInputFromJsonText,cl as processFileContentAPI,Qo as providerSupports,gs as readCacheMeta,lt as readCredentialsStore,Jf as recordCircuitFailure,Ta as recordCircuitSuccess,Nn as redactPath,Oc as refreshAuthToken,sd as relativizeResultPaths,q as relaxedPageNumberField,ji as reloadConfig,hs as removeCloneDir,rG as resetCircuitBreaker,DA as resetSessionManager,Wc as resetSessionStats,_i as resetTokenResolution,Qi as resolveConfig,rr as resolveConfigSync,Ge as resolveDefaultBranch,fa as resolveFileAnchor,Ef as resolveSymbolAnchor,wi as resolveToken,Tt as resolveTokenFull,Ai as resolveTokenWithRefresh,Ae as responseEnvelopeFields,On as safeExec,Le as safeParseOrError,Oa as sanitizeCallToolResult,ot as sanitizeStructuredContent,Ql as searchCode,af as searchContentRipgrep,Nu as searchGitHubCodeAPI,Ol as searchGitHubPullRequestsAPI,Ml as searchGitHubReposAPI,Gd as searchMultipleGitHubCode,Zd as searchMultipleGitHubPullRequests,op as searchMultipleGitHubRepos,pm as searchNpmPackage,fm as searchPackage,mm as searchPackages,Vl as searchPullRequests,jl as searchRepos,RQ as securityRegistry,_O as serializeForPagination,ec as setLogHandler,Kd as shapePullRequestForContent,cr as shouldIgnoreDir,xn as shouldIgnoreFile,aB as shouldUseMCPLsp,Ou as shouldUseSearchForPRs,wO as sliceByCharRespectLines,Ss as sliceContent,To as snapToSemanticBoundary,KU as sortDirectToolNames,Zl as spawnCheckSuccess,Av as spawnCollectStdout,Xt as spawnWithTimeout,Rr as splitLines,aO as startCacheGC,cO as stopCacheGC,Li as storeCredentials,ca as summarizeEntries,hf as toEntryObject,gf as toGroupedLists,qa as toToolError,pR as transformCodeSearchResult,gR as transformFileContentResult,Lo as transformPullRequestItemFromREST,xl as transformPullRequestItemFromSearch,bR as transformPullRequestResult,fR as transformRepoSearchResult,CR as transformRepoStructureResult,dl as trimDiffContext,Sb as truncateSnippetChars,He as updateSessionStats,Xr as updateToken,Bo as validateArgs,po as validateConfig,ve as validateToolPath,Ul as viewGitHubRepositoryStructureAPI,yf as viewStructure,ja as withBasicSecurityValidation,we as withDataCache,dv as withResponseEnvelope,Qa as withSecurityValidation,fr as writeCacheMeta,FQ as z};
52
+ `);if(t){let i=n?t:t.toLowerCase();for(let s of o)if((n?s:s.toLowerCase()).includes(i))return s}return o.find(i=>i.trim().length>0)??o[0]??""}function pA(e,t,n,r){if(n==="markdown")return/<!--/.test(e)?"comment":"code";if(n==="json")return"code";if(zv.test(e))return"comment";let o=fA(e,t,r);if(o<0)return"code";let i=mA(e);return i>=0&&o>i?"comment":gA(e,o)?"string":"code"}function fA(e,t,n){return t?n?e.indexOf(t):e.toLowerCase().indexOf(t.toLowerCase()):-1}function mA(e){let t=-1,n=i=>{i>=0&&(t<0||i<t)&&(t=i)};for(let i of["//","/*","<!--"])n(e.indexOf(i));let r=/(^|\s)#(?![!{])/.exec(e);r&&n(r.index+(r[1]?.length??0));let o=/(^|\s)--\s/.exec(e);return o&&n(o.index+(o[1]?.length??0)),t}function gA(e,t){let n="";for(let r=0;r<t&&r<e.length;r++){let o=e[r];n?o===n&&e[r-1]!=="\\"&&(n=""):(o==='"'||o==="'"||o==="`")&&(n=o)}return n!==""}function Ab(e){if(!e)return!1;if(md.test(e))return!0;let t=kb(e);return t==="test"||t==="docs"||t==="fixture"||t==="generated"}var xb,ce,Hv,zv,wb,fi,Bv,md,Qv,Uv,jv,$v,qv,Vv,Wv,Tb,Lb=y(()=>{"use strict";xb=["typescript","javascript","rust","python","go","java","scala","markdown","json","yaml","generic"],ce={exactWholeWord:6,exactCaseInsensitive:3,substring:1,declarationLine:8,exportLine:4,importLine:3,configKeyLine:4,headingLine:4,commentOrStringPenalty:-2,pathUnderQuery:4,pathSegmentToken:3,extMatchesLangType:2,sourceDir:1.5,lowSignalPathPenalty:-5,rareQueryTokenScale:2,rareQueryTokenCap:3,matchCountScale:1.5,matchCountCap:6},Hv=2e3,zv=/^\s*(\/\/|#|\*|\/\*|<!--|--)/,wb={declaration:[/\b(function|class|interface|type|enum|const|let|var)\s+\w/,/\b\w+\s*[:=]\s*(async\s+)?(function|\()/],export:[/\bexport\b/,/\bmodule\.exports\b/,/\bexport\s+default\b/],import:[/\b(import|require)\b/,/\bfrom\s+['"]/]},fi={typescript:{id:"typescript",extensions:["ts","tsx","mts","cts"],...wb},javascript:{id:"javascript",extensions:["js","jsx","mjs","cjs"],...wb},rust:{id:"rust",extensions:["rs"],declaration:[/\b(fn|struct|enum|trait|impl|mod|type|const|static|macro_rules!)\b/],export:[/\bpub(\s*\([^)]*\))?\s+(fn|struct|enum|trait|mod|type|const|static)\b/],import:[/\buse\s+/,/\bextern\s+crate\b/]},python:{id:"python",extensions:["py","pyi"],declaration:[/^\s*(async\s+)?def\s+\w/,/^\s*class\s+\w/,/^\s*@\w/],export:[/^\s*__all__\s*=/],import:[/^\s*(import|from)\s+/]},go:{id:"go",extensions:["go"],declaration:[/\b(func|type|struct|interface)\b/,/^\s*(const|var)\s+/],export:[/\b(func|type)\s+[A-Z]\w*/],import:[/^\s*import\s+/,/^\s*"[^"]+"\s*$/]},java:{id:"java",extensions:["java"],declaration:[/\b(class|interface|enum|record)\s+\w/,/\b\w+\s*\([^)]*\)\s*\{/],export:[/\b(public|protected)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},scala:{id:"scala",extensions:["scala","sc"],declaration:[/\b(class|object|trait|def|val|var|type|case\s+class)\s+\w/],export:[/\b(export|implicit)\b/,/^\s*@\w/],import:[/^\s*import\s+/]},markdown:{id:"markdown",extensions:["md","markdown","mdx"],declaration:[],export:[],import:[/^\s*\[[^\]]+\]\([^)]+\)/]},json:{id:"json",extensions:["json","jsonc","json5"],declaration:[],export:[],import:[]},yaml:{id:"yaml",extensions:["yaml","yml"],declaration:[],export:[],import:[]},generic:{id:"generic",extensions:[],declaration:[/\b(function|def|fn|func|class|struct|interface|type)\b/],export:[/\b(export|public|pub)\b/],import:[/\b(import|require|use|include)\b/]}},Bv=/^\s*#{1,6}\s/,md=/(^|\/)(dist|build|out|coverage|node_modules|vendor|\.next|__snapshots__)(\/|$)/,Qv=/(\.min\.|\.bundle\.|\.generated\.|\.d\.ts$|-lock\.)/,Uv=/(^|\/)(tests?|__tests__|spec|e2e)(\/|$)|\.(test|spec)\./,jv=/(^|\/)(fixtures?|__fixtures__|snapshots?)(\/|$)/,$v=/(^|\/)(docs?|examples?)(\/|$)|\.(md|markdown|mdx|rst|txt)$/i,qv=/(^|\/)(config|\.github)(\/|$)|\.(json|ya?ml|toml|ini|cfg|conf|env)$|(^|\/)[^/]*\.config\.[jt]s$/i,Vv=/(^|\/)(src|lib|app|packages|internal|pkg|cmd|crates|include|sources?)(\/|$)/,Wv=new Set(["typescript","javascript","rust","python","go","java","scala"]),Tb=/\.([a-z0-9]+)$/i});async function La(e,t,n,r,o){let i=n==="structural"?"path":"relevance",s=t.sort??i,a;try{a=Ob(e,s,PA(t),{debug:!!t.debugRanking})}catch{a={files:e,cappedCandidates:0},r.push("Relevance ranking failed; returning results in unranked engine order.")}let c=a.files,l=a.debug,u=c.length,d=!!(t.filesOnly||t.filesWithoutMatch),p=!!(t.countLinesPerFile||t.countMatchesPerFile),f=d||p,m=c.reduce((z,X)=>z+(X.matchCount??0),0),g=f?o?.totalOccurrences??o?.totalStructuralMatches??m:m,b=t,C=Math.min(b.itemsPerPage||Tt.DEFAULT_FILES_PER_PAGE,t.maxFiles||Number.POSITIVE_INFINITY),S=b.page||1,T=Math.max(1,Math.ceil(u/C)),L=(S-1)*C,k=Math.min(L+C,u),O=c.slice(L,k),w=b.maxMatchesPerFile||Tt.DEFAULT_MATCHES_PER_PAGE,N=O.map(z=>{let X=z.matches?.length??0,j=Math.ceil(X/w),xe=Math.max(1,b.matchPage||1),we=(xe-1)*w,jt=Math.min(we+w,X),$t=f?void 0:z.matches?.slice(we,jt),ee=$t?.length,St=l?.get(z.path);return{path:z.path,...d?{}:t.countLinesPerFile?{totalMatchedLines:z.matchCount||1}:t.countMatchesPerFile?{totalOccurrences:z.matchCount||1}:{totalMatchRows:X,...ee!==void 0?{returnedMatchRows:ee}:{}},...$t!==void 0&&{matches:$t},...St?{ranking:{score:St.score,profile:St.profile,pathRole:St.pathRole,reasons:St.reasons}}:{},pagination:!f&&X>w?{currentPage:xe,totalPages:j,matchesPerPage:w,totalMatches:X,hasMore:xe<j,...xe<j?{nextMatchPage:xe+1}:{}}:void 0}}),I=N.filter(z=>z.pagination?.hasMore),v=bA(N,t,n,{isFileListMode:f,currentPage:S,totalFilePages:T,matchPage:b.matchPage||1,matchesPerPage:w,hasFileWithMoreMatches:I.length>0}),B={searchEngine:n,...o?{stats:o}:{},files:N,pagination:{currentPage:S,totalPages:T,filesPerPage:C,totalFiles:u,...d?{}:{totalMatches:g},hasMore:S<T,...S<T?{nextPage:S+1}:{}},...r.length>0?{warnings:r}:{},...Object.keys(v).length>0?{next:v}:{}};return Ib(B,t,{totalMatches:g,totalFiles:u})}function Ib(e,t,n){return e}function bA(e,t,n,r){let o=e.find(a=>a.path),i=o?.matches?.find(a=>a.line),s={};if(o?.path){if(i?.line){let c=RA(i);s.fetchExact={tool:"localGetFileContent",query:Aa({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"none"}),why:"Read exact source around the first grep match before editing, quoting, or validating comments/tests.",confidence:"exact"},s.fetchStandard={tool:"localGetFileContent",query:Aa({path:o.path,startLine:c.startLine,endLine:c.endLine,minify:"standard"}),why:"Read a token-efficient source slice around the first grep match.",confidence:"exact"}}else r.isFileListMode&&(s.fetchStandard={tool:"localGetFileContent",query:{path:o.path,minify:"standard"},why:"Read the first matched file from file-list/count mode.",confidence:"heuristic"});s.fetchSymbols={tool:"localGetFileContent",query:{path:o.path,minify:"symbols"},why:"Get a symbol skeleton for fast orientation before opening large bodies.",confidence:"exact"};let a=SA(i,t,n);if(a&&i?.line){let c={uri:o.path,symbolName:a,lineHint:i.line};s.lspDefinition={tool:"lspGetSemantics",query:{...c,type:"definition"},why:"Use the grep line as an LSP lineHint to resolve the symbol definition.",confidence:"heuristic"},s.lspReferences={tool:"lspGetSemantics",query:{...c,type:"references"},why:"Use the grep line as an LSP lineHint to inspect semantic usages.",confidence:"heuristic"}}}return r.currentPage<r.totalFilePages&&(s.nextPage={tool:"localSearchCode",query:Aa({...t,page:r.currentPage+1}),why:"Continue to the next page of matched files.",confidence:"exact"}),r.hasFileWithMoreMatches&&(s.nextMatchPage={tool:"localSearchCode",query:Aa({...t,maxMatchesPerFile:r.matchesPerPage,matchPage:r.matchPage+1}),why:"Continue within files that have more matches than this response returned.",confidence:"exact"}),s}function RA(e){let t=Math.max(1,e.line??1),n=Math.max(t,e.endLine??t);return{startLine:Math.max(1,t-_b),endLine:n+_b}}function SA(e,t,n){if(!(t.countLinesPerFile||t.countMatchesPerFile||t.countUnique||t.unique)){if(n==="structural")return CA(e?.metavars);if(!t.matchWindow)return t.onlyMatching?hd(e?.value):hd(t.keywords)}}function CA(e){if(e)for(let t of Object.values(e))for(let n of t){let r=hd(n);if(r)return r}}function hd(e){if(typeof e!="string")return;let t=e.trim();if(yA.test(t)&&!hA.has(t))return t}function Aa(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function PA(e){let t=e.rankingProfile,n=!!(e.include?.length||Ab(e.path));return{queryPath:e.path,keyword:e.keywords,langType:e.langType,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,profileOverride:t,explicitLowSignal:n}}var _b,hA,yA,mi=y(()=>{"use strict";vr();Lb();_b=8,hA=new Set(["async","await","break","case","catch","class","const","def","do","else","enum","export","for","function","if","import","interface","let","match","return","struct","switch","type","var","while","true","false","null","undefined","NaN","Infinity","this","super"]),yA=/^[A-Za-z_$][A-Za-z0-9_$]*$/});function Fb(e){let t=[],n=[],r=e.pattern;if(typeof r!="string"||r.length===0)return t.push("pattern is empty \u2014 provide a non-empty search string"),{isValid:!1,errors:t,warnings:n};let o=F.validateRipgrepPattern(r,e.fixedString,e.perlRegex);return o.valid||t.push(`invalid regex: ${o.error??"unknown regex parse error"}`),!e.fixedString&&xA(r)&&n.push(`pattern '${r}' looks literal \u2014 pass fixedString: true to skip regex parsing and avoid accidental wildcards`),!e.perlRegex&&wA(r)&&n.push("pattern uses lookaround (?= / ?! / ?<= / ?<!) which requires perlRegex: true; ripgrep will refuse it otherwise"),{isValid:t.length===0,errors:t,warnings:n}}function xA(e){return/[\\^$|()[\]{}+*?]/.test(e)?!1:!!(e.includes(".")&&/^[\w.\-/:]+$/.test(e))}function wA(e){return/\(\?[=!<]/.test(e)}var yd=y(()=>{"use strict";be()});import{validateRipgrepQuery as EA}from"@octocodeai/octocode-core/schemas/runtime";function TA(e){return e==="created"||e==="modified"||e==="accessed"?e:"path"}function kA(e){return{path:e.path,pattern:e.keywords??"",fixedString:e.fixedString,perlRegex:e.perlRegex,caseSensitive:e.caseSensitive,caseInsensitive:e.caseInsensitive,wholeWord:e.wholeWord,invertMatch:e.invertMatch,multiline:e.multiline,multilineDotall:e.multilineDotall,filesOnly:e.filesOnly,filesWithoutMatch:e.filesWithoutMatch,countLinesPerFile:e.countLinesPerFile,countMatchesPerFile:e.countMatchesPerFile,contextLines:e.contextLines,langType:e.langType,include:e.include,exclude:e.exclude,excludeDir:e.excludeDir,noIgnore:e.noIgnore,hidden:e.hidden,sort:TA(e.sort),sortReverse:e.sortReverse,classifyMatches:e.sort==="relevance"||e.sort===void 0,maxSnippetChars:e.matchContentLength,onlyMatching:e.onlyMatching,unique:e.unique,countUnique:e.countUnique,matchWindow:e.matchWindow}}function OA(e){let t=0;for(let n of e)if(t+=n.path.length,n.matches)for(let r of n.matches)t+=r.value?.length??0;return t}async function Mb(e){let t=[],n=EA(e);if(!n.isValid)return M(new Error(`Query validation failed: ${n.errors.join("; ")}`),e,{toolName:A.LOCAL_RIPGREP,extra:{warnings:n.warnings}});t.push(...n.warnings);let r=rn.safeParse(e);if(!r.success){let g=r.error.issues.map(b=>b.message);return M(new Error(`Query validation failed: ${g.join(", ")}`),e,{toolName:A.LOCAL_RIPGREP,extra:{warnings:t}})}let o=r.data;if(!o.path)return M(new Error("Path is required for search"),o,{toolName:A.LOCAL_RIPGREP,extra:{warnings:t}});let s=Ke(o,A.LOCAL_RIPGREP);if(!s.isValid)return s.errorResult;let a={...o,path:s.sanitizedPath},c=Fb({pattern:a.keywords??"",fixedString:a.fixedString,perlRegex:a.perlRegex});if(!c.isValid)return M(new Error(`Pattern validation failed: ${c.errors.join("; ")}`),o,{toolName:A.LOCAL_RIPGREP,extra:{warnings:[...t,...c.warnings]}});let l=[...c.warnings],u;try{u=await F.searchRipgrep(kA(a))}catch(g){return M(g instanceof Error?g:new Error(String(g)),o,{toolName:A.LOCAL_RIPGREP})}let d=u.files.map(g=>({path:g.path,matchCount:g.matchCount,matches:g.matches.map(b=>{let C={line:b.line,column:b.column,value:b.value};return b.count!==void 0&&(C.count=b.count),b.kind!==void 0&&(C.kind=b.kind),b.scoreHint!==void 0&&(C.scoreHint=b.scoreHint),C})})),p=OA(d),f={totalOccurrences:u.stats.matchCount,matchedLines:u.stats.matchedLines,filesMatched:u.stats.filesMatched,filesSearched:u.stats.filesSearched,bytesSearched:u.stats.bytesSearched??void 0,searchTime:u.stats.searchTime};if(d.length===0)return $({status:"empty",searchEngine:"rg",stats:f,warnings:[...t,...l]},p);!a.filesOnly&&p>Tt.LARGE_RESULT_BYTES_HINT&&l.push(`Result payload is large (~${Math.round(p/1024)}KB).`);let m=await La(d,o,"rg",[...t,...l],f);return $(m,p)}var bd=y(()=>{"use strict";Et();Mr();vr();fe();mi();yd();oe();be()});function LA(e){return e.trim().replace(/^\./,"").toLowerCase()}function Dr(e){if(!e?.trim())return;let t=LA(e),n=vA[t]??AA[t];return n?{raw:e,normalized:t,...n}:{raw:e,normalized:t,kind:"unknown",canonicalLanguage:e.trim()}}function _A(e){return[...e??[]].map(t=>`**/*.${t}`)}function Rd(e){return[...e??[]].map(t=>`*.${t}`)}function _a(e){let t=Dr(e);return t?t.kind==="extension"&&t.extension?{extension:t.extension}:t.canonicalLanguage?{language:t.canonicalLanguage}:{}:{}}function Sd(e){let t=Dr(e);return t?t.kind==="extension"&&t.extension?{include:_A([t.extension])}:t.kind==="language"?{langType:t.normalized}:t.normalized?{langType:t.normalized}:{}:{}}function Cd(e){let t=Dr(e);return t?t.kind==="extension"&&t.extension?Rd([t.extension]):t.kind==="language"?Rd(t.extensions):t.normalized?Rd([t.normalized]):[]:[]}function Db(e){let t=Dr(e);if(!t)return;let r=(t.extensions?.length?t.extensions:[t.normalized.replace(/^[.*]+/,"")]).filter(Boolean).map(o=>`*.${o}`);return r.length?r:void 0}function Pd(e){return Dr(e)?.canonicalLanguage}var vA,AA,xd=y(()=>{"use strict";vA={bash:{kind:"extension",canonicalLanguage:"Shell",extension:"bash",extensions:["bash"]},c:{kind:"extension",canonicalLanguage:"C",extension:"c",extensions:["c"]},cc:{kind:"extension",canonicalLanguage:"C++",extension:"cc",extensions:["cc"]},cjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"cjs",extensions:["cjs"]},cpp:{kind:"extension",canonicalLanguage:"C++",extension:"cpp",extensions:["cpp"]},cs:{kind:"extension",canonicalLanguage:"C#",extension:"cs",extensions:["cs"]},cts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"cts",extensions:["cts"]},cxx:{kind:"extension",canonicalLanguage:"C++",extension:"cxx",extensions:["cxx"]},go:{kind:"extension",canonicalLanguage:"Go",extension:"go",extensions:["go"]},h:{kind:"extension",canonicalLanguage:"C",extension:"h",extensions:["h"]},html:{kind:"extension",canonicalLanguage:"HTML",extension:"html",extensions:["html"]},htm:{kind:"extension",canonicalLanguage:"HTML",extension:"htm",extensions:["htm"]},hpp:{kind:"extension",canonicalLanguage:"C++",extension:"hpp",extensions:["hpp"]},js:{kind:"extension",canonicalLanguage:"JavaScript",extension:"js",extensions:["js"]},json:{kind:"extension",canonicalLanguage:"JSON",extension:"json",extensions:["json"]},jsonc:{kind:"extension",canonicalLanguage:"JSON",extension:"jsonc",extensions:["jsonc"]},jsx:{kind:"extension",canonicalLanguage:"JavaScript",extension:"jsx",extensions:["jsx"]},java:{kind:"extension",canonicalLanguage:"Java",extension:"java",extensions:["java"]},less:{kind:"extension",canonicalLanguage:"Less",extension:"less",extensions:["less"]},md:{kind:"extension",canonicalLanguage:"Markdown",extension:"md",extensions:["md"]},mdx:{kind:"extension",canonicalLanguage:"MDX",extension:"mdx",extensions:["mdx"]},mjs:{kind:"extension",canonicalLanguage:"JavaScript",extension:"mjs",extensions:["mjs"]},mts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"mts",extensions:["mts"]},py:{kind:"extension",canonicalLanguage:"Python",extension:"py",extensions:["py"]},pyi:{kind:"extension",canonicalLanguage:"Python",extension:"pyi",extensions:["pyi"]},rs:{kind:"extension",canonicalLanguage:"Rust",extension:"rs",extensions:["rs"]},scala:{kind:"extension",canonicalLanguage:"Scala",extension:"scala",extensions:["scala"]},sc:{kind:"extension",canonicalLanguage:"Scala",extension:"sc",extensions:["sc"]},scss:{kind:"extension",canonicalLanguage:"SCSS",extension:"scss",extensions:["scss"]},sh:{kind:"extension",canonicalLanguage:"Shell",extension:"sh",extensions:["sh"]},ts:{kind:"extension",canonicalLanguage:"TypeScript",extension:"ts",extensions:["ts"]},tsx:{kind:"extension",canonicalLanguage:"TypeScript",extension:"tsx",extensions:["tsx"]},toml:{kind:"extension",canonicalLanguage:"TOML",extension:"toml",extensions:["toml"]},yaml:{kind:"extension",canonicalLanguage:"YAML",extension:"yaml",extensions:["yaml"]},yml:{kind:"extension",canonicalLanguage:"YAML",extension:"yml",extensions:["yml"]},zsh:{kind:"extension",canonicalLanguage:"Shell",extension:"zsh",extensions:["zsh"]}},AA={bash:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},c:{kind:"language",canonicalLanguage:"C",extensions:["c","h"]},"c++":{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},cpp:{kind:"language",canonicalLanguage:"C++",extensions:["cpp","hpp","cc","cxx","hh","hxx"]},csharp:{kind:"language",canonicalLanguage:"C#",extensions:["cs"]},css:{kind:"language",canonicalLanguage:"CSS",extensions:["css"]},go:{kind:"language",canonicalLanguage:"Go",extensions:["go"]},html:{kind:"language",canonicalLanguage:"HTML",extensions:["html","htm"]},java:{kind:"language",canonicalLanguage:"Java",extensions:["java"]},javascript:{kind:"language",canonicalLanguage:"JavaScript",extensions:["js","jsx","mjs","cjs"]},json:{kind:"language",canonicalLanguage:"JSON",extensions:["json","jsonc"]},less:{kind:"language",canonicalLanguage:"Less",extensions:["less"]},markdown:{kind:"language",canonicalLanguage:"Markdown",extensions:["md","markdown"]},python:{kind:"language",canonicalLanguage:"Python",extensions:["py","pyi"]},rust:{kind:"language",canonicalLanguage:"Rust",extensions:["rs"]},scala:{kind:"language",canonicalLanguage:"Scala",extensions:["scala","sc","sbt"]},scss:{kind:"language",canonicalLanguage:"SCSS",extensions:["scss"]},shell:{kind:"language",canonicalLanguage:"Shell",extensions:["sh","bash","zsh"]},typescript:{kind:"language",canonicalLanguage:"TypeScript",extensions:["ts","tsx","mts","cts"]},toml:{kind:"language",canonicalLanguage:"TOML",extensions:["toml"]},yaml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]},yml:{kind:"language",canonicalLanguage:"YAML",extensions:["yaml","yml"]}}});import{readFile as IA,stat as FA}from"node:fs/promises";function GA(e){if(!e||!/\)\s*\{/.test(e))return"";let t=e.replace(/\)\s*\{/,"): $R {");return t===e?"":` Try: \`${t}\`.`}function Gb(e){return e.include?.length?e.include:Db(e.langType)}async function HA(e){try{return(await FA(e)).isFile()}catch{return!1}}async function zA(e,t){let n=await IA(e,"utf8"),r=F.structuralSearch(n,e,t.pattern,t.rule);return{files:r.length>0?[{path:e,matches:r}]:[],totalMatches:r.length,parsedFiles:1,skippedByPreFilter:0,skippedUnreadable:0,skippedLarge:0,warnings:[]}}async function Hb(e){let t=Ke(e,A.LOCAL_RIPGREP);if(!t.isValid)return t.errorResult;let n;try{n=await HA(t.sanitizedPath)?await zA(t.sanitizedPath,e):F.structuralSearchFiles({path:t.sanitizedPath,pattern:e.pattern,rule:e.rule,...Gb(e)?{include:Gb(e)}:{},...e.exclude?.length?{exclude:e.exclude}:{},...e.excludeDir?.length?{excludeDir:e.excludeDir}:Nb.length?{excludeDir:Nb}:{},...e.hidden!==void 0?{hidden:e.hidden}:{},...e.noIgnore!==void 0?{noIgnore:e.noIgnore}:{},maxFiles:e.maxFiles??MA,maxFileBytes:DA})}catch(s){let a=s instanceof Error?s.message:String(s),c=e.langType||"source";return M(new Error(`Invalid structural ${e.rule?"rule":"pattern"}: ${a} \u2014 patterns must be valid ${c} and match a complete node; a class/def usually needs a body (add \`$$$BODY\`). Run \`octocode tools localSearchCode --scheme\` for the live schema.`),e,{toolName:A.LOCAL_RIPGREP})}let r=n.files.map(s=>({path:s.path,matchCount:s.matches.length,matches:s.matches.map(a=>({line:a.startLine,endLine:a.endLine,value:a.text.split(`
53
+ `,1)[0],column:a.startCol,endColumn:a.endCol,metavars:a.metavars,...a.metavarRanges&&Object.keys(a.metavarRanges).length>0?{metavarRanges:a.metavarRanges}:{}}))})),o={totalStructuralMatches:n.totalMatches},i=[...n.warnings];return(r.length===0||n.totalMatches===0)&&e.pattern&&!e.rule&&i.push(NA+GA(e.pattern)),await La(r,e,"structural",i,o)}var Nb,MA,DA,NA,zb=y(()=>{"use strict";be();Et();fe();xd();mi();Nb=[],MA=2e3,DA=1e6,NA="0 structural matches. A pattern matches a complete AST node \u2014 a class/function usually needs a body (add `$$$BODY`), and Python/TS definitions may carry a return type (`-> $RET:`) or decorators the pattern must include. For partial or relational matches use a YAML `rule` instead of `pattern`."});function BA(e){let t=e.mode;if(!t)return e;let n={...e};return t==="discovery"&&n.filesOnly===void 0?n.filesOnly=!0:t==="detailed"&&n.contextLines===void 0&&(n.contextLines=3),n}async function on(e){let t=BA(e);if(t.mode==="structural")return await Hb(t);t.contextLines===void 0&&(t.contextLines=2);try{return await Mb(t)}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("Output size limit exceeded")?{status:"error",error:r,errorCode:Q.OUTPUT_TOO_LARGE}:M(n,t,{toolName:A.LOCAL_RIPGREP})}}var Ia=y(()=>{"use strict";Et();mn();fe();bd();zb()});async function Bb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_RIPGREP,query:n,contextMessage:"localSearchCode execution failed",execute:async()=>{let r=Ue(rn,n);return r.ok===!1?r.error:await on(r.data)}}),{toolName:A.LOCAL_RIPGREP},e)}var wd=y(()=>{"use strict";Mr();fe();je();Ia();De();Ht();mi()});import{ViewStructureQuerySchema as Qb}from"@octocodeai/octocode-core/schemas";var Ub,QA,Nr,Fa,gi=y(()=>{"use strict";me();Be();tt();Ub={maxDepth:G(0,20).optional(),limit:G(1,1e4).optional(),page:ae.default(1),itemsPerPage:G(1,50).optional()},QA=he(Qb,Ub),Nr=ue(Qb,Ub),Fa=ie(QA,{maxQueries:5})});function $A(e,t){let n=t+1;for(;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n++,n++;return n+1}function jb(e,t){let n=e[t];return n===void 0?!1:UA.has(n)||n==="{"&&WA(e,t)}function qA(e,t,n){let r=n.pop()??!1,o=jb(e,t+1);return o&&r?{unsafe:!0,next:t+1}:((o||r)&&n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:o?$b(e,t+1):t+1})}function VA(e,t,n){return n.some(r=>r)?{unsafe:!0,next:t+1}:(n.length>0&&(n[n.length-1]=!0),{unsafe:!1,next:$b(e,t)})}function Ed(e){if(e.length>jA)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let t="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",n=[],r=0;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o==="["){r=$A(e,r);continue}if(o==="("){n.push(!1),r++;continue}if(o===")"){let i=qA(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}if(jb(e,r)){let i=VA(e,r,n);if(i.unsafe)return{safe:!1,reason:t};r=i.next;continue}r++}return{safe:!0}}function WA(e,t){if(e[t]!=="{")return!1;let n=e.indexOf("}",t);return n===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(t,n+1))}function $b(e,t){return e[t]==="{"?t=e.indexOf("}",t)+1:t++,t<e.length&&(e[t]==="?"||e[t]==="+")&&t++,t}function iK(e,t){let n=Ed(e);if(!n.safe)throw new Error(n.reason);return new RegExp(e,t)}var UA,jA,Td=y(()=>{"use strict";UA=new Set(["+","*","?"]),jA=1e3});function qb(e,t){let n=e;if(t.pattern){let r=t.pattern;if(r.includes("*")||r.includes("?")||r.includes("[")){let i=r.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");i=i.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${i}$`;if(!Ed(s).safe)return n=n.filter(l=>(l.name.includes("/")?l.name.split("/").pop():l.name).includes(r)),n;let c=new RegExp(s,"i");n=n.filter(l=>{let u=l.name.includes("/")?l.name.split("/").pop():l.name;return c.test(u)})}catch{n=n.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(r))}}else n=n.filter(i=>(i.name.includes("/")?i.name.split("/").pop():i.name).includes(r))}return t.directoriesOnly&&(n=n.filter(r=>r.type==="directory")),t.filesOnly&&(n=n.filter(r=>r.type==="file")),n}function Vb(e){let t=[],n=[],r=[];for(let o of e)o.type==="directory"?n.push(o.name):o.type==="symlink"?r.push(o.name):t.push(o.size?`${o.name} (${o.size})`:o.name);return{...t.length>0&&{files:t},...n.length>0&&{folders:n},...r.length>0&&{links:r}}}function Wb(e){let t={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(t.depth=e.depth),e.size&&e.type==="file"&&(t.size=e.size),e.modified&&(t.modified=e.modified),e.permissions&&(t.permissions=e.permissions),t}var kd=y(()=>{"use strict";Td()});function Od(e){let t=e.filter(o=>o.type==="file").length,n=e.filter(o=>o.type==="directory").length,r=e.reduce((o,i)=>i.type==="file"&&i.size?o+ui(i.size):o,0);return`${e.length} entries (${t} files, ${n} dirs, ${_r(r)})`}function vd(e,t){let n=e.length,r=t.itemsPerPage||Tt.DEFAULT_ENTRIES_PER_PAGE,o=Math.max(1,Math.ceil(n/r)),i=Math.min(t.page||1,o),s=(i-1)*r,a=Math.min(s+r,n),c=i<o;return{paginatedEntries:e.slice(s,a),endIdx:a,pagination:{currentPage:i,totalPages:o,entriesPerPage:r,totalEntries:n,hasMore:c,...c?{nextPage:i+1}:{}}}}function KA(e,t,n,r){if(!n.hasMore)return[];let o=e.slice(r,r+3).map(i=>i.name).join(", ");return[`Page ${n.currentPage}/${n.totalPages} (showing ${t} of ${n.totalEntries}). Next: page=${n.currentPage+1}${o?` (starts with: ${o}...)`:""}`]}function Ad(e){if(e.skipped<=0)return[];let t=e.skipped-e.permissionDenied;return e.permissionDenied>0&&t>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${t} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}var Ld=y(()=>{"use strict";vr();di()});async function Ma(e){try{let t=Ke(e,A.LOCAL_VIEW_STRUCTURE);if(!t.isValid)return t.errorResult;let n=e.showFileLastModified??(e.sortBy==="time"||e.details===!0);return YA(e,t.sanitizedPath,n)}catch(t){let n=Xe.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",t instanceof Error?t:void 0);return{status:"error",error:n.message,errorCode:n.errorCode}}}function YA(e,t,n=!1){let r=!!(e.maxDepth||e.recursive),o=r?e.maxDepth||(e.recursive?5:2):1,i=JA(e),s=r&&e.limit&&!XA(e,i)?e.limit*2:1e4,a;try{a=F.queryFileSystem({path:t,recursive:r,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:o,names:i,extensions:e.extensions,entryType:ZA(e),limit:s})}catch(T){return nL(T,e,t)}let c=a.entries.map(T=>eL(T,n,e.details??!1)),l=qb(c,e),u=e.sortBy??"name";l=l.sort((T,L)=>{let k=0;switch(u){case"size":{let O=T.sizeBytes??(T.size?ui(T.size):0),w=L.sizeBytes??(L.size?ui(L.size):0);k=O-w;break}case"time":n&&T.modified&&L.modified?k=T.modified.localeCompare(L.modified):k=T.name.localeCompare(L.name);break;case"extension":k=(T.extension||"").localeCompare(L.extension||"");break;default:k=T.name.localeCompare(L.name);break}return e.reverse?-k:k}),e.limit&&(l=l.slice(0,e.limit));let d=l.length,{paginatedEntries:p,pagination:f}=vd(l,e),g=e.details===!0||e.showFileLastModified===!0?{path:t,entries:p.map(T=>({...Wb(T),path:T.path??`${t.replace(/\/$/,"")}/${T.name}`}))}:{path:t,...Vb(p)},b=[...a.warnings,...Ad({skipped:a.skipped,permissionDenied:a.permissionDenied}),...a.wasCapped?[`Results capped at ${s} entries \u2014 add a pattern/extensions filter or reduce depth to narrow the scope.`]:[]],C=d===0,S=Od(l);return $(Kb({...C?{status:"empty"}:{},...g,summary:S,...f.hasMore||f.totalPages>1?{pagination:f}:{},...b.length>0&&{warnings:b}},e),a.entries.reduce((T,L)=>T+L.path.length,0))}function XA(e,t){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!t)}function JA(e){let t=typeof e.pattern=="string"?e.pattern:void 0;if(t&&!t.includes("["))return t.includes("*")||t.includes("?")?[t]:[`*${t}*`]}function ZA(e){if(e.filesOnly&&!e.directoriesOnly)return"f";if(e.directoriesOnly&&!e.filesOnly)return"d"}function eL(e,t,n){let r=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",o={name:e.relativePath||e.name,path:e.path,type:r,...e.size!==void 0?{size:_r(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(n||t)&&e.modifiedMs!==void 0&&(o.modified=new Date(e.modifiedMs).toISOString()),n&&e.permissions&&(o.permissions=tL(e.permissions)),o}function tL(e){let t=Number.parseInt(e,8);if(!Number.isFinite(t))return e;let n=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${n[t>>6&7]}${n[t>>3&7]}${n[t&7]}`}function nL(e,t,n){let r=e instanceof Error?e.message:String(e),o=/ENOENT|not found|no such file/i.test(r),i=/EACCES|permission denied/i.test(r),s=/ENOTDIR|not a directory/i.test(r),a=Xe.pathValidationFailed(n,o?`Directory not found: ${n}`:i?`Permission denied: ${n}`:s?`Not a directory: ${n}`:`Cannot access path: ${n}`);return M(a,t,{toolName:A.LOCAL_VIEW_STRUCTURE})}function Kb(e,t){return e}var hi=y(()=>{"use strict";di();fe();Et();no();kd();Ld();oe();be()});async function Yb(e){let{queries:t}=e;return se(t||[],async n=>Ve({toolName:A.LOCAL_VIEW_STRUCTURE,query:n,contextMessage:"localViewStructure execution failed",execute:async()=>{let r=Ue(Nr,n);return r.ok===!1?r.error:await Ma(r.data)}}),{toolName:A.LOCAL_VIEW_STRUCTURE,keysPriority:["path","summary","pagination","files","folders","entries"]},e)}var _d=y(()=>{"use strict";gi();fe();je();hi();De();Ht();hi()});function Jb(e){return Array.isArray(e.queries)}function Zb(e){return Array.isArray(e.queries)}function eR(e){return Array.isArray(e.children)}var sn,Da,Xb,yi=y(()=>{"use strict";sn=["code","content","structure","files","semantics","repositories","packages","pullRequests","commits","artifacts","diff","research","graph","materialize"],Da=["fixes","dataflow"],Xb=["packages","repositories"]});import{z as h}from"zod";var Fd,Id,rL,tR,nR,oL,iL,Gr,rR,sL,aL,_n,oR,iR,sR,aR,Na,cL,_K,lL,uL,cR,lR,uR,Ga,dR,pR,In,Hr=y(()=>{"use strict";yi();Fd=h.lazy(()=>h.union([h.strictObject({kind:h.literal("local"),path:h.string().min(1)}),h.strictObject({kind:h.literal("github"),repo:h.string().min(1).optional(),owner:h.string().min(1).optional(),ref:h.string().min(1).optional()}),h.strictObject({kind:h.literal("materialized"),localPath:h.string().min(1),source:Fd.optional()}),h.strictObject({kind:h.literal("npm")})])),Id=h.union([h.string(),h.array(h.string()).max(100)]),rL=h.strictObject({path:Id.optional(),language:Id.optional(),include:h.array(h.string()).max(100).optional(),exclude:h.array(h.string()).max(100).optional(),excludeDir:h.array(h.string()).max(100).optional(),hidden:h.boolean().optional(),noIgnore:h.boolean().optional(),minDepth:h.number().int().min(0).max(64).optional(),maxDepth:h.number().int().min(0).max(64).optional()}).optional(),tR=h.enum(["smart","sensitive","insensitive"]),nR=h.string().max(1e4),oL=h.strictObject({id:h.string().optional(),kind:h.literal("text"),value:nR,case:tR.optional(),wholeWord:h.boolean().optional()}),iL=h.strictObject({id:h.string().optional(),kind:h.literal("regex"),value:nR,dialect:h.enum(["rust","pcre2","provider"]).optional(),case:tR.optional(),wholeWord:h.boolean().optional(),multiline:h.boolean().optional(),dotAll:h.boolean().optional()}),Gr=h.lazy(()=>h.strictObject({pattern:h.string().optional(),kind:h.string().optional(),inside:Gr.optional(),has:Gr.optional(),not:Gr.optional(),all:h.array(Gr).optional(),any:h.array(Gr).optional(),stopBy:h.literal("end").optional()})),rR=h.union([Gr,h.string().min(1)]),sL=h.strictObject({id:h.string().optional(),kind:h.literal("structural"),lang:h.string().min(1),pattern:h.string().optional(),rule:rR.optional()}),aL=h.strictObject({id:h.string().optional(),kind:h.literal("field"),field:h.enum(["path","basename","extension","size","modified","accessed","empty","permissions","executable","readable","writable","entryType"]),op:h.enum(["=","!=","in","exists","glob","regex",">",">=","<","<=","within","before"]),value:h.unknown().optional()}),_n=h.lazy(()=>h.discriminatedUnion("kind",[h.strictObject({kind:h.literal("all"),id:h.string().optional(),of:h.array(_n).min(1)}),h.strictObject({kind:h.literal("any"),id:h.string().optional(),of:h.array(_n).min(1)}),h.strictObject({kind:h.literal("not"),id:h.string().optional(),predicate:_n}),oL,iL,sL,aL])),oR=h.strictObject({mode:h.enum(["never","auto","required"]),strategy:h.enum(["file","tree","subtree","repo"]).optional(),allowFullRepo:h.boolean().optional(),forceRefresh:h.boolean().optional()}),iR=h.strictObject({content:h.strictObject({range:h.strictObject({startLine:h.number().int().min(1).optional(),endLine:h.number().int().min(1).optional(),contextLines:h.number().int().min(0).max(100).optional()}).optional(),match:h.strictObject({text:h.string(),regex:h.boolean().optional(),caseSensitive:h.boolean().optional()}).optional(),contentView:h.enum(["exact","compact","symbols"]).optional(),charOffset:h.number().int().min(0).max(1e8).optional(),charLength:h.number().int().min(1).max(5e4).optional(),fullContent:h.boolean().optional()}).optional(),tree:h.strictObject({maxDepth:h.number().int().min(0).max(64).optional(),pattern:h.string().optional(),includeSizes:h.boolean().optional(),extensions:h.array(h.string()).optional(),filesOnly:h.boolean().optional(),directoriesOnly:h.boolean().optional(),sortBy:h.enum(["name","size","time","extension"]).optional(),reverse:h.boolean().optional()}).optional()}),sR=h.strictObject({search:h.strictObject({countLinesPerFile:h.boolean().optional(),countMatchesPerFile:h.boolean().optional(),onlyMatching:h.boolean().optional(),unique:h.boolean().optional(),countUnique:h.boolean().optional(),contextLines:h.number().int().min(0).max(100).optional(),invertMatch:h.boolean().optional(),matchWindow:h.number().int().min(0).optional(),matchContentLength:h.number().int().min(1).optional(),maxMatchesPerFile:h.number().int().min(1).optional(),matchPage:h.number().int().min(1).optional(),sort:h.enum(["relevance","matchCount","path","modified","accessed","created"]).optional(),sortReverse:h.boolean().optional(),rankingProfile:h.string().optional(),debugRanking:h.boolean().optional()}).optional(),budget:h.strictObject({maxFiles:h.number().int().min(1).optional(),maxCandidates:h.number().int().min(1).optional(),maxBytes:h.number().int().min(1).optional(),maxMaterializedBytes:h.number().int().min(1).optional(),maxPlanNodes:h.number().int().min(1).optional(),maxBooleanExpansion:h.number().int().min(1).optional(),timeoutMs:h.number().int().min(1).optional()}).optional()}),aR=h.enum(["discovery","paginated","detailed"]),Na=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),target:h.enum(sn),from:Fd.optional(),scope:rL,where:_n.optional(),materialize:oR.optional(),fetch:iR.optional(),select:h.array(h.string()).optional(),view:aR.optional(),controls:sR.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional()}),cL=h.strictObject({schema:h.literal("oql"),id:h.string().optional(),queries:h.array(Na).min(1).max(5),combine:h.enum(["independent","merge"]).optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),explain:h.boolean().optional()}),_K=h.union([Na,cL]),lL=sn,uL=[...sn,...Da],cR={schema:h.literal("oql").optional(),id:h.string().optional(),mainResearchGoal:h.string().optional(),researchGoal:h.string().optional(),reasoning:h.string().optional()},lR={...cR,target:h.enum(uL).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:Fd.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:_n.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:h.union([oR,h.enum(["never","auto","required"])]).optional(),fetch:iR.optional(),select:h.array(h.string()).optional(),view:aR.optional(),controls:sR.optional(),limit:h.number().int().min(1).optional(),page:h.number().int().min(1).optional(),itemsPerPage:h.number().int().min(1).optional(),params:h.record(h.string(),h.unknown()).optional(),explain:h.boolean().optional(),repo:h.string().optional(),owner:h.string().optional(),ref:h.string().optional(),path:Id.optional(),text:h.string().optional().describe("Shorthand text search (\u2192 where.text, target code). Do not combine with a canonical `where`."),regex:h.string().optional(),pattern:h.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:rR.optional(),lang:h.string().optional(),and:h.array(h.unknown()).optional(),or:h.array(h.unknown()).optional(),xor:h.array(h.unknown()).optional(),noneOf:h.array(h.unknown()).optional(),oneOf:h.array(h.unknown()).optional(),invert:h.unknown().optional(),filesOnly:h.boolean().optional(),filesWithoutMatch:h.boolean().optional(),verbose:h.boolean().optional()},uR={...lR,target:h.enum(lL).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.")},Ga=h.object(uR).catchall(h.unknown()),dR=h.object(lR).catchall(h.unknown()),pR=h.object({...cR,queries:h.array(h.unknown()).min(1)}).catchall(h.unknown()),In=h.object({...uR,queries:h.array(h.unknown()).min(1).max(5).optional(),combine:h.enum(["independent","merge"]).optional()}).catchall(h.unknown())});function x(e,t,n={}){let r=n.severity??(pL.has(e)?"error":"warning"),o=n.blocksAnswer??(dL.has(e)||r==="error");return{code:e,severity:r,message:t,blocksAnswer:o,...n.queryPath?{queryPath:n.queryPath}:{},...n.predicateId?{predicateId:n.predicateId}:{},...n.backend?{backend:n.backend}:{},...n.repair?{repair:n.repair}:{},...n.continuation?{continuation:n.continuation}:{}}}function fR(e){return e.some(t=>t.blocksAnswer)}var dL,pL,an,Rt=y(()=>{"use strict";dL=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","negativeUniverseRequired","residualNotExact","fieldTypeMismatch","requiresMaterialization","vendorNoEquivalent","lossyTransform","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed","parserFailed","lspUnavailable","budgetExhausted","contentTruncated"]),pL=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","fieldTypeMismatch","unsupportedVendorPredicate","responseShapeMismatch","materializationNotAllowed","materializationFailed"]);an=class extends Error{diagnostics;constructor(t){super(t.map(n=>`${n.code}: ${n.message}`).join("; ")),this.name="OqlValidationError",this.diagnostics=t}}});import{z as P}from"zod";function gR(e,t){let n=xL[e];if(!n||t===void 0)return null;let r=n.safeParse(t);return r.success?null:r.error.issues.map(o=>`params.${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}var de,Md,mR,fL,mL,gL,hL,yL,bL,RL,SL,CL,PL,xL,hR=y(()=>{"use strict";de=P.number().int().min(1),Md=P.number().int().min(0),mR=P.enum(["symbols","files","dependencies","relations"]),fL=P.object({match:P.enum(["file","path"]).optional(),concise:P.boolean().optional(),extension:P.string().optional(),filename:P.string().optional(),page:de.optional(),limit:de.optional()}).passthrough(),mL=P.object({type:P.enum(["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]).optional(),uri:P.string().optional(),symbolName:P.string().optional(),symbolKind:P.string().optional(),lineHint:de.optional(),orderHint:P.number().int().optional(),includeDeclaration:P.boolean().optional(),depth:P.number().int().min(0).max(20).optional(),groupByFile:P.boolean().optional(),workspaceRoot:P.string().optional(),format:P.enum(["structured","compact"]).optional(),page:de.optional(),itemsPerPage:de.optional()}).passthrough(),gL=P.object({keywords:P.array(P.string()).optional(),topicsToSearch:P.union([P.string(),P.array(P.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),language:P.string().optional(),owner:P.string().optional(),stars:P.union([P.string(),P.number()]).optional(),forks:P.string().optional(),goodFirstIssues:P.string().optional(),size:P.string().optional(),created:P.string().optional(),updated:P.string().optional(),license:P.string().optional(),match:P.array(P.enum(["name","description","readme"])).optional(),visibility:P.enum(["public","private"]).optional(),archived:P.boolean().optional(),sort:P.enum(["stars","forks","help-wanted-issues","updated","best-match"]).optional(),concise:P.boolean().optional(),page:de.optional()}).passthrough(),hL=P.object({packageName:P.string().optional(),keywords:P.array(P.string()).optional(),mode:P.enum(["lean","full"]).optional(),page:de.optional()}).passthrough(),yL=P.object({prNumber:de.optional(),concise:P.boolean().optional(),state:P.enum(["open","closed","merged"]).optional(),author:P.string().optional(),label:P.union([P.string(),P.array(P.string())]).optional(),keywordsToSearch:P.union([P.string(),P.array(P.string())]).transform(e=>typeof e=="string"?[e]:e).optional(),head:P.string().optional(),base:P.string().optional(),created:P.string().optional(),updated:P.string().optional(),closed:P.string().optional(),"merged-at":P.string().optional(),draft:P.boolean().optional(),archived:P.boolean().optional(),sort:P.enum(["created","updated","best-match","comments","reactions"]).optional(),order:P.enum(["asc","desc"]).optional(),reviewMode:P.string().optional(),filePage:de.optional(),commentPage:de.optional(),commitPage:de.optional(),charOffset:Md.optional(),charLength:de.optional(),minify:P.enum(["none","standard"]).optional(),limit:de.optional(),page:de.optional(),matchString:P.string().optional(),matchScope:P.enum(["body","title","comments","reviews","all"]).optional(),content:P.record(P.string(),P.unknown()).optional()}).passthrough(),bL=P.object({path:P.string().optional(),branch:P.string().optional(),since:P.string().optional(),until:P.string().optional(),author:P.string().optional(),includeDiff:P.boolean().optional(),limit:de.optional(),page:de.optional()}).passthrough(),RL=P.object({mode:P.enum(["inspect","list","extract","decompress","strings","unpack"]).optional(),archiveFile:P.string().optional(),entryPageNumber:de.optional(),maxEntries:de.optional(),entriesPerPage:de.optional(),minLength:P.number().int().min(1).max(128).optional(),scanOffset:Md.optional(),charOffset:Md.optional(),charLength:de.optional(),matchString:P.string().optional(),detailed:P.boolean().optional(),format:P.string().optional(),verbose:P.boolean().optional(),includeOffsets:P.boolean().optional()}).passthrough(),SL=P.object({prNumber:de.optional(),files:P.array(P.string()).optional(),baseRef:P.string().optional(),headRef:P.string().optional(),path:P.string().optional()}).passthrough(),CL=P.object({goal:P.string().optional(),intent:P.enum(["general","reachability","dependencies","symbols"]).optional(),facets:P.array(mR).optional(),mode:P.enum(["plan","analyze","prove"]).optional(),maxFiles:de.optional()}).passthrough(),PL=P.object({goal:P.string().optional(),intent:P.enum(["general","reachability","dependencies","symbols"]).optional(),facets:P.array(mR).optional(),mode:P.enum(["plan","analyze","prove"]).optional(),maxFiles:de.optional(),subject:P.string().optional(),subjectKind:P.enum(["file","symbol","function","class","method","interface","type","dependency","package","entrypoint"]).optional(),relation:P.union([P.string(),P.array(P.string())]).optional(),verdict:P.union([P.string(),P.array(P.string())]).optional(),direction:P.enum(["incoming","outgoing","both"]).optional(),proof:P.enum(["none","lsp"]).optional(),proofLimit:de.max(25).optional(),includePackets:P.boolean().optional(),includeFacts:P.boolean().optional(),includeEdges:P.boolean().optional()}).passthrough(),xL={semantics:mL,repositories:gL,packages:hL,pullRequests:yL,commits:bL,artifacts:RL,diff:SL,research:CL,graph:PL,code:fL}});function Z(...e){throw new an(e)}function yR(e){return Jb(e)?EL(e):bR(e)}function EL(e){let t=pR.safeParse(e);t.success||Z(x("invalidQuery",Ha(t.error)));let n=t.data,r=new Set(["schema","id","queries","combine","limit","page","itemsPerPage","explain"]);for(let i of Object.keys(n))r.has(i)||Z(x("unknownField",`Unknown batch field "${i}" is not part of OQL.`,{queryPath:i}));n.queries.length>5&&Z(x("invalidQuery","OQL batches are capped at 5 queries per call.",{queryPath:"queries"}));let o=n.queries.map((i,s)=>{try{return bR(i)}catch(a){throw a instanceof an?new an(a.diagnostics.map(c=>({...c,queryPath:`queries[${s}]${c.queryPath?`.${c.queryPath}`:""}`}))):a}});return{schema:"oql",...n.id?{id:n.id}:{},queries:o,combine:n.combine??"independent",...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}}}function bR(e){let t=dR.safeParse(e);t.success||Z(x("invalidQuery",Ha(t.error)));let n={...t.data},r=n.filesWithoutMatch?"files":n.target??TL(n);r===void 0&&Z(x("invalidQuery",`Could not determine \`target\`; specify one of: ${sn.join(", ")}.`,{queryPath:"target"})),Da.includes(r)&&Z(x("unsupportedTarget",`Target "${r}" is reserved until proof/dry-run support exists.`,{queryPath:"target",repair:{message:`Use an active target: ${sn.join(", ")}.`}})),sn.includes(r)||Z(x("unknownField",`Unknown target "${r}".`));for(let m of Object.keys(n))wL.has(m)||Z(x("unknownField",`Unknown field "${m}" is not part of OQL.`,{queryPath:m}));let o=n.filesOnly===!0?Array.isArray(n.select)?n.select:["path","next.fetch"]:n.select,i=n.filesOnly===!0?"discovery":n.view??"paginated",s=AL(n,r),a=_L(n,s),c=IL(n,r),l=HL(n,s,c,r),u=zL(n),d=OL(n,r),p={schema:"oql",...n.id?{id:n.id}:{},target:r,...s?{from:s}:{},...d?{params:d}:{},...a?{scope:a}:{},...c?{where:c}:{},...l?{materialize:l}:{},...u?{fetch:u}:{},...o?{select:o}:{},view:i,...n.controls?{controls:n.controls}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.page!==void 0?{page:n.page}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.explain!==void 0?{explain:n.explain}:{}};if(p.target==="code"&&!p.where&&Z(x("invalidQuery",'target:"code" requires a `where` predicate (text/regex/structural). `where` omission is not a wildcard.',{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.where&&Z(x("invalidQuery",`target:"${p.target}" does not use \`where\`. Use fetch.content.match for content anchors, or target:"code"/"files" for predicates.`,{queryPath:"where"})),(p.target==="content"||p.target==="structure")&&p.from?.kind==="github"&&!(p.from.repo&&p.from.repo.includes("/"))&&Z(x("invalidQuery",`target:"${p.target}" over GitHub requires a concrete repository ("owner/name"); a provider-wide or owner-only source cannot read a specific tree.`,{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} (and scope.path for a subtree).'}})),p.target==="materialize"&&(p.where&&Z(x("invalidQuery",'target:"materialize" does not use `where`; it clones/caches a corpus and returns a stable local checkpoint. Run a search against the returned localPath instead.',{queryPath:"where"})),p.from?.kind!=="github"&&p.from?.kind!=="materialized"&&Z(x("invalidQuery",'target:"materialize" needs from:{kind:"github",repo:"owner/name"} (and scope.path to bound the subtree) or an already-materialized `from`.',{queryPath:"from",repair:{message:'Set from:{kind:"github",repo:"owner/name"} with scope.path.'}}))),p.params!==void 0){let m=gR(p.target,p.params);m&&Z(x("invalidQuery",m,{queryPath:"params"}))}let f=Na.safeParse(p);return f.success||Z(x("invalidQuery",Ha(f.error))),f.data}function TL(e){if(e.where!==void 0||typeof e.text=="string"||typeof e.regex=="string"||typeof e.pattern=="string"||e.rule!==void 0||Array.isArray(e.and)||Array.isArray(e.or)||Array.isArray(e.xor)||Array.isArray(e.noneOf)||Array.isArray(e.oneOf))return"code";if(e.fetch?.content)return"content";if(e.fetch?.tree)return"structure"}function OL(e,t){let n=e.params?{...e.params}:void 0;return t!=="graph"||!n||!vL(n)?n:{...n,proof:"lsp",proofLimit:typeof n.proofLimit=="number"&&n.proofLimit>0?n.proofLimit:5}}function vL(e){if(e.proof!==void 0||e.mode==="plan"||e.mode==="prove")return!1;if(e.relation!==void 0||e.direction!==void 0)return!0;let t=typeof e.goal=="string"?e.goal.toLowerCase():"";return kL.some(n=>t.includes(n))}function AL(e,t){let n=e.from,r=typeof e.repo=="string"||typeof e.owner=="string",o=e.path;if(n)return r&&Z(x("ambiguousSugar","Provide either `from` or top-level repo/owner sugar, not both.",{queryPath:"from"})),LL(n);if(r){let i=typeof e.owner=="string"?e.owner:void 0,s=typeof e.repo=="string"?e.repo:void 0;i&&s&&!s.includes("/")&&(s=`${i}/${s}`);let a={kind:"github"};return s&&(a.repo=s),i&&!s&&(a.owner=i),typeof e.ref=="string"&&(a.ref=e.ref),a}if(typeof o=="string")return{kind:"local",path:o};if(Array.isArray(o)&&typeof o[0]=="string")return{kind:"local",path:o[0]};if(t==="packages")return{kind:"npm"};if(t==="repositories")return{kind:"github"};Xb.includes(t)||Z(x("invalidQuery","A corpus is required: provide `from`, a `repo`, or a local `path`.",{queryPath:"from"}))}function LL(e){if(e.kind!=="github")return e;let t=e.owner,n=e.repo;if(t&&n&&!n.includes("/")){n=`${t}/${n}`;let r={kind:"github",repo:n};return e.ref&&(r.ref=e.ref),r}return e}function _L(e,t){let n={...e.scope??{}},r=e.path,o=t?.kind==="local"&&!e.from&&typeof e.repo!="string"&&typeof e.owner!="string";return r!==void 0&&!o&&(e.scope&&e.scope.path!==void 0&&Z(x("ambiguousSugar","Both top-level `path` and `scope.path` provided; the path intent is ambiguous.",{queryPath:"path"})),n.path=r),Object.keys(n).length>0?n:void 0}function IL(e,t){let n=DL(e);e.where&&n&&Z(x("ambiguousSugar","Provide either a canonical `where` predicate or top-level match sugar, not both.",{queryPath:"where"}));let r=e.where??n;if(e.filesWithoutMatch&&r&&(r={kind:"not",predicate:r}),e.invert===!0&&r&&(r={kind:"not",predicate:r}),!r)return void 0;Nd(r,"where");let o=_n.safeParse(r);return o.success||Z(x("invalidQuery",Ha(o.error),{queryPath:"where"})),o.data}function Dd(e){return e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Dd(n),0):e.kind==="not"?1+Dd(e.predicate):1}function ML(e){let t=e.controls?.budget?.maxBooleanExpansion;return typeof t=="number"&&t>0?t:FL}function DL(e){let t=n=>{let r=Dd(n),o=ML(e);return r>o&&Z(x("budgetExhausted",`Boolean sugar expanded to ${r} predicate nodes, over controls.budget.maxBooleanExpansion (${o}). Narrow the query or raise the budget.`,{queryPath:"where"})),n};if(Array.isArray(e.and))return{kind:"all",of:e.and.map(zr)};if(Array.isArray(e.or))return{kind:"any",of:e.or.map(zr)};if(Array.isArray(e.noneOf))return{kind:"not",predicate:{kind:"any",of:e.noneOf.map(zr)}};if(Array.isArray(e.xor)){e.xor.length!==2&&Z(x("invalidQuery","xor is binary; use oneOf for multi-way exclusive matching.",{queryPath:"xor"}));let n=zr(e.xor[0]),r=zr(e.xor[1]);return t({kind:"any",of:[{kind:"all",of:[n,{kind:"not",predicate:r}]},{kind:"all",of:[{kind:"not",predicate:n},r]}]})}if(Array.isArray(e.oneOf))return t(NL(e.oneOf.map(zr)));if(typeof e.pattern=="string"||e.rule!==void 0)return typeof e.pattern=="string"&&e.rule!==void 0&&Z(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:"pattern"})),typeof e.lang!="string"&&Z(x("invalidQuery","Structural sugar requires `lang`.",{queryPath:"lang"})),{kind:"structural",lang:e.lang,...typeof e.pattern=="string"?{pattern:e.pattern}:{},...e.rule!==void 0?{rule:e.rule}:{}};if(typeof e.text=="string")return{kind:"text",value:e.text};if(typeof e.regex=="string")return{kind:"regex",value:e.regex}}function zr(e){if(e&&typeof e=="object"&&"kind"in e)return e;Z(x("invalidQuery","Boolean sugar children must be predicate objects with a `kind`.",{queryPath:"where"}))}function NL(e){return{kind:"any",of:e.map((n,r)=>{let o=e.filter((i,s)=>s!==r).map(i=>({kind:"not",predicate:i}));return{kind:"all",of:[n,...o]}})}}function Nd(e,t){switch(e.kind){case"all":case"any":(!Array.isArray(e.of)||e.of.length===0)&&Z(x("invalidQuery",`Empty \`${e.kind}.of\` is invalid.`,{queryPath:t})),e.of.forEach((n,r)=>Nd(n,`${t}.of[${r}]`));break;case"not":e.predicate||Z(x("invalidQuery","`not` must contain exactly one child.",{queryPath:t})),Nd(e.predicate,`${t}.predicate`);break;case"structural":typeof e.pattern=="string"==(e.rule!==void 0)&&Z(x("invalidQuery","A structural predicate uses exactly one of `pattern` or `rule`.",{queryPath:t}));break;case"field":GL(e,t);break;default:break}}function GL(e,t){if(e.op==="exists"){e.value!==void 0&&Z(x("fieldTypeMismatch","`exists` takes no value.",{queryPath:t}));return}e.value===void 0&&Z(x("fieldTypeMismatch",`Operator "${e.op}" requires a value.`,{queryPath:t})),e.op==="in"&&(!Array.isArray(e.value)||e.value.length===0)&&Z(x("fieldTypeMismatch","`in` requires a non-empty array of values.",{queryPath:t}))}function RR(e){if(!e)return!1;switch(e.kind){case"structural":return!0;case"regex":return e.dialect==="pcre2";case"all":case"any":return!0;case"not":return RR(e.predicate);default:return!1}}function HL(e,t,n,r){let o;return typeof e.materialize=="string"?o={mode:e.materialize}:e.materialize&&typeof e.materialize=="object"&&(o=e.materialize),r==="materialize"&&t?.kind==="github"?o?{...o,mode:o.mode==="never"?"required":o.mode,strategy:o.strategy??"subtree"}:{mode:"required",strategy:"subtree"}:r==="semantics"&&t?.kind==="github"?{...o??{},mode:"required",strategy:"file"}:t?.kind!=="github"||o?o:RR(n)?{mode:"auto",strategy:"subtree"}:{mode:"never"}}function zL(e){return e.fetch?{...e.fetch}:void 0}function Ha(e){let t=e;return t&&Array.isArray(t.issues)?t.issues.map(n=>`${n.path.join(".")||"(root)"}: ${n.message}`).join("; "):"Invalid OQL query."}var wL,kL,FL,SR=y(()=>{"use strict";Hr();Rt();hR();yi();wL=new Set(["schema","id","target","from","scope","where","materialize","fetch","select","view","controls","limit","page","itemsPerPage","params","explain","repo","owner","ref","path","text","regex","pattern","rule","lang","and","or","xor","noneOf","oneOf","invert","filesOnly","filesWithoutMatch","mainResearchGoal","researchGoal","reasoning","verbose"]);kL=["relationship","relationships","reference","references","who uses","used by","usage","caller","callers","callee","callees","call hierarchy","blast radius","safe to delete","what breaks","delete","dead code","unused export","unused symbol","retained by"];FL=64});function BL(e){return e?.mode==="auto"||e?.mode==="required"}function QL(e,t){let n=e.target==="files"?Fn:cn;switch(t.kind){case"text":case"regex":case"structural":return{route:"PUSHDOWN",backend:cn,exact:!0,reason:`${t.kind} evaluated locally by ${cn}`};case"field":return{route:"PUSHDOWN",backend:n,exact:!0,reason:`field predicate evaluated locally by ${n}`}}}function UL(e,t,n){let r=BL(e.materialize);if(n)return jL(e,t,r);if(e.target==="files")return t.kind==="text"||t.kind==="regex"&&t.dialect!=="pcre2"?r?{route:"ROUTE",backend:Fn,exact:!0,reason:"files-containing-term routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"files containing the term listed via provider code search (approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub lists files containing a term via provider code search; materialize for an exact file set."}}:t.kind==="field"&&t.op==="="&&(t.field==="path"||t.field==="basename"||t.field==="extension")?r?{route:"ROUTE",backend:Fn,exact:!0,reason:"path/name field equality routed to materialization for an exact file set"}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"path/name field equality listed via provider path search"}:r?{route:"ROUTE",backend:Fn,exact:!0,reason:`${za(t)} over a file listing routed to materialization`}:{route:"UNSUPPORTED",backend:Fn,exact:!1,reason:`GitHub cannot enumerate files by ${za(t)} without materialization`,diagnostic:{code:"requiresMaterialization",message:`target:"files" over GitHub cannot enumerate by ${za(t)} without materialization (set materialize.mode "auto"/"required" with scope.path).`}};switch(t.kind){case"text":return e.materialize?.mode==="required"?{route:"ROUTE",backend:cn,exact:!0,reason:"literal text routed to materialization because materialize.mode is required"}:t.case==="sensitive"||t.wholeWord===!0?r?{route:"ROUTE",backend:cn,exact:!0,reason:"case-sensitive / whole-word text routed to materialization for exact proof"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"GitHub code search cannot honor case:sensitive / wholeWord (case-insensitive substring); approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub code search is a case-insensitive substring match and cannot honor case:sensitive or wholeWord; materialize for exact proof."}}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"literal text pushed to GitHub code search"};case"regex":return t.dialect==="pcre2"?Gd(e,"PCRE2 regex",r):r?{route:"ROUTE",backend:cn,exact:!0,reason:"regex routed to bounded materialization for exact local proof"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"regex pushed to GitHub search (provider regex is approximate)",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub regex search is approximate; materialize for exact regex proof."}};case"structural":return Gd(e,"structural AST",r);case"field":return t.field==="path"||t.field==="basename"||t.field==="extension"?t.op==="glob"||t.op==="regex"?r?{route:"ROUTE",backend:Fn,exact:!0,reason:"path glob/regex routed to materialization for proof"}:{route:"PUSHDOWN",backend:zt,exact:!1,reason:"provider path filter is prefix-only / approximate",diagnostic:{code:"providerSemanticsApproximate",message:"GitHub path qualifiers are prefix filters; materialize to prove glob/regex."}}:{route:"PUSHDOWN",backend:zt,exact:!0,reason:"path/name predicate pushed to provider"}:Gd(e,`field "${t.field}"`,r)}}function za(e){switch(e.kind){case"text":return"text match";case"regex":return e.dialect==="pcre2"?"PCRE2 regex":"regex match";case"structural":return"structural AST match";case"field":return`field "${e.field}"`}}function jL(e,t,n){let r=za(t);return n?{route:"ROUTE",backend:e.target==="files"?Fn:cn,exact:!0,reason:`negated ${r} needs a complete universe; routed to bounded materialization for local proof`}:{route:"UNSUPPORTED",backend:zt,exact:!1,reason:`negated ${r} cannot be proven by the GitHub provider (no complete universe)`,diagnostic:{code:"negativeUniverseRequired",message:"Negation over a GitHub provider source needs a complete candidate universe; materialize to prove absence."}}}function Gd(e,t,n){if(n)return{route:"ROUTE",backend:cn,exact:!0,reason:`${t} requires local proof; routed to bounded materialization`};let r=e.materialize?.mode;return{route:"UNSUPPORTED",backend:zt,exact:!1,reason:`${t} cannot be evaluated by the GitHub provider`,diagnostic:r==="never"?{code:"materializationNotAllowed",message:`${t} needs local proof but materialize.mode is "never".`}:{code:"requiresMaterialization",message:`${t} needs bounded materialization (set materialize.mode "auto" or "required").`}}}function CR(e,t,n=!1){return e.sourceKind==="github"?UL(e,t,n):QL(e,t)}var cn,Fn,zt,PR=y(()=>{"use strict";cn="localSearchCode",Fn="localFindFiles",zt="ghSearchCode"});function Br(e){let t=e??{};return t.prNumber!==void 0&&t.prNumber!==null?{kind:"prPatch",prNumber:t.prNumber,...Array.isArray(t.files)?{files:t.files}:{}}:typeof t.baseRef=="string"&&typeof t.headRef=="string"&&typeof t.path=="string"?{kind:"directFile",baseRef:t.baseRef,headRef:t.headRef,path:t.path}:{kind:"neither"}}var Ba=y(()=>{"use strict"});function xR(e){let t=[];return e.fetch?.content?.contentView==="symbols"&&$L.has(e.target)&&t.push(x("signatureUnsupported",`A "symbols" content view is not available for target:"${e.target}" (PR/commit/diff content has no symbol skeleton); request "exact" or "compact".`,{queryPath:"fetch.content.contentView",severity:"warning",blocksAnswer:!1,repair:{message:'Set fetch.content.contentView to "exact" or "compact".'}})),t}var $L,wR=y(()=>{"use strict";Rt();$L=new Set(["pullRequests","commits","diff"])});function ER(e){let t={schema:lt.schema,view:e.view??lt.view,page:e.page??lt.page,itemsPerPage:e.itemsPerPage??lt.itemsPerPage,maxPlanNodes:e.controls?.budget?.maxPlanNodes??lt.maxPlanNodes};return e.from?.kind==="github"&&(t["materialize.mode"]=e.materialize?.mode??lt.githubMaterializeMode),e.target==="content"&&(t["fetch.content.contentView"]=e.fetch?.content?.contentView??lt.contentView),e.target==="code"&&(t.codeContext=e.view==="detailed"?lt.detailedCodeContext:lt.normalCodeContext,t["search.sort"]=e.controls?.search?.sort??lt.localSearchSort),t}var lt,TR=y(()=>{"use strict";lt={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"}});function kR(e){return JSON.stringify(e)}function Hd(e,t){let n=" ".repeat(t),r=[];e.pattern!==void 0&&r.push(`${n}pattern: ${kR(e.pattern)}`),e.kind!==void 0&&r.push(`${n}kind: ${kR(e.kind)}`);for(let o of["inside","has","not"]){let i=e[o];i&&(r.push(`${n}${o}:`),r.push(...Hd(i,t+1)))}for(let o of["all","any"]){let i=e[o];if(i&&i.length>0){r.push(`${n}${o}:`);for(let s of i){let a=Hd(s,t+1),c=`${" ".repeat(t+1)}- `,l=`${" ".repeat(t+1)} `;if(a.length!==0){r.push(c+a[0].trimStart());for(let u of a.slice(1))r.push(l+u.trimStart())}}}}return e.stopBy!==void 0&&r.push(`${n}stopBy: ${e.stopBy}`),r}function OR(e){return["rule:",...Hd(e,1)].join(`
54
+ `)}var vR=y(()=>{"use strict"});function AR(e,t){t==="sensitive"?e.caseSensitive=!0:t==="insensitive"&&(e.caseInsensitive=!0)}function LR(e){switch(e.kind){case"text":{let t={keywords:e.value,fixedString:!0};return AR(t,e.case),e.wholeWord&&(t.wholeWord=!0),{match:t}}case"regex":{let t={keywords:e.value};return e.dialect==="pcre2"&&(t.perlRegex=!0),AR(t,e.case),e.wholeWord&&(t.wholeWord=!0),e.multiline&&(t.multiline=!0),e.dotAll&&(t.multilineDotall=!0),{match:t}}case"structural":{let t={mode:"structural",langType:e.lang};return typeof e.pattern=="string"&&(t.pattern=e.pattern),typeof e.rule=="string"?t.rule=e.rule:e.rule!==void 0&&(t.rule=OR(e.rule)),{match:t}}case"field":return{unsupported:{code:"unsupportedPredicate",message:"Field predicates compile through the files backend, not local code search.",predicateId:e.id}};default:return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" is not compilable to a single local-search call.`}}}}function Mn(e){if(e.kind==="text"||e.kind==="regex"||e.kind==="structural"||e.kind==="field")return LR(e);if(e.kind==="not"){let t=e.predicate;if(t.kind==="text"||t.kind==="regex"||t.kind==="field"){let n=LR(t);return n.unsupported?n:{...n,negate:!0}}return{unsupported:{code:"unsupportedBoolean",message:"not() over structural/boolean predicates is not supported by the local-search adapter."}}}return{unsupported:{code:"unsupportedBoolean",message:`Boolean predicate "${e.kind}" requires multiple backend calls; not supported by the single-call local-search adapter.`}}}var zd=y(()=>{"use strict";vR()});var Qa=y(()=>{"use strict";xd()});function Bd(e){if(e?.kind!=="github")return{};if(e.repo?.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{...e.owner?{owner:e.owner}:{},...e.repo?{repo:e.repo}:{}}}function nt(e){if(e?.path)return Array.isArray(e.path)?e.path[0]:e.path}function Qr(e){if(e?.language)return Array.isArray(e.language)?e.language[0]:e.language}function Qd(e){return typeof e.limit=="number"?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0}var bi=y(()=>{"use strict"});function qL(e){if(e.kind!=="field"||e.op!=="="||typeof e.value!="string"||e.value.length===0)return null;switch(e.field){case"basename":return{filename:e.value,match:"path"};case"extension":return{extension:e.value.replace(/^\./,""),match:"path"};case"path":return{keywords:[e.value],match:"path"};default:return null}}function Ri(e,t={}){if(!e.where)return{ok:!1,diagnostics:[x("vendorNoEquivalent",t.unsupportedMessage??"GitHub code search needs a positive code predicate.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let n=qL(e.where);if(n){let p=_R(e,t);if(p.length>0)return{ok:!1,diagnostics:p};let{owner:f,repo:m}=Bd(e.from),g=e.params??{},b=typeof g.extension=="string"||typeof n.extension=="string"?{}:_a(Qr(e.scope)),C=Qd(e),S=nt(e.scope);return{ok:!0,diagnostics:[],query:{...f?{owner:f}:{},...m?{repo:m}:{},...b,...n,...S?{path:S}:{},...typeof g.extension=="string"?{extension:g.extension}:{},...C?{limit:C}:{},...e.page?{page:e.page}:{}}}}let r=Mn(e.where);if(r.unsupported||r.negate||r.match?.mode==="structural")return{ok:!1,diagnostics:[x("unsupportedVendorPredicate",r.unsupported?.message??t.unsupportedMessage??"This predicate cannot be evaluated by GitHub code search; materialize for local proof.",{backend:t.unsupportedBackend??"ghSearchCode",...r.unsupported?.predicateId?{predicateId:r.unsupported.predicateId}:{}})]};let o=_R(e,t);if(o.length>0)return{ok:!1,diagnostics:o};let i=r.match?.keywords??"";if(i.trim().length===0)return{ok:!1,diagnostics:[x("vendorNoEquivalent","GitHub code search needs a non-empty search term.",{backend:t.unsupportedBackend??"ghSearchCode"})]};let{owner:s,repo:a}=Bd(e.from),c=e.params??{},l=typeof c.extension=="string"?{}:_a(Qr(e.scope)),u=Qd(e),d=typeof c.match=="string"?c.match:t.defaultMatch;return{ok:!0,diagnostics:[],query:{...s?{owner:s}:{},...a?{repo:a}:{},keywords:r.match?.fixedString===!0&&i.includes(" ")?i.split(/\s+/).filter(Boolean):[i],...l,...nt(e.scope)?{path:nt(e.scope)}:{},...d?{match:d}:{},...typeof c.concise=="boolean"?{concise:c.concise}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...u?{limit:u}:{},...e.page?{page:e.page}:{}}}}function _R(e,t){let n=[],r=t.unsupportedBackend??"ghSearchCode";return Array.isArray(e.scope?.language)&&e.scope.language.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.language values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.language"})),Array.isArray(e.scope?.path)&&e.scope.path.length>1&&n.push(x("lossyTransform","GitHub code search cannot express multiple scope.path values without dropping values; materialize for local proof.",{backend:r,queryPath:"scope.path"})),n}var Ud=y(()=>{"use strict";zd();Rt();Qa();bi()});function Ur(e){if(e.target==="diff"&&e.variant){let t=e.sourceKind==="materialized"?"local":e.sourceKind;return jd.find(n=>n.id===`${t}.diff.${e.variant}`)}return jd.find(t=>t.target===e.target&&t.sourceKinds.includes(e.sourceKind))}function $d(e){return jd.find(t=>t.id===e)}function qd(e){let t=VL(e.source,e.target);if(e.target==="diff"){let n=Br(e.params),r=n.kind==="prPatch"?"prPatch":n.kind==="directFile"?"directFile":void 0;if(r)return Ur({sourceKind:t,target:"diff",variant:r})}return Ur({sourceKind:t,target:e.target})}function IR(e,t){return e.backends.map(n=>({backend:n.backend,operation:n.operation,exact:n.exact,source:t}))}function FR(e){return{id:e.id,status:e.status,sourceKinds:e.sourceKinds,target:e.target,backends:e.backends}}function VL(e,t){return e?.kind?e.kind:t==="packages"?"npm":"github"}var jd,MR=y(()=>{"use strict";Ba();jd=[{id:"github.code",target:"code",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"transformers/github/code.ts",adapterFunctions:["toGithubCodeSearchToolQuery"]},{id:"github.files",target:"files",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchCode",operation:"findFiles",exact:!1}],rowKind:"file",adapterModule:"adapters/github.ts",adapterFunctions:["githubFiles"]},{id:"github.content",target:"content",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/github.ts",adapterFunctions:["githubContent"]},{id:"github.structure",target:"structure",sourceKinds:["github"],status:"active",backends:[{backend:"ghViewRepoStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/github.ts",adapterFunctions:["githubStructure"]},{id:"local.code.textRegex",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.code.structural",target:"code",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localSearchCode",operation:"searchCode",exact:!0}],rowKind:"code",adapterModule:"adapters/local.ts",adapterFunctions:["executeCode"]},{id:"local.files",target:"files",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localFindFiles",operation:"findFiles",exact:!0}],rowKind:"file",adapterModule:"adapters/local.ts",adapterFunctions:["executeFiles"]},{id:"local.content",target:"content",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"getContent",exact:!0}],rowKind:"content",adapterModule:"adapters/local.ts",adapterFunctions:["executeContent"]},{id:"local.structure",target:"structure",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localViewStructure",operation:"viewStructure",exact:!0}],rowKind:"tree",adapterModule:"adapters/local.ts",adapterFunctions:["executeStructure"]},{id:"local.semantics",target:"semantics",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.semantics",target:"semantics",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0},{backend:"lspGetSemantics",operation:"getSemantics",exact:!0}],rowKind:"record",recordType:"semantics",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeSemantics"]},{id:"github.repositories",target:"repositories",sourceKinds:["github"],status:"active",backends:[{backend:"ghSearchRepos",operation:"searchRepos",exact:!0}],rowKind:"record",recordType:"repository",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeRepositories"]},{id:"npm.packages",target:"packages",sourceKinds:["npm"],status:"active",backends:[{backend:"npmSearch",operation:"searchPackages",exact:!0}],rowKind:"record",recordType:"package",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executePackages"]},{id:"github.pullRequests",target:"pullRequests",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchPullRequests",exact:!0}],rowKind:"record",recordType:"pullRequest",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.commits",target:"commits",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"searchCommits",exact:!0}],rowKind:"record",recordType:"commit",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeHistory"]},{id:"github.diff.prPatch",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghHistoryResearch",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"github.diff.directFile",target:"diff",sourceKinds:["github"],status:"active",backends:[{backend:"ghGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.diff.directFile",target:"diff",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localGetFileContent",operation:"diff",exact:!0}],rowKind:"record",recordType:"diff",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeDiff"]},{id:"local.artifacts",target:"artifacts",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"localBinaryInspect",operation:"inspectArtifact",exact:!0}],rowKind:"record",recordType:"artifact",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeArtifacts"]},{id:"local.research",target:"research",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlResearch",operation:"runResearchFlow",exact:!1}],rowKind:"record",recordType:"research",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeResearch"]},{id:"local.graph",target:"graph",sourceKinds:["local","materialized"],status:"active",backends:[{backend:"smartOqlGraph",operation:"queryRelationshipGraph",exact:!1}],rowKind:"record",recordType:"graph",adapterModule:"adapters/researchTargets.ts",adapterFunctions:["executeGraph"]},{id:"github.materialize",target:"materialize",sourceKinds:["github"],status:"active",backends:[{backend:"ghCloneRepo",operation:"materialize",exact:!0}],rowKind:"record",recordType:"materialized",adapterModule:"adapters/materialize.ts",adapterFunctions:["executeMaterializeCheckpoint"]}]});function WL(e,t){return e.id??t}function Vd(e,t,n,r,o,i=!1){let s=WL(t,n);if(t.kind==="all"||t.kind==="any"){let c=t.of.map((d,p)=>Vd(e,d,`${n}.of[${p}]`,r,o,i)),l=KL(t.kind,c),u=`${t.kind} over ${c.length} children`;return r.sourceKind==="github"&&(r.target==="code"||r.target==="files")&&l!=="UNSUPPORTED"&&(r.materialize?.mode==="auto"||r.materialize?.mode==="required"?(l="ROUTE",u+=" (routed to materialization: GitHub cannot evaluate a multi-leaf boolean in one call)"):(l="UNSUPPORTED",u+=" (GitHub cannot evaluate a multi-leaf boolean; materialize for local proof)",o.diagnostics.push(x("requiresMaterialization","A multi-leaf boolean over a GitHub code source needs bounded materialization (clone then local set-algebra).",{queryPath:n,repair:{message:'Add materialize:{mode:"auto"} with scope.path, or run one query per branch.'}})))),o.nodes.push({predicateId:s,path:n,route:l,reason:u}),l}if(t.kind==="not"){let c=Vd(e,t.predicate,`${n}.predicate`,r,o,!i);return o.nodes.push({predicateId:s,path:n,route:c,reason:"not requires a complete evaluation universe to be exact"}),c}let a=CR(r,t,i);return o.nodes.push({predicateId:s,path:n,route:a.route,backend:a.backend,reason:a.reason}),a.diagnostic&&o.diagnostics.push(x(a.diagnostic.code,a.diagnostic.message,{predicateId:s,queryPath:n,backend:a.backend})),a.route!=="UNSUPPORTED"&&DR(o.backendCalls,{backend:a.backend,source:a.route==="ROUTE"?void 0:e.from,operation:YL(e.target),exact:a.exact}),a.route}function KL(e,t){return t.includes("UNSUPPORTED")&&e==="any"?"UNSUPPORTED":t.every(n=>n==="PUSHDOWN")?"PUSHDOWN":t.includes("ROUTE")?"ROUTE":t.includes("RESIDUAL")||t.includes("UNSUPPORTED")?"RESIDUAL":t[0]??"PUSHDOWN"}function YL(e){switch(e){case"code":return"searchCode";case"content":return"getContent";case"structure":return"viewStructure";case"files":return"findFiles";case"semantics":return"getSemantics";case"repositories":return"searchRepos";case"packages":return"searchPackages";case"pullRequests":return"searchPullRequests";case"commits":return"searchCommits";case"artifacts":return"inspectArtifact";case"diff":return"diff";case"research":return"runResearchFlow";case"graph":return"queryRelationshipGraph";case"materialize":return"materialize"}}function DR(e,t){e.some(r=>r.backend===t.backend&&r.operation===t.operation&&r.exact===t.exact)||e.push(t)}function Wd(e,t){if(!t)return;let n=FR(t);e.transformers?.some(o=>o.id===n.id)||(e.transformers=[...e.transformers??[],n])}function Ua(e,t,n){if(!t)return!1;for(let r of IR(t,n))DR(e.backendCalls,r);return!0}function XL(e,t){return NR(e,t,"files")}function NR(e,t,n,r=Ur({sourceKind:"materialized",target:n})){let o=Ur({sourceKind:"github",target:"materialize"});if(!o||!r)return!1;e.transformers=(e.transformers??[]).filter(s=>s.id!==`github.${n}`),Wd(e,o),Wd(e,r);let i=new Set(r.backends.map(s=>`${s.backend}:${s.operation}`));return e.backendCalls=e.backendCalls.filter(s=>!i.has(`${s.backend}:${s.operation}`)),Ua(e,o,t),Ua(e,r,void 0),!0}function ja(e){return e?e.kind==="structural"?!0:e.kind==="all"||e.kind==="any"?e.of.some(ja):e.kind==="not"?ja(e.predicate):!1:!1}function JL(e){return e.target==="code"?$d(ja(e.where)?"local.code.structural":"local.code.textRegex"):Ur({sourceKind:"materialized",target:e.target})}function ZL(e,t){return e.target==="code"&&(t.kind==="local"||t.kind==="materialized")?$d(ja(e.where)?"local.code.structural":"local.code.textRegex")??qd({source:t,target:e.target,params:e.params}):qd({source:t,target:e.target,params:e.params})}function Kd(e){return e?e.kind==="all"||e.kind==="any"?1+e.of.reduce((t,n)=>t+Kd(n),0):e.kind==="not"?1+Kd(e.predicate):1:0}function GR(e,t){let n={nodes:[],diagnostics:[],backendCalls:[],transformers:[]},r=e.materialize,o=e.from??{kind:"github"},i={sourceKind:o.kind==="npm"?"github":o.kind,target:e.target,materialize:r},s=ZL(e,o);if(Wd(n,s),e.where)Vd(e,e.where,"where",i,n),o.kind==="github"&&n.nodes.some(m=>m.route==="ROUTE")&&NR(n,o,e.target,JL(e));else if(e.target==="diff"){let m=Br(e.params);m.kind==="prPatch"||m.kind==="directFile"?Ua(n,s,o)||n.diagnostics.push(x("unsupportedTarget",`No transformer registered for target:"diff" lane "${m.kind}".`,{queryPath:"target",backend:"ghHistoryResearch",severity:"error"})):n.diagnostics.push(x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{queryPath:"params",backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}}))}else{let m=o.kind==="github"&&e.target==="files"&&!e.where,g=r?.mode==="auto"||r?.mode==="required";!(m?g&&XL(n,o):Ua(n,s,o))&&(!m||g)&&n.diagnostics.push(x("unsupportedTarget",m?'No transformer chain registered for target:"files" GitHub materialization.':`No transformer registered for target:"${e.target}" from ${o.kind}.`,{queryPath:"target",severity:"error"}))}o.kind==="github"&&e.target==="files"&&!e.where&&(r?.mode==="auto"||r?.mode==="required"||n.diagnostics.push(x("requiresMaterialization",'target:"files" over a GitHub source needs bounded materialization to enumerate files (set materialize.mode "auto"/"required" with scope.path), or use a local source.',{queryPath:"target",backend:"localFindFiles",severity:"error",repair:{message:'Add materialize:{mode:"auto"} with scope.path, or use a local `from`.'}}))),n.diagnostics.push(...e_(e,n.nodes)),n.diagnostics.push(...xR(e));let a=t_(e,n.diagnostics),c=e.controls?.budget?.maxPlanNodes??lt.maxPlanNodes,l=!1,u=n.nodes;u.length>c&&(l=!0,u=u.slice(0,c),n.diagnostics.push(x("planTruncated",`Explain plan truncated to ${c} nodes; execution semantics are unchanged.`)));let d=Kd(e.where);!l&&n.nodes.length!==d&&n.diagnostics.push(x("invalidQuery",`Planner invariant violated: ${n.nodes.length} routed vs ${d} predicate nodes.`));let p={input:t,normalized:e,defaults:ER(e),nodes:u,backendCalls:n.backendCalls,...n.transformers?.length?{transformers:n.transformers}:{},...a?{materialization:a}:{},budgets:e.controls?.budget,...l?{truncated:l}:{},diagnostics:n.diagnostics},f=!n.nodes.some(m=>m.route==="UNSUPPORTED")&&!n.diagnostics.some(m=>m.severity==="error"&&m.code!=="planTruncated");return{plan:p,executable:f}}function HR(e){return e.kind==="not"&&e.predicate.kind==="not"?HR(e.predicate.predicate):e}function e_(e,t){if(e.from?.kind!=="github"||e.target!=="code"&&e.target!=="files"||!e.where||e.materialize?.mode==="required"||t.some(o=>o.route==="ROUTE"))return[];let n=HR(e.where),r=Ri({...e,where:n},{...e.target==="files"?{defaultMatch:"file"}:{}});return r.ok?[]:r.diagnostics}function t_(e,t){let n=e.materialize;if(!n||e.from?.kind!=="github")return;if(n.mode==="never")return{...n,required:!1,reason:'provider-only execution (materialize.mode:"never")'};let r=!!e.scope?.path||n.strategy==="file",o=n.strategy==="repo";return o&&!n.allowFullRepo?t.push(x("materializationNotAllowed",'strategy:"repo" requires allowFullRepo:true and a byte budget; repair to "subtree" with a concrete scope.path.',{queryPath:"materialize",repair:{message:'Use materialize.strategy:"subtree" with scope.path.'}})):!o&&!r&&t.push(x("materializationNotAllowed",'Bounded materialization needs scope.path (or strategy:"file"); refusing to clone an unbounded scope.',{queryPath:"materialize",repair:{message:"Add scope.path to bound the materialized subtree."}})),{...n,strategy:n.strategy??"subtree",required:n.mode==="required",reason:n.mode==="required"?"local-only proof required; must materialize before execution":"planner may materialize bounded source for local proof"}}var zR=y(()=>{"use strict";PR();Ba();wR();Rt();TR();Ud();MR()});function $a(e){let t=r_(e),n=i_(e),r=t==="proof"&&n;return{...e.queryId?{queryId:e.queryId}:{},...e.queryIndex!==void 0?{queryIndex:e.queryIndex}:{},results:e.results,...e.shared&&Object.keys(e.shared).length?{shared:e.shared}:{},...e.pagination?{pagination:e.pagination}:{},...e.next&&Object.keys(e.next).length?{next:e.next}:{},...e.nextHints&&Object.keys(e.nextHints).length?{nextHints:e.nextHints}:{},diagnostics:e.diagnostics,provenance:e.provenance,evidence:{answerReady:r,complete:n,kind:t},...e.plan?{plan:e.plan}:{}}}function r_(e){return!e.executable||e.diagnostics.some(t=>n_.has(t.code))?"unsupported":e.approximate||o_(e.diagnostics)?"candidate":fR(e.diagnostics)||BR(e)?"partial":"proof"}function o_(e){return e.some(t=>t.code==="providerSemanticsApproximate")}function BR(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")||t==="next.matchPage"))}function i_(e){return!e.executable||BR(e)?!1:!e.diagnostics.some(t=>t.blocksAnswer||t.code==="partialResult")}function QR(e){return e.some(t=>!t.exact)}function Yd(e,t,n,r,o){return $a({queryId:n,queryIndex:r,results:[],diagnostics:e,provenance:[],executable:!1,plan:t,...o&&Object.keys(o).length?{next:o}:{}})}var n_,UR=y(()=>{"use strict";Rt();n_=new Set(["invalidQuery","ambiguousSugar","unknownField","unsupportedTarget","unsupportedPredicate","unsupportedBoolean","unsupportedScope","unsupportedVendorPredicate","vendorNoEquivalent","responseShapeMismatch"])});function Bt(e,t=!1){if(!e)return t?{hasMore:!0}:void 0;let n=e.itemsPerPage??e.entriesPerPage??e.filesPerPage??e.perPage,r=e.totalItems??e.totalEntries??e.totalFiles??e.totalMatches,o=e.totalMatchesCapped===!0,i=!o&&typeof r=="number"&&Number.isFinite(r)&&typeof n=="number"&&Number.isFinite(n)&&n>0,s=i?Math.max(1,Math.ceil(r/n)):void 0,a=i?s:o?void 0:e.totalPages,c=o?e.hasMore??(typeof e.currentPage=="number"&&typeof e.totalPages=="number"?e.currentPage<e.totalPages:t):typeof e.currentPage=="number"&&typeof a=="number"?e.currentPage<a:e.hasMore??t,l=e.nextPage!==void 0&&c?e.nextPage:void 0;return{hasMore:!!c,...e.currentPage!==void 0?{currentPage:e.currentPage}:{},...a!==void 0?{totalPages:a}:{},...l!==void 0?{nextPage:l}:{},...n!==void 0?{itemsPerPage:n}:{},...r!==void 0?{totalItems:r}:{},...e.reportedTotalMatches!==void 0?{reportedTotalItems:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalItems:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalItemsKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalItemsCapped:e.totalMatchesCapped}:{},...e.uniqueFileCount!==void 0?{uniqueFileCount:e.uniqueFileCount}:{}}}var qa=y(()=>{"use strict"});function Xd(e){return Bt(e)}function s_(e){if(e)return Bt({currentPage:e.currentPage,totalPages:e.totalPages,nextPage:e.nextPage,hasMore:e.hasMore,itemsPerPage:e.filesPerPage??e.itemsPerPage??e.perPage,totalItems:e.totalFiles??e.totalItems,reportedTotalMatches:e.totalMatches??e.reportedTotalMatches,reachableTotalMatches:e.reachableTotalMatches,totalMatchesKind:e.totalFiles!==void 0?"files":e.totalMatchesKind,totalMatchesCapped:e.totalMatchesCapped,uniqueFileCount:e.uniqueFileCount??e.totalFiles})}function Va(e,t){let n=[];for(let r of e.files??[]){let o=r.matches??[];if(o.length===0){let i=r;n.push({kind:"code",source:t,path:r.path,...i.totalMatchedLines!==void 0?{totalMatchedLines:i.totalMatchedLines}:{},...i.totalOccurrences!==void 0?{totalOccurrences:i.totalOccurrences}:{}});continue}for(let i of o){let s=i.metavars,a=i.metavarRanges;n.push({kind:"code",source:t,path:r.path,line:i.line,...i.endLine!==void 0?{endLine:i.endLine}:{},...i.column!==void 0?{column:i.column}:{},...i.value!==void 0?{snippet:i.value}:{},...s&&Object.keys(s).length?{metavars:s}:{},...a&&Object.keys(a).length?{metavarRanges:a}:{}})}}return{results:n,pagination:a_(s_(e.pagination),n.length)}}function a_(e,t){if(e)return e.totalItemsKind!=="files"?e:{...e,itemUnit:"files",rowCount:t,...e.reportedTotalItems!==void 0?{reportedRowCount:e.reportedTotalItems}:{}}}function Wa(e,t){return{results:(e.files??[]).map(r=>{let o=r.type,i=o==="d"||o==="directory"?"directory":"file";return{kind:"file",source:t,path:r.path,entryType:i,...r.size!==void 0?{size:r.size}:{},...r.modified!==void 0?{modified:r.modified}:{}}}),pagination:Xd(e.pagination)}}function jR(e,t){if(!e.entries&&(e.files||e.folders)){let r=e.path??"",o=s=>`${r.replace(/\/$/,"")}/${s}`;return{results:[...(e.folders??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"directory",depth:0})),...(e.files??[]).map(s=>({kind:"tree",source:t,path:o(s),entryType:"file",depth:0}))],pagination:Xd(e.pagination)}}return{results:(e.entries??[]).map(r=>{let o=r.type,i=o==="dir"||o==="directory"?"directory":"file",s=l_(r.size);return{kind:"tree",source:t,path:r.path??r.name??"",entryType:i,depth:r.depth??0,...s!==void 0?{size:s}:{}}}),pagination:Xd(e.pagination)}}function l_(e){if(typeof e=="number")return e;if(typeof e!="string")return;let t=e.trim().match(/^([0-9.]+)\s*([kmgt]?b)$/i);if(!t){let o=Number(e);return Number.isFinite(o)?o:void 0}let n=Number(t[1]),r=c_[t[2].toLowerCase()]??1;return Number.isFinite(n)?Math.round(n*r):void 0}function $R(e,t,n,r="compact"){let o=e.pagination,i=typeof o?.charOffset=="number",s={...e.startLine!==void 0?{startLine:e.startLine}:{},...e.endLine!==void 0?{endLine:e.endLine}:{},...i?{charOffset:o.charOffset,...typeof o.charLength=="number"?{charLength:o.charLength}:{}}:{}};return{results:[{kind:"content",source:t,path:e.filePath??n,content:e.content??"",contentView:r,...Object.keys(s).length?{range:s}:{}}],...o?.hasMore!==void 0?{pagination:{hasMore:!!o.hasMore}}:{}}}var c_,qR=y(()=>{"use strict";qa();c_={b:1,kb:1024,mb:1024**2,gb:1024**3,tb:1024**4}});import Xa from"node:path";import u_ from"node:fs";function d_(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath;throw new Error("localExecute requires a local or materialized source.")}function Za(e){let t={};return e?.include&&(t.include=e.include),e?.exclude&&(t.exclude=e.exclude),e?.excludeDir&&(t.excludeDir=e.excludeDir),e?.hidden!==void 0&&(t.hidden=e.hidden),e?.noIgnore!==void 0&&(t.noIgnore=e.noIgnore),t}function KR(e,t){let n=Array.isArray(e)?e.filter(r=>typeof r=="string"):[];return[...new Set([...n,...t])]}function ec(e,t,n){if(n){e.langType=n;return}let r=Sd(Qr(t));r.langType&&(e.langType=r.langType),r.include?.length&&(e.include=KR(e.include,r.include))}function p_(e){return Cd(Qr(e))}function VR(e){let t=Ja(e),n=t.match(/^\*\*\/(\*\.[^/]+)$/);if(n)return n[1];if(!t.includes("/"))return t}function tc(e){return!!(e?.include?.length||e?.exclude?.length)}function ep(e,t){t?.excludeDir&&(e.excludeDir=t.excludeDir),t?.minDepth!==void 0&&(e.minDepth=t.minDepth),t?.maxDepth!==void 0&&(e.maxDepth=t.maxDepth);let n=(t?.include??[]).map(VR).filter(i=>!!i);n.length>0&&!e.names&&(e.names=KR(e.names,n));let r=(t?.include??[]).filter(i=>!VR(i));r.length===1&&!e.pathPattern&&(e.pathPattern=r[0]);let o=p_(t);o.length>0&&!e.names&&!e.pathPattern&&(e.names=o)}function f_(e,t){if(tc(t.scope)){tp(e),e.page=1;return}t.itemsPerPage&&(e.itemsPerPage=t.itemsPerPage),t.page&&(e.page=t.page)}function tp(e){e.limit=Jd,e.itemsPerPage=Jd}async function Ci(e){let t=e.from,n=d_(e),r=nt(e.scope),o=r?Xa.join(n,r):n;if(!u_.existsSync(o))return{results:[],diagnostics:[x("invalidQuery",`Local path does not exist: ${o}. Check the path/spelling (and branch or materialization for remote sources) before treating this as absence.`,{backend:"localExecute",queryPath:o,repair:{message:'Verify the path exists (orient with target:"structure" on a known-good parent), fix typos, or materialize the remote source first.'}})],provenance:[]};switch(e.target){case"files":return y_(e,t,o);case"structure":return k_(e,t,o);case"content":return O_(e,t,o);default:return XR(e,t,o)}}function m_(e){return e.kind==="all"||e.kind==="any"?!0:e.kind==="not"?JR(e.predicate):!1}function g_(e){return e.kind==="text"||e.kind==="regex"}function YR(e){return e?.kind==="not"&&g_(e.predicate)}async function XR(e,t,n){let r=e.where;if(m_(r))return E_(e,t,n,r);if(e.view==="discovery"&&YR(r))return S_(e,t,n,r);let o=Mn(r);if(o.unsupported)return{results:[],diagnostics:[x(o.unsupported.code,o.unsupported.message,{backend:"localSearchCode",...o.unsupported.predicateId?{predicateId:o.unsupported.predicateId}:{}})],provenance:[]};let i=o.match,s={path:n,...Za(e.scope),...e.view==="discovery"?{filesOnly:!0}:{},...e.view==="detailed"?{contextLines:3}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...oS(e)};ec(s,e.scope,i.langType),i.mode==="structural"?(s.mode="structural",i.pattern!==void 0&&(s.pattern=i.pattern),i.rule!==void 0&&(s.rule=i.rule)):(s.keywords=i.keywords,i.fixedString&&(s.fixedString=!0),i.perlRegex&&(s.perlRegex=!0),i.caseSensitive&&(s.caseSensitive=!0),i.caseInsensitive&&(s.caseInsensitive=!0),i.wholeWord&&(s.wholeWord=!0),i.multiline&&(s.multiline=!0),i.multilineDotall&&(s.multilineDotall=!0),o.negate&&(s.invertMatch=!0));let a=await on(s),c=Va(a,t),l=jr(a,"localSearchCode"),u=h_(a);if(u.length>0){let d=u.reduce((f,m)=>f+(m.total??0),0),p=u.reduce((f,m)=>f+m.shown,0);l.push(x("matchTruncated",`${u.length} file(s) have more matches (showed ${p} of ${d}) \u2014 page with controls.search.matchPage, or raise controls.search.maxMatchesPerFile.`,{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:"Follow next.matchPage to page within files, or set controls.search.maxMatchesPerFile higher."}}))}return i.mode==="structural"&&i.pattern!==void 0&&c.results.length===0&&l.push(x("zeroMatches","Structural pattern matched 0 nodes. A pattern must match the COMPLETE node \u2014 if the target has a return type or typed params the pattern omits, it returns 0 (not genuine absence).",{backend:"localSearchCode",severity:"info",blocksAnswer:!1,repair:{message:'To find a named symbol, prefer a rule over a pattern: where = { kind:"structural", lang, rule:{ kind:"<node e.g. function_declaration>", has:{ pattern:"<name>" } } }. Or complete the pattern (e.g. add a return type `: $R`).'}})),{...c,diagnostics:l,provenance:[$r("localSearchCode",t,r)]}}function h_(e){let t=[];for(let n of e.files??[]){let r=n.returnedMatchRows??n.matches?.length??0,o=n.pagination?.totalMatches??n.totalMatchRows??n.matchCount,i=n.pagination?.hasMore===!0,s=typeof o=="number"&&o>r;(i||s)&&t.push({path:n.path,shown:r,total:o})}return t}async function y_(e,t,n){let r=e.where;if(YR(r))return R_(e,t,n,r);if(r&&JR(r))return b_(e,t,n,r);if(r&&nS(r)){let l=await XR({...e,view:"discovery"},t,n),u=l.results.map(d=>({kind:"file",source:t,path:d.path,entryType:"file"}));return{...l,results:u}}let o={path:n,details:!0,showFileLastModified:!0};ep(o,e.scope),f_(o,e);let i=[];r&&rS(r,o,i);let s=await Ir(o),a=rp(s,e,n);return{...Wa(a,t),diagnostics:[...i,...jr(a,"localFindFiles")],provenance:[$r("localFindFiles",t,r)]}}function JR(e){return e.kind==="all"||e.kind==="any"||e.kind==="not"}async function b_(e,t,n,r){let o=[],i=[],a=[...(await Ka(e,r,t,n,o,i)).values()].sort((c,l)=>c.path.localeCompare(l.path));return a.length===0&&!i.some(c=>c.severity==="error")&&i.push(x("zeroMatches","Boolean file query matched no files.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:a,diagnostics:i,provenance:o}}async function Ka(e,t,n,r,o,i){switch(t.kind){case"all":return(await Promise.all(t.of.map(a=>Ka(e,a,n,r,o,i)))).reduce((a,c)=>a===void 0?c:C_(a,c));case"any":{let s=await Promise.all(t.of.map(c=>Ka(e,c,n,r,o,i))),a=new Map;for(let c of s)for(let[l,u]of c)a.set(l,np(a.get(l),u));return a}case"not":{let s=await eS(e,n,r,o),a=await Ka(e,t.predicate,n,r,o,i);return new Map([...s].filter(([c])=>!a.has(c)))}default:return tS(e,t,n,r,o,i)}}async function R_(e,t,n,r){let o=await on(ZR(e,n,r.predicate)),i=jr(o,"localSearchCode");return{results:(o.files??[]).map(a=>({kind:"file",source:t,path:a.path,entryType:"file"})),diagnostics:i,provenance:[$r("localSearchCode",t,r)]}}async function S_(e,t,n,r){let o=await on(ZR(e,n,r.predicate));return{...Va(o,t),diagnostics:jr(o,"localSearchCode"),provenance:[$r("localSearchCode",t,r)]}}function ZR(e,t,n){let o=Mn(n).match,i={path:t,filesWithoutMatch:!0,...Za(e.scope),...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{},...oS(e)};return ec(i,e.scope,o.langType),i.keywords=o.keywords,o.fixedString&&(i.fixedString=!0),o.perlRegex&&(i.perlRegex=!0),o.caseSensitive&&(i.caseSensitive=!0),o.caseInsensitive&&(i.caseInsensitive=!0),o.wholeWord&&(i.wholeWord=!0),o.multiline&&(i.multiline=!0),o.multilineDotall&&(i.multilineDotall=!0),i}function C_(e,t){let n=new Map;for(let[r,o]of e){let i=t.get(r);i&&n.set(r,np(o,i))}return n}function P_(e,t){return new Set([...e].filter(n=>t.has(n)))}function np(e,t){return e?{...e,...t,entryType:e.entryType==="directory"||t.entryType==="directory"?"directory":"file",...e.size!==void 0||t.size!==void 0?{size:e.size??t.size}:{},...e.modified!==void 0||t.modified!==void 0?{modified:e.modified??t.modified}:{}}:t}async function x_(e,t,n){return new Set((await eS(e,e.from,t,n)).keys())}async function eS(e,t,n,r){let o={path:n,entryType:"f"};ep(o,e.scope),tc(e.scope)&&(tp(o),o.page=1);let i=await Ir(o),s=rp(i,e,n);return r.push({backend:"localFindFiles",source:e.from}),Zd(Wa({...s,files:(s.files??[]).filter(a=>a.type===void 0||a.type==="f"||a.type==="file")},t).results)}async function w_(e,t,n,r,o){return new Set((await tS(e,t,e.from,n,r,o)).keys())}async function tS(e,t,n,r,o,i){if(t.kind==="field"){let u={path:r,details:!0};ep(u,e.scope),rS(t,u,i),tc(e.scope)&&(tp(u),u.page=1);let d=await Ir(u),p=rp(d,e,r);return o.push({backend:"localFindFiles",source:e.from}),Zd(Wa(p,n).results)}let s=Mn(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),new Map;let a=s.match,c={path:r,filesOnly:!0,maxFiles:Jd,...Za(e.scope)};ec(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),a.rule!==void 0&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0));let l=await on(c);return o.push({backend:"localSearchCode",source:e.from}),Zd((l.files??[]).map(u=>({kind:"file",source:n,path:u.path,entryType:"file"})))}function Zd(e){let t=new Map;for(let n of e)t.set(n.path,np(t.get(n.path),n));return t}async function E_(e,t,n,r){let o=[],i=[],s=await Ya(e,r,t,n,o,i),a=new Set,c=s.rows.filter(l=>s.files.has(l.path)).filter(l=>{let u=`${l.path}:${l.line??""}`;return a.has(u)?!1:(a.add(u),!0)});return c.length===0&&!i.some(l=>l.severity==="error")&&i.push(x("zeroMatches","Boolean code query matched no occurrences.",{backend:"localSearchCode",severity:"info",blocksAnswer:!1})),{results:c,diagnostics:i,provenance:o}}async function Ya(e,t,n,r,o,i){switch(t.kind){case"all":{let s=await Promise.all(t.of.map(l=>Ya(e,l,n,r,o,i))),a=s.map(l=>l.files).reduce((l,u)=>l===void 0?u:P_(l,u)),c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"any":{let s=await Promise.all(t.of.map(l=>Ya(e,l,n,r,o,i))),a=new Set;for(let l of s)for(let u of l.files)a.add(u);let c=s.flatMap(l=>l.rows);return{files:a,rows:c}}case"not":{let s=await x_(e,r,o),a=await Ya(e,t.predicate,n,r,o,i);return{files:new Set([...s].filter(c=>!a.files.has(c))),rows:[]}}case"field":return{files:await w_(e,t,r,o,i),rows:[]};default:{let s=await T_(e,t,n,r,o,i);return{files:new Set(s.map(a=>a.path)),rows:s}}}}async function T_(e,t,n,r,o,i){let s=Mn(t);if(s.unsupported)return i.push(x(s.unsupported.code,s.unsupported.message,{backend:"localSearchCode"})),[];let a=s.match,c={path:r,...Za(e.scope)};ec(c,e.scope,a.langType),a.mode==="structural"?(c.mode="structural",a.pattern!==void 0&&(c.pattern=a.pattern),a.rule!==void 0&&(c.rule=a.rule)):(c.keywords=a.keywords,a.fixedString&&(c.fixedString=!0),a.perlRegex&&(c.perlRegex=!0),a.caseSensitive&&(c.caseSensitive=!0),a.caseInsensitive&&(c.caseInsensitive=!0),a.wholeWord&&(c.wholeWord=!0),a.multiline&&(c.multiline=!0),a.multilineDotall&&(c.multilineDotall=!0));let l=await on(c);return o.push({backend:"localSearchCode",source:n}),Va(l,n).results}async function k_(e,t,n){let r={path:n,details:!0,...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth,recursive:!0}:{},...e.fetch?.tree?.pattern?{pattern:e.fetch.tree.pattern}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.fetch?.tree?.extensions?.length?{extensions:e.fetch.tree.extensions}:{},...e.fetch?.tree?.filesOnly?{filesOnly:!0}:{},...e.fetch?.tree?.directoriesOnly?{directoriesOnly:!0}:{},...e.fetch?.tree?.sortBy?{sortBy:e.fetch.tree.sortBy}:{},...e.fetch?.tree?.reverse?{reverse:!0}:{},...e.scope?.hidden!==void 0?{hidden:e.scope.hidden}:{},...e.limit?{limit:e.limit}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Ma(r);return{...jR(o,t),diagnostics:jr(o,"localViewStructure"),provenance:[$r("localViewStructure",t,void 0)]}}async function O_(e,t,n){let r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=I_(r?.range),s={path:n,minify:o,...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.range?.contextLines!==void 0&&r?.range?.startLine===void 0?{contextLines:r.range.contextLines}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Ta(s),c=r?.contentView==="exact"?"exact":r?.contentView==="symbols"?"symbols":"compact";return{...$R(a,t,n,c),diagnostics:jr(a,"localGetFileContent"),provenance:[$r("localGetFileContent",t,void 0)]}}function rp(e,t,n){if(!tc(t.scope)||e.status==="error")return e;let r=(e.files??[]).filter(d=>v_(d.path,n,t.scope)),o=Math.max(1,t.page??1),i=Math.max(1,(t.itemsPerPage??t.limit??r.length)||1),s=Math.max(1,Math.ceil(r.length/i)),a=(o-1)*i,c=r.slice(a,a+i),{status:l,...u}=e;return{...u,...c.length===0?{status:"empty"}:{},files:c,pagination:{currentPage:o,totalPages:s,filesPerPage:i,totalFiles:r.length,hasMore:o<s,...o<s?{nextPage:o+1}:{}}}}function v_(e,t,n){let r=Ja(A_(e,t)),o=n?.include??[];return o.length>0&&!o.some(i=>WR(r,i))?!1:!(n?.exclude??[]).some(i=>WR(r,i))}function A_(e,t){let n=Xa.relative(t,e);return!n||n.startsWith("..")||Xa.isAbsolute(n)?e:n}function Ja(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function WR(e,t){let n=Ja(t),r=Ja(e),o=L_(n);return o.test(r)?!0:n.includes("/")?!1:o.test(Xa.posix.basename(r))}function L_(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1],i=e[n+2];if(r==="*"&&o==="*"&&i==="/"){t+="(?:.*/)?",n+=2;continue}if(r==="*"&&o==="*"){t+=".*",n+=1;continue}if(r==="*"){t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=__(r)}return new RegExp(`${t}$`)}function __(e){return/[|\\{}()[\]^$+?.]/.test(e)?`\\${e}`:e}function I_(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function nS(e){return e.kind==="text"||e.kind==="regex"||e.kind==="structural"?!0:e.kind==="not"?nS(e.predicate):!1}function rS(e,t,n){let r=e.kind==="not",o=e.kind==="not"?e.predicate:e;if(o.kind!=="field"){n.push(x("unsupportedPredicate","Only field predicates (and field-negation) compile to the files backend.",{backend:"localFindFiles"}));return}let i=o,s=i.value;switch(i.field){case"basename":case"path":i.op==="regex"?t.regex=String(s):i.op==="glob"||i.op==="="||i.op==="in"?t.names=Array.isArray(s)?s.map(String):[String(s)]:n.push(Si(i));break;case"extension":{let a=(Array.isArray(s)?s:[s]).map(c=>`*.${String(c).replace(/^\./,"")}`);i.op==="="||i.op==="in"||i.op==="glob"?t.names=a:n.push(Si(i));break}case"size":i.op===">"||i.op===">="?t.sizeGreater=String(s):i.op==="<"||i.op==="<="?t.sizeLess=String(s):n.push(Si(i));break;case"modified":i.op==="within"?t.modifiedWithin=String(s):i.op==="before"?t.modifiedBefore=String(s):n.push(x("unsupportedPredicate",'field "modified" supports only `within` / `before` (relative windows like "7d"); findFiles has no absolute-date filter for >/</>=/<=.',{backend:"localFindFiles"}));break;case"accessed":i.op==="within"?t.accessedWithin=String(s):n.push(Si(i));break;case"empty":t.empty=!!s;break;case"permissions":t.permissions=String(s);break;case"executable":case"readable":case"writable":t[i.field]=!!s;break;case"entryType":t.entryType=String(s)==="directory"?"d":"f";break;default:n.push(Si(i));break}r&&n.push(x("residualNotExact","Negated field predicates over findFiles are best-effort.",{backend:"localFindFiles",severity:"warning"}))}function Si(e){return x("unsupportedPredicate",`field "${e.field}" with operator "${e.op}" is not supported by the files backend.`,{backend:"localFindFiles"})}function oS(e){let t={},n=e.controls?.search;return n&&(n.onlyMatching&&(t.onlyMatching=!0),n.unique&&(t.unique=!0),n.countUnique&&(t.countUnique=!0),n.countMatchesPerFile&&(t.countMatchesPerFile=!0),n.countLinesPerFile&&(t.countLinesPerFile=!0),n.contextLines!==void 0&&(t.contextLines=n.contextLines),n.invertMatch&&(t.invertMatch=!0),n.matchWindow!==void 0&&(t.matchWindow=n.matchWindow),n.matchContentLength!==void 0&&(t.matchContentLength=n.matchContentLength),n.maxMatchesPerFile!==void 0&&(t.maxMatchesPerFile=n.maxMatchesPerFile),n.matchPage!==void 0&&(t.matchPage=n.matchPage),n.sort&&(t.sort=n.sort),n.sortReverse&&(t.sortReverse=!0),n.rankingProfile&&(t.rankingProfile=n.rankingProfile),n.debugRanking&&(t.debugRanking=!0)),e.controls?.budget?.maxFiles!==void 0&&(t.maxFiles=e.controls.budget.maxFiles),t}function jr(e,t){let n=[];e.status==="error"?n.push(x("invalidQuery",e.error??"Backend error",{backend:t})):e.status==="empty"&&n.push(x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1}));for(let r of e.warnings??[])n.push(x(F_(r),r,{backend:t,severity:"warning",blocksAnswer:!1}));return n}function F_(e){let t=e.toLowerCase();return t.includes("skipped parsing")||t.includes("parse error")?"partialParse":t.includes("capped")||t.includes("truncat")?"matchTruncated":t.includes("redact")||t.includes("sanitiz")||t.includes("secret")?"sanitized":"partialResult"}function $r(e,t,n){return{backend:e,source:t,...n?.id?{pushed:[n.id]}:{}}}var Jd,op=y(()=>{"use strict";me();Ia();pi();hi();ai();zd();qR();Rt();Qa();bi();Jd=1e4});import{completeMetadata as M_}from"@octocodeai/octocode-core";function I2(e){return D_.has(e)}var V,Le,Dn,D_,Pi=y(()=>{"use strict";V=M_.toolNames,Le=V.LSP_GET_SEMANTIC_CONTENT,Dn="oqlSearch",D_=new Set([V.LOCAL_RIPGREP,V.LOCAL_FETCH_CONTENT,V.LOCAL_FIND_FILES,V.LOCAL_VIEW_STRUCTURE,V.LOCAL_BINARY_INSPECT,Le])});function Nn(e){return{name:e.name,uri:e.uri,foundAtLine:e.foundAtLine,...e.orderHint!==void 0&&{orderHint:e.orderHint},...e.isAmbiguous===!0&&{isAmbiguous:!0}}}function ip(e){let t=e.displayRange??(e.range?{startLine:e.range.start.line+1,endLine:e.range.end.line+1}:void 0);return{uri:e.uri,...e.content!==void 0&&{content:e.content},...t&&{displayRange:t},...e.isDefinition&&{isDefinition:!0}}}var iS,Gn=y(()=>{"use strict";Pi();iS=["definition","references","callers","callees","callHierarchy","hover","documentSymbols","typeDefinition","implementation","workspaceSymbol","supertypes","subtypes","diagnostic"]});import{z as K}from"zod";import{NpmPackageQuerySchema as sS}from"@octocodeai/octocode-core/schemas";var aS,nc,rc,Q2,oc=y(()=>{"use strict";Be();tt();Gt();aS={page:ae,mode:K.enum(["lean","full"]).optional()},nc=ue(sS,aS),rc=ie(he(sS,aS,{strict:!0}),{maxQueries:5}),Q2=K.object({results:K.array(K.looseObject({id:K.string(),data:K.looseObject({packages:K.array(K.object({name:K.string(),version:K.string().optional(),description:K.string().optional(),license:K.string().optional(),downloads:K.number().optional(),repository:K.string().optional(),repositoryDirectory:K.string().optional(),repositoryId:K.string().optional(),next:K.record(K.string(),K.unknown()).optional()}).passthrough()).optional(),repositories:K.record(K.string(),K.object({repository:K.string(),owner:K.string(),repo:K.string(),repositoryDirectory:K.string().optional(),next:K.record(K.string(),K.unknown())}).passthrough()).optional(),pagination:K.object({currentPage:K.number(),totalPages:K.number(),perPage:K.number(),totalFound:K.number(),returned:K.number(),hasMore:K.boolean(),nextPage:K.number().optional()}).optional()}).optional(),status:K.string().optional()})).optional()}).extend(Qe)});import{z as R}from"zod";import{LspGetSemanticsQuerySchema as uS}from"@octocodeai/octocode-core/schemas";import{ErrorDataSchema as N_}from"@octocodeai/octocode-core/schemas/outputs";var G_,H_,z_,dS,B_,xi,Q_,wi,cS,U_,j_,ic,sc,$_,q_,pS,qr,V_,W_,K_,fS,Y_,X_,J_,Z_,eI,tI,nI,lS,rI,Ei=y(()=>{"use strict";me();Be();tt();Gn();G_=G(1,1e9).describe("1-based source line for symbol-anchored semantic operations. Get it from search/localSearchCode, structural AST captures, or documentSymbols; never guess."),H_=G(0,1e5).optional(),z_=["structured","compact"],dS={type:R.enum(iS).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:R.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:G_.optional(),orderHint:H_,depth:G(0,20).optional(),includeDeclaration:R.boolean().optional().default(!0),page:ae,itemsPerPage:G(1,100).optional(),contextLines:G(0,100).optional(),format:R.enum(z_).optional().default("structured")},B_=he(uS,dS),xi=ue(uS,dS),Q_=xi,wi=ie(B_,{maxQueries:5}),cS=R.object({line:R.number(),character:R.number()}),U_=R.object({start:cS,end:cS}),j_=R.object({startLine:R.number(),endLine:R.number()}),ic=R.object({uri:R.string(),content:R.string().optional(),displayRange:j_.optional(),isDefinition:R.boolean().optional()}),sc=R.string(),$_=R.object({name:R.string(),uri:R.string(),foundAtLine:R.number(),orderHint:R.number().optional()}),q_=R.object({serverAvailable:R.boolean().optional(),provider:R.string().optional(),source:R.string().optional()}),pS=R.enum(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),qr=R.object({category:pS,reason:R.string()}),V_=R.object({currentPage:R.number(),totalPages:R.number(),totalResults:R.number(),hasMore:R.boolean(),itemsPerPage:R.number(),nextPage:R.number().optional()}),W_=R.object({name:R.string(),kind:R.string(),line:R.number(),character:R.number(),endLine:R.number(),childCount:R.number(),containerName:R.string().optional()}),K_=R.string(),fS=R.object({name:R.string(),kind:R.string(),uri:R.string(),line:R.number(),endLine:R.number(),selectionLine:R.number().optional()}),Y_=R.string(),X_=R.object({direction:R.enum(["incoming","outgoing"]),item:fS,ranges:R.array(R.object({line:R.number(),character:R.number()})),rangeCount:R.number(),rangeSampleCount:R.number(),contentPreview:R.string().optional()}),J_=R.string(),Z_=R.object({complete:R.boolean(),truncatedByDepth:R.boolean(),cycleCount:R.number(),failedRequestCount:R.number(),dynamicCallsExcluded:R.literal(!0),stdlibCallsExcluded:R.number().optional()}),eI=R.object({uri:R.string(),count:R.number(),firstLine:R.number(),firstCharacter:R.number(),lines:R.array(R.number()),hasDefinition:R.boolean().optional()}),tI=R.string(),nI=R.discriminatedUnion("kind",[R.object({kind:R.literal("definition"),locations:R.array(R.union([ic,sc]))}),R.object({kind:R.literal("typeDefinition"),locations:R.array(R.union([ic,sc]))}),R.object({kind:R.literal("implementation"),locations:R.array(R.union([ic,sc]))}),R.object({kind:R.literal("references"),locations:R.array(R.union([ic,sc])).optional(),byFile:R.array(R.union([eI,tI])).optional(),totalReferences:R.number(),totalFiles:R.number(),empty:qr.optional()}),...["callers","callees","callHierarchy"].map(e=>R.object({kind:R.literal(e),root:R.union([fS,Y_]).optional(),direction:R.enum(["incoming","outgoing","both"]),calls:R.array(R.union([X_,J_])),incomingCalls:R.number(),outgoingCalls:R.number(),completeness:Z_,empty:qr.optional()})),R.object({kind:R.literal("hover"),markdown:R.string().optional(),text:R.string().optional(),range:U_.optional()}),R.object({kind:R.literal("documentSymbols"),symbols:R.array(R.union([W_,K_])),totalSymbols:R.number().optional(),topLevelSymbols:R.number().optional(),empty:qr.optional()}),R.object({kind:R.literal("workspaceSymbol"),query:R.string(),symbols:R.array(R.unknown()),totalSymbols:R.number(),empty:qr.optional()}),R.object({kind:R.literal("typeHierarchy"),direction:R.enum(["supertypes","subtypes"]),root:R.unknown().optional(),items:R.array(R.unknown()),totalItems:R.number(),empty:qr.optional()}),R.object({kind:R.literal("diagnostic"),diagnostics:R.array(R.unknown()),totalDiagnostics:R.number(),errorCount:R.number(),warningCount:R.number(),empty:qr.optional()}),R.object({kind:R.literal("empty"),category:pS,reason:R.string()})]),lS=R.object({type:R.string(),uri:R.string(),format:R.enum(["structured","compact"]).optional(),resolvedSymbol:$_.optional(),lsp:q_,payload:nI,pagination:V_.optional(),summary:R.record(R.string(),R.unknown()).optional(),warnings:R.array(R.string()).optional()}),rI=R.object({base:R.string().optional(),shared:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])).optional(),results:R.array(R.union([R.object({id:R.string().min(1),status:R.literal("empty"),data:lS}),R.object({id:R.string().min(1),status:R.literal("error"),data:N_}),R.object({id:R.string().min(1),data:lS})]))})});import{z as sp}from"zod";function cc(e){return sI.find(t=>t.name===e)}function ac(e){return e.startsWith("gh")?"GitHub":e.startsWith("local")||e.startsWith("lsp")?"Local Code":e===V.PACKAGE_SEARCH?"Package":"Other"}function g4(e){return[...e].sort((t,n)=>{let r=mS.indexOf(ac(t)),o=mS.indexOf(ac(n));if(r!==o)return r-o;let i=gS.get(t)??Number.MAX_SAFE_INTEGER,s=gS.get(n)??Number.MAX_SAFE_INTEGER;return i!==s?i-s:t.localeCompare(n)})}function h4(e){let t=cc(e);if(!t)return"{}";try{return JSON.stringify(sp.toJSONSchema(t.inputSchema),null,2)}catch{return JSON.stringify(sp.toJSONSchema(t.schema),null,2)}}function y4(e){return JSON.stringify(e??{},null,2)}function b4(e){let t=ac(e),n=[...iI];return(t==="GitHub"||t==="Package")&&n.splice(1,0,"mainResearchGoal"),n}function R4(){return RS.map(e=>({...e}))}function S4(){return JSON.stringify(Object.fromEntries(RS.map(e=>[e.name,e.optional?`${e.type} (optional)`:e.type])),null,2)}function C4(e,t){return t?.tools?.[e]?.description??e}function SS(e){let t=cc(e);if(!t)return[];let n=sp.toJSONSchema(t.schema);if(!Vr(n))return[];let r=ln(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(i=>!dp.has(i)&&!up(r[i])):[]);return lp(r,o)}function hS(e,t){return`tools ${e} --queries '${JSON.stringify(t)}'`}function aI(e){let t=lI(e);if(t.length>0)return t.map(r=>({...r,command:hS(e,r.query)}));let n=cI(e);return Object.keys(n).length===0?[]:[{label:"schema-derived",query:n,command:hS(e,n)}]}function P4(e){return aI(e)[0]?.query??{}}function cI(e){if(!cc(e))return{};let t=SS(e),n=t.filter(i=>!i.name.includes(".")),r=yI(n),o={};for(let i of r)o[i.name]=CI(i.name,i.type);return e.startsWith("lsp")&&t.some(i=>i.name==="uri")&&(o.uri??="uri"),e===Le&&(o.type??="definition",o.symbolName??="symbolName",o.lineHint??=1),o}function lI(e){return e===Dn?[{label:"local code query",query:{schema:"oql",target:"code",from:{kind:"local",path:"."},where:{kind:"text",value:"executeDirectTool"},view:"discovery",limit:5}}]:e===V.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}}]:e===V.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}}]:e===V.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}}]:e===V.GITHUB_VIEW_REPO_STRUCTURE?[{label:"repo tree",query:{owner:"facebook",repo:"react",path:"packages",maxDepth:2,itemsPerPage:50}}]:e===V.GITHUB_CLONE_REPO?[{label:"full repo clone",query:{owner:"bgauryy",repo:"octocode"}},{label:"subtree clone",query:{owner:"facebook",repo:"react",sparsePath:"packages/react"}}]:e===V.LOCAL_RIPGREP?[{label:"text search",query:{path:".",keywords:"runCLI"}},{label:"structural code search",query:{path:"src",mode:"structural",pattern:"eval($X)"}}]:e===V.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"}}]:e===V.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}}]:e===V.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}}]:e===Le?[{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 x4(e,t,n={}){if(typeof t!="string")return null;let r;try{r=JSON.parse(t)}catch{throw new kt("Tool input must be valid JSON.")}return uI(e,r,n)}function uI(e,t,n={}){let r=pI(e,t,n),o=cc(e);if(!o)throw new kt(`Unknown tool: ${e}`);let i=o.inputSchema.safeParse(r);if(!i.success)throw new kt("Tool input does not match the expected schema.",dI(i.error));return i.data}function dI(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"input"}: ${t.message}`)}function pI(e,t,n){let r=[];if(Array.isArray(t))r=t;else if(ln(t)&&Array.isArray(t.queries))r=t.queries;else if(ln(t))r=[t];else throw new kt('Tool input must be a JSON object, an array of query objects, or { "queries": [...] }.');if(r.length===0)throw new kt("At least one query is required.");let o=ln(t)&&Array.isArray(t.queries)?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="queries")):{},i=r.map((s,a)=>fI(e,a,gI(e,s,a,n),{sourceLabel:n.sourceLabel}));return{...o,queries:i}}function fI(e,t,n,r){let o={...n},i=ac(e),s=r.sourceLabel??"direct tool execution",a=mI(e,s);return(typeof o.id!="string"||o.id.trim().length===0)&&(o.id=`${e}-${t+1}`),(i==="GitHub"||i==="Package")&&(typeof o.mainResearchGoal!="string"||o.mainResearchGoal.trim().length===0)&&(o.mainResearchGoal=a),(typeof o.researchGoal!="string"||o.researchGoal.trim().length===0)&&(o.researchGoal=a),(typeof o.reasoning!="string"||o.reasoning.trim().length===0)&&(o.reasoning=`Executed via ${s} tool command`),o}function mI(e,t){return`Execute ${e} via ${t}`}function gI(e,t,n,r={}){if(!ln(t))throw new kt("Tool input must be a JSON object or an array of objects.");let o=new Set([...SS(e).filter(a=>!a.name.includes(".")).map(a=>a.name),...dp]),i={},s=[];for(let[a,c]of Object.entries(t)){if(o.has(a)){i[a]=c;continue}s.push(a)}if(s.length>0&&o.size>0&&(r.onUnknownFields?.(s,n),r.rejectUnknownFields===!0))throw new kt(`Unknown field(s): ${s.join(", ")}`,[`Remove unknown field(s) from query ${n+1}: ${s.join(", ")}`,`Run tools ${e} --scheme to see valid fields.`]);return i}function hI(e){let t=[],n=typeof e.minimum=="number"?e.minimum:void 0,r=typeof e.maximum=="number"?e.maximum:void 0;return n!==void 0&&r!==void 0?t.push(`${n}-${r}`):n!==void 0?t.push(`>=${n}`):r!==void 0&&t.push(`<=${r}`),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t.length>0?t.join(", "):void 0}function ap(e){if(Array.isArray(e.enum)&&e.enum.length>0)return`enum(${e.enum.map(String).join(", ")})`;if(e.type==="array"){let n=Vr(e.items)?e.items:void 0;return`array<${n?ap(n):"value"}>`}let t=Array.isArray(e.anyOf)?e.anyOf:Array.isArray(e.oneOf)?e.oneOf:void 0;if(t){let n=t.filter(Vr).map(ap).filter(r=>r!=="value");if(n.length>0)return[...new Set(n)].join(" | ")}return Array.isArray(e.type)?e.type.join(" | "):typeof e.type=="string"?e.type:"value"}function yI(e){let t=e.filter(i=>i.required),n=new Map;for(let i of t)n.set(i.name,i);let r=e.filter(i=>!i.required&&bI(i)).sort(RI),o=Math.max(yS,t.length);for(let i of r){if(n.size>=o)break;n.set(i.name,i)}return n.size>0?[...n.values()]:e.filter(i=>!CS.has(i.name)).filter(i=>i.type!=="boolean").slice(0,yS)}function bI(e){return CS.has(e.name)||e.type==="boolean"?!1:SI(e)?cp.has(e.name):!0}function RI(e,t){let n=cp.get(e.name)??Number.MAX_SAFE_INTEGER,r=cp.get(t.name)??Number.MAX_SAFE_INTEGER;return n!==r?n-r:e.name.localeCompare(t.name)}function SI(e){return e.constraints?.includes("default ")===!0}function lp(e,t,n=""){let r=[];for(let[o,i]of Object.entries(e)){if(!n&&dp.has(o))continue;let s=Vr(i)?i:{},a=n?`${n}.${o}`:o;if(r.push({name:a,required:t.has(o),type:ap(s),constraints:hI(s),description:typeof s.description=="string"?s.description:void 0}),ln(s.properties)){let l=new Set(Array.isArray(s.required)?s.required.filter(u=>typeof u=="string"?!up(s.properties?.[u]):!1):[]);r.push(...lp(s.properties,l,a))}let c=s.type==="array"&&Vr(s.items)?s.items:void 0;if(c&&ln(c.properties)){let l=new Set(Array.isArray(c.required)?c.required.filter(u=>typeof u=="string"?!up(c.properties?.[u]):!1):[]);r.push(...lp(c.properties,l,a))}}return r}function CI(e,t){if(t.startsWith("array<")){let n=t.slice(6,-1);return[bS(e,n)]}return bS(e,t)}function bS(e,t){if(t.startsWith("enum("))return/^enum\(([^,)]+)/.exec(t)?.[1]??e;if(t==="integer"||t==="number")return e==="lineHint"?42:5;if(t==="boolean")return!0;switch(e){case"keywords":case"keywordsToSearch":case"query":case"text":return"runCLI";case"path":return".";case"uri":return"/path/to/file.ts";case"owner":return"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 e}}function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vr(e){return ln(e)}function up(e){return Vr(e)&&"default"in e}var mS,gS,kt,oI,dp,iI,RS,sI,yS,cp,CS,pp=y(()=>{"use strict";Pi();Gn();ra();ri();da();ii();Ra();Pa();oc();ci();li();Mr();gi();Ei();si();Hr();mS=["GitHub","Local Code","Package","Other"],gS=new Map([V.GITHUB_SEARCH_CODE,V.GITHUB_SEARCH_REPOSITORIES,V.GITHUB_SEARCH_PULL_REQUESTS,V.GITHUB_FETCH_CONTENT,V.GITHUB_VIEW_REPO_STRUCTURE,V.GITHUB_CLONE_REPO,V.LOCAL_RIPGREP,V.LOCAL_FIND_FILES,V.LOCAL_FETCH_CONTENT,V.LOCAL_VIEW_STRUCTURE,Le,V.PACKAGE_SEARCH,Dn].map((e,t)=>[e,t])),kt=class extends Error{constructor(n,r=[]){super(n);this.details=r;this.name="DirectToolInputError"}details},oI=["id","mainResearchGoal","researchGoal","reasoning"],dp=new Set([...oI]),iI=["id","researchGoal","reasoning"],RS=[{name:"content",type:"Array<{ type: string; text: string }>"},{name:"structuredContent",type:"object",optional:!0},{name:"isError",type:"boolean",optional:!0}],sI=[{name:V.GITHUB_SEARCH_CODE,schema:la,inputSchema:ua},{name:V.GITHUB_FETCH_CONTENT,schema:wr,inputSchema:oa},{name:V.GITHUB_VIEW_REPO_STRUCTURE,schema:Sa,inputSchema:Ca},{name:V.GITHUB_SEARCH_REPOSITORIES,schema:ya,inputSchema:ba},{name:V.GITHUB_SEARCH_PULL_REQUESTS,schema:Er,inputSchema:ha},{name:V.PACKAGE_SEARCH,schema:nc,inputSchema:rc},{name:V.GITHUB_CLONE_REPO,schema:ni,inputSchema:na},{name:V.LOCAL_RIPGREP,schema:rn,inputSchema:va},{name:V.LOCAL_VIEW_STRUCTURE,schema:Nr,inputSchema:Fa},{name:V.LOCAL_FIND_FILES,schema:Lr,inputSchema:Oa},{name:V.LOCAL_FETCH_CONTENT,schema:Ar,inputSchema:ka},{name:Le,schema:xi,inputSchema:wi},{name:V.LOCAL_BINARY_INSPECT,schema:Tr,inputSchema:xa},{name:Dn,schema:Ga,inputSchema:In}];yS=4,cp=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]]),CS=new Set(["page","itemsPerPage","limit","matchPage","maxFiles","maxMatchesPerFile","matchContentLength","responseCharLength","responseCharOffset"])});import{existsSync as PS}from"fs";import{delimiter as PI,dirname as xI,join as xS}from"path";function wS(){return process.platform==="win32"?"npm.cmd":"npm"}function wI(){let e=xI(process.execPath);return xS(e,wS())}function EI(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function TI(){let e=(process.env.PATH??"").split(PI).map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...EI()])]}function ES(){let e=wI();if(PS(e))return{command:process.execPath,argsPrefix:[e]};let t=wS();for(let n of TI()){let r=xS(n,t);if(PS(r))return{command:r,argsPrefix:[]}}return{command:t,argsPrefix:[]}}async function O4(e=1e4){let t=ES();return Dh(t.command,[...t.argsPrefix,"--version"],e)}async function Ti(e,t,n={}){if(!kI.includes(e))return{stdout:"",stderr:"",error:new Error(`Command '${e}' is not allowed`)};let r=Zs(t);if(!r.valid)return{stdout:"",stderr:"",error:new Error(`Invalid arguments: ${r.error}`)};let{timeout:o=3e4,cwd:i,env:s}=n,a=ES(),c=await vn(a.command,[...a.argsPrefix,e,...t],{timeout:o,cwd:i,env:s,allowEnvVars:OI});return{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode??void 0,error:c.error}}var kI,OI,fp=y(()=>{"use strict";ei();kI=["view","search","ping","config","whoami"],OI=[...Zo,...Mh]});function Oi(e){try{return new URL(e).host||e}catch{return e}}function TS(e,t=Date.now()){let n=Wr.get(Oi(e));if(!(!n||n.state==="closed")&&n.state==="open"){let r=t-n.openedAt;if(r<ki)throw new mp(Oi(e),ki-r);n.state="half-open"}}function hp(e){let t=Wr.get(Oi(e));t&&(t.failures=0,t.state="closed")}function kS(e,t=Date.now()){let n=Oi(e),r=Wr.get(n)??{failures:0,state:"closed",openedAt:0};r.state==="half-open"?(r.state="open",r.openedAt=t):(r.failures+=1,r.failures>=gp&&(r.state="open",r.openedAt=t)),Wr.set(n,r)}function L4(){Wr.clear(),gp=5,ki=3e4}function _4(e){typeof e.failureThreshold=="number"&&(gp=e.failureThreshold),typeof e.cooldownMs=="number"&&(ki=e.cooldownMs)}function OS(e,t=Date.now()){let n=Wr.get(Oi(e));return!n||n.state==="closed"?!1:n.state==="open"?t-n.openedAt<ki:!1}var A4,Wr,gp,ki,mp,lc=y(()=>{"use strict";A4=5,Wr=new Map,gp=5,ki=3e4;mp=class extends Error{retryable=!1;host;retryAfterMs;constructor(t,n){super(`Circuit open for ${t}: too many recent failures \u2014 failing fast, retry in ~${Math.ceil(n/1e3)}s.`),this.name="CircuitOpenError",this.host=t,this.retryAfterMs=n}}});function vS(e){let t=e.get("Retry-After");if(!t)return;let n=parseInt(t,10);return isNaN(n)?void 0:n}function AI(e,t,n,r){e&&Jt({limit_type:"primary",retry_after_seconds:vS(r),api_method:t,api_url:n,provider:e})}function LI(e,t,n,r,o){e.body?.cancel?.().catch(()=>{});let i=new Error(Jr.FETCH_HTTP_ERROR.message(e.status,e.statusText));return i.status=e.status,i.headers=e.headers,r&&e.status!==404&&jm(r),e.status===429&&AI(o,t,n,e.headers),i.retryable=e.status===429||e.status===408||e.status>=500&&e.status<600,i}function _I(e,t,n,r){let o=Math.min(t*Math.pow(2,e-1),n);if(o+=Math.floor(Math.random()*t),r&&r.headers&&typeof r.headers.get=="function"){let i=vS(r.headers);i!==void 0&&(o=Math.min(i*1e3,n))}return o}async function un(e,t={}){let{maxRetries:n=3,initialDelayMs:r=1e3,maxDelayMs:o=vI,headers:i={},method:s="GET",includeVersion:a=!1,signal:c,rateLimitProvider:l,packageRegistry:u}=t,d=e;if(a){let b=e.includes("?")?"&":"?";d=`${e}${b}version=${encodeURIComponent(xn)}`}let p={"User-Agent":`Octocode-MCP/${xn}`,...i},f=globalThis.fetch;if(!f)throw new Error(Jr.FETCH_NOT_AVAILABLE.message);TS(d);let m,g=n+1;for(let b=1;b<=g;b++){if(c?.aborted)throw new Error("Request aborted");try{let C=await f(d,{method:s,headers:p,signal:c});if(!C.ok)throw LI(C,s,d,u,l);if(C.status===204)return hp(d),null;let S=await C.json();return hp(d),S}catch(C){let S=C;if(c?.aborted||C instanceof Error&&C.name==="AbortError")throw new Error("Request aborted");if(S&&S.retryable===!1)throw C;if(m=C instanceof Error?C:new Error(String(C)),b===g)break;let T=_I(b,r,o,S);await new Promise(L=>setTimeout(L,T))}}throw kS(d),new Error(Jr.FETCH_FAILED_AFTER_RETRIES.message(g,m?.message||""))}var vI,yp=y(()=>{"use strict";ys();pt();ko();lc();vI=6e4});import{z as _}from"zod";var uc,II,AS,LS,bp=y(()=>{"use strict";uc=_.looseObject({name:_.string(),version:_.string(),repository:_.union([_.string(),_.object({url:_.string().optional(),type:_.string().optional(),directory:_.string().optional()})]).optional(),main:_.string().optional(),module:_.string().optional(),type:_.string().optional(),exports:_.unknown().optional(),types:_.string().optional(),typings:_.string().optional(),description:_.string().optional(),keywords:_.array(_.string()).optional(),license:_.union([_.string(),_.object({type:_.string().optional()})]).optional(),homepage:_.string().optional(),author:_.union([_.string(),_.object({name:_.string().optional(),email:_.string().optional(),url:_.string().optional()})]).optional(),maintainers:_.array(_.object({name:_.string().optional(),email:_.string().optional()})).optional(),engines:_.record(_.string(),_.string()).optional(),dependencies:_.record(_.string(),_.string()).optional(),devDependencies:_.record(_.string(),_.string()).optional(),peerDependencies:_.record(_.string(),_.string()).optional(),time:_.record(_.string(),_.string().optional()).optional()}),II=_.looseObject({package:_.looseObject({name:_.string().nullish(),version:_.string().nullish(),description:_.string().nullish(),links:_.looseObject({npm:_.string().nullish(),homepage:_.string().nullish(),repository:_.string().nullish()}).nullish()}),score:_.looseObject({final:_.number().nullish(),detail:_.looseObject({quality:_.number().nullish(),popularity:_.number().nullish(),maintenance:_.number().nullish()}).nullish()}).nullish()}),AS=_.looseObject({objects:_.array(II),total:_.union([_.number(),_.string()]).optional()}),LS=_.union([_.string(),_.boolean(),_.number(),_.null(),_.record(_.string(),_.unknown())])});async function Rp(){if(vi)return vi;try{let e=await Ti("config",["get","registry","--no-workspaces"],{timeout:1e4});if(!e.error&&e.exitCode===0){let t=e.stdout.trim().replace(/\/+$/,"");if(t&&t.startsWith("http"))return vi=t,t}}catch{}return vi=dc,dc}function V4(){vi=null}async function W4(){try{let e=await Rp(),t=globalThis.fetch;return t?(await t(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok:!1}catch{return!1}}function Hn(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function rt(e){return e===void 0?0:U(e)}async function NS(e){try{let t=`${MI}/${encodeURIComponent(e)}`,n=await un(t,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"});return{downloads:typeof n?.downloads=="number"?n.downloads:void 0,rawResponseChars:rt(n)}}catch{return{rawResponseChars:0}}}function pc(e){return e.startsWith("@")&&e.includes("/")?!0:e.includes(" ")?!1:/^[a-z0-9][a-z0-9._-]*$/i.test(e)}function GS(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("fetch failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("connect timeout")||t.includes("command timeout")||t.includes("circuit open")||t.includes("circuit breaker")}function DI(e){return e.replace(/^@/,"").replace(/[/_-]/g," ").replace(/\s+/g," ").trim()}function NI(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=Number.parseInt(e,10);if(Number.isFinite(n))return n}return t}function _S(e){if(typeof e=="string")return[e];if(!e||typeof e!="object")return;let n=Object.entries(e).flatMap(([r,o])=>typeof o=="string"?[`${r}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,s])=>`${r}:${i}:${s}`):[]).slice(0,12);return n.length>0?n:void 0}function IS(e,t){if(typeof e=="string"){let n=t?.replace(/^@[^/]+\//,"")??"";return[n?`${n} \u2192 ${e}`:e]}if(e&&typeof e=="object"){let n=Object.entries(e).filter(([,r])=>typeof r=="string").map(([r,o])=>`${r} \u2192 ${o}`).slice(0,8);return n.length>0?n:void 0}}function GI(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function Sp(e,t=!1,n="cli"){let r=null,o;e.repository&&(typeof e.repository=="string"?r=Hn(e.repository):(e.repository.url&&(r=Hn(e.repository.url)),e.repository.directory&&(o=e.repository.directory.replace(/^\.\//,""))));let i;if(e.time){let c=(e.version?e.time[e.version]:void 0)||e.time.modified;c&&(i=c)}let s={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:r,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:GI(e),...o?{repositoryDirectory:o}:{},..._S(e.exports)?{exports:_S(e.exports)}:{},...IS(e.bin,e.name)?{bin:IS(e.bin,e.name)}:{},lastPublished:i,source:n};return e.description&&(s.description=e.description),e.license&&(s.license=typeof e.license=="string"?e.license:e.license.type),t&&(e.author&&(typeof e.author=="string"?s.author=e.author:e.author.name&&(s.author=e.author.name)),e.keywords&&e.keywords.length>0&&(s.keywords=e.keywords),e.homepage&&(s.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(s.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(s.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(s.peerDependencies=e.peerDependencies)),s}function HI(e){return typeof e.links?.repository=="string"?Hn(e.links.repository):typeof e.repository=="string"?Hn(e.repository):typeof e.repository?.url=="string"?Hn(e.repository.url):null}function zI(e){if(!e.name)return null;let t=(e.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,n=e.links?.homepage??void 0;return{name:e.name,npmUrl:t,repoUrl:HI(e),version:e.version??"unknown",source:"cli",...e.description?{description:e.description}:{},...n?{homepage:n}:{},...e.keywords&&e.keywords.length>0?{keywords:e.keywords}:{}}}function HS(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}async function zS(e){try{let t=await Rp(),n=HS(e),r=`${t}/${n}`,o=AbortSignal.timeout(8e3);try{let s=await un(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/vnd.npm.install-v1+json"},signal:o,packageRegistry:"npm"}),a=rt(s);if(s?.modified)return{lastPublished:s.modified,rawResponseChars:a}}catch{}let i=await un(r,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:o,packageRegistry:"npm"});return{lastPublished:i?.time?.modified||void 0,rawResponseChars:rt(i)}}catch{return{rawResponseChars:0}}}async function Cp(e,t,n){let[r,o]=await Promise.all([NS(e),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):zS(e)]);return r.downloads!==void 0&&(t.weeklyDownloads=r.downloads),o.lastPublished&&!t.lastPublished&&(t.lastPublished=o.lastPublished),{pkg:t,rawResponseChars:n+r.rawResponseChars+o.rawResponseChars}}function fc(e){let t=e.toLowerCase();return t.includes("404")||t.includes("not found")||t.includes("e404")}async function BI(e,t){try{let n=await Ti("view",[e,"--json"],{timeout:FI});if(!n)return{pkg:null,rawResponseChars:0};if(n.error||n.exitCode!==0){let c=n.error?.message||n.stderr||`npm exited ${n.exitCode}`;return{pkg:null,...fc(c)?{}:{errorDetail:c},rawResponseChars:rt(n.stdout)}}let r=n.stdout.trim();if(!r||r==="undefined")return{pkg:null,rawResponseChars:0};let o;try{o=JSON.parse(r)}catch{return{pkg:null,errorDetail:"Invalid npm view JSON output",rawResponseChars:r.length}}let i=rt(o),s=uc.safeParse(o);return s.success?{pkg:Sp(s.data,t,"cli"),rawResponseChars:i}:{pkg:null,errorDetail:"Invalid npm view response format",rawResponseChars:i}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...fc(r)?{}:{errorDetail:r},rawResponseChars:0}}}async function QI(e,t){try{let n=await Rp(),r=HS(e),o=`${n}/${r}/latest`,i;try{i=await un(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("404")||u.toLowerCase().includes("not found")?{pkg:null,rawResponseChars:0}:{pkg:null,errorDetail:u,rawResponseChars:0}}let s=rt(i);if(!i||typeof i!="object")return{pkg:null,rawResponseChars:s};let a=uc.safeParse(i);return a.success?{pkg:Sp(a.data,t,"registry"),rawResponseChars:s}:{pkg:null,errorDetail:"Invalid npm registry response format",rawResponseChars:s}}catch(n){let r=n instanceof Error?n.message:String(n);return{pkg:null,...fc(r)?{}:{errorDetail:r},rawResponseChars:0}}}function UI(e){return[`https://cdn.jsdelivr.net/npm/${e}/package.json`,`https://unpkg.com/${e}/package.json`]}async function BS(e,t){let n=0,r;for(let o of UI(e)){let i;try{i=await un(o,{maxRetries:0,initialDelayMs:300,headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(c){let l=c instanceof Error?c.message:String(c);fc(l)||(r=l);continue}if(n+=rt(i),!i||typeof i!="object")continue;let s=uc.safeParse(i);if(!s.success){r="Invalid npm CDN package.json response format";continue}return{pkg:Sp(s.data,t,"cdn"),rawResponseChars:n}}return{pkg:null,...r?{errorDetail:r}:{},rawResponseChars:n}}async function Pp(e,t=!1){let[n,r]=await Promise.allSettled([BI(e,t),QI(e,t)]),o=n.status==="fulfilled"?n.value:{pkg:null,rawResponseChars:0},i=r.status==="fulfilled"?r.value:{pkg:null,rawResponseChars:0},s=o.pkg?o:i.pkg?i:null;return s?.pkg?Cp(e,s.pkg,s.rawResponseChars):{pkg:null,errorDetail:o.errorDetail||i.errorDetail,rawResponseChars:o.rawResponseChars+i.rawResponseChars}}async function jI(e,t,n=!1){let{pkg:r,errorDetail:o,rawResponseChars:i}=await Pp(e,t);if(!r){if(o){let s=GS(o);if(s&&n){let a=await BS(e,t);if(a.pkg){let c=await Cp(e,a.pkg,a.rawResponseChars);return{packages:c.pkg?[c.pkg]:[],totalFound:c.pkg?1:0,rawResponseChars:i+c.rawResponseChars}}}return{error:`NPM view failed for '${e}': ${o}`,rawResponseChars:i,hints:s?["npm registry is unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]:["Ensure npm is installed and available in PATH","Check package name for typos",`Try: npm view ${e} --json`]}}return{packages:[],totalFound:0,rawResponseChars:i}}return{packages:[r],totalFound:1,rawResponseChars:i}}async function $I(e,t,n,r=0){let o=Math.max(t+r,t),i=await Ti("search",[e,"--json","--searchlimit",String(o)],{timeout:8e3});if(!i)return{error:"NPM CLI search unavailable",rawResponseChars:0};if(i.error||i.exitCode!==0)return{error:`NPM CLI search failed: ${i.error?.message||i.stderr||`npm exited ${i.exitCode}`}`,rawResponseChars:rt(i.stdout)};let s=i.stdout.trim();if(!s)return{packages:[],totalFound:0,rawResponseChars:0};let a;try{a=JSON.parse(s)}catch{return{error:"Invalid npm search JSON output",rawResponseChars:s.length}}let c=rt(a);if(!Array.isArray(a))return{error:"Invalid npm search response format",rawResponseChars:c};let u=[...a].sort((m,g)=>{let b=m?.score?.final??0;return(g?.score?.final??0)-b}).slice(r,r+t),d=await Promise.all(u.map(async m=>{if(!m||typeof m!="object")return null;let g=m;if(!g.name)return null;if(n){let b=await Pp(g.name,!0);if(b.pkg)return b}return{pkg:zI(g),rawResponseChars:0}})),p=d.map(m=>m?.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+(g?.rawResponseChars??0),0);return{packages:p,totalFound:a.length,rawResponseChars:c+f}}async function qI(e,t,n,r=0){try{let o=r>0?`&from=${r}`:"",i=`${dc}/-/v1/search?text=${encodeURIComponent(e)}&size=${t}${o}`,s;try{s=await un(i,{maxRetries:1,initialDelayMs:500,signal:AbortSignal.timeout(8e3),packageRegistry:"npm"})}catch(m){return{error:`NPM registry search failed: ${m instanceof Error?m.message:String(m)}`,hints:["Check package name for typos","Try searching with a simpler term"]}}let a=rt(s);if(!s||typeof s!="object")return{packages:[],totalFound:0,rawResponseChars:a};let c=AS.safeParse(s);if(!c.success)return{error:`Invalid npm registry search response format: ${c.error.issues.map(g=>g.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Try itemsPerPage=1 for an exact package lookup"]};let u=[...c.data.objects].sort((m,g)=>{let b=m.score?.final??0;return(g.score?.final??0)-b}).map(m=>m.package).filter(m=>typeof m.name=="string"&&m.name.length>0).slice(0,t),d=await Promise.all(u.map(async m=>{if(n){let g=await Pp(m.name,!0);if(g.pkg)return g}return{pkg:{name:m.name,npmUrl:(m.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(m.name)}`,repoUrl:m.links?.repository&&typeof m.links.repository=="string"?Hn(m.links.repository):null,version:m.version??"unknown",source:"registry",...m.description?{description:m.description}:{},...m.links?.homepage?{homepage:m.links.homepage}:{}},rawResponseChars:0}})),p=d.map(m=>m.pkg).filter(m=>!!m),f=d.reduce((m,g)=>m+g.rawResponseChars,0);return{packages:p,totalFound:NI(c.data.total,p.length),rawResponseChars:a+f}}catch(o){return{error:`NPM registry search failed: ${o instanceof Error?o.message:String(o)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function FS(e,t){let n="https://api.npms.io/v2/search",r="octocode-mcp/1.0 (+https://github.com/bgauryy/octocode-mcp)";try{let o=`${n}?q=${encodeURIComponent(e)}&size=${t}`,i;try{i=await un(o,{maxRetries:1,initialDelayMs:500,headers:{Accept:"application/json","User-Agent":r},signal:AbortSignal.timeout(8e3)})}catch(c){return{error:`Web search failed: ${c instanceof Error?c.message:String(c)}`}}if(!i||typeof i!="object")return{packages:[],totalFound:0,rawResponseChars:rt(i)};let s=i;if(!Array.isArray(s.results))return{packages:[],totalFound:0,rawResponseChars:rt(i)};let a=s.results.slice(0,t).map(c=>c.package).filter(c=>typeof c?.name=="string"&&c.name.length>0).map(c=>({name:c.name,npmUrl:c.links?.npm??`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?Hn(c.links.repository):null,version:c.version??"unknown",source:"web",...c.description?{description:c.description}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}}));return{packages:a,totalFound:typeof s.total=="number"?s.total:a.length,rawResponseChars:rt(i)}}catch(o){return{error:`Web search failed: ${o instanceof Error?o.message:String(o)}`}}}async function MS(e,t,n,r=0){try{let o=await $I(e,t,n,r);if(!("error"in o))return o}catch{}return qI(e,t,n,r)}async function DS(e){if(e.packages.length===0)return e;let t=e.packages[0];if(t.weeklyDownloads!==void 0&&t.lastPublished)return e;let[n,r]=await Promise.all([t.weeklyDownloads!==void 0?Promise.resolve({downloads:void 0,rawResponseChars:0}):NS(t.name),t.lastPublished?Promise.resolve({lastPublished:void 0,rawResponseChars:0}):zS(t.name)]),o={...t};return n.downloads!==void 0&&(o.weeklyDownloads=n.downloads),r.lastPublished&&(o.lastPublished=r.lastPublished),{...e,packages:[o,...e.packages.slice(1)]}}async function QS(e,t,n,r=0){let o=He("npm-search",{name:e,limit:t,metadata:n,from:r});return ze(o,async()=>{if(OS(dc)){if(r===0&&t===1&&pc(e)){let u=await BS(e,n);if(u.pkg){let d=await Cp(e,u.pkg,u.rawResponseChars);return{packages:d.pkg?[d.pkg]:[],totalFound:d.pkg?1:0,rawResponseChars:d.rawResponseChars}}}let l=await FS(e,t);return!("error"in l)&&l.packages.length>0?l:{error:"npm registry circuit open and web search returned no results.",hints:["Use `ghSearchRepos` to find the source repo directly."]}}if(r===0&&pc(e)){let l=await jI(e,n,t===1);if("error"in l){if(!GS(l.error))return l}else if(l.packages.length>0||t===1)return l}let s=await MS(e,t,n,r);if(!("error"in s)&&s.packages.length>0)return DS(s);let a=DI(e);if(a!==e){let l=await MS(a,t,n,r);if(!("error"in l)&&l.packages.length>0)return DS(l)}let c=await FS(e,t);return!("error"in c)&&c.packages.length>0?c:"error"in s?{...s,hints:["npm registry and web search (npms.io) are both unreachable.","Use `ghSearchRepos` to find the source repo directly by package name or domain terms."]}:s},{shouldCache:i=>!("error"in i||"totalFound"in i&&i.totalFound===0)})}async function VI(e){try{let t=await Ti("view",[e,"deprecated","--json"]);if(t.error||t.exitCode!==0)return null;let n=t.stdout.trim();if(!n||n==="undefined"||n==="")return{deprecated:!1};try{let r=JSON.parse(n),o=LS.safeParse(r),i=o.success?o.data:n;return{deprecated:!0,message:typeof i=="string"?i:"This package is deprecated"}}catch{return{deprecated:!0,message:n}}}catch{return null}}var dc,FI,vi,MI,xp=y(()=>{"use strict";fp();yp();Mt();lc();bp();oe();dc="https://registry.npmjs.org",FI=3e3,vi=null;MI="https://api.npmjs.org/downloads/point/last-week"});async function US(e){let t=pc(e.name),n=e.itemsPerPage??(t?1:10),r=Math.max(0,((e.page??1)-1)*n);return QS(e.name,n,!0,r)}var wp=y(()=>{"use strict";xp()});function WI(e){return"error"in e}function mc(e){return"npmUrl"in e}function KI(e){return mc(e)&&e.path?e.path:e.name}function YI(e){return mc(e)?e.repoUrl:e.repository}function XI(e){if(!e)return;let t=e.replace(/^\.\//,"").replace(/^\//,"");return t.length>0?t:void 0}function JI(e){if(!e)return;let t=e.trim();if(!t)return;t=t.replace(/^git\+/,"");let n=i=>i.replace(/\.git$/,""),r=t.match(/^[^@/]+@([^:/]+):(.+)$/);if(r&&r[1]&&r[2])return n(`https://${r[1]}/${r[2]}`);let o=t.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(o&&o[1]){let i=o[1].replace(/^[^@/]+@/,"");return n(`https://${i}`)}return n(t)}function jS(e){if(!e)return;let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!t||!t[1]||!t[2]))return{owner:t[1],repo:t[2]}}function $S(e,t){let n=jS(e);if(!n)return;let{owner:r,repo:o}=n;return{viewRepoStructure:{tool:"ghViewRepoStructure",query:{owner:r,repo:o,...t?{path:t}:{}}},searchCode:{tool:"ghSearchCode",query:{owner:r,repo:o}},cloneRepo:{tool:"ghCloneRepo",query:{owner:r,repo:o,...t?{sparsePath:t}:{}}}}}function ZI(e){let t=KI(e),n=JI(YI(e)),r={name:t};mc(e)&&(e.version&&e.version!=="unknown"&&(r.version=e.version),e.description&&(r.description=e.description),e.license&&(r.license=e.license),typeof e.weeklyDownloads=="number"&&(r.downloads=e.weeklyDownloads)),n&&(r.repository=n);let o=XI(mc(e)?e.repositoryDirectory:void 0);o&&(r.repositoryDirectory=o);let i=$S(n,o);return i&&(r.next=i),r}function eF(e){if(e.length<=1)return{packages:e};let t={},n=new Map,r=1,o=e.map(i=>{if(!i.repository)return i;let s=jS(i.repository);if(!s)return i;let a=`${i.repository}\0${i.repositoryDirectory??""}`,c=n.get(a);c||(c=`r${r++}`,n.set(a,c),t[c]={repository:i.repository,owner:s.owner,repo:s.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:$S(i.repository,i.repositoryDirectory)});let{repository:l,repositoryDirectory:u,next:d,...p}=i;return{...p,repositoryId:c}});return Object.keys(t).length?{packages:o,repositories:t}:{packages:e}}function tF(e,t,n,r){let o=Math.max(1,e.page??1),i=r?10:1,s=r&&n>=i,a=Math.max(1,Math.ceil(t/i)),c=s||o<a,l=s&&o>=a?o+1:a;return{currentPage:o,totalPages:l,perPage:i,totalFound:t,returned:n,hasMore:c,...c?{nextPage:o+1}:{}}}async function qS(e){return se(e.queries,async t=>{try{if(!t.packageName)return M("Package name is required for package search",t);let n=await US({name:t.packageName,page:t.page,itemsPerPage:t.itemsPerPage,mainResearchGoal:t.mainResearchGoal,researchGoal:t.researchGoal,reasoning:t.reasoning});if(WI(n))return M(n.error,t,{rawResponse:n});let r=n.packages,o=r.map(ZI),i=o.length>0,s=r.length>1||n.totalFound>1,a=tF(t,n.totalFound,o.length,s),l={...eF(o),pagination:a};return Fe(t,l,i,A.PACKAGE_SEARCH,{rawResponse:n.rawResponseChars??n})}catch(n){return M(n,t,{toolName:A.PACKAGE_SEARCH})}},{toolName:A.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}var Ep=y(()=>{"use strict";wp();je();De();fe()});import{safeReadFile as nF}from"@octocodeai/octocode-engine/lsp/validation";function Ai(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function WS(e,t,n){if(t<=0)return e;let r=await nF(e.uri);if(!r)return e;let o=Ho(r),i=n?.[0]?.start.line??e.range.start.line,s=Math.max(0,i-t),a=Math.min(o.length-1,i+t),c=o.slice(s,a+1).map((l,u)=>{let d=s+u+1;return`${d===i+1?">":" "}${String(d).padStart(4," ")}| ${l}`}).join(`
55
+ `);return{...e,content:c,displayRange:{startLine:s+1,endLine:a+1}}}async function rF(e,t){return Promise.all(e.map(async n=>({...n,from:await WS(n.from,t,n.fromRanges)})))}async function oF(e,t){return Promise.all(e.map(async n=>({...n,to:await WS(n.to,t)})))}async function Tp(e,t,n,r,o){if(n<=0||!e)return{calls:[],...VS};try{let i=await e.getIncomingCalls(t),s=o>0?await rF(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Ai(c.from);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),Tp(e,c.from,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}async function kp(e,t,n,r,o){if(n<=0||!e)return{calls:[],...VS};try{let i=await e.getOutgoingCalls(t),s=o>0?await oF(i,o):i;if(n===1)return{calls:s,truncatedByDepth:s.length>0,cycleCount:0,failedRequestCount:0};let a=await Promise.all(s.map(async c=>{let l=Ai(c.to);return r.has(l)?{calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0}:(r.add(l),kp(e,c.to,n-1,r,o))}));return{calls:[...s,...a.flatMap(c=>c.calls)],truncatedByDepth:a.some(c=>c.truncatedByDepth),cycleCount:a.reduce((c,l)=>c+l.cycleCount,0),failedRequestCount:a.reduce((c,l)=>c+l.failedRequestCount,0)}}catch{return{calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1}}}var VS,Op=y(()=>{"use strict";Rr();VS={truncatedByDepth:!1,cycleCount:0,failedRequestCount:0}});import{readFile as iF,stat as sF}from"node:fs/promises";import{SymbolResolver as aF,SymbolResolutionError as cF}from"@octocodeai/octocode-engine/lsp/resolver";import{LSP_ERROR_CODES as gc}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";async function vp(e,t){let n=e.uri,r=Ke({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{if((await sF(o)).isDirectory())return{ok:!1,error:{status:"error",error:`Path is a directory, not a file: ${o}. lspGetSemantics needs a single file uri.`,errorType:"not_a_file",errorCode:gc.LSP_REQUEST_FAILED,hints:["Pass the path to a specific source file (e.g. via search --op on a file, or workspaceSymbol with symbolName for whole-project lookup)."]}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}. Check the path and spelling.`,errorType:"file_not_found",errorCode:gc.LSP_REQUEST_FAILED,hints:[`Could not find file: ${n??"<missing>"}. Run search/localFindFiles to get the exact path first.`]}}}try{return{ok:!0,value:{uri:o,absolutePath:o,content:await iF(o,"utf-8")}}}catch(i){return{ok:!1,error:{status:"error",error:i instanceof Error?i.message:String(i),errorType:"file_not_found",errorCode:gc.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function KS(e,t){let n=await vp(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new aF({lineSearchRadius:5});try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),i=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`,"g"),a=(n.value.content.match(s)??[]).length,c=Math.abs(o.foundAtLine-(e.lineHint??0)),l=a>1&&c>3?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.absolutePath,range:lF(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...l&&{isAmbiguous:l}}}}}catch(o){if(o instanceof cF)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:gc.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,"Run localSearchCode with the exact symbol name to refresh lineHint, then retry."]}};throw o}}function lF(e){return{start:e,end:{line:e.line,character:e.character}}}var Ap=y(()=>{"use strict";Et()});import Li from"node:path";import{fileURLToPath as uF}from"node:url";import{acquirePooledClient as yc,isLanguageServerAvailable as bc,unavailableHintFor as dF}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as pF}from"@octocodeai/octocode-engine/lsp/config";import{resolveImportAliasDefinitions as fF}from"@octocodeai/octocode-engine/lsp/resolver";import{resolveWorkspaceRootForFile as Ip}from"@octocodeai/octocode-engine/lsp/workspaceRoot";function mF(e){return Lp||(Lp=new Set(F.getSupportedJsTsExtensions().map(t=>`.${t}`))),Lp.has(Li.extname(e).toLowerCase())}function zn(e,t){let n=pF(e),r=dF(n,void 0);throw new Oe(Q.LSP_SERVER_UNAVAILABLE,`No ${n} language server is available for ${e}, so "${t}" cannot be answered semantically. ${r} Meanwhile, use localSearchCode (text or structural search) to find the symbol's occurrences and localGetFileContent to read the surrounding code.`)}function hF(e,t){let n=e.startsWith("file://")?uF(e):e;return Li.isAbsolute(n)?n:Li.resolve(t,n)}function ZS(){return[...F.getSupportedJsTsExtensions(),...gF]}function yF(){return ZS().map(e=>`**/*.${e}`)}async function RF(e,t){let n=e.symbolName?.trim();if(n)try{return(await F.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:yF(),excludeDir:[...bF],maxSnippetChars:1})).files[0]?.path}catch{return}}async function SF(e,t){if(e.uri)return hF(e.uri,t);let n=await RF(e,t);if(n)return n;try{let o=F.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:ZS(),maxDepth:5,limit:1}).entries[0];if(o)return o.path}catch{}return t}function CF(e){return e instanceof Error?e.message:String(e)}function PF(e,t){if(!mF(e))return null;try{let n=F.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}async function Fp(e){return se(e.queries||[],async t=>Ve({toolName:Le,query:t,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let n=await FF(t);return EF(TF(t,n))}}),{toolName:Le,minQueryTimeoutMs:3e4},e)}function EF(e){return $(e,U(e))}function TF(e,t){return e.format!=="compact"||!kF(t)?t:OF(t)}function kF(e){return Bn(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&Bn(e.payload)}function OF(e){return{...e,format:"compact",payload:vF(e.payload)}}function vF(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{kind:e.kind,locations:e.locations.map(YS)};case"references":return{kind:"references",...e.byFile?{byFile:e.byFile.map(LF)}:{locations:(e.locations??[]).map(YS)},totalReferences:e.totalReferences,totalFiles:e.totalFiles};case"callers":case"callees":case"callHierarchy":return{kind:e.kind,...e.root?{root:tC(e.root)}:{},direction:e.direction,calls:e.calls.map(_F),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{kind:"documentSymbols",symbols:e.symbols.map(AF)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function AF(e){if(!Bn(e))return String(e);let t=Ye(e,"line"),n=Ye(e,"character"),r=Ye(e,"endLine"),o=Ut(e,"kind"),i=Ut(e,"name"),s=Ye(e,"childCount"),a=Ut(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,i,a?`< ${a}`:"",s>0?`children=${s}`:""].filter(Boolean).join(" ")}function YS(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${rC(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function LF(e){if(!Bn(e))return String(e);let t=Ut(e,"uri"),n=Ye(e,"firstLine"),r=Ye(e,"firstCharacter"),o=Ye(e,"count"),i=nC(e,"lines").map(a=>typeof a=="number"?a:void 0).filter(a=>a!==void 0).join(","),s=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${i}${s}`}function _F(e){if(!Bn(e))return String(e);let t=Ut(e,"direction"),n=tC(e.item),r=nC(e,"ranges").map(IF).join(","),o=Ye(e,"rangeCount"),i=Ye(e,"rangeSampleCount"),s=Ut(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>i?`totalRanges=${o}`:"",s?`| ${rC(s,180)}`:""].filter(Boolean).join(" ")}function tC(e){if(!Bn(e))return String(e);let t=Ut(e,"name"),n=Ut(e,"kind"),r=Ut(e,"uri"),o=Ye(e,"line"),i=Ye(e,"endLine"),s=Ye(e,"selectionLine"),a=s>0?` sel=${s}`:"";return`${t} ${n} ${r}:${o}-${i}${a}`}function IF(e){return Bn(e)?`${Ye(e,"line")}:${Ye(e,"character")}`:String(e)}function Bn(e){return typeof e=="object"&&e!==null}function Ut(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function Ye(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function nC(e,t){let n=e[t];return Array.isArray(n)?n:[]}function rC(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}async function FF(e){if(e.type==="documentSymbols")return MF(e);if(e.type==="workspaceSymbol")return HF(e);if(e.type==="diagnostic")return QF(e);let t=await KS(e,Le);if(t.ok===!1){let i=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return JF(e,i)}let n=e.workspaceRoot??await Ip(t.value.uri);await bc(t.value.uri,n)||zn(t.value.uri,e.type);let o=await yc(n,t.value.uri);switch(o||zn(t.value.uri,e.type),e.type){case"definition":return o.hasCapability("definitionProvider")?_p(e,t.value,"definition","definitionProvider",await fF({anchorUri:t.value.uri,symbolName:t.value.resolvedSymbol.name,locations:await o.gotoDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)})):Qt(e.type,t.value,"definitionProvider unsupported",!0);case"typeDefinition":return o.hasCapability("typeDefinitionProvider")?_p(e,t.value,"typeDefinition","typeDefinitionProvider",await o.typeDefinition(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Qt(e.type,t.value,"typeDefinitionProvider unsupported",!0);case"implementation":return o.hasCapability("implementationProvider")?_p(e,t.value,"implementation","implementationProvider",await o.implementation(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Qt(e.type,t.value,"implementationProvider unsupported",!0);case"references":return o.hasCapability("referencesProvider")?DF(e,t.value,await o.findReferences(t.value.uri,t.value.resolvedSymbol.position,e.includeDeclaration??!0,t.value.content)):Qt(e.type,t.value,"referencesProvider unsupported",!0);case"hover":return o.hasCapability("hoverProvider")?NF(e,t.value,await o.hover(t.value.uri,t.value.resolvedSymbol.position,t.value.content)):Qt(e.type,t.value,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return o.hasCapability("callHierarchyProvider")?GF(e,t.value,o):Qt(e.type,t.value,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return o.hasCapability("typeHierarchyProvider")?BF(e,t.value,o):Qt(e.type,t.value,"typeHierarchyProvider unsupported",!0)}}async function MF(e){let t=await vp(e,Le);if(t.ok===!1)return t.error;let n=e.workspaceRoot??await Ip(t.value.uri),r=await bc(t.value.uri,n),o=r?await yc(n,t.value.uri):null,i=!!o?.hasCapability("documentSymbolProvider"),s=[],a,c=PF(t.value.uri,t.value.content);if(c?.length)s=c,a="native";else if(i&&o){let b=await o.documentSymbols(t.value.uri,t.value.content);s=Array.isArray(b)?b:[],a="lsp"}else{let b=Hg(t.value.content,t.value.uri);b&&(s=b,a="markdown")}let l=a!==void 0;!l&&!r&&zn(t.value.uri,"documentSymbols");let u=$F(s),d=WF(s),{pageItems:p,pagination:f}=Qn(u,e.page??1,e.itemsPerPage??Rc),m=KF(u,b=>b.kind),g=l?void 0:{category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"};return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:r,...a==="lsp"?{provider:"documentSymbolProvider"}:{},...a?{source:a}:{}},summary:{totalSymbols:u.length,returnedSymbols:p.length,topLevelSymbols:d,kinds:m},payload:{kind:"documentSymbols",symbols:p,...g?{empty:g}:{}},pagination:f}}function _p(e,t,n,r,o){let i=o.length>0,s=o.map(ip),{pageItems:a,pagination:c}=Qn(s,e.page??1,e.itemsPerPage??eC);return{type:e.type,uri:t.uri,resolvedSymbol:Nn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:a}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`},...i?{pagination:c}:{}}}function DF(e,t,n){let r=n.map(l=>{let u=l.uri===t.uri&&l.range.start.line===t.resolvedSymbol.position.line&&l.range.start.character===t.resolvedSymbol.position.character;return{...l,...u?{isDefinition:!0}:{}}}),o=e.groupByFile?ZF(r):void 0,i=o??r.map(ip),{pageItems:s,pagination:a}=Qn(i,e.page??1,e.itemsPerPage??eC),c=r.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0;return{type:"references",uri:t.uri,resolvedSymbol:Nn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...o?{byFile:s}:{locations:s},totalReferences:r.length,totalFiles:new Set(r.map(l=>l.uri)).size,...c?{empty:c}:{}},pagination:a}}async function NF(e,t,n){let r=e0(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:Nn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}async function GF(e,t,n){let o=(await n.prepareCallHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Qt(e.type,t,"No callable symbol found",!0);let i=e.depth??1,s={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a=e.type==="callers"||e.type==="callHierarchy"?await Tp(n,o,i,new Set([Ai(o)]),e.contextLines??0):s,c=e.type==="callees"||e.type==="callHierarchy"?await kp(n,o,i,new Set([Ai(o)]),e.contextLines??0):s,l=S=>/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(S.to.uri),u=c.calls.filter(l).length,d=c.calls.filter(S=>!l(S)),p=[...a.calls.map(S=>({direction:"incoming",...S})),...d.map(S=>({direction:"outgoing",...S}))],f=p.map(S=>S.direction==="incoming"?YF(S,e.contextLines??0):XF(S,e.contextLines??0)),{pageItems:m,pagination:g}=Qn(f,e.page??1,e.itemsPerPage??xF),b=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",C=!a.truncatedByDepth&&!c.truncatedByDepth&&a.failedRequestCount+c.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:Nn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Mp(o),direction:b,calls:m,incomingCalls:a.calls.length,outgoingCalls:d.length,completeness:{complete:C,truncatedByDepth:a.truncatedByDepth||c.truncatedByDepth,cycleCount:a.cycleCount+c.cycleCount,failedRequestCount:a.failedRequestCount+c.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:"callHierarchyProvider returned no calls"}}:{}},pagination:g}}async function HF(e){let t=e.symbolName??"",n=Li.resolve(e.workspaceRoot??process.cwd()),r=await SF(e,n);await bc(r,n)||zn(r,"workspaceSymbol");let i=await yc(n,r);if(i||zn(r,"workspaceSymbol"),!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};let s;try{Li.extname(r)&&await i.openDocument(r),s=await i.workspaceSymbol(t)}catch(u){return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:`workspaceSymbolProvider failed: ${CF(u)}`}}}let a=zF(s),{pageItems:c,pagination:l}=Qn(a,e.page??1,e.itemsPerPage??Rc);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:a.length},payload:a.length>0?{kind:"workspaceSymbol",query:t,symbols:c,totalSymbols:a.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:l}}function zF(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,i=n.location,s=i?.range,a=typeof i?.uri=="string"?i.uri:"",c=(s?.start?.line??0)+1,l=(s?.end?.line??s?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:hc(o),line:c,character:s?.start?.character??0,endLine:l,childCount:0,...u?{containerName:u}:{},uri:a}]})}async function BF(e,t,n){let o=(await n.prepareTypeHierarchy(t.uri,t.resolvedSymbol.position,t.content))[0];if(!o)return Qt(e.type,t,"No type-hierarchy item found at position",!0);let i=e.type==="supertypes"?"supertypes":"subtypes",s=i==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:a,pagination:c}=Qn(s,e.page??1,e.itemsPerPage??Rc);return{type:e.type,uri:t.uri,resolvedSymbol:Nn(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:s.length>0?{kind:"typeHierarchy",direction:i,root:o,items:a,totalItems:s.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${i} for this symbol`},pagination:c}}async function QF(e){let t=e.uri??"",n=e.workspaceRoot??(t?await Ip(t):process.cwd());await bc(t,n)||zn(t,"diagnostic");let o=await yc(n,t);if(o||zn(t,"diagnostic"),!o.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let i=await o.getDiagnostics(t),s=UF(i),a=s.filter(d=>d.severity===1).length,c=s.filter(d=>d.severity===2).length,{pageItems:l,pagination:u}=Qn(s,e.page??1,e.itemsPerPage??Rc);return{type:"diagnostic",uri:t,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:s.length,errorCount:a,warningCount:c},payload:s.length>0?{kind:"diagnostic",diagnostics:l,totalDiagnostics:s.length,errorCount:a,warningCount:c}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:u}}function UF(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>jF(r))}return[]}function jF(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}function Qn(e,t,n){let r=Math.max(1,n),o=Math.max(1,Math.ceil(e.length/r)),i=Math.min(Math.max(1,t),o),s=(i-1)*r,a=e.slice(s,s+r),c=i<o;return{pageItems:a,pagination:{currentPage:i,totalPages:o,totalResults:e.length,hasMore:c,itemsPerPage:r,...c?{nextPage:i+1}:{}}}}function $F(e){let t=[];for(let n of e)oC(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function oC(e,t,n){if(!e||typeof e!="object")return;let r=e,o=VF(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:hc(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&qF.has(hc(r.kind))){let i=typeof r.name=="string"?r.name:n;for(let s of r.children)oC(s,t,i)}}function VF(e){if(XS(e.range))return e.range;let t=e.location;return t&&XS(t.range)?t.range:void 0}function XS(e){if(!e||typeof e!="object")return!1;let t=e;return JS(t.start)&&JS(t.end)}function JS(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function WF(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function KF(e,t){let n={};for(let r of e){let o=t(r);n[o]=(n[o]??0)+1}return n}function YF(e,t){let n=iC(e.fromRanges);return{direction:"incoming",item:Mp(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...sC(e.from,t)}}function XF(e,t){let n=iC(e.fromRanges);return{direction:"outgoing",item:Mp(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,...sC(e.to,t)}}function Mp(e){return{name:e.name,kind:hc(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function iC(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,i=r.start.character,s=`${o}:${i}`;if(!t.has(s)&&(t.add(s),n.push({line:o,character:i}),n.length>=wF))break}return n}function sC(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function hc(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}function aC(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function JF(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:aC(e.type,t),reason:t}}}function Qt(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:Nn(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:aC(e,n),reason:n}}}function ZF(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function e0(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>t0(r)).join(`
56
+ `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function t0(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var Lp,gF,bF,Rc,eC,xF,wF,qF,Sc=y(()=>{"use strict";je();oe();Ht();eo();mn();Op();Gn();Ap();be();Ms();gF=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","lua","dart","ex","exs","erl","hrl","clj","cljs"];bF=[".git","node_modules","dist","out","coverage","target"];Rc=40,eC=40,xF=10,wF=8;qF=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"])});var Dp,Np=y(()=>{"use strict";fe();Dp={hasTool(e){return Nl(e)},getDescription(e){return Ml[e]??""},getToolName(e){return A[e]??String(e)}}});function n0(e,t){return t.getToolName(e)}function ut(e,t,n){let r=n0(t,e);return{...n,name:r,description:Gp(r,e)}}function r0(e=Dp){let t=ut(e,"GITHUB_SEARCH_CODE",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:la,inputSchema:ua,executionFn:Ey,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),n=ut(e,"GITHUB_FETCH_CONTENT",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:wr,inputSchema:oa,executionFn:Py,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),r=ut(e,"GITHUB_VIEW_REPO_STRUCTURE",{isDefault:!0,isLocal:!1,type:"content",direct:{schema:Sa,inputSchema:Ca,executionFn:jy,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),o=ut(e,"GITHUB_SEARCH_REPOSITORIES",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:ya,inputSchema:ba,executionFn:By,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),i=ut(e,"GITHUB_SEARCH_PULL_REQUESTS",{isDefault:!0,isLocal:!1,type:"history",direct:{schema:Er,inputSchema:ha,executionFn:My,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),s=ut(e,"PACKAGE_SEARCH",{isDefault:!0,isLocal:!1,type:"search",direct:{schema:nc,inputSchema:rc,executionFn:qS,security:"remote",requiresServerRuntime:!0}}),a=ut(e,"GITHUB_CLONE_REPO",{isDefault:!0,isLocal:!0,isClone:!0,type:"content",skipMetadataCheck:!0,direct:{schema:ni,inputSchema:na,executionFn:ny,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}}),c=ut(e,"LOCAL_RIPGREP",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:rn,inputSchema:va,executionFn:Bb,security:"basic"}}),l=ut(e,"LOCAL_VIEW_STRUCTURE",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Nr,inputSchema:Fa,executionFn:Yb,security:"basic"}}),u=ut(e,"LOCAL_FIND_FILES",{isDefault:!0,isLocal:!0,type:"search",direct:{schema:Lr,inputSchema:Oa,executionFn:Sb,security:"basic"}}),d=ut(e,"LOCAL_FETCH_CONTENT",{isDefault:!0,isLocal:!0,type:"content",direct:{schema:Ar,inputSchema:ka,executionFn:hb,security:"basic"}}),p={name:Le,description:Gp(Le,e),isDefault:!0,isLocal:!0,skipMetadataCheck:!0,type:"content",direct:{schema:xi,inputSchema:wi,executionFn:Fp,security:"basic",requiresServerRuntime:!0}},f=ut(e,"LOCAL_BINARY_INSPECT",{isDefault:!0,isLocal:!0,isBinary:!0,type:"content",direct:{schema:Tr,inputSchema:xa,executionFn:db,security:"basic"}}),m={name:Dn,description:Gp(Dn,e),isDefault:!0,isLocal:!1,type:"search",direct:{schema:Ga,inputSchema:In,executionFn:lC,security:"remote",requiresServerRuntime:!0,requiresProviders:!0}};return{GITHUB_SEARCH_CODE:t,GITHUB_FETCH_CONTENT:n,GITHUB_VIEW_REPO_STRUCTURE:r,GITHUB_SEARCH_REPOSITORIES:o,GITHUB_SEARCH_PULL_REQUESTS:i,PACKAGE_SEARCH:s,GITHUB_CLONE_REPO:a,LOCAL_RIPGREP:c,LOCAL_VIEW_STRUCTURE:l,LOCAL_FIND_FILES:u,LOCAL_FETCH_CONTENT:d,LSP_GET_SEMANTIC_CONTENT:p,LOCAL_BINARY_INSPECT:f,OQL_SEARCH:m,ALL_TOOLS:[t,n,r,o,i,s,a,c,l,u,d,p,f,m]}}var Gp,$e,aX,cX,lX,uX,dX,pX,fX,mX,gX,hX,yX,bX,RX,SX,cC,Hp=y(()=>{"use strict";ra();ri();da();ii();Ra();Pa();oc();ci();li();Mr();gi();Ei();si();Hr();ad();Du();Gu();zu();Wu();Xu();Ju();Ep();dd();pd();wd();_d();Sc();zp();Gn();Pi();Np();Gp=(e,t=Dp)=>t.getDescription(e);$e=r0(),aX=$e.GITHUB_SEARCH_CODE,cX=$e.GITHUB_FETCH_CONTENT,lX=$e.GITHUB_VIEW_REPO_STRUCTURE,uX=$e.GITHUB_SEARCH_REPOSITORIES,dX=$e.GITHUB_SEARCH_PULL_REQUESTS,pX=$e.PACKAGE_SEARCH,fX=$e.GITHUB_CLONE_REPO,mX=$e.LOCAL_RIPGREP,gX=$e.LOCAL_VIEW_STRUCTURE,hX=$e.LOCAL_FIND_FILES,yX=$e.LOCAL_FETCH_CONTENT,bX=$e.LSP_GET_SEMANTIC_CONTENT,RX=$e.LOCAL_BINARY_INSPECT,SX=$e.OQL_SEARCH,cC=$e.ALL_TOOLS});import{ContentSanitizer as o0}from"@octocodeai/octocode-engine/security";function Qp(e){let t=e;if(t.structuredContent)try{t={...t,structuredContent:ht(t.structuredContent)}}catch{}return s0(t)?a0(t):(t.content?.length&&(t={...t,content:t.content.map(n=>{if(n.type==="text"&&"text"in n&&typeof n.text=="string")try{let{content:r}=o0.sanitizeContent(n.text);return{...n,text:r}}catch{return n}return n})}),t)}function s0(e){return xo()==="mcp"&&process.env[i0]!=="true"&&e.isError!==!0&&e.structuredContent!==void 0}function a0(e){let t=(e.content??[]).filter(n=>n.type!=="text");return{...e,content:[{type:"text",text:c0(e.structuredContent)},...t]}}function c0(e){let t=["structuredContent available"];if(Bp(e)){if(typeof e.status=="string"&&t.push(`status=${e.status}`),Array.isArray(e.results)){t.push(`results=${e.results.length}`);let r=l0(e.results);r.error>0&&t.push(`errors=${r.error}`),r.empty>0&&t.push(`empty=${r.empty}`)}let n=e.pagination;Bp(n)&&typeof n.hasMore=="boolean"&&t.push(`hasMore=${n.hasMore}`)}return`${t.join(" \xB7 ")}. Read structuredContent for full data.`}function l0(e){let t=0,n=0;for(let r of e)Bp(r)&&(r.status==="error"&&(t+=1),r.status==="empty"&&(n+=1));return{error:t,empty:n}}function Bp(e){return typeof e=="object"&&e!==null}function Up(e,t){let n=d0(t),r={content:[{type:"text",text:`error: tool "${e}" threw an exception
57
+ message: ${n.message}`}],structuredContent:{status:"error",tool:e,code:u0,error:{name:n.name,message:n.message,code:n.code}},isError:!0};try{return Qp(r)}catch{return r}}function d0(e){if(e instanceof Error){let t=e.code;return{name:e.name||"Error",message:e.message||String(e),code:typeof t=="string"?t:void 0}}if(typeof e=="string")return{name:"Error",message:e};if(e&&typeof e=="object"){let t=e,n=typeof t.message=="string"?t.message:p0(t)??"Unknown error",r=typeof t.name=="string"?t.name:"Error",o=typeof t.code=="string"?t.code:void 0;return{name:r,message:n,code:o}}return{name:"Error",message:e===void 0?"undefined":String(e)}}function p0(e){try{return JSON.stringify(e)}catch{return}}var i0,u0,jp=y(()=>{"use strict";Jo();ms();i0="OCTOCODE_MCP_FULL_TEXT";u0="TOOL_CALLBACK_EXCEPTION"});import{releaseAllPooledClients as f0}from"@octocodeai/octocode-engine/lsp/manager";function m0(e){return async t=>e(t)}function g0(e){let{direct:t}=e;return{name:e.name,schema:t.schema,inputSchema:t.inputSchema,execute:m0(t.executionFn),security:t.security,isLocal:e.isLocal,isClone:e.isClone,requiresServerRuntime:t.requiresServerRuntime,requiresProviders:t.requiresProviders}}function y0(e){return h0.find(t=>t.name===e)}async function Vp(e,t){let n=y0(e);if(!n)throw new Error(`Unknown tool: ${e}`);try{let r=b0(n,t);return await R0(n),S0(n),await C0(n,r)}catch(r){return Up(n.name,r)}finally{e===Le&&await f0()}}function b0(e,t){let n=e.inputSchema.safeParse(t);if(!n.success)throw n.error;return n.data}async function R0(e){e.requiresServerRuntime&&($p||($p=Qm()),await $p),e.requiresProviders&&(qp||(qp=_h().then(()=>{})),await qp)}function S0(e){if(!e.isLocal&&!e.isClone)return;let t=ge();if(e.isLocal&&!t.local.enabled){let n=new Error(`Tool "${e.name}" requires local tools. Set ENABLE_LOCAL=true to use it.`);throw n.code="localToolsDisabled",n}if(e.isClone&&!(t.local.enabled&&t.local.enableClone)){let n=new Error(`Tool "${e.name}" requires clone support. Set ENABLE_CLONE=true and make sure ENABLE_LOCAL is not false.`);throw n.code="cloneDisabled",n}}async function C0(e,t){try{let n=e.security==="remote"?await P0(e,t):await x0(e,t);return Qp(n)}catch(n){return Up(e.name,n)}}async function P0(e,t){return uf(e.name,async(r,o,i)=>e.execute({...r,authInfo:o,sessionId:i}))(t,{})}async function x0(e,t){return df(e.execute,e.name)(t)}var $p,qp,h0,uC=y(()=>{"use strict";dr();js();_e();Gn();Hp();jp();Ac();pp();$p=null,qp=null;h0=cC.map(g0)});var Wp=y(()=>{"use strict";pp();uC()});function Pe(e,t){return Vp(e,{queries:[{...w0,...t}]})}var w0,Cc=y(()=>{"use strict";Wp();w0={mainResearchGoal:"octocode search (OQL)",researchGoal:"OQL target execution",reasoning:"Compiled from an OQL query."}});function fC(e){if(e?.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function _i(e){let n=e.structuredContent?.results?.[0];if(n)return"data"in n?n.data:n}function E0(e){return e.structuredContent?.results?.[0]?.status}function Pc(e,t){return e>0?[]:[x("providerUnindexed",`${t} returned no results \u2014 GitHub may not index this repo/branch (or the name redirected). Do not treat this as absence: verify with \`search owner/repo[/path] --tree\`, then use bounded local proof via \`search <term> <path> --repo owner/repo --materialize required\`, \`clone owner/repo[/path]\`, or \`cache fetch owner/repo [path] --depth file|tree|clone\`.`,{backend:t,severity:"warning",blocksAnswer:!0})]}function mC(e){return!e||e==="."?"":e.replace(/^\/+|\/+$/g,"")}function dC(...e){return e.map(mC).filter(Boolean).join("/")}function T0(e){return e?Array.isArray(e)?[...e]:Object.entries(e).map(([t,n])=>({dir:t,files:n.files,folders:n.folders})):[]}function pC(e){return mC(e).split("/").filter(Boolean).length}function k0(e){return e.trim().toLowerCase().replace(/^\*\./,"").replace(/^\./,"")}function O0(e){let t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}function v0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A0(e,t){let n=t.trim();if(!n)return!0;let r=e.split("/").pop()??e;if(!n.includes("*")&&!n.includes("?"))return r.includes(n)||e.includes(n);let o=n.split("**").map(s=>s.split("*").map(a=>a.split("?").map(v0).join("[^/]")).join("[^/]*")).join(".*"),i=new RegExp(`^${o}$`);return i.test(r)||i.test(e)}function L0(e,t){let n=t.fetch?.tree;if(!n)return[...e];let r=(n.extensions??[]).map(k0).filter(Boolean);return e.filter(o=>n.filesOnly&&o.entryType!=="file"||n.directoriesOnly&&o.entryType!=="directory"||n.pattern&&!A0(o.path,n.pattern)?!1:o.entryType==="directory"||r.length===0||r.includes(O0(o.path)))}function gC(e){if(typeof e!="string")return e.path;let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function _0(e){if(typeof e=="string")return;let t={...e.owner!==void 0?{owner:e.owner}:{},...e.repo!==void 0?{repo:e.repo}:{},...e.queryId!==void 0?{queryId:e.queryId}:{}};return Object.keys(t).length?t:void 0}function I0(e){return typeof e=="string"?[]:e.matches??[]}async function hC(e){switch(e.target){case"content":return D0(e);case"structure":return N0(e);case"files":return F0(e);default:return M0(e)}}async function F0(e){let t=Ri(e,{defaultMatch:"file",unsupportedBackend:"localFindFiles",unsupportedMessage:'target:"files" over a GitHub source can only list files containing a term via the provider; everything else needs materialization (set materialize.mode:"auto" with a bounded scope.path, or use a local source).'});if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Pe("ghSearchCode",t.query),r=_i(n),o=new Set,i=[];for(let a of r?.files??[]){let c=gC(a);o.has(c)||(o.add(c),i.push({kind:"file",source:ke(e),path:c,entryType:"file"}))}let s=Bt(r?.pagination);return{results:i,...s?{pagination:s}:{},diagnostics:[...xc(n,"ghSearchCode"),...Pc(i.length,"ghSearchCode"),...i.length>0?[x("providerSemanticsApproximate","GitHub lists files containing a term via provider code search (index may be incomplete); materialize for an exact file set.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:ke(e)}]}}function ke(e){return e.from??{kind:"github"}}async function M0(e){let t=Ri(e);if(!t.ok)return{results:[],diagnostics:t.diagnostics,provenance:[]};let n=await Pe("ghSearchCode",t.query),r=_i(n),o=[];for(let s of r?.files??[]){let a=gC(s),c=_0(s),l=I0(s);if(l.length===0){o.push({kind:"code",source:ke(e),path:a,...c?{metadata:c}:{}});continue}for(let u of l)o.push({kind:"code",source:ke(e),path:a,...u.value!==void 0?{snippet:u.value}:{},...u.matchIndices!==void 0?{matchIndices:u.matchIndices}:{},...c?{metadata:c}:{}})}let i=Bt(r?.pagination);return{results:o,...i?{pagination:i}:{},diagnostics:[...xc(n,"ghSearchCode"),...Pc(o.length,"ghSearchCode"),...o.length>0?[x("providerSemanticsApproximate","GitHub code search returns path-level hits without line numbers; follow next.fetch for exact location/lines.",{backend:"ghSearchCode",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghSearchCode",source:ke(e)}]}}async function D0(e){let{owner:t,repo:n}=fC(ke(e)),r=e.fetch?.content,o=r?.contentView==="exact"?"none":r?.contentView==="symbols"?"symbols":"standard",i=G0(r?.range),s={...t?{owner:t}:{},...n?{repo:n}:{},path:nt(e.scope)??"",type:"file",minify:o,...ke(e).kind==="github"&&ke(e).ref?{branch:ke(e).ref}:{},...i,...r?.match?.text!==void 0?{matchString:r.match.text}:{},...r?.match?.regex?{matchStringIsRegex:!0}:{},...r?.match?.caseSensitive?{matchStringCaseSensitive:!0}:{},...r?.charOffset!==void 0?{charOffset:r.charOffset}:{},...r?.charLength!==void 0?{charLength:r.charLength}:{},...r?.fullContent?{fullContent:!0}:{}},a=await Pe("ghGetFileContent",s),c=_i(a),l=o==="none"?"exact":o==="symbols"?"symbols":"compact",u=c?.pagination,d=c?.results??c?.files??[],p=d.map(m=>{let g=m.pagination??u,b=typeof g?.charOffset=="number",C={...m.startLine!==void 0?{startLine:m.startLine}:{},...m.endLine!==void 0?{endLine:m.endLine}:{},...b?{charOffset:g.charOffset,...typeof g.charLength=="number"?{charLength:g.charLength}:{}}:{}};return{kind:"content",source:ke(e),path:m.path,content:m.content,contentView:l,...Object.keys(C).length?{range:C}:{}}}),f=u??d.find(m=>m.pagination)?.pagination;return{results:p,...f?.hasMore!==void 0?{pagination:{hasMore:!!f.hasMore,...f.currentPage!==void 0?{currentPage:f.currentPage}:{},...f.totalPages!==void 0?{totalPages:f.totalPages}:{},...f.charLength!==void 0?{itemsPerPage:f.charLength}:{},...f.totalChars!==void 0?{totalItems:f.totalChars,totalItemsKind:"chars"}:{}}}:{},diagnostics:[...xc(a,"ghGetFileContent"),...Pc(p.length,"ghGetFileContent")],provenance:[{backend:"ghGetFileContent",source:ke(e)}]}}async function N0(e){let{owner:t,repo:n}=fC(ke(e)),r={...t?{owner:t}:{},...n?{repo:n}:{},path:nt(e.scope)??"",...ke(e).kind==="github"&&ke(e).ref?{branch:ke(e).ref}:{},...e.fetch?.tree?.maxDepth!==void 0?{maxDepth:e.fetch.tree.maxDepth}:{},...e.fetch?.tree?.includeSizes?{includeSizes:!0}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{},...e.page?{page:e.page}:{}},o=await Pe("ghViewRepoStructure",r),i=_i(o),s=[],a=nt(e.scope);for(let u of T0(i?.structure)){let d=u.dir??".";for(let p of u.folders??[]){let f=dC(a,d,p);s.push({kind:"tree",source:ke(e),path:f,entryType:"directory",depth:pC(f)})}for(let p of u.files??[]){let f=dC(a,d,p);s.push({kind:"tree",source:ke(e),path:f,entryType:"file",depth:pC(f)})}}let c=L0(s,e),l=Bt(i?.pagination);return{results:e.limit!==void 0?c.slice(0,e.limit):c,...l?{pagination:l}:{},diagnostics:[...xc(o,"ghViewRepoStructure"),...Pc(c.length,"ghViewRepoStructure")],provenance:[{backend:"ghViewRepoStructure",source:ke(e)}]}}function G0(e){if(e?.startLine===void 0)return{};let t=e.contextLines??0,n=Math.max(1,e.startLine-t),r=(e.endLine??e.startLine)+t;return{startLine:n,endLine:r}}function xc(e,t){let n=E0(e);if(n==="error"){let r=_i(e);return[x("invalidQuery",r?.error??"GitHub backend error",{backend:t})]}return n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}var yC=y(()=>{"use strict";Cc();qa();Rt();Ud();bi()});import bC from"node:path";function RC(e){return[...new Set(e)]}function CC(e){if(e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function PC(e){let t=e.structuredContent,n=t?.results?.[0],r=n?.data;return{localPath:r?.localPath&&t?.base&&!bC.isAbsolute(r.localPath)?bC.join(t.base,r.localPath):r?.localPath,cached:r?.cached,error:r?.error,status:n?.status}}async function xC(e){if(e.from?.kind!=="github")return Ci(e);let t=e.from,{owner:n,repo:r}=CC(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let o=nt(e.scope),i={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...e.materialize?.strategy!=="repo"&&o?{sparsePath:o}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},s=await Pe("ghCloneRepo",i),{localPath:a,cached:c,error:l,status:u}=PC(s);if(u==="error"||!a)return{results:[],diagnostics:[x("materializationFailed",l??"Clone/fetch failed; cannot run local proof.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let d=e.scope??{},p={...e,from:{kind:"materialized",localPath:a,source:t},scope:{...d,path:void 0,excludeDir:RC([...d.excludeDir??[],".git"]),exclude:RC([...d.exclude??[],".octocode-clone-meta.json","**/.octocode-clone-meta.json"])}},f=await Ci(p);return{...f,diagnostics:[...f.diagnostics,...c?[x("staleCache","Result came from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[]],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:a,cache:c?"hit":"miss"},...f.provenance]}}async function wC(e){if(e.from?.kind==="materialized"){let f=e.from.localPath;return{results:[SC(f,e.from.source,void 0,!0)],diagnostics:[],provenance:[{backend:"ghCloneRepo",source:e.from}]}}if(e.from?.kind!=="github")return{results:[],diagnostics:[x("invalidQuery",'target:"materialize" needs a GitHub source (owner/repo) or an already-materialized `from`.',{backend:"ghCloneRepo"})],provenance:[]};let t=e.from,{owner:n,repo:r}=CC(t);if(!n||!r)return{results:[],diagnostics:[x("materializationFailed","Materialization requires a concrete owner/repo.",{backend:"ghCloneRepo"})],provenance:[]};let i=e.materialize?.strategy==="repo"?void 0:nt(e.scope),s={owner:n,repo:r,...t.ref?{branch:t.ref}:{},...i?{sparsePath:i}:{},...e.materialize?.forceRefresh?{forceRefresh:!0}:{}},a=await Pe("ghCloneRepo",s),{localPath:c,cached:l,error:u,status:d}=PC(a);if(d==="error"||!c)return{results:[],diagnostics:[x("materializationFailed",u??"Clone/fetch failed; no checkpoint produced.",{backend:"ghCloneRepo"})],provenance:[{backend:"ghCloneRepo",source:t}]};let p=!i;return{results:[SC(c,t,t.ref,p,l)],diagnostics:l?[x("staleCache","Checkpoint served from a cached clone; set materialize.forceRefresh to refresh.",{backend:"ghCloneRepo",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghCloneRepo",source:t,materializedPath:c,cache:l?"hit":"miss"}]}}function SC(e,t,n,r,o){return{kind:"record",recordType:"materialized",id:e,...t?{source:t}:{},data:{localPath:e,repoRoot:e,...t?{sourceRef:t}:{},...n?{ref:n}:{},cache:o?"hit":"miss",complete:r}}}var EC=y(()=>{"use strict";Cc();op();Rt();bi()});import{builtinModules as H0}from"node:module";import Re from"node:path";import{readFile as wc,readdir as z0}from"node:fs/promises";async function Xp(e){let t=Re.resolve(e.root),n=e.mode??"analyze",r=e.goal?.trim()||"Analyze this repository.",o=j0(r,e.intent,e.facets),i=$0(o,e.facets),s=q0(o,i),a=tM();if(n==="plan")return V0({root:t,goal:r,intent:o,facets:i,mode:n,flow:s,graphCapabilities:kC([],[],a)});let c=await W0(t,e.maxFiles??5e3),l=await K0(c.filter(w=>w.endsWith(B0))),u=await Z0(t,c),d=u.map(w=>w.graphFacts).filter(w=>w!==void 0),p=kC(u,d,a);await mM(u);let f=new Set(l.map(w=>w.name).filter(_C)),m=oM(u),g=iM(t,l,u),b=sM(g,m),C=u.filter(w=>!b.has(w.path)).map(w=>({kind:"unusedFile",file:w.rel,retainedBy:[],verdict:"unused-file"})),S=aM(t,l,u,f),T=await lM(u),L=pM(T,u,b),k=L.filter(w=>w.verdict==="candidate-unused-export"||w.verdict==="unused-export").length,O=L.filter(w=>w.verdict==="transitive-dead").length;return{kind:"researchFlow",goal:r,intent:o,facets:i,mode:n,root:t,flow:s,summary:{manifests:l.length,sourceFiles:u.length,entrypoints:g.length,reachableFiles:b.size,unusedFiles:C.length,unlistedDependencies:S.filter(w=>w.kind==="unlistedDependency").length,unusedDependencies:S.filter(w=>w.kind==="unusedDependency").length,duplicateDependencies:S.filter(w=>w.kind==="duplicateDependency").length,exportedSymbols:L.length,candidateUnusedExports:k,transitiveDeadExports:O,nativeGraphFiles:d.length,nativeGraphDeclarations:d.reduce((w,N)=>w+N.declarations.length,0),nativeGraphCalls:d.reduce((w,N)=>w+N.calls.length,0)},manifests:l.map(w=>({manifest:Un(t,w.path),...w.name?{name:w.name}:{},entrypoints:w.entrypoints.map(N=>Un(t,N)),dependencyCount:[...w.deps.keys()].length})),files:C,dependencies:S,symbols:L,graphFacts:d,graphCapabilities:p,caveats:["This is a smart research flow with native AST graph facts where available plus heuristic cross-file reachability. LSP references should be used before destructive cleanup.","Graph capability coverage is explicit: tree-sitter/OXC facts are syntax inventory, not semantic deletion proof.","Dynamic imports, framework entrypoints, generated files, test-only retention, and package-manager-specific workspace rules may require project-specific refinement."]}}function j0(e,t,n){let r=`${t??""} ${n?.join(" ")??""} ${e}`.toLowerCase();return/dead|unused|reachab|entry\s*point|transitive/.test(r)?"reachability":/dep|package|manifest|unlisted|duplicate/.test(r)?"dependencies":/symbol|export|reference|lsp|ast/.test(r)?"symbols":"general"}function $0(e,t){if(t&&t.length>0)return[...new Set(t)];switch(e){case"reachability":return["entrypoints","files","symbols","dependencies"];case"dependencies":return["manifests","dependencies","imports"];case"symbols":return["symbols","references","ast","lsp"];case"general":return["structure","symbols","dependencies"]}}function q0(e,t){let n=[{id:"orient",purpose:"Discover manifests, source files, and analysis boundaries.",tools:["localFindFiles","localViewStructure"],produces:["fileUniverse","manifestSet"],evidence:"proof"},{id:"manifest-graph",purpose:"Extract package entrypoints, declared dependencies, workspace package names, and script hints.",tools:["package.json parser"],produces:["entrypoints","declaredDependencies","workspacePackages"],evidence:"heuristic"}];return(e==="reachability"||t.includes("symbols"))&&n.push({id:"symbol-inventory",purpose:"Enumerate exports and declaration anchors for symbol-level questions.",tools:["localSearchCode structural","lspGetSemantics documentSymbols"],produces:["symbols","lineHints"],evidence:"proof"},{id:"reference-proof",purpose:"Use references grouped by file to separate direct, external, and transitive retention.",tools:["lspGetSemantics references","localSearchCode"],produces:["directRefs","externalRefs","retainedBy","transitiveDead"],evidence:"proof"}),(e==="dependencies"||t.includes("dependencies"))&&n.push({id:"dependency-audit",purpose:"Compare import specifiers with package manifests to find unlisted, unused, and duplicate dependencies.",tools:["package.json parser","import graph"],produces:["unlistedDependencies","unusedDependencies","duplicateDependencies"],evidence:"heuristic"}),n}function V0(e){return{kind:"researchFlow",goal:e.goal,intent:e.intent,facets:e.facets,mode:e.mode,root:e.root,flow:e.flow,summary:{manifests:0,sourceFiles:0,entrypoints:0,reachableFiles:0,unusedFiles:0,unlistedDependencies:0,unusedDependencies:0,duplicateDependencies:0,exportedSymbols:0,candidateUnusedExports:0,transitiveDeadExports:0,nativeGraphFiles:0,nativeGraphDeclarations:0,nativeGraphCalls:0},manifests:[],files:[],dependencies:[],symbols:[],graphFacts:[],graphCapabilities:e.graphCapabilities,caveats:["Planning mode returned the research flow without scanning files."]}}async function W0(e,t){let n=[];async function r(o){if(n.length>=t)return;let i=await z0(o,{withFileTypes:!0});for(let s of i){if(n.length>=t)return;if(s.isDirectory()){if(Q0.has(s.name))continue;await r(Re.join(o,s.name));continue}s.isFile()&&n.push(Re.join(o,s.name))}}return await r(e),n}async function K0(e){return(await Promise.all(e.map(async n=>Y0(n)))).filter(n=>n!==null)}async function Y0(e){let t=await X0(e);if(!t)return null;let n=Re.dirname(e),r=new Map;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=bM(t[o]);if(i)for(let s of Object.keys(i))r.set(s,[...r.get(s)??[],o])}return{path:e,dir:n,name:LC(t.name),deps:r,entrypoints:J0(n,t)}}async function X0(e){try{let t=JSON.parse(await wc(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function J0(e,t){let n=new Set;for(let o of["main","module","types","typings"]){let i=LC(t[o]);i&&n.add(Re.resolve(e,i))}let r=t.bin;if(typeof r=="string"&&n.add(Re.resolve(e,r)),r&&typeof r=="object"&&!Array.isArray(r))for(let o of Object.values(r))typeof o=="string"&&n.add(Re.resolve(e,o));vC(e,t.exports,n);for(let o of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js","src/lib.rs","src/main.rs","main.rs","__init__.py","main.py","src/main.py","main.go","cmd/main.go","src/main/java/Main.java"])n.add(Re.resolve(e,o));return[...n]}function vC(e,t,n){if(typeof t=="string"){n.add(Re.resolve(e,t));return}if(!(!t||typeof t!="object"||Array.isArray(t)))for(let r of Object.values(t))vC(e,r,n)}async function Z0(e,t){let n=Jp(),r=t.filter(i=>n.has(Re.extname(i).toLowerCase()));return await Promise.all(r.map(async i=>{let s=await wc(i,"utf8").catch(()=>""),a=Re.extname(i).toLowerCase(),c=eM(s,i,Un(e,i)),l=SM(c?c.imports.map(u=>u.specifier):rM(s));return{path:i,rel:Un(e,i),extension:a,language:c?.language??a.slice(1),imports:l,externalPackages:l.filter(u=>!AC(u)).map(yM).filter(_C).filter(u=>!U0.has(u)),...c?{graphFacts:c}:{}}}))}function eM(e,t,n){try{let r=F.extractGraphFacts(e,t);if(!r)return;let o=JSON.parse(r);return o.kind!=="graphFacts"||o.source!=="native-ast"||!Array.isArray(o.declarations)||!Array.isArray(o.imports)||!Array.isArray(o.exports)||!Array.isArray(o.calls)||!Array.isArray(o.edges)?void 0:{file:n,source:o.source,language:o.language??Re.extname(t).slice(1),declarations:o.declarations.map(i=>({name:i.name,kind:i.kind,line:i.line,exported:i.exported,...i.parent?{parent:i.parent}:{}})),imports:o.imports.map(i=>({specifier:i.specifier,line:i.line,importKind:i.importKind,...i.localName?{localName:i.localName}:{},...i.importedName?{importedName:i.importedName}:{}})),exports:o.exports.map(i=>({name:i.name,line:i.line,exportKind:i.exportKind,...i.localName?{localName:i.localName}:{},...i.source?{source:i.source}:{}})),calls:o.calls.map(i=>({caller:i.caller,callee:i.callee,line:i.line,kind:i.kind})),edges:o.edges.map(i=>({from:i.from,to:i.to,relation:i.relation,source:i.source,line:i.line})),diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(RM):[]}}catch{return}}function Jp(){if(Ii)return Ii;try{let e=F.getSupportedGraphFactExtensions().map(t=>(t.startsWith(".")?t:`.${t}`).toLowerCase());Ii=new Set(e.length>0?e:TC)}catch{Ii=new Set(TC)}return Ii}function tM(){if(Fi)return Fi;try{let e=JSON.parse(F.getGraphFactCapabilities());Fi=Array.isArray(e)?e.filter(nM):[]}catch{Fi=[]}return Fi}function nM(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.extension=="string"&&typeof t.language=="string"&&Array.isArray(t.factFamilies)}function kC(e,t,n){let r=n.length>0?n.map(l=>l.extension).sort():[...Jp()].map(l=>l.slice(1)).sort(),o=[...new Set(n.flatMap(l=>l.factFamilies))].sort(),i=OC(e,l=>l.language),s=OC(t,l=>l.language),a=new Set(t.map(l=>l.file)),c=new Map;for(let l of e)a.has(l.rel)||c.set(l.extension,(c.get(l.extension)??0)+1);return{graphFactExtensions:r,capabilityCount:n.length,factFamilies:o,sourceFilesByLanguage:i,graphFilesByLanguage:s,missingGraphFacts:[...c.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({extension:l.startsWith(".")?l.slice(1):l,files:u,reason:"extension entered the source universe, but native graph facts were unavailable or parser output was empty"}))}}function OC(e,t){let n={};for(let r of e){let o=t(r)||"unknown";n[o]=(n[o]??0)+1}return n}function rM(e){let t=[],n=[/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g,/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/g,/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let r of n)for(let o of e.matchAll(r))o[1]&&t.push(o[1]);return t}function oM(e){let t=new Set(e.map(o=>o.path)),n=new Map(e.map(o=>[o.path,Re.dirname(o.path)])),r=new Map;for(let o of e){let i=[],s=n.get(o.path)??Re.dirname(o.path);for(let a of o.imports){if(!AC(a))continue;let c=hM(s,a,t);c&&i.push(c)}r.set(o.path,i)}return r}function iM(e,t,n){let r=new Set(n.map(i=>i.path)),o=new Set;for(let i of t)for(let s of i.entrypoints){let a=Yp(s,r);a&&o.add(a)}for(let i of["src/index.ts","src/index.tsx","src/index.js","index.ts","index.js"]){let s=Yp(Re.resolve(e,i),r);s&&o.add(s)}return[...o]}function sM(e,t){let n=new Set,r=[...e];for(;r.length>0;){let o=r.pop();if(!(!o||n.has(o))){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function aM(e,t,n,r){let o=new Map,i=new Map;for(let a of n){let c=cM(a.path,t);if(!c)continue;let l=o.get(c.path)??new Set;o.set(c.path,l);for(let u of a.externalPackages){l.add(u);let d=i.get(`${c.path}\0${u}`)??new Set;d.add(a.rel),i.set(`${c.path}\0${u}`,d)}}let s=[];for(let a of t){let c=o.get(a.path)??new Set;for(let l of c)r.has(l)||a.deps.has(l)||s.push({kind:"unlistedDependency",packageName:l,manifest:Un(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:[],verdict:"unlisted-dependency"});for(let[l,u]of a.deps)u.length>1&&s.push({kind:"duplicateDependency",packageName:l,manifest:Un(e,a.path),usedBy:[...i.get(`${a.path}\0${l}`)??[]],declaredIn:u,verdict:"duplicate-dependency"}),!c.has(l)&&!r.has(l)&&s.push({kind:"unusedDependency",packageName:l,manifest:Un(e,a.path),usedBy:[],declaredIn:u,verdict:"candidate-unused-dependency"})}return s}function cM(e,t){return t.filter(r=>e.startsWith(`${r.dir}${Re.sep}`)).sort((r,o)=>o.dir.length-r.dir.length)[0]}async function lM(e){return(await Promise.all(e.map(async n=>{let r=uM(n);if(r.length>0)return r;let o=await wc(n.path,"utf8").catch(()=>"");return dM(n.rel,o)}))).flat()}function uM(e){let t=e.graphFacts;return t?t.declarations.filter(n=>n.exported).map(n=>({symbol:n.name,kind:n.kind,file:e.rel,line:n.line,evidenceSource:"ast"})):[]}function dM(e,t){let n=[],r=t.split(/\r?\n/);for(let o=0;o<r.length;o++){let i=r[o]??"",s=/\bexport\s+(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\s+([A-Za-z_$][\w$]*)/.exec(i);s&&n.push({symbol:s[1],kind:gM(i),file:e,line:o+1,evidenceSource:"regex"});let a=/\bexport\s*\{([^}]+)\}/.exec(i);if(a)for(let c of a[1].split(",")){let l=c.trim().split(/\s+as\s+/)[0]?.trim();l&&/^[A-Za-z_$][\w$]*$/.test(l)&&n.push({symbol:l,kind:"export",file:e,line:o+1,evidenceSource:"regex"})}}return n}function pM(e,t,n){let r=new Map(t.map(o=>[o.rel,o]));return e.map(o=>{let i=t.filter(u=>u.rel!==o.file&&fM(u.path,o.symbol)),s=i.filter(u=>n.has(u.path)),a=r.get(o.file),c=a?n.has(a.path):!1,l=s.length>0?"reachable":i.length>0?"transitive-dead":c?"candidate-unused-export":"unused-export";return{symbol:o.symbol,kind:o.kind,file:o.file,line:o.line,evidenceSource:o.evidenceSource,directRefs:i.length,externalRefs:s.length,retainedBy:i.map(u=>u.rel),verdict:l}})}function fM(e,t){return Kp.get(e)?.has(t)??!1}async function mM(e){Kp.clear(),await Promise.all(e.map(async t=>{let n=await wc(t.path,"utf8").catch(()=>"");Kp.set(t.path,new Set(n.match(/[A-Za-z_$][\w$]*/g)??[]))}))}function gM(e){return/\b(function|class|const|let|var|type|interface|enum)\b/.exec(e)?.[1]??"export"}function hM(e,t,n){return Yp(Re.resolve(e,t),n)}function Yp(e,t){let n=Jp(),r=[e];for(let o of n)r.push(`${e}${o}`);for(let o of n)r.push(Re.join(e,`index${o}`));return r.find(o=>t.has(o))}function AC(e){return e.startsWith("./")||e.startsWith("../")}function yM(e){if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:void 0}return e.split("/")[0]}function bM(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function LC(e){return typeof e=="string"&&e.trim()?e:void 0}function _C(e){return typeof e=="string"&&e.length>0}function RM(e){return typeof e=="string"}function SM(e){return[...new Set(e)]}function Un(e,t){return Re.relative(e,t)||Re.basename(t)}var TC,B0,Q0,U0,Ii,Fi,Kp,IC=y(()=>{"use strict";be();TC=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],B0="package.json",Q0=new Set([".claude",".context",".cursor",".git","node_modules","dist","out","coverage","target",".next",".turbo",".yarn"]),U0=new Set(H0.flatMap(e=>[e,`node:${e}`]));Kp=new Map});import Zp from"node:path";function ef(e){let t=e.root,n=[...e.symbols.map(a=>CM(t,a)),...e.files.map(a=>EM(t,a)),...e.dependencies.filter(a=>a.kind==="unusedDependency").map(a=>TM(a))],r=a=>a==="reachable"?1:a==="unknown"?.5:0;n.sort((a,c)=>r(a.verdict)-r(c.verdict));let o={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},i=0,s=0;for(let a of n)o[a.verdict]+=1,i+=a.why.length,s+=a.retainedBy.length+(a.retains?.length??0);return{packets:n,graphSummary:{subjects:n.length,facts:i,edges:s,byVerdict:o}}}function CM(e,t){let n={id:`sym:${t.file}#${t.symbol}`,kind:"symbol",name:t.symbol,symbolKind:t.kind,uri:t.file,range:{start:{line:t.line}}},r=PM(t.verdict),o=r!=="reachable",i=[{id:`${n.id}:exports`,subject:n,claim:"exports",source:t.evidenceSource,confidence:t.evidenceSource==="ast"?"exact":"heuristic",flags:["declaration"]}],s=t.retainedBy.map((c,l)=>({id:`${n.id}:ref:${l}`,from:{id:`file:${c}`,kind:"file",uri:c},to:n,relation:"references",source:"ripgrep",confidence:"heuristic",flags:t.externalRefs>0?void 0:["unreachable"]})),a=[{kind:"lsp-unavailable",severity:o?"high":"low",location:{uri:t.file,range:{start:{line:t.line}}}}];return{subject:n,verdict:r,proofStatus:r==="transitive-dead"&&t.directRefs>0?"conflicting-evidence":"candidate",why:i,retainedBy:s,missingProof:a,risk:xM(r),next:wM(e,t)}}function PM(e){switch(e){case"reachable":return"reachable";case"candidate-unused-export":case"unused-export":return"candidate-dead";case"transitive-dead":return"transitive-dead";default:return"unknown"}}function xM(e){switch(e){case"reachable":return{deleteRisk:"high",reason:"Reachable from entrypoints via reference scan; likely used \u2014 do not delete without confirming."};case"candidate-dead":return{deleteRisk:"medium",reason:"No reachable references found, but the scan is token-based. Confirm with LSP references (next.semantic) before deleting."};case"transitive-dead":return{deleteRisk:"medium",reason:"Only referenced from unreachable code. Confirm the retention chain with LSP before deleting."};default:return{deleteRisk:"unknown",reason:"Insufficient evidence."}}}function wM(e,t){let n=Zp.resolve(e,t.file);return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:n},fetch:{content:{range:{startLine:t.line,contextLines:3},contentView:"exact"}}},why:"Read the declaration at this symbol.",confidence:"exact"},"next.semantic":{query:{schema:"oql",target:"semantics",from:{kind:"local",path:n},params:{type:"references",symbolName:t.symbol,lineHint:t.line,includeDeclaration:!1}},why:"Confirm references with LSP \u2014 upgrades this candidate to proof.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:t.symbol},view:"discovery"},why:"Find string/dynamic usages of the name the reference scan may miss.",confidence:"heuristic"}}}function EM(e,t){let n={id:`file:${t.file}`,kind:"file",uri:t.file};return{subject:n,verdict:"candidate-unused-file",proofStatus:"needs-framework-graph",why:[{id:`${n.id}:no-importer`,subject:n,claim:"unresolved",source:"graph",confidence:"heuristic",value:{reason:"no static importer reaches this file from an entrypoint"}}],retainedBy:[],missingProof:[{kind:"dynamic-import-unresolved",severity:"medium"},{kind:"framework-entrypoint-unknown",severity:"medium"}],risk:{deleteRisk:"medium",reason:"No static importer found, but dynamic imports, framework entrypoints, and config globs are not modeled. Verify before deleting."},next:{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:Zp.resolve(e,t.file)},fetch:{content:{contentView:"symbols"}}},why:"Read the file outline.",confidence:"exact"},"next.search":{query:{schema:"oql",target:"code",from:{kind:"local",path:e},where:{kind:"text",value:Zp.basename(t.file)},view:"discovery"},why:"Find references to the file name (dynamic import / config).",confidence:"heuristic"}}}}function TM(e){let t={id:`dep:${e.manifest}#${e.packageName}`,kind:"dependency",name:e.packageName,uri:e.manifest};return{subject:t,verdict:"candidate-unused-dependency",proofStatus:"candidate",why:[{id:`${t.id}:declared`,subject:t,claim:"declares",source:"manifest",confidence:"exact",value:{declaredIn:e.declaredIn}},{id:`${t.id}:no-import`,subject:t,claim:"unresolved",source:"regex",confidence:"heuristic",value:{reason:"no import specifier resolves to this package"}}],retainedBy:[],missingProof:[{kind:"manifest-rule-missing",severity:"medium"},{kind:"dynamic-import-unresolved",severity:"low"}],risk:{deleteRisk:"medium",reason:"No import specifier resolves to this dependency, but it may be used via config, scripts, types, or transitive re-export. Verify before removing."},next:{}}}var FC=y(()=>{"use strict"});import{statSync as kM}from"node:fs";import te from"node:path";function dn(e){let n=e.structuredContent?.results?.[0];return{data:n?.data,status:n?.status}}function MC(e){let n=e.structuredContent?.results?.[0];if(!n)return{};let r="data"in n?n.data:n,o=r?.files?.[0]??r?.results?.[0]??r??{},i=o.content;return{content:typeof i=="string"?i:void 0,status:n.status,error:o.error??r?.error??n.error}}function of(e,t){if(typeof e=="string"&&e.trim())return e;if(e instanceof Error&&e.message)return e.message;if(e&&typeof e=="object"){let n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message;let r=JSON.stringify(e);if(r)return r}return t}function OM(e,t){if(!t||te.isAbsolute(t))return t;let n=e.structuredContent;return n?.base?te.join(n.base,t):t}function vM(e,t,n){let r=t??n??".";if(!e)return r;if(te.isAbsolute(e))return e;if(n&&te.isAbsolute(n))return te.resolve(n,e);if(t&&te.isAbsolute(t)){let o=KC(t)?t:te.dirname(t);return te.resolve(o,e)}return e}function DC(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function jC(e){if(!e)return[];for(let t of UC){let n=e[t];if(Array.isArray(n))return n}return[e]}function LM(e){let t=e?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n={};for(let[r,o]of Object.entries(t)){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s={};for(let a of["repository","repositoryDirectory","owner","repo"])typeof i[a]=="string"&&(s[a]=i[a]);Object.keys(s).length>0&&(n[r]=s)}return Object.keys(n).length?{repositories:n}:void 0}function _M(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))AM.has(n)||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(t[n]=r);return Object.keys(t).length?t:void 0}function Di(e,t,n,r){return e.map(o=>{let i=o&&typeof o=="object"?o:{value:o},s=eD(t,i);return{kind:"record",recordType:t,...s?{id:s}:{},...n?{source:n}:{},...r?{metadata:r}:{},data:i}})}function $C(e){return e==="plan"||e==="prove"?e:"analyze"}function Ec(e,t){let n=Math.max(1,e.page??1),r=Math.max(1,e.itemsPerPage??e.limit??IM),o=Math.max(1,Math.ceil(t/r)),i=(n-1)*r;return{packetsStart:i,packetsEnd:i+r,pagination:{currentPage:n,totalPages:o,itemsPerPage:r,totalItems:t,hasMore:n<o}}}function FM(e){if(!e||e.length===0)return;let t=new Set;for(let n of e){let r=n.trim(),o=r.startsWith("data.")?r.slice(5):r;qC.includes(o)&&t.add(o)}return t.size>0?t:void 0}function MM(e,t){let n=FM(e.select),r={manifests:t.manifests,files:t.files,dependencies:t.dependencies,symbols:t.symbols,graphFacts:t.graphFacts},o={},i=Math.max(1,e.page??1),s,a=1,c=!1;for(let l of qC){if(n&&!n.has(l))continue;let u=r[l]??[],{packetsStart:d,packetsEnd:p,pagination:f}=Ec(e,u.length);o[l]=u.slice(d,p),o[`${l}Page`]=f,s=f.itemsPerPage,a=Math.max(a,f.totalPages??1),f.hasMore&&(c=!0)}return Object.keys(o).length===0?{fields:o}:{fields:o,pagination:{currentPage:i,...s!==void 0?{itemsPerPage:s}:{},totalPages:a,hasMore:c||i<a}}}function DM(e,t){if(!e)return t;if(!t)return e;let n=e.currentPage??t.currentPage,r=e.itemsPerPage??t.itemsPerPage;return{...n!==void 0?{currentPage:n}:{},...r!==void 0?{itemsPerPage:r}:{},totalPages:Math.max(e.totalPages??1,t.totalPages??1),...e.totalItems!==void 0?{totalItems:e.totalItems}:{},hasMore:!!(e.hasMore||t.hasMore)}}function NC(e){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase());return n.length?new Set(n):void 0}function NM(e){return{...typeof e.subject=="string"&&e.subject.trim()?{subject:e.subject.trim().toLowerCase()}:{},...typeof e.subjectKind=="string"&&e.subjectKind.trim()?{subjectKind:e.subjectKind.trim().toLowerCase()}:{},relations:NC(e.relation),verdicts:NC(e.verdict),direction:e.direction==="incoming"||e.direction==="outgoing"?e.direction:"both",includePackets:e.includePackets!==!1,includeFacts:e.includeFacts!==!1,includeEdges:e.includeEdges!==!1}}function GM(e,t){if(t.subjectKind){let r=e.kind.toLowerCase(),o=e.symbolKind===void 0?void 0:String(e.symbolKind).toLowerCase();if(r!==t.subjectKind&&o!==t.subjectKind)return!1}return t.subject?[e.id,e.name,e.uri].filter(r=>typeof r=="string").map(r=>r.toLowerCase()).some(r=>r.includes(t.subject)):!0}function Kr(e,t){return!t.relations||!e?!0:t.relations.has(e.toLowerCase())}function VC(e,t){if(!GM(e.subject,t)||t.verdicts&&!t.verdicts.has(e.verdict.toLowerCase()))return!1;if(!t.relations)return!0;let n=t.direction!=="outgoing"&&e.retainedBy.some(i=>Kr(i.relation,t)),r=t.direction!=="incoming"&&(e.retains??[]).some(i=>Kr(i.relation,t)),o=e.why.some(i=>Kr(i.claim,t));return n||r||o}function tf(e,t){e.set(t.id,t)}function HM(e,t,n){Kr(t.claim,n)&&e.set(t.id,t)}function nf(e,t,n,r){Kr(n.relation,r)&&(tf(e,n.from),tf(e,n.to),t.set(n.id,n))}function zM(e){let t=e.location?.range?.start.line;return[e.kind,e.severity,e.location?.uri??"",t===void 0?"":String(t)].join(":")}function BM(e,t,n,r,o,i){let s=t.filter(g=>VC(g,r)),a=Ec(e,s.length),c=s.slice(a.packetsStart,a.packetsEnd),l=new Map,u=new Map,d=new Map,p=new Map,f={},m={};for(let g of s)f[g.verdict]=(f[g.verdict]??0)+1,m[g.proofStatus]=(m[g.proofStatus]??0)+1;for(let g of c){if(tf(l,g.subject),r.includeFacts)for(let b of g.why)HM(d,b,r);if(r.includeEdges){if(r.direction!=="outgoing")for(let b of g.retainedBy)nf(l,u,b,r);if(r.direction!=="incoming")for(let b of g.retains??[])nf(l,u,b,r)}for(let b of g.missingProof)p.set(zM(b),b)}return r.includeEdges&&jM(i,o,new Set(l.keys()),l,u,r),{data:{kind:"relationshipGraph",filters:{...r.subject?{subject:r.subject}:{},...r.subjectKind?{subjectKind:r.subjectKind}:{},...r.relations?{relation:[...r.relations]}:{},...r.verdicts?{verdict:[...r.verdicts]}:{},direction:r.direction,includePackets:r.includePackets,includeFacts:r.includeFacts,includeEdges:r.includeEdges},summary:{totalPackets:s.length,returnedPackets:c.length,nodes:l.size,edges:u.size,facts:d.size,missingProof:p.size,byVerdict:f,proofStatus:m},graphSummary:n,packetPage:a.pagination,nodes:[...l.values()],edges:[...u.values()],facts:[...d.values()],missingProof:[...p.values()],...r.includePackets?{packets:c}:{},caveats:['target:"graph" uses native AST facts where available plus research-packet reachability. LSP proof is page-bounded; follow next.page / next.semantic before treating deletion as safe.']},pagination:a.pagination}}function WC(e){return{files:e.length,declarations:e.reduce((t,n)=>t+n.declarations.length,0),imports:e.reduce((t,n)=>t+n.imports.length,0),exports:e.reduce((t,n)=>t+n.exports.length,0),calls:e.reduce((t,n)=>t+n.calls.length,0),edges:e.reduce((t,n)=>t+n.edges.length,0)}}function QM(e){let t={reachable:0,"candidate-dead":0,"transitive-dead":0,"candidate-unused-file":0,"candidate-unused-dependency":0,unknown:0},n=0,r=0;for(let o of e)t[o.verdict]+=1,n+=o.why.length,r+=o.retainedBy.length+(o.retains?.length??0);return{subjects:e.length,facts:n,edges:r,byVerdict:t}}function jM(e,t,n,r,o,i){if(n.size!==0)for(let s of t)for(let a of s.edges){let c=$M(a.relation);if(!Kr(c,i))continue;let l=GC(a.from,e,a.line),u=GC(a.to,e,a.line);!n.has(l.id)&&!n.has(u.id)||nf(r,o,{id:`ast:${l.id}->${u.id}:${c}:${a.line}`,from:l,to:u,relation:c,source:"ast",confidence:"exact",via:{uri:s.file,range:{start:{line:a.line}}}},i)}}function $M(e){let t=e.trim();return UM.has(t)?t:"references"}function GC(e,t,n){let r=qM(e,t);return r?{id:`sym:${r.uri}#${r.name}`,kind:"symbol",name:r.name,uri:r.uri,range:{start:{line:n}}}:{id:`ast:${e}`,kind:"symbol",name:e,uri:e,range:{start:{line:n}}}}function qM(e,t){if(!e.startsWith("symbol:"))return;let n=e.slice(7),r=n.lastIndexOf("#");if(r<1||r===n.length-1)return;let o=n.slice(0,r),i=n.slice(r+1);return{uri:te.isAbsolute(o)?te.relative(t,o):o,name:i}}function HC(e,t){return e==="plan"||t.proof==="none"?!1:t.proof==="lsp"||e==="prove"}function VM(e,t){if(typeof t.proofLimit=="number")return Math.min(25,t.proofLimit);let n=e.itemsPerPage??e.limit??5;return Math.max(1,Math.min(5,n))}async function WM(e,t,n,r,o){let i=n.filter(l=>VC(l,r)),s=Ec(t,i.length),a=i.slice(s.packetsStart,s.packetsEnd).filter(l=>l.subject.kind==="symbol").slice(0,o),c=[];for(let l of a){let u=await YM(e,l);if(l.proof={...l.proof??{},lsp:u},u.status==="unavailable"||u.status==="error"){c.push(x(u.status==="unavailable"?"lspUnavailable":"partialResult",u.message??"LSP proof escalation did not complete.",{backend:"lspGetSemantics",severity:"warning"}));continue}if(typeof u.totalReferences!="number"){c.push(x("partialResult","LSP proof escalation returned without a numeric reference count.",{backend:"lspGetSemantics",blocksAnswer:!0}));continue}l.missingProof=l.missingProof.filter(d=>d.kind!=="lsp-unavailable"),KM(l,u),u.paginationOpen&&(l.missingProof.push({kind:"pagination-open",severity:"high",location:l.subject}),c.push(x("partialResult","LSP proof result is paginated; follow the semantic continuation before deletion.",{backend:"lspGetSemantics",blocksAnswer:!0}))),u.totalReferences===0?(l.proofStatus="confirmed-by-lsp",l.risk={deleteRisk:l.verdict==="reachable"?"high":"medium",reason:"LSP references found zero non-declaration references for this symbol. Still verify dynamic/framework retention before deleting."}):typeof u.totalReferences=="number"&&(l.proofStatus=l.verdict==="reachable"?"confirmed-by-lsp":"conflicting-evidence",l.risk={deleteRisk:"high",reason:"LSP found non-declaration references. Inspect proof.lsp.files and next.fetch before deleting."})}return c}function KM(e,t){if(t.status!=="ok"||!t.totalReferences||t.files.length===0)return;let n=new Set(e.retainedBy.map(r=>r.id));for(let[r,o]of t.files.entries()){let i={id:`file:${o}`,kind:"file",uri:o},s={id:`${e.subject.id}:lsp-ref:${r}`,from:i,to:e.subject,relation:"references",source:"lsp",confidence:"exact",flags:o===e.subject.uri?["same-file"]:["external"]};n.has(s.id)||(e.retainedBy.push(s),n.add(s.id))}}async function YM(e,t){let n=t.subject.name,r=t.subject.range?.start.line;if(!n||typeof r!="number")return{status:"error",files:[],paginationOpen:!1,message:"Symbol packet has no name or line hint for LSP proof."};let o=te.isAbsolute(t.subject.uri)?t.subject.uri:te.resolve(e,t.subject.uri);try{let i=await Pe("lspGetSemantics",{type:"references",uri:o,symbolName:n,lineHint:r,includeDeclaration:!1,groupByFile:!0,itemsPerPage:50}),s=XM(i);if(s)return{status:s.code==="localToolsDisabled"?"unavailable":"error",files:[],paginationOpen:!1,message:s.message};let{data:a,status:c}=dn(i);if(c==="error")return{status:"error",files:[],paginationOpen:!1,message:sf(a?.error)??"lspGetSemantics returned error."};let l=a?.lsp;if(l?.serverAvailable===!1)return{status:"unavailable",files:[],paginationOpen:!1,message:l.source==="native"?"Language server unavailable; native fallback cannot prove cross-file references.":"Language server unavailable; reference proof is incomplete."};let u=a?.payload&&typeof a.payload=="object"?a.payload:void 0,d=a?.pagination,p=Mi(a?.totalReferences)??Mi(u?.totalReferences)??Mi(a?.referenceCount)??Mi(u?.referenceCount)??Mi(d?.totalItems)??zC(u)??zC(a);return{status:"ok",...typeof p=="number"?{totalReferences:p}:{},files:JM(a,e),paginationOpen:d?.hasMore===!0}}catch(i){return{status:"error",files:[],paginationOpen:!1,message:i instanceof Error?i.message:"Could not run LSP proof."}}}function XM(e){let t=e.structuredContent;if(!t||typeof t!="object")return;let n=t;if(n.status!=="error")return;let r=n.error&&typeof n.error=="object"?n.error:void 0;return{...typeof r?.code=="string"?{code:r.code}:{},message:typeof r?.message=="string"&&r.message||typeof n.code=="string"&&n.code||"Direct tool call failed."}}function zC(e){if(e)for(let t of["references","locations","results","byFile"]){let n=e[t];if(Array.isArray(n))return t!=="byFile"?n.length:n.reduce((r,o)=>{if(!o||typeof o!="object")return r+1;let i=o.count;return r+(typeof i=="number"?i:1)},0)}}function JM(e,t){let n=new Set;return rf(e,n,t),[...n].slice(0,25)}function rf(e,t,n){if(t.size>=25||e===null||e===void 0)return;if(Array.isArray(e)){for(let o of e)rf(o,t,n);return}if(typeof e!="object")return;let r=e;for(let o of["uri","file","path"]){let i=r[o];typeof i=="string"&&ZM(i)&&t.add(te.isAbsolute(i)?te.relative(n,i):i)}for(let o of["references","locations","byFile","results","files","groups","items"])rf(r[o],t,n)}function ZM(e){return e.includes("/")||e.includes("\\")||/\.[cm]?[jt]sx?$/.test(e)}function Mi(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function sf(e){return typeof e=="string"?e:void 0}function BC(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function eD(e,t){let n=r=>typeof t[r]=="string"||typeof t[r]=="number"?String(t[r]):void 0;switch(e){case"repository":return n("fullName")??(n("owner")&&n("repo")?`${n("owner")}/${n("repo")}`:n("url"));case"package":{let r=n("name")??n("packageName"),o=n("version");return r?o?`${r}@${o}`:r:void 0}case"pullRequest":return n("number")?`#${n("number")}`:n("url");case"commit":return n("sha")?.slice(0,12)??n("oid")?.slice(0,12);case"artifact":return n("localPath")??n("path");case"materialized":return n("localPath")??n("repoRoot");case"diff":return n("path")??n("filename");case"semantics":{let r=n("uri"),o=n("line")??n("startLine");return r?o?`${r}:${o}`:r:void 0}case"research":return n("intent")??n("goal")??"research";case"graph":return n("intent")?`graph:${n("intent")}`:"graph"}}function af(e,t){let{status:n,data:r}=dn(e);return n==="error"?[x("invalidQuery",of(r?.error,`${t} failed`),{backend:t})]:n==="empty"?[x("zeroMatches","Query ran and matched nothing.",{backend:t,severity:"info",blocksAnswer:!1})]:[]}function KC(e){try{let t=te.isAbsolute(e)?e:te.resolve(e);return kM(t).isDirectory()}catch{return!1}}function Tc(e){if(!e||e.kind!=="github")return{};if(e.repo&&e.repo.includes("/")){let[t,n]=e.repo.split("/");return{owner:t,repo:n}}return{owner:e.owner}}function pn(e){return e.params??{}}function tD(e){let t=e.scope?.language;if(t)return Array.isArray(t)?t[0]:t}function cf(e,t){let n={...pn(e)};if(n.page===void 0&&e.page!==void 0&&(n.page=e.page),t&&n[t]===void 0){let r=e.limit??e.itemsPerPage;r!==void 0&&(n[t]=r)}return n}function kc(e,t,n,r){let{data:o,status:i}=dn(e),s=af(e,n),a=i==="error"?[]:jC(o);a.length===0&&!s.some(p=>p.code==="zeroMatches"||p.severity==="error")&&s.push(x("zeroMatches",`${n} returned no results.`,{backend:n,severity:"info",blocksAnswer:!1}));let c=o?.pagination,l=c?.hasMore===!0||!!o?.next||typeof c?.currentPage=="number"&&typeof c?.totalPages=="number"&&c.currentPage<c.totalPages,u=Bt(c,l),d=t==="package"?LM(o):void 0;return{results:Di(a,t,r,_M(o)),...d?{shared:d}:{},...u?{pagination:u}:{},diagnostics:s,provenance:[{backend:n,source:r}]}}function nD(e,t){let n=[],r=e?.lsp;r?.serverAvailable===!1&&n.push(x("lspUnavailable",r.source==="native"?"Language server was unavailable; native fallback returned partial semantic data.":"Language server was unavailable; semantic proof is incomplete.",{backend:"lspGetSemantics"}));let o=e?.pagination;return o?.hasMore&&n.push(x("partialResult","Semantic result is paginated; follow the continuation before treating it as complete proof.",{backend:"lspGetSemantics",blocksAnswer:!0,continuation:YC(o,t)})),n}function YC(e,t){let n=typeof e.nextPage=="number"?e.nextPage:typeof e.currentPage=="number"?e.currentPage+1:(t.page??1)+1;return{query:{...t,params:{...t.params??{},page:n}},why:"Continue the LSP semantic result page.",confidence:"exact"}}function rD(e,t){let n=e?.pagination;if(n?.hasMore)return{hasMore:!0,...n.currentPage!==void 0?{currentPage:n.currentPage}:{},...n.totalPages!==void 0?{totalPages:n.totalPages}:{},...n.itemsPerPage!==void 0?{itemsPerPage:n.itemsPerPage}:{},...n.totalItems!==void 0?{totalItems:n.totalItems}:{},next:YC(n,t)}}async function oD(e){let{owner:t}=Tc(e.from),n=cf(e,"limit"),r=typeof n.language=="string"?n.language:tD(e),o=Pd(r);o&&(n.language=o);let i=await Pe("ghSearchRepos",{...t?{owner:t}:{},...n});return kc(i,"repository","ghSearchRepos",e.from??{kind:"github"})}async function iD(e){let t=await Pe("npmSearch",{...cf(e)});return kc(t,"package","npmSearch",e.from??{kind:"npm"})}async function QC(e){let{owner:t,repo:n}=Tc(e.from),r=e.target==="commits",o=r?void 0:cD(e),i=r?sD(e):void 0,s=cf(e,r?"perPage":"limit");(o||i)&&(delete s.matchString,delete s.matchScope);let a=await Pe("ghHistoryResearch",{...t?{owner:t}:{},...n?{repo:n}:{},...r?{type:"commits"}:{},...s}),c=kc(a,r?"commit":"pullRequest","ghHistoryResearch",e.from??{kind:"github"});return o?uD(c,o):i?aD(c,i):c}function sD(e){let t=pn(e);return typeof t.matchString=="string"&&t.matchString.length>0?t.matchString:void 0}function aD(e,t){let n=t.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=a.message,l=typeof c=="string"?c:"",u=l.toLowerCase().indexOf(n);if(u<0)return!1;let d=Math.max(0,u-80),p=Math.min(l.length,u+t.length+80);return a.match={matchString:t,scope:"message",spotlight:(d>0?"\u2026":"")+l.slice(d,p)+(p<l.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No commit message matched "${t}" (content filter over ${r} fetched commit(s); not a search-index query). Broaden the fetch (branch/perPage/page).`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched commit(s) matching "${t}" in message. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}function cD(e){let t=pn(e),n=typeof t.matchString=="string"?t.matchString:void 0;if(!n)return;let r=t.matchScope==="title"||t.matchScope==="comments"||t.matchScope==="reviews"||t.matchScope==="all"?t.matchScope:"body";return{needle:n,scope:r}}function lD(e,t){let n=[],r=i=>{typeof i=="string"&&i.length>0&&n.push(i)},o=i=>{let s=e[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&r(a.body)};return(t==="body"||t==="all")&&r(e.body),(t==="title"||t==="all")&&r(e.title),(t==="comments"||t==="all")&&o("comments"),(t==="reviews"||t==="all")&&o("reviews"),n.join(`
58
+ `)}function uD(e,t){let n=t.needle.toLowerCase(),r=e.results.length,o=e.results.filter(s=>{if(s.kind!=="record")return!1;let a=s.data,c=lD(a,t.scope),l=c.toLowerCase().indexOf(n);if(l<0)return!1;let u=Math.max(0,l-80),d=Math.min(c.length,l+t.needle.length+80);return a.match={matchString:t.needle,scope:t.scope,spotlight:(u>0?"\u2026":"")+c.slice(u,d)+(d<c.length?"\u2026":"")},!0}),i=e.diagnostics.filter(s=>s.code!=="zeroMatches");return o.length===0?i.push(x("zeroMatches",`No pull request ${t.scope} matched "${t.needle}" (content filter over ${r} fetched PR(s); not a search-index query). Broaden the fetch (state/keywordsToSearch/page) or the match scope.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})):o.length<r&&i.push(x("partialResult",`Content filter kept ${o.length} of ${r} fetched PR(s) matching "${t.needle}" in ${t.scope}. This filters fetched content only \u2014 page the fetch to widen the candidate set.`,{backend:"ghHistoryResearch",severity:"info",blocksAnswer:!1})),{...e,results:o,diagnostics:i}}async function dD(e){let t=pn(e),{owner:n,repo:r}=Tc(e.from),o=Br(t);if(o.kind==="prPatch"){let i=await Pe("ghHistoryResearch",{...n?{owner:n}:{},...r?{repo:r}:{},content:{patches:{mode:"all"}},...t});return kc(i,"diff","ghHistoryResearch",e.from??{kind:"github"})}return o.kind==="directFile"?e.from?.kind==="local"||e.from?.kind==="materialized"?pD(e,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):fD(e,n,r,{baseRef:o.baseRef,headRef:o.headRef,path:o.path}):{results:[],diagnostics:[x("invalidQuery",'target:"diff" needs either {prNumber} (PR patch diff) or {baseRef,headRef,path} (direct file diff between two refs).',{backend:"ghHistoryResearch",repair:{message:"Add params.prNumber for a PR patch, or params.baseRef + params.headRef + params.path for a direct file diff."}})],provenance:[]}}async function pD(e,t){let n=e.from,r=n?.kind==="local"?n.path:n?.kind==="materialized"?n.localPath:void 0;if(!r)return{results:[],diagnostics:[x("invalidQuery","Local direct file diff needs from.path.",{backend:"localGetFileContent"})],provenance:[]};let o=f=>Pe("localGetFileContent",{path:f,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r),o(t.path)]),a=dn(i),c=dn(s),l=typeof a.data?.content=="string"?a.data.content:void 0,u=typeof c.data?.content=="string"?c.data.content:void 0;if(a.status==="error"||c.status==="error"||l===void 0||u===void 0){let f=of(a.data?.error??c.data?.error,"Could not read local file.");return{results:[],diagnostics:[x("invalidQuery",f,{backend:"localGetFileContent"})],provenance:[{backend:"localGetFileContent",source:e.from}]}}let d=XC(l,u);return{results:[{kind:"record",recordType:"diff",id:`${r}..${t.path}`,...e.from?{source:e.from}:{},data:{path:t.path,basePath:r,headPath:t.path,baseRef:t.baseRef,headRef:t.headRef,additions:d.additions,deletions:d.deletions,patch:d.patch,unchanged:d.unchanged}}],diagnostics:d.additions===0&&d.deletions===0?[x("zeroMatches","Files are identical.",{backend:"localGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"localGetFileContent",source:e.from}]}}async function fD(e,t,n,r){if(!t||!n)return{results:[],diagnostics:[x("invalidQuery","Direct file diff needs a concrete owner/repo.",{backend:"ghGetFileContent"})],provenance:[]};let o=p=>Pe("ghGetFileContent",{owner:t,repo:n,path:r.path,branch:p,fullContent:!0,minify:"none"}),[i,s]=await Promise.all([o(r.baseRef),o(r.headRef)]),a=MC(i),c=MC(s),l=[{label:"base",ref:r.baseRef,...a},{label:"head",ref:r.headRef,...c}].find(p=>p.status==="error"||typeof p.content!="string");if(l){let p=of(l.error,`Could not read ${l.label} ref "${l.ref}" for ${r.path}.`);return{results:[],diagnostics:[x("invalidQuery",p,{backend:"ghGetFileContent"})],provenance:[{backend:"ghGetFileContent",source:e.from}]}}let u=XC(a.content??"",c.content??"");return{results:[{kind:"record",recordType:"diff",id:r.path,...e.from?{source:e.from}:{},data:{path:r.path,baseRef:r.baseRef,headRef:r.headRef,additions:u.additions,deletions:u.deletions,patch:u.patch,unchanged:u.unchanged}}],diagnostics:u.additions===0&&u.deletions===0?[x("zeroMatches","Files are identical at both refs.",{backend:"ghGetFileContent",severity:"info",blocksAnswer:!1})]:[],provenance:[{backend:"ghGetFileContent",source:e.from}]}}function XC(e,t){let n=e===""?[]:e.split(`
59
+ `),r=t===""?[]:t.split(`
60
+ `),o=n.length,i=r.length,s=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let f=o-1;f>=0;f--)for(let m=i-1;m>=0;m--)s[f][m]=n[f]===r[m]?s[f+1][m+1]+1:Math.max(s[f+1][m],s[f][m+1]);let a=[],c=0,l=0,u=0,d=0,p=0;for(;d<o&&p<i;)n[d]===r[p]?(a.push(` ${n[d]}`),u++,d++,p++):s[d+1][p]>=s[d][p+1]?(a.push(`- ${n[d]}`),l++,d++):(a.push(`+ ${r[p]}`),c++,p++);for(;d<o;)a.push(`- ${n[d++]}`),l++;for(;p<i;)a.push(`+ ${r[p++]}`),c++;return{additions:c,deletions:l,unchanged:u,patch:a.join(`
61
+ `)}}async function mD(e){let t=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!t)return{results:[],diagnostics:[x("invalidQuery",'target:"artifacts" needs a local file `from` (path).',{backend:"localBinaryInspect"})],provenance:[]};let n=await Pe("localBinaryInspect",{path:t,...pn(e)}),{data:r,status:o}=dn(n),i=af(n,"localBinaryInspect");return o==="error"||!r?{results:[],diagnostics:i.length?i:[x("zeroMatches","localBinaryInspect returned no data.",{backend:"localBinaryInspect",severity:"info",blocksAnswer:!1})],provenance:[{backend:"localBinaryInspect",source:e.from}]}:{results:Di([r],"artifact",e.from),diagnostics:[...i,...gD(r,e)],provenance:[{backend:"localBinaryInspect",source:e.from}]}}function gD(e,t){let n=e.pagination&&typeof e.pagination=="object"?e.pagination:void 0;return e.isPartial!==!0&&n?.hasMore!==!0?[]:[x("partialResult","Artifact text is paginated; follow the artifact continuation before treating the inline content as complete.",{backend:"localBinaryInspect",blocksAnswer:!0,continuation:hD(t,n)})]}function hD(e,t){if(!(t?.hasMore!==!0||typeof t.nextCharOffset!="number"))return{query:{...e,params:{...e.params??{},charOffset:t.nextCharOffset,...typeof t.charLength=="number"?{charLength:t.charLength}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}async function yD(e){let t,n,r=[],o=[],i=pn(e),s=i.type==="workspaceSymbol",a=typeof i.uri=="string"?i.uri:void 0,c=typeof i.workspaceRoot=="string"?i.workspaceRoot:void 0;if(e.from?.kind==="local")if(s){let k=e.from.path,O=KC(k);n=c??(O?te.resolve(k):void 0),t=a??(O?void 0:k)}else t=a??e.from.path;else if(e.from?.kind==="materialized"){let k=DC(e),O=k?te.isAbsolute(k)?k:te.join(e.from.localPath,k):void 0;s?(n=c??e.from.localPath,t=a??O):t=a??O??e.from.localPath}else if(e.from?.kind==="github"){let{owner:k,repo:O}=Tc(e.from);if(!k||!O)return o.push(x("invalidQuery","Remote semantics needs owner/repo.",{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let w=typeof i.uri=="string"?i.uri:void 0,N=DC(e),I=w&&!te.isAbsolute(w)?w:N,v=await Pe("ghCloneRepo",{owner:k,repo:O,...e.from.ref?{branch:e.from.ref}:{},...I?{sparsePath:I}:{}}),B=dn(v).data,z=OM(v,B?.localPath);if(!z)return o.push(x("materializationFailed","Could not materialize repo for remote LSP.",{backend:"ghCloneRepo"})),{results:[],diagnostics:o,provenance:r};r.push({backend:"ghCloneRepo",source:e.from,materializedPath:z}),s?(n=c??z,w?t=te.isAbsolute(w)?w:te.join(z,w):N&&(t=te.isAbsolute(N)?N:te.join(z,N))):w?t=te.isAbsolute(w)?w:te.join(z,w):N?t=te.isAbsolute(N)?N:te.join(z,N):t=z}if(!t&&!n)return o.push(x("invalidQuery",'target:"semantics" needs a `from` anchor.',{backend:"lspGetSemantics"})),{results:[],diagnostics:o,provenance:r};let{uri:l,symbolKind:u,workspaceRoot:d,...p}=i,f=await Pe("lspGetSemantics",{...p,...n?{workspaceRoot:n}:{},...t?{uri:t}:{}}),{data:m,status:g}=dn(f),b=m,C=rD(b,e),S=vM(sf(b?.uri),t,n),T=SD(e,S),L=RD(bD(b),u);return{results:g==="error"?[]:Di(L,"semantics",T),...C?{pagination:C}:{},diagnostics:[...o,...af(f,"lspGetSemantics"),...nD(b,e)],provenance:[...r,{backend:"lspGetSemantics",source:T}]}}function bD(e){if(!e)return[];let n=(BC(e.payload)?e.payload:void 0)?.symbols;if(Array.isArray(n)){let r=sf(e.uri);return n.map(o=>BC(o)?{...r&&typeof o.uri!="string"?{uri:r}:{},...o}:o)}return jC(e)}function RD(e,t){if(typeof t!="string"||!t.trim())return e;let n=t.trim().toLowerCase();return e.filter(r=>{if(!r||typeof r!="object")return!1;let o=r.kind;return String(o??"").toLowerCase()===n})}function SD(e,t){return e.from?.kind==="local"?{...e.from,path:t}:e.from?.kind==="materialized"?{...e.from,localPath:t}:e.from?.kind==="github"?{kind:"materialized",localPath:t,source:e.from}:e.from??{kind:"local",path:t}}async function CD(e){let t=pn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"research" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlResearch",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"research" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=$C(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"research" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlResearch",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", facets:["symbols","files","relations"] }.'}})],provenance:[{backend:"smartOqlResearch",source:e.from}]};let i;try{i=await Xp({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[x("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested research root.",{backend:"smartOqlResearch"})],provenance:[{backend:"smartOqlResearch",source:e.from}]}}let{packets:s,graphSummary:a}=i.mode==="plan"?{packets:[],graphSummary:void 0}:ef(i),c=[...i.caveats];t.mode==="prove"&&c.push(`mode:"prove" requested on target:"research": packets are candidate-grade unless LSP proof is attached. Native AST facts are included where available, but LSP reference proof is not run here. Use target:"graph" with proof:"lsp" or follow each packet's next.semantic.`);let l=a?Ec(e,s.length):void 0,u=l?s.slice(l.packetsStart,l.packetsEnd):[];l&&s.length>0&&l.packetsStart>=s.length&&c.push(`Packet page ${l.pagination.currentPage} is outside the available packet range (${l.pagination.totalPages} page(s)).`);let d=e.view==="detailed"?MM(e,i):{fields:{}},p={kind:i.kind,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,summary:i.summary,graphCapabilities:i.graphCapabilities,nativeGraphSummary:WC(i.graphFacts),caveats:c,...a?{graphSummary:a,packetPage:l?.pagination,packets:u}:{},...d.fields},f=DM(l?.pagination,d.pagination);return{results:Di([p],"research",e.from),...f?{pagination:f}:{},diagnostics:[],provenance:[{backend:"smartOqlResearch",source:e.from}]}}async function PD(e){let t=pn(e),n=e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0;if(!n)return{results:[],diagnostics:[x("requiresMaterialization",'target:"graph" needs a complete local file universe. Use a local/materialized source, or materialize a bounded GitHub corpus first.',{backend:"smartOqlGraph",repair:{message:'Run target:"materialize" for a bounded GitHub repo/subtree, then run target:"graph" against the returned localPath.'}})],provenance:[]};let r=Array.isArray(t.facets)?t.facets.filter(m=>typeof m=="string"):void 0,o=$C(t.mode);if(o==="prove"&&typeof t.intent!="string")return{results:[],diagnostics:[x("invalidQuery",'target:"graph" mode:"prove" requires params.intent so the proof lane is deterministic. Use intent:"reachability"|"dependencies"|"symbols"|"general", then follow graph packet next.semantic/next.fetch continuations for missing proof.',{backend:"smartOqlGraph",queryPath:"params.intent",repair:{message:'Add params.intent. Example: params:{ mode:"prove", intent:"reachability", direction:"incoming" }.'}})],provenance:[{backend:"smartOqlGraph",source:e.from}]};let i;try{i=await Xp({root:n,goal:typeof t.goal=="string"?t.goal:void 0,intent:typeof t.intent=="string"?t.intent:void 0,facets:r,mode:o,maxFiles:typeof t.maxFiles=="number"?t.maxFiles:void 0})}catch(m){return{results:[],diagnostics:[x("invalidQuery",m instanceof Error?m.message:"Could not analyze the requested graph root.",{backend:"smartOqlGraph"})],provenance:[{backend:"smartOqlGraph",source:e.from}]}}let s=i.mode==="plan"?void 0:ef(i),a=NM(t),c=s?.packets??[],l=HC(i.mode,t)?await WM(n,e,c,a,VM(e,t)):[],u=QM(c),d=BM(e,c,u,a,i.graphFacts,n),p=[...d.data.caveats??[],...i.caveats,...i.mode==="plan"?['mode:"plan" requested: graph packets were not built.']:[],...t.mode==="prove"?[HC(i.mode,t)?'mode:"prove" requested: LSP proof escalation ran for the current graph page only. Follow next.page and next.semantic for remaining/open proof.':'mode:"prove" requested: graph rows are candidate-grade only. Follow packet next.semantic to confirm references.']:[]],f={...d.data,goal:i.goal,intent:i.intent,facets:i.facets,mode:i.mode,root:i.root,flow:i.flow,graphCapabilities:i.graphCapabilities,nativeGraphSummary:WC(i.graphFacts),caveats:p};return{results:Di([f],"graph",e.from),pagination:d.pagination,diagnostics:l,provenance:[{backend:"smartOqlGraph",source:e.from}]}}var UC,AM,IM,qC,UM,JC,ZC=y(()=>{"use strict";Cc();qa();Rt();Ba();Qa();IC();FC();UC=["repositories","pull_requests","commits","packages","results","locations","references","symbols","strings","entries","incomingCalls","outgoingCalls"],AM=new Set([...UC,"pagination","contentPagination","next"]);IM=25;qC=["manifests","files","dependencies","symbols","graphFacts"];UM=new Set(["contains","defines","exports","imports","references","calls","constructs","extends","implements","typeUses"]);JC={repositories:oD,packages:iD,pullRequests:QC,commits:QC,diff:dD,artifacts:mD,semantics:yD,research:CD,graph:PD}});var uP={};bP(uP,{buildArtifactContinuations:()=>sP,runOqlSearch:()=>xD});import dt from"node:path";import{statSync as tP}from"node:fs";async function xD(e,t={}){let n;try{n=yR(e)}catch(o){if(o instanceof an)return Yd(o.diagnostics);throw o}if(Zb(n))return sN(n,e,t);let r=await nP(n,e,t);return lf(r.results),r}function lf(e){if(e.length===0)return;let t=r=>JSON.stringify(r.source??null),n=t(e[0]);if(e.every(r=>t(r)===n))for(let r of e)delete r.source}async function nP(e,t,n,r){let o=GR(e,t),s=!!e.explain||!!n.dryRun?o.plan:void 0;if(!o.executable||n.dryRun)return YD(o,s,e.id,r,n.dryRun,e);let a=await iN(e,o);ZD(e,a.results),wD(e,a),ED(a);let c=AD(e,a);_D(e,a.results);let l=oN(e,a.results),u=LD(a.results);return $a({queryId:e.id,queryIndex:r,results:a.results,...a.shared?{shared:a.shared}:{},...a.pagination?{pagination:a.pagination}:{},...Object.keys(c).length?{next:c}:{},...u?{nextHints:u}:{},diagnostics:[...o.plan.diagnostics,...a.diagnostics,...l],provenance:a.provenance,executable:!0,approximate:QR(o.plan.backendCalls),plan:s})}function wD(e,t){if(e.target==="content")return;let n=typeof e.limit=="number"&&e.limit>0;if(e.target==="code"&&t.pagination?.totalItemsKind==="files"&&!n)return;let r=n?e.limit:typeof e.itemsPerPage=="number"?e.itemsPerPage:void 0;if(!r||r<1||t.results.length<=r)return;let o=t.pagination?.totalItems??t.results.length,i=t.pagination?.currentPage??e.page??1;if(t.results=t.results.slice(0,r),n){let s=t.pagination?.hasMore??!0;t.pagination={...t.pagination,currentPage:i,itemsPerPage:r,totalItems:o,totalItemsCapped:!0,hasMore:s};return}t.pagination={...t.pagination,currentPage:i,itemsPerPage:t.pagination?.itemsPerPage??r,totalItems:o,totalPages:t.pagination?.totalPages??Math.max(1,Math.ceil(o/r)),hasMore:!0}}function ED(e){let t=e.shared?.repositories;if(!t||typeof t!="object"||Array.isArray(t))return;let n=new Set;for(let o of e.results){if(o.kind!=="record"||o.recordType!=="package")continue;let i=o.data.repositoryId;typeof i=="string"&&n.add(i)}if(n.size===0){delete e.shared?.repositories,e.shared&&Object.keys(e.shared).length===0&&delete e.shared;return}let r={};for(let o of n){let i=t[o];i!==void 0&&(r[o]=i)}e.shared={...e.shared,repositories:r}}function TD(e){let t=e.where;if(t){if(t.kind==="text")return{text:t.value,...t.case==="sensitive"?{caseSensitive:!0}:{}};if(t.kind==="regex")return{text:t.value,regex:!0,...t.case==="sensitive"?{caseSensitive:!0}:{}}}}function kD(e){let t=e.scope?.path;return Array.isArray(t)?t[0]:t}function OD(e){return e.from?.kind!=="github"?"owner/repo":e.from.repo?.includes("/")?e.from.repo:e.from.owner&&e.from.repo?`${e.from.owner}/${e.from.repo}`:e.from.repo??"owner/repo"}function vD(e){let t=OD(e),n=kD(e),r=e.from?.kind==="github"&&e.from.ref?`${t}@${e.from.ref}`:t,o=n?`${t}/${n}`:t,i=e.from?.kind==="github"&&e.from.ref?` --branch ${e.from.ref}`:"";return n?`Use \`search ${eP(e)} ${n} --repo ${r} --materialize required\` for one-step local proof, or \`clone ${o}${i}\` / \`cache fetch ${t} ${n}${i} --depth tree\` before retrying local search.`:`Choose a bounded path first with \`search ${t} --tree\`, then use \`search ${eP(e)} <path> --repo ${r} --materialize required\`, \`clone ${t}/<path>${i}\`, or \`cache fetch ${t} <path>${i} --depth tree\`. For deliberate whole-repo work, use \`clone ${t}${i}\` or \`cache fetch ${t}${i} --depth clone\`.`}function eP(e){let t=e.where;return t?.kind==="text"||t?.kind==="regex"?t.value:t?.kind==="structural"?"pattern":"<term>"}function AD(e,t){let n={},r=typeof e.limit=="number"&&e.itemsPerPage===void 0;t.pagination?.hasMore&&e.target!=="content"&&!r&&(n["next.page"]=t.pagination.next??{query:{...e,page:(e.page??1)+1},why:"More result pages remain.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="matchTruncated")&&(n["next.matchPage"]={query:{...e,controls:{...e.controls,search:{...e.controls?.search,matchPage:(e.controls?.search?.matchPage??1)+1}}},why:"Per-file matches were capped; page within files.",confidence:"exact"}),t.diagnostics.some(i=>i.code==="providerUnindexed")&&e.from?.kind==="github"&&e.target==="code"&&(n["next.materialize"]={query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:`GitHub code search returned no results; this is not proof of absence. ${vD(e)}`,confidence:"heuristic"});let o={query:e,fileFrom:WD(e)};for(let i of t.results){let s=i.kind==="record"?`record:${i.recordType}`:i.kind,a=MD[s];if(!a)continue;let c=a(i,o);c&&Object.keys(c).length&&(i.next=c)}return n}function LD(e){let t={},n=!1;for(let r of e){let o=r.next;if(o)for(let[i,s]of Object.entries(o)){if(!s.why||!s.confidence)continue;let a={why:s.why,confidence:s.confidence},c=t[i];if(c||(t[i]=a,n=!0),!c||rP(c,a)){let{why:l,confidence:u,...d}=s;o[i]=d}}}return n?t:void 0}function rP(e,t){return e.why===t.why&&e.confidence===t.confidence}function _D(e,t){for(let n of t)n.proofGrade??=ID(e,n)}function ID(e,t){return t.kind==="code"?Ni(e.where,"structural")||t.metavars!==void 0||t.metavarRanges!==void 0?"structural":Ni(e.where,"text")||Ni(e.where,"regex")||t.line!==void 0||t.snippet!==void 0||t.matchIndices!==void 0?"text":"candidate":t.kind==="content"||t.kind==="file"||t.kind==="tree"?"text":t.kind!=="record"?"candidate":t.recordType==="semantics"?"semantic":t.recordType==="graph"?Oc(t.data)?"missing":"graph":t.recordType==="research"?Oc(t.data)?"missing":t.data.mode==="prove"?"graph":"candidate":t.recordType==="diff"||t.recordType==="artifact"?"text":"candidate"}function Ni(e,t){return e?e.kind===t?!0:e.kind==="all"||e.kind==="any"?e.of.some(n=>Ni(n,t)):e.kind==="not"?Ni(e.predicate,t):!1:!1}function Oc(e){let t=e.missingProof;if(Array.isArray(t)&&t.length>0)return!0;let n=e.packets;return Array.isArray(n)&&n.some(r=>{if(!FD(r))return!1;let o=r.missingProof;return r.proofStatus==="missing"||Array.isArray(o)&&o.length>0})}function FD(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DD(e,t){let n=e,r=t.fileFrom?t.fileFrom(n.path):n.source??t.query.from;if(!r)return;let o=typeof n.line=="number"?{startLine:n.line,contextLines:2}:void 0,i=o?void 0:TD(t.query),s={"next.fetch":{query:{schema:"oql",target:"content",from:r,...t.fileFrom?{}:{scope:{path:n.path}},fetch:{content:{contentView:"exact",...o?{range:o}:{},...i?{match:i}:{}}}},why:"Read the exact content at this hit.",confidence:"exact"}};return t.fileFrom&&(s["next.semantic"]={query:{schema:"oql",target:"semantics",from:r,params:{type:"documentSymbols"}},why:"List the semantic symbols in this file.",confidence:"exact"}),s}function ND(e,t){let n=e,r=n.range?.charOffset;if(typeof r=="number")return{"next.charRange":{query:{...t.query,fetch:{...t.query.fetch,content:{...t.query.fetch?.content,charOffset:r+(n.range?.charLength??2e4)}}},why:"Read the next content window.",confidence:"exact"}}}function oP(e,t){let n={kind:"local",path:e};return{"next.structure":{query:{schema:"oql",target:"structure",from:n},why:`List the ${t} tree.`,confidence:"exact"},"next.files":{query:{schema:"oql",target:"files",from:n},why:`Enumerate files in the ${t}.`,confidence:"exact"}}}function iP(e){let t=e.data;return typeof t?.localPath=="string"?t.localPath:void 0}function sP(e,t){let n={},r=e.data,o=typeof r?.mode=="string"?r.mode:void 0,i=iP(e);i&&(o==="strings"?n["next.search"]={query:{schema:"oql",target:"code",from:{kind:"local",path:i},where:{kind:"regex",value:"https?://\\S+"},controls:{search:{maxMatchesPerFile:100,matchPage:1}}},why:"Grep this strings dump with local code search (ripgrep) \u2014 swap the regex/pattern for what you need (URLs, hosts, symbols); page noisy hits losslessly with matchPage. For a huge binary this beats reading the capped inline preview.",confidence:"heuristic"}:Object.assign(n,oP(i,"extracted")));let s=typeof r?.nextScanOffset=="number"?r.nextScanOffset:void 0;s!==void 0&&(n["next.artifactStrings"]={query:{...t.query,params:{...t.query.params??{},scanOffset:s}},why:"Scan the next window of printable strings.",confidence:"exact"});let a=r?.pagination&&typeof r.pagination=="object"?r.pagination:void 0,c=typeof a?.nextCharOffset=="number"?a.nextCharOffset:void 0;if(a?.hasMore===!0&&c!==void 0){let l=typeof a.charLength=="number"?a.charLength:void 0;n["next.artifactContent"]={query:{...t.query,params:{...t.query.params??{},charOffset:c,...l!==void 0?{charLength:l}:{}}},why:"Read the next inline artifact text window.",confidence:"exact"}}return Object.keys(n).length?n:void 0}function GD(e){let t=iP(e);return t?oP(t,"materialized"):void 0}function HD(e,t){return aP(e,t,{why:"Upgrade this candidate research to LSP-proven relationships for the current page (bounded proof).",force:!0})}function zD(e,t){let n=t.query.params??{};if(n.proof==="none"||n.proof==="lsp"||n.mode==="prove")return;let r=e.data;if(Oc(r))return aP(e,t,{why:"Upgrade this candidate graph page to LSP-proven relationships (bounded proof)."})}function aP(e,t,n){let r=t.query.from;if(r?.kind!=="local"&&r?.kind!=="materialized")return;let o=e.data;if(!n.force&&!Oc(o))return;let i=typeof o?.intent=="string"&&o.intent.length>0?o.intent:typeof t.query.params?.intent=="string"&&t.query.params.intent.length>0?t.query.params.intent:"reachability",s=Math.min(25,Math.max(1,t.query.itemsPerPage??10)),a=t.query.params??{},c=QD(o,a);return{"next.graph":{query:{schema:"oql",target:"graph",from:r,params:{...a,mode:"prove",proof:"lsp",intent:i,proofLimit:s,...c?{facets:c}:{}},...t.query.page?{page:t.query.page}:{},...t.query.itemsPerPage?{itemsPerPage:t.query.itemsPerPage}:{}},why:n.why,confidence:"exact"}}}function QD(e,t){let n=Array.isArray(t.facets)?t.facets:Array.isArray(e.facets)?e.facets:void 0;if(!n)return;let r=n.filter(o=>typeof o=="string"&&BD.has(o));return r.length>0?r:void 0}function UD(e,t){let n=e.data,r=typeof n?.uri=="string"?n.uri:void 0,o=qD(e)??VD(t.query),i=jD(r,o);if(!i)return;let s=typeof n.line=="number"?n.line:typeof n.startLine=="number"?n.startLine:void 0;return{"next.fetch":{query:{schema:"oql",target:"content",from:{kind:"local",path:i},fetch:{content:{contentView:"exact",...s?{range:{startLine:s,contextLines:2}}:{}}}},why:"Read the code at this symbol location.",confidence:"exact"}}}function jD(e,t){if(e&&dt.isAbsolute(e))return e;if(t&&dt.isAbsolute(t)){let n=$D(t);return e?dt.resolve(n,e):t}return t??e}function $D(e){try{return tP(e).isDirectory()?e:dt.dirname(e)}catch{return dt.dirname(e)}}function qD(e){let t=e.source;if(t?.kind==="local")return t.path;if(t?.kind==="materialized")return t.localPath}function VD(e){if(e.from?.kind==="local")return e.from.path;if(e.from?.kind==="materialized")return e.from.localPath}function WD(e){let t=lP(e);if(!t)return;let n=cP(t).slice(0,-dt.sep.length);return r=>({kind:"local",path:dt.isAbsolute(r)?r:dt.join(n,r)})}function KD(e){if(!(!e||e.from?.kind!=="github"||e.target!=="files"||e.where))return{"next.materialize":{query:{schema:"oql",target:"materialize",from:e.from,...e.scope?{scope:e.scope}:{},materialize:{mode:"required"}},why:'target:"files" over GitHub needs a local corpus to enumerate; clone a bounded path (add scope.path to narrow), then list files from the materialized checkpoint.',confidence:"heuristic"}}}function YD(e,t,n,r,o,i){let s=o&&i?XD(i):[],a=o&&i?JD(i):void 0;if(!e.executable){let c=e.plan.nodes.some(l=>l.route==="UNSUPPORTED");return o&&!c?{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}:Yd(e.plan.diagnostics,t,n,r,KD(i))}return{...n?{queryId:n}:{},...r!==void 0?{queryIndex:r}:{},results:[],diagnostics:[...e.plan.diagnostics,...s],provenance:[],evidence:{answerReady:!1,complete:!1,kind:"partial"},...t?{plan:t}:{},...a?{next:a}:{}}}function XD(e){if(e.target!=="research"&&e.target!=="graph")return[];let t=e.target==="research"?'Dry run only planned target:"research"; execute without --dry-run to get the summary plus paged candidate packets. Compact text shows packet subject IDs and next.graph; follow next.graph to upgrade the current page to bounded LSP proof.':'Dry run only planned target:"graph"; execute without --dry-run to get reachability packets. Use params:{mode:"prove",proof:"lsp"} or follow next.graph to run bounded LSP proof for the current page.';return[x("partialResult",t,{backend:e.target==="graph"?"smartOqlGraph":"smartOqlResearch",blocksAnswer:!1,severity:"info"})]}function JD(e){if(e.target!=="research"&&e.target!=="graph")return;let t=e.from;if(t?.kind!=="local"&&t?.kind!=="materialized")return;let n=e.params??{},r=typeof n.intent=="string"&&n.intent.length>0?n.intent:"reachability",o=Math.min(25,Math.max(1,e.itemsPerPage??10));return{"next.graph":{query:{schema:"oql",target:"graph",from:t,params:{...n,mode:"prove",proof:"lsp",intent:r,proofLimit:o},...e.page?{page:e.page}:{},...e.itemsPerPage?{itemsPerPage:e.itemsPerPage}:{}},why:"Run the bounded LSP proof lane for this research/graph page.",confidence:"exact"}}}function cP(e){let t=dt.resolve(e);try{if(tP(t).isDirectory())return`${t}${dt.sep}`}catch{}return`${dt.dirname(t)}${dt.sep}`}function lP(e){return e.from?.kind==="local"?e.from.path:e.from?.kind==="materialized"?e.from.localPath:void 0}function ZD(e,t){let n=lP(e);if(!n)return;let r=cP(n);for(let o of t){let i=o.path;typeof i=="string"&&i.startsWith(r)&&(o.path=i.slice(r.length))}}function oN(e,t){let n=e.select;if(!n||n.length===0)return[];let r=new Set,o=new Set,i=!1,s=[];for(let a of n){let c=a.trim();c==="next"?i=!0:c.startsWith("next.")?r.add(c):tN.has(c)?o.add(c):nN.has(c)?o.add("data"):rN.has(c)||(c.includes(".")?o.add("data"):s.push(c))}for(let a of t){let c=a;for(let l of Object.keys(c))if(!eN.has(l)){if(l==="next"){if(i)continue;let u=c.next;if(!u)continue;if(r.size===0){delete c.next;continue}for(let d of Object.keys(u))r.has(d)||delete u[d];Object.keys(u).length===0&&delete c.next;continue}o.has(l)||delete c[l]}}return s.length?[x("unknownField",`select contains unknown field(s): ${s.join(", ")}. They were ignored.`,{queryPath:"select",severity:"warning",blocksAnswer:!1})]:[]}async function iN(e,t){if(e.target==="materialize")return wC(e);let n=JC[e.target];return n?n(e):e.from?.kind==="local"||e.from?.kind==="materialized"?Ci(e):e.from?.kind==="github"&&e.target==="files"&&!e.where||t.plan.nodes.some(o=>o.route==="ROUTE")||t.plan.materialization?.required===!0||e.materialize?.mode==="required"?xC(e):hC(e)}async function sN(e,t,n){let r=await Promise.all(e.queries.map(async(i,s)=>{let a=await nP(i,t,n,s);return{queryId:i.id??`q${s}`,queryIndex:s,envelope:a}})),o={...e.id?{batchId:e.id}:{},mode:e.combine??"independent",children:r,diagnostics:[]};if(e.combine==="merge"){let i=aN(r);i.error?o.diagnostics.push(i.error):i.envelope&&(o.merged=i.envelope),o.merged&&lf(o.merged.results)}else for(let i of r)lf(i.envelope.results);return o}function aN(e){let t=new Set;for(let u of e)for(let d of u.envelope.results)t.add(d.kind);if(t.size>1)return{error:{code:"invalidQuery",severity:"error",message:'combine:"merge" requires compatible rows (same target/result kind); use combine:"independent".',blocksAnswer:!0,repair:{message:'Set combine:"independent" to keep per-query envelopes.'}}};let n=new Set,r=[],o=[],i=[],s={},a={},c=!1,l=!1;for(let u of e){for(let d of u.envelope.results){let p=dN(d);n.has(p)||(n.add(p),r.push(d))}o.push(...u.envelope.diagnostics),i.push(...u.envelope.provenance),cN(s,u.envelope.nextHints),lN(a,u.envelope.shared),u.envelope.evidence.kind==="candidate"&&(c=!0),uN(u.envelope)&&(l=!0)}return l&&o.push(x("partialResult",'combine:"merge" has child queries with more pages remaining; a merged batch carries no single continuation cursor \u2014 page each query with combine:"independent" to reach completeness.',{severity:"info",blocksAnswer:!1})),{envelope:$a({results:r,...Object.keys(a).length?{shared:a}:{},...l?{pagination:{hasMore:!0}}:{},...Object.keys(s).length?{nextHints:s}:{},diagnostics:o,provenance:i,executable:e.every(u=>u.envelope.evidence.kind!=="unsupported"),approximate:c})}}function cN(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(!o||rP(o,r))&&(e[n]=r)}}function lN(e,t){if(t)for(let[n,r]of Object.entries(t)){let o=e[n];(o===void 0||JSON.stringify(o)===JSON.stringify(r))&&(e[n]=r)}}function uN(e){return!!(e.pagination?.hasMore||e.next&&Object.keys(e.next).some(t=>t.startsWith("next.page")))}function dN(e){let t=e.path??"",n=e.line??"",r=JSON.stringify(e.source??{});return`${e.kind}:${r}:${t}:${n}`}var MD,BD,eN,tN,nN,rN,dP=y(()=>{"use strict";SR();zR();Rt();UR();op();yC();EC();ZC();yi();MD={code:DD,content:ND,"record:artifact":sP,"record:materialized":GD,"record:semantics":UD,"record:research":HD,"record:graph":zD};BD=new Set(["symbols","files","dependencies","relations"]);eN=new Set(["kind","source","recordType","id","proofGrade"]),tN=new Set(["path","line","endLine","column","snippet","matchIndices","metadata","content","contentView","range","metavars","metavarRanges","proofGrade","size","modified","entryType","depth","children","data"]),nN=new Set(["manifests","files","dependencies","symbols","graphFacts","packets","nodes","edges","facts"]),rN=new Set(["pagination","diagnostics","provenance","evidence","repo","localPath"])});async function lC(e){let t=pN(e),n=In.safeParse(t);if(!n.success)throw n.error;let{runOqlSearch:r}=await Promise.resolve().then(()=>(dP(),uP)),o=await r(n.data,{authInfo:e.authInfo});return fN(o)}function pN(e){let t={...e};return delete t.authInfo,delete t.sessionId,delete t.responseCharOffset,delete t.responseCharLength,t}function fN(e){let t=mN(e),n=t.results.some(r=>r.status==="error");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],...n?{isError:!0}:{},structuredContent:t}}function mN(e){return eR(e)?{results:e.children.map(t=>pP(t.envelope,t.queryId)),mode:e.mode,...e.merged?{merged:fP(e.merged)}:{},...e.diagnostics.length>0?{diagnostics:e.diagnostics}:{}}:{results:[pP(e,e.queryId??"oqlSearch-1")]}}function pP(e,t){let n=fP(e);return{id:e.queryId??t,...hN(e),data:n}}function fP(e){let t={...e.nextHints??{}},n=Object.keys(t).length>0,r=e.results.map(o=>{let i=o.next;if(!i)return o;let s={},a=!1;for(let[c,l]of Object.entries(i)){if(!l.why||!l.confidence){s[c]=l;continue}let u={why:l.why,confidence:l.confidence},d=t[c];if(d||(t[c]=u,n=!0),!d||gN(d,u)){let{why:p,confidence:f,...m}=l;s[c]=m,a=!0}else s[c]=l}return a?{...o,next:s}:o});return{...e,results:r,...n?{nextHints:t}:{}}}function gN(e,t){return e.why===t.why&&e.confidence===t.confidence}function hN(e){return e.evidence.kind==="unsupported"||e.diagnostics.some(t=>t.severity==="error")?{status:"error"}:e.results.length===0?{status:"empty"}:{}}var zp=y(()=>{"use strict";Hr();yi()});Ac();me();pt();no();mn();Ic();eo();Ge();_l();Wl();Tl();wt();Jl();Xl();ws();ou();Hs();Wo();iu();su();vo();au();fu();cu();pu();Ps();mu();js();hu();Ru();yu();gu();bu();mt();Jo();Be();Gt();dr();ko();Ht();ks();Ou();Du();ra();Gu();Nu();ri();zu();Hu();da();Bu();Vu();Wu();ii();Xu();Ra();Ko();Ju();Pa();ad();si();Is();dd();ai();ci();pd();pi();li();wd();yd();bd();mi();Mr();Ia();_d();hi();gi();kd();zp();Sc();Sc();Ei();Ei();Op();Ap();Gn();Ep();oc();nn();An();Hp();zl();Dl();Np();Gl();Fl();fe();import{completeMetadata as yN}from"@octocodeai/octocode-core";var Gi=null;function mP(){return Gi||(Gi=yN),Gi}async function F5(){return mP()}async function M5(){mP()}function D5(){return Gi}function N5(){Gi=null}Wp();Pi();De();Hr();Pu();cd();Ku();vr();Rr();vu();Td();_e();function z5(){return process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK?"vscode":process.env.CURSOR_CHANNEL||process.env.CURSOR_TRACE_ID?"cursor":"standalone"}function B5(){try{return ge().local.enabled}catch{return!1}}function Q5(){try{if(!ge().local.enabled)return"Local tools are disabled (ENABLE_LOCAL=false). MCP LSP tools are unavailable."}catch{}return null}fp();wa();ei();Yl();hr();di();Et();Mt();lc();yp();wp();xp();bp();Ls();br();zo();Bs();$o();be();function $5(e,t){let n={contextLines:t.contextLines??0,maxSnippetChars:t.matchContentLength},r=F.parseRipgrepJson(e,n),o=r.files.map(s=>({path:s.path,matchCount:s.matchCount,matches:s.matches.map(a=>({line:a.line,column:a.column,value:a.value}))})),i={totalOccurrences:r.stats.matchCount,matchedLines:r.stats.matchedLines,filesMatched:r.stats.filesMatched,filesSearched:r.stats.filesSearched,bytesSearched:r.stats.bytesSearched??void 0,searchTime:r.stats.searchTime};return{files:o,stats:i}}import{z as H}from"zod";var vc=H.object({text:H.string()}),bN=H.object({match:H.object({text:H.string()}).optional(),start:H.number(),end:H.number()}),RN=H.object({type:H.literal("match"),data:H.object({path:vc,lines:H.object({text:H.string()}),line_number:H.number(),absolute_offset:H.number(),submatches:H.array(bN)})}),SN=H.object({type:H.literal("context"),data:H.object({path:vc,lines:H.object({text:H.string()}),line_number:H.number(),absolute_offset:H.number()})}),CN=H.object({type:H.literal("begin"),data:H.object({path:vc})}),PN=H.object({type:H.literal("end"),data:H.object({path:vc,stats:H.object({elapsed:H.object({human:H.string()}),searches:H.number(),searches_with_match:H.number()}).optional()})}),xN=H.object({type:H.literal("summary"),data:H.object({elapsed_total:H.object({human:H.string()}),stats:H.object({elapsed:H.object({human:H.string()}),searches:H.number(),searches_with_match:H.number(),bytes_searched:H.number(),bytes_printed:H.number(),matched_lines:H.number(),matches:H.number()})})}),W5=H.discriminatedUnion("type",[RN,SN,CN,PN,xN]);je();jp();oe();Ys();aa();_u();Yo();Fu();Ld();Yc();$i();rl();hl();hn();yl();import{securityRegistry as Q6,ContentSanitizer as U6}from"@octocodeai/octocode-engine/security";import{maskSensitiveData as $6}from"@octocodeai/octocode-engine/mask";import{configureSecurity as V6}from"@octocodeai/octocode-engine/withSecurityValidation";import{completeMetadata as t8}from"@octocodeai/octocode-core";import{z as r8}from"zod";export{AN as ALL_ERROR_CODES,cC as ALL_TOOLS,Tw as BASE_SCHEMA,na as BulkCloneRepoLocalSchema,wi as BulkLspGetSemanticsQuerySchema,Lc as CONFIG_ERRORS,wm as CONFIG_FILE_NAME,Co as CONFIG_FILE_PATH,yo as CONFIG_SCHEMA_VERSION,Js as CORE_ALLOWED_ENV_VARS,Lt as CREDENTIALS_FILE,mp as CircuitOpenError,ni as CloneRepoQueryLocalSchema,$s as ContentBuilder,U6 as ContentSanitizer,aV as DEFAULTS,A4 as DEFAULT_CIRCUIT_FAILURE_THRESHOLD,us as DEFAULT_CONFIG,bo as DEFAULT_GITHUB_CONFIG,Xt as DEFAULT_LOCAL_CONFIG,Ro as DEFAULT_LSP_CONFIG,yf as DEFAULT_MATCH_SNIPPET_CHARS,tr as DEFAULT_NETWORK_CONFIG,Ft as DEFAULT_OUTPUT_CONFIG,Sn as DEFAULT_TOOLS_CONFIG,Dp as DEFAULT_TOOL_METADATA_GATEWAY,Ml as DESCRIPTIONS,yE as DIFF_PREVIEW_MAX_LINES,mS as DIRECT_TOOL_CATEGORIES,sI as DIRECT_TOOL_DEFINITIONS,kt as DirectToolInputError,Jn as ENV_TOKEN_VARS,q as ERROR_CODES,Se as ERROR_MESSAGES,Jr as FETCH_ERRORS,qt as FILE_OPERATION_ERRORS,oa as FileContentBulkQueryLocalSchema,ak as FileContentQueryBaseLocalSchema,wr as FileContentQueryLocalSchema,fX as GITHUB_CLONE_REPO,cX as GITHUB_FETCH_CONTENT,hf as GITHUB_FILE_CONTENT_DEFAULT_CHAR_LENGTH,aX as GITHUB_SEARCH_CODE,ot as GITHUB_SEARCH_DEFAULT_LIMIT,Ee as GITHUB_SEARCH_MAX_LIMIT,kN as GITHUB_SEARCH_MAX_PAGES,dX as GITHUB_SEARCH_PULL_REQUESTS,uX as GITHUB_SEARCH_REPOSITORIES,kn as GITHUB_STRUCTURE_DEFAULTS,ON as GITHUB_STRUCTURE_DEFAULT_ENTRIES_PER_PAGE,pf as GITHUB_STRUCTURE_MAX_ENTRIES_PER_PAGE,lX as GITHUB_VIEW_REPO_STRUCTURE,C$ as GitHubCloneRepoOutputLocalSchema,ua as GitHubCodeSearchBulkQueryLocalSchema,f1 as GitHubCodeSearchOutputLocalSchema,la as GitHubCodeSearchQueryLocalSchema,v$ as GitHubFetchContentOutputLocalSchema,Us as GitHubProvider,ha as GitHubPullRequestSearchBulkQueryLocalSchema,Er as GitHubPullRequestSearchQueryLocalSchema,ba as GitHubReposSearchBulkQueryLocalSchema,ya as GitHubReposSearchSingleQueryLocalSchema,k1 as GitHubSearchPullRequestsOutputLocalSchema,nq as GitHubSearchRepositoriesOutputLocalSchema,Ca as GitHubViewRepoStructureBulkQueryLocalSchema,bq as GitHubViewRepoStructureOutputLocalSchema,Sa as GitHubViewRepoStructureQueryLocalSchema,At as HOME,Fz as IGNORED_FILE_EXTENSIONS,Mz as IGNORED_FILE_NAMES,Dz as IGNORED_FOLDER_NAMES,Pt as KEY_FILE,RX as LOCAL_BINARY_INSPECT,mf as LOCAL_DEFAULT_FILES_PER_PAGE,yX as LOCAL_FETCH_CONTENT,hX as LOCAL_FIND_FILES,jn as LOCAL_MAX_DEPTH,zi as LOCAL_MAX_FILES_PER_PAGE,Ot as LOCAL_MAX_LIMIT,mX as LOCAL_RIPGREP,Q as LOCAL_TOOL_ERROR_CODES,bf as LOCAL_TOOL_ERROR_REGISTRY,gX as LOCAL_VIEW_STRUCTURE,Le as LSP_GET_SEMANTICS_TOOL_NAME,bX as LSP_GET_SEMANTIC_CONTENT,xa as LocalBinaryInspectBulkQuerySchema,Tr as LocalBinaryInspectQuerySchema,ka as LocalFetchContentBulkQuerySchema,Ar as LocalFetchContentQuerySchema,Oa as LocalFindFilesBulkQuerySchema,Lr as LocalFindFilesQuerySchema,va as LocalRipgrepBulkQuerySchema,rn as LocalRipgrepQuerySchema,wP as LocalToolErrorCategory,Fa as LocalViewStructureBulkQuerySchema,Nr as LocalViewStructureQuerySchema,rI as LspGetSemanticsOutputSchema,xi as LspGetSemanticsQueryDisplaySchema,Q_ as LspGetSemanticsQuerySchema,Qx as MAX_BRANCH_CACHE_SIZE,$n as MAX_CHAR_LENGTH,gf as MAX_CONTEXT_LINES,Ig as MAX_DEFAULT_OUTPUT_CHAR_LENGTH,Vl as MAX_DIRECTORY_FILES,Qi as MAX_MATCH_CONTENT_LENGTH,ar as MAX_OUTPUT_DEFAULT_CHAR_LENGTH,Bi as MAX_PAGE_NUMBER,ir as MAX_RETRIES,rr as MAX_TIMEOUT,vg as MAX_TOTAL_SIZE,sr as MIN_OUTPUT_DEFAULT_CHAR_LENGTH,or as MIN_RETRIES,nr as MIN_TIMEOUT,wl as NETWORK_ERROR_PATTERNS,LS as NpmDeprecationOutputSchema,AS as NpmRegistrySearchSchema,rc as NpmSearchBulkQueryLocalSchema,Q2 as NpmSearchOutputLocalSchema,nc as NpmSearchQueryLocalSchema,uc as NpmViewResultSchema,Dc as OCTOCODE_DIR,Ne as OCTOCODE_HOME,SX as OQL_SEARCH,Dn as OQL_SEARCH_TOOL_NAME,ds as OctocodeConfigSchema,Dx as OctokitWithThrottling,In as OqlSearchInputSchema,pX as PACKAGE_SEARCH,Zr as PROMISE_ERRORS,wh as PROVIDER_CAPABILITIES,Mh as PROXY_ENV_VARS,fn as PR_CONTENT_DEFAULT_ITEMS_PER_PAGE,ff as PR_CONTENT_MAX_ITEMS_PER_PAGE,Mu as ProviderInitializationError,dj as QuickResult,Ss as RATE_LIMIT_CONFIG,El as RATE_LIMIT_PATTERNS,qn as REPOSITORY_ERRORS,Tt as RESOURCE_LIMITS,W5 as RipgrepJsonMessageSchema,qe as SEARCH_ERRORS,iS as SEMANTIC_CONTENT_TYPES,Ij as SENSITIVE_ENV_VARS,bn as SESSION_FILE,PP as STARTUP_ERRORS,V as STATIC_TOOL_NAMES,Rn as STATS_FILE,Jm as STATUS_TO_ERROR_CODE,qs as StatusEmoji,aT as StatusEmojis,Zo as TOOLING_ALLOWED_ENV_VARS,xP as TOOL_ERRORS,CP as TOOL_METADATA_ERRORS,A as TOOL_NAMES,Oe as ToolError,Xe as ToolErrors,Xr as VALIDATION_ERRORS,ml as _getCacheState,DI as _packageNameToSearchKeywords,fl as _resetConfigCache,N5 as _resetMetadataState,V4 as _resetNpmRegistryUrlCache,xm as _resetSessionState,JH as _resetTokenResolvers,XH as _setTokenResolvers,Ug as applyContentPagination,qb as applyEntryFilters,Nk as applyExactMatchRanking,Sr as applyPagination,Ds as applyPartialContentFilter,Rh as applyStructurePagination,TS as assertCircuitAvailable,$ as attachRawResponseChars,VB as buildBlockBoundaryHint,Eu as buildChildProcessEnv,tg as buildCodeSearchQuery,jo as buildDiffPreview,aI as buildDirectToolCommandPatterns,P4 as buildDirectToolExampleQuery,KA as buildEntryPaginationHints,wy as buildGhSearchCodeFinalizer,Cy as buildGithubFetchContentFinalizer,tF as buildPackagePagination,I$ as buildPaginationHints,rg as buildPullRequestSearchQuery,ng as buildRepoSearchQuery,La as buildSearchResult,Up as buildToolErrorResult,Ad as buildWalkWarnings,sE as byteSlice,vs as byteToCharIndex,Fg as charToByteIndex,vq as checkLargeOutputSafety,O4 as checkNpmAvailability,VI as checkNpmDeprecation,W4 as checkNpmRegistryReachable,Ed as checkRegexSafety,G as clampedInt,ZH as cleanup,Tz as clearAllCache,Oz as clearLSPToolCache,kz as clearLocalToolCache,fz as clearOctokitInstances,oj as clearProviderCache,vz as clearRemoteAPICache,zh as cloneRepo,ia as collectFlatErrors,DT as commonDirPrefix,ip as compactLocation,eF as compactPackageRepositories,Nn as compactResolvedSymbol,Dy as compareIsoDateDescending,t8 as completeMetadata,jT as computeQueryTimeout,Tm as configExists,_4 as configureCircuitBreaker,V6 as configureSecurity,Pr as contextLinesField,zB as convertByteMatchToChar,Dt as countLines,U as countSerializedChars,Zl as createBasePRTransformation,No as createCacheMeta,Ai as createCallItemKey,M as createErrorResult,Nt as createGitHubProviderError,Qs as createGitHubProviderErrorFromResult,at as createLazyProviderContext,Dg as createPaginationInfo,JT as createProviderExecutionContext,ie as createRelaxedBulkQuerySchema,Xo as createResponseFormat,uj as createResult,Vs as createRoleBasedResult,iK as createSafeRegExp,Fe as createSuccessResult,Ki as decrypt,qf as deleteCredentials,Pm as deleteSession,z5 as detectEnvironment,Wi as encrypt,AP as ensureBinary,Af as ensureClone,Tn as ensureCloneParentDir,qi as ensureHome,Vt as ensureOctocodeDir,OP as ensureRepos,ao as ensureTmp,vP as ensureTree,LP as ensureUnzip,Es as evictExpiredClones,Io as evictExpiredTrees,se as executeBulkOperation,ny as executeCloneRepo,Vp as executeDirectTool,hb as executeFetchContent,Sb as executeFindFiles,db as executeInspectBinary,Fp as executeLspGetSemantics,Ti as executeNpmCommand,lC as executeOqlSearchTool,tn as executeProviderOperation,ty as executeProviderOperations,Bb as executeRipgrepSearch,Mb as executeRipgrepSearchInternal,Yb as executeViewStructure,jh as executeWithErrorIsolation,Ve as executeWithToolBoundary,jy as exploreMultipleRepositoryStructures,_s as extractMatchingLines,pb as fallbackOnBestEffortFailure,Ta as fetchContent,Lg as fetchDirectoryContents,du as fetchDirectoryContentsRecursivelyAPI,_g as fetchFileContentToDisk,jg as fetchFileTimestamp,qg as fetchGitHubFileContentAPI,MQ as fetchGitHubPullRequestByNumberAPI,ru as fetchGitHubPullRequestByNumberAPIInternal,gh as fetchHistory,Py as fetchMultipleGitHubFileContents,xs as fetchRawGitHubFileContent,un as fetchWithRetries,Vg as filterPatch,PO as filterStructure,ud as finalizeFetchContentResult,Rb as finalizeFindFilesResult,Ib as finalizeRipgrepResult,Kb as finalizeViewStructureResult,cc as findDirectToolDefinition,Ir as findFiles,Qo as findNextBlockBoundary,fm as flushSession,mm as flushSessionSync,Ox as formatBytes,pj as formatCallToolResultForOutput,hS as formatDirectToolCommandPattern,y4 as formatDirectToolMetadataSchemaText,S4 as formatDirectToolOutputSchemaText,h4 as formatDirectToolSchemaText,dI as formatDirectToolValidationIssues,_r as formatFileSize,sa as formatFinalizedResponse,qo as formatPRForResponse,j1 as formatRepoLine,Tp as gatherIncomingCallsRecursive,kp as gatherOutgoingCallsRecursive,He as generateCacheKey,lU as generatePaginationHints,zs as generateStructurePaginationHints,Sl as getActiveProvider,Cl as getActiveProviderConfig,ji as getAppDataPath,Tf as getArchitecture,DB as getBulkDefaultCharLength,Mg as getByteLength,Az as getCacheStats,Uw as getCacheTTL,Bl as getCloneBaseDir,Rg as getCloneDir,hs as getConfig,Om as getConfigPath,ge as getConfigSync,zm as getConfigValue,yn as getCredentials,Xf as getCredentialsFilePath,Zi as getCredentialsSync,vf as getDefaultOctocodeHome,Gp as getDescription,b4 as getDirectToolAutoFilledFields,ac as getDirectToolCategory,C4 as getDirectToolDescription,SS as getDirectToolDisplayFields,R4 as getDirectToolOutputFields,To as getDirectorySizeBytes,zc as getEnvTokenSource,sg as getExtension,Oh as getFileContent,Xi as getGhCliToken,Um as getGitHubToken,wf as getLocalAppDataPath,Q5 as getLspEnvironmentHint,jw as getMaxCacheSizeBytes,$w as getMaxCloneCount,D5 as getMetadataOrNull,Rp as getNpmRegistryUrl,Cn as getOctocodeDir,pe as getOctokit,gm as getOrCreateSession,et as getOutputCharLimit,rw as getOwnerQualifier,Ef as getPlatformName,Cu as getProvider,le as getRawResponseChars,uu as getRecursiveFetchFailureCount,Ah as getRepoStructure,PB as getReposBaseDir,bs as getServerConfig,hm as getSessionId,Jf as getToken,Yi as getTokenFromEnv,nz as getTokenSource,Zf as getTokenSync,Wc as getTokenWithRefresh,bg as getTreeBaseDir,Ql as getTreeDir,Me as handleCatchError,re as handleGitHubAPIError,Xs as handleProviderError,Kf as hasCredentials,Yf as hasCredentialsSync,Bc as hasEnvToken,g1 as hasExpensiveContentRequest,Wh as hoistSharedFields,lV as ignoreBestEffortFailure,bm as incrementErrors,cs as incrementGitHubCacheHits,ls as incrementGitHubCacheRateLimits,Sm as incrementPackageRegistryFailures,Rm as incrementRateLimitByProvider,ss as incrementRateLimits,ym as incrementToolCalls,as as incrementToolCharSavings,SA as inferLspSymbolName,Qm as initialize,_h as initializeProviders,M5 as initializeToolMetadata,cr as invalidateConfigCache,io as invalidateCredentialsCache,Tj as invokeCallbackSafely,Do as isCacheHit,Sg as isCacheValid,OS as isCircuitOpen,tz as isCloneEnabled,pc as isExactPackageName,On as isGitHubAPIError,HE as isGitHubAPISuccess,Fc as isLinux,ez as isLocalEnabled,I2 as isLocalTool,so as isMac,Bo as isMidBlockCut,wn as isNoResultsSearchError,YT as isProviderError,ea as isProviderSuccess,ro as isRefreshTokenExpired,zE as isRepository,vt as isTokenExpired,_c as isToolError,Nl as isToolInMetadata,gn as isWindows,xr as lineNumberField,Vf as listStoredHosts,Wf as listStoredHostsSync,km as loadConfig,Po as loadConfigSync,F5 as loadToolContent,dy as mapCodeSearchProviderResult,ly as mapCodeSearchToolQuery,yy as mapFileContentProviderResult,hy as mapFileContentToolQuery,gy as mapPullRequestProviderResultData,my as mapPullRequestToolQuery,fy as mapRepoSearchProviderRepositories,py as mapRepoSearchToolQuery,Ry as mapRepoStructureProviderResult,by as mapRepoStructureToolQuery,$6 as maskSensitiveData,Vo as normalizeOwnerRepo,Oy as normalizePullRequestContentRequest,Cs as normalizeResponseHeaders,vd as paginateEntries,ui as parseFileSize,Ce as parseGitHubProjectId,$5 as parseRipgrepJson,ne as paths,Fb as preflightValidateRipgrepPattern,uI as prepareDirectToolInput,x4 as prepareDirectToolInputFromJsonText,$g as processFileContentAPI,ta as providerSupports,Ul as readCacheMeta,_t as readCredentialsStore,kS as recordCircuitFailure,hp as recordCircuitSuccess,jm as recordPackageRegistryFailure,Jt as recordRateLimit,to as redactPath,em as refreshAuthToken,Vh as relativizeResultPaths,ae as relaxedPageNumberField,pl as reloadConfig,Ts as removeCloneDir,L4 as resetCircuitBreaker,Cm as resetSessionStats,jc as resetTokenResolution,dl as resolveConfig,Eo as resolveConfigSync,Ze as resolveDefaultBranch,vp as resolveFileAnchor,KS as resolveSymbolAnchor,$c as resolveToken,Kt as resolveTokenFull,qc as resolveTokenWithRefresh,Qe as responseEnvelopeFields,kr as safeExec,Ue as safeParseOrError,Qp as sanitizeCallToolResult,ht as sanitizeStructuredContent,Th as searchCode,on as searchContentRipgrep,ug as searchGitHubCodeAPI,fh as searchGitHubPullRequestsAPI,bh as searchGitHubReposAPI,Ey as searchMultipleGitHubCode,My as searchMultipleGitHubPullRequests,By as searchMultipleGitHubRepos,QS as searchNpmPackage,US as searchPackage,qS as searchPackages,vh as searchPullRequests,kh as searchRepos,Q6 as securityRegistry,UB as serializeForPagination,_y as shapePullRequestForContent,Ao as shouldIgnoreDir,gr as shouldIgnoreFile,B5 as shouldUseMCPLsp,og as shouldUseSearchForPRs,jB as sliceByCharRespectLines,Kl as sliceContent,As as snapToSemanticBoundary,g4 as sortDirectToolNames,Dh as spawnCheckSuccess,Fj as spawnCollectStdout,vn as spawnWithTimeout,Ho as splitLines,xB as startCacheGC,wB as stopCacheGC,Vc as storeCredentials,Od as summarizeEntries,Wb as toEntryObject,Vb as toGroupedLists,Rf as toToolError,jE as transformCodeSearchResult,VE as transformFileContentResult,Gs as transformPullRequestItemFromREST,ch as transformPullRequestItemFromSearch,XE as transformPullRequestResult,$E as transformRepoSearchResult,ZE as transformRepoStructureResult,Wg as trimDiffContext,ck as truncateSnippetChars,Je as updateSessionStats,es as updateToken,Zs as validateArgs,fs as validateConfig,Ke as validateToolPath,xh as viewGitHubRepositoryStructureAPI,Ma as viewStructure,df as withBasicSecurityValidation,ze as withDataCache,Rj as withResponseEnvelope,uf as withSecurityValidation,Mo as writeCacheMeta,r8 as z};