githits 0.4.13 → 0.4.15

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.
@@ -6,7 +6,7 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "GitHits plugins for Claude Code - code examples from global open source",
9
- "version": "0.4.13"
9
+ "version": "0.4.15"
10
10
  },
11
11
  "plugins": [
12
12
  {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "githits",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "Code examples from global open source for developers and AI assistants",
5
5
  "author": {
6
6
  "name": "GitHits"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "githits",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "Code examples from global open source for developers and AI assistants",
5
5
  "author": {
6
6
  "name": "GitHits"
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{AuthConfigError,AuthStorageLockTimeoutError,AuthStoragePolicyError,AuthenticationError,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,CodeNavigationAccessError,CodeNavigationBackendError,CodeNavigationFeatureFlagRequiredError,CodeNavigationFileNotFoundError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationNetworkError,CodeNavigationTargetNotFoundError,CodeNavigationUnresolvableError,CodeNavigationValidationError,CodeNavigationVersionNotFoundError,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,DEFAULT_MCP_URL,FileSystemServiceImpl,LOCAL_AUTHENTICATION_MISSING_MESSAGE,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,PackageIntelligenceAccessError,PackageIntelligenceBackendError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceGraphQLError,PackageIntelligenceNetworkError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer,debugLog,endTelemetrySpan,flushTelemetry,getAppConfigDirForEnv,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getCodeNavigationUrl,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,isKnownPkgseerRegistryArg,isTelemetryEnabled,loadAutoLoginAuthSessionMetadata,normalizeBaseUrl,parseAuthStorageMode,refreshExpiredToken,startTelemetrySpan,toPkgseerRegistry,toPkgseerRegistryLowercase,withTelemetrySpan}from"./shared/chunk-ancbjszp.js";import{__require,version}from"./shared/chunk-33j95qx6.js";import{Command}from"commander";class AuthRequiredError extends Error{mcpUrl;constructor(message,mcpUrl){super(message);this.name="AuthRequiredError";this.mcpUrl=mcpUrl}}function requireAuth(deps,context){if(deps.hasValidToken)return;const suffix=context?` ${context}`:"";throw new AuthRequiredError(`${LOCAL_AUTHENTICATION_MISSING_MESSAGE.slice(0,-1)}${suffix}.`,deps.mcpUrl)}function buildAuthRequiredErrorPayload(error){return{error:error.message,code:"AUTH_REQUIRED",retryable:false,details:{authSource:"local"}}}function formatAuthRequiredForTerminal(error){const lines=[`${error.message}
2
+ import{AuthConfigError,AuthStorageLockTimeoutError,AuthStoragePolicyError,AuthenticationError,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,CodeNavigationAccessError,CodeNavigationBackendError,CodeNavigationFeatureFlagRequiredError,CodeNavigationFileNotFoundError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationNetworkError,CodeNavigationTargetNotFoundError,CodeNavigationUnresolvableError,CodeNavigationValidationError,CodeNavigationVersionNotFoundError,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,DEFAULT_MCP_URL,FileSystemServiceImpl,LOCAL_AUTHENTICATION_MISSING_MESSAGE,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,PackageIntelligenceAccessError,PackageIntelligenceBackendError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceGraphQLError,PackageIntelligenceNetworkError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer,debugLog,endTelemetrySpan,flushTelemetry,getAppConfigDirForEnv,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getCodeNavigationUrl,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,isAuthClearReason,isKnownPkgseerRegistryArg,isTelemetryEnabled,loadAutoLoginAuthSessionMetadata,normalizeBaseUrl,parseAuthStorageMode,refreshExpiredToken,startTelemetrySpan,toPkgseerRegistry,toPkgseerRegistryLowercase,withTelemetrySpan}from"./shared/chunk-y3y83gbt.js";import{__require,version}from"./shared/chunk-y1k5vkfm.js";import{Command}from"commander";class AuthRequiredError extends Error{mcpUrl;constructor(message,mcpUrl){super(message);this.name="AuthRequiredError";this.mcpUrl=mcpUrl}}function requireAuth(deps,context){if(deps.hasValidToken)return;const suffix=context?` ${context}`:"";throw new AuthRequiredError(`${LOCAL_AUTHENTICATION_MISSING_MESSAGE.slice(0,-1)}${suffix}.`,deps.mcpUrl)}function buildAuthRequiredErrorPayload(error){return{error:error.message,code:"AUTH_REQUIRED",retryable:false,details:{authSource:"local"}}}function formatAuthRequiredForTerminal(error){const lines=[`${error.message}
3
3
  `];if(error.mcpUrl!=="https://mcp.githits.com"){lines.push(` Environment: ${error.mcpUrl}`);lines.push(` You're using a custom environment.
4
4
  `)}lines.push("To authenticate:");lines.push(` githits login
5
5
  `);lines.push("Or set GITHITS_API_TOKEN environment variable.");lines.push(`
@@ -35,11 +35,12 @@ without reading local OAuth storage. Useful for debugging authentication issues.
35
35
  `:undefined}}function formatVerbose(envelope,options){const lines=[];lines.push(buildSummaryHeader(envelope,options));if(envelope.resolution||envelope.indexedVersion){lines.push(buildResolutionLine(envelope,options))}appendTargetResolutionNotes(lines,envelope,options);lines.push("");const pathWidth=longestPathLength(envelope.files);for(const file of envelope.files){lines.push(formatVerboseFileRow(file,pathWidth,options))}if(envelope.hasMore){lines.push("");lines.push(dim("More files available — pass --limit higher to fetch more.",options.useColors))}if(envelope.hint){lines.push("");lines.push(dim(envelope.hint,options.useColors))}lines.push("");return{stdout:lines.join(`
36
36
  `)}}function formatEmpty(envelope,options,verbose){const hint=envelope.hint??"No files match the requested path prefix.";if(!verbose){return{stdout:"",stderr:`${dim(hint,options.useColors)}
37
37
  `}}const lines=[];lines.push(buildSummaryHeader(envelope,options));if(envelope.resolution||envelope.indexedVersion){lines.push(buildResolutionLine(envelope,options))}appendTargetResolutionNotes(lines,envelope,options);lines.push("");lines.push(dim(hint,options.useColors));lines.push("");return{stdout:lines.join(`
38
- `)}}function buildSummaryHeader(envelope,options){const identity=buildIdentityLabel(envelope);const countValue=envelope.hasMore?`${envelope.files.length}+`:String(envelope.total);const counts=`${countValue} ${plural("file","files",envelope.files.length)}`;return colorize(`${identity} · ${counts}`,"bold",options.useColors)}function buildResolutionLine(envelope,options){const parts=[];const ref=envelope.resolution?.resolvedRef??envelope.indexedVersion;if(ref)parts.push(`indexed at ${ref}`);const commit=envelope.resolution?.commitSha;if(commit)parts.push(`commit ${commit.slice(0,7)}`);return dim(parts.join(" · "),options.useColors)}function appendTargetResolutionNotes(lines,envelope,options){const notes=buildTargetResolutionNotes(envelope.targetResolution);for(const note of notes)lines.push(dim(note,options.useColors))}function buildIdentityLabel(envelope){if(envelope.registry&&envelope.name){return`${envelope.name} · ${envelope.registry}`}if(envelope.repoUrl){return envelope.gitRef?`${envelope.repoUrl} @ ${envelope.gitRef}`:envelope.repoUrl}return"(unknown)"}function formatVerboseFileRow(file,pathWidth,options){const annotations=[];if(file.language)annotations.push(file.language);if(file.fileType)annotations.push(file.fileType);if(file.byteSize!=null)annotations.push(humanBytes(file.byteSize));const annotation=annotations.length?dim(`· ${annotations.join(" · ")}`,options.useColors):"";const paddedPath=padRight(file.path,pathWidth);return`${paddedPath} ${annotation}`.trimEnd()}function humanBytes(bytes){if(bytes<1024)return`${bytes} B`;if(bytes<1024*1024)return`${(bytes/1024).toFixed(1)} KB`;return`${(bytes/(1024*1024)).toFixed(1)} MB`}function plural(singular,pluralForm,count){return count===1?singular:pluralForm}function longestPathLength(entries){let max=0;for(const entry of entries){if(entry.path.length>max)max=entry.path.length}return max}function padRight(text,width){return text.length>=width?text:text+" ".repeat(width-text.length)}var SPINNER_FRAMES=["|","/","-","\\"];var FRAME_INTERVAL_MS=80;var MESSAGE_INTERVAL_MS=2000;function startSpinner(message,enabled=true,runtime={}){const stdoutIsTTY=runtime.stdoutIsTTY??process.stdout.isTTY;const stderrIsTTY=runtime.stderrIsTTY??process.stderr.isTTY;const writeStderr=runtime.writeStderr??((chunk)=>process.stderr.write(chunk));if(!enabled||!stdoutIsTTY||!stderrIsTTY){return{stop:()=>{}}}const messages=typeof message==="string"?[message]:message;const framesPerMessage=Math.round(MESSAGE_INTERVAL_MS/FRAME_INTERVAL_MS);const useColors=runtime.useColors??process.env.NO_COLOR===undefined;let frame=0;const render=()=>{const glyph=SPINNER_FRAMES[frame%SPINNER_FRAMES.length]??"|";const label=messages[Math.floor(frame/framesPerMessage)%messages.length]??"";frame+=1;writeStderr(`\r\x1B[2K${colorizeBrand(glyph,"primary",useColors)} ${label}`)};render();const interval=setInterval(render,FRAME_INTERVAL_MS);return{stop:()=>{clearInterval(interval);writeStderr("\r\x1B[2K")}}}var SPINNER_MESSAGES={example:["Searching real implementations...","Exploring open-source code...","Finding production patterns...","Grounding results..."],search:["Exploring repositories...","Tracing symbols...","Inspecting dependencies...","Scanning source code..."],code:["Inspecting source code...","Resolving symbols...","Reading dependency internals..."],docs:["Reading documentation...","Resolving references...","Collecting package docs..."]};function mapCodeNavigationError(error2){const mapped=classify(error2);debugLog("code-nav",{event:"error-classified",code:mapped.code,errorName:error2 instanceof Error?error2.name:typeof error2,detailKeys:mapped.details?Object.keys(mapped.details):[]});return mapped}function classify(error2){if(error2 instanceof ClientUpdateRequiredError){return buildUpdateRequiredError(error2.reason,error2.currentVersion)}if(error2 instanceof CodeNavigationVersionNotFoundError){const details={};if(error2.packageName)details.package=error2.packageName;if(error2.requestedVersion){details.requestedVersion=error2.requestedVersion}if(error2.latestIndexed)details.latestIndexed=error2.latestIndexed;if(error2.availableVersions&&error2.availableVersions.length>0){details.availableVersions=error2.availableVersions}return{code:"VERSION_NOT_FOUND",message:error2.message,retryable:false,details:Object.keys(details).length>0?details:undefined}}if(error2 instanceof CodeNavigationTargetNotFoundError){return{code:"NOT_FOUND",message:error2.message,retryable:false,details:error2.availableVersions?{availableVersions:error2.availableVersions}:undefined}}if(error2 instanceof CodeNavigationFileNotFoundError){return{code:"FILE_NOT_FOUND",message:error2.message,retryable:false,details:error2.filePath?{filePath:error2.filePath}:undefined}}if(error2 instanceof CodeNavigationIndexingError){const details={};if(error2.indexingRef)details.indexingRef=error2.indexingRef;if(error2.availableVersions&&error2.availableVersions.length>0){details.availableVersions=error2.availableVersions}if(error2.availableRefs&&error2.availableRefs.length>0){details.availableRefs=error2.availableRefs}if(error2.targetResolution){details.targetResolution=error2.targetResolution}return{code:"INDEXING",message:error2.message,retryable:true,details:Object.keys(details).length>0?details:undefined}}if(error2 instanceof CodeNavigationUnresolvableError){return{code:"UNRESOLVABLE",message:error2.message,retryable:false}}if(error2 instanceof CodeNavigationAccessError||error2 instanceof CodeNavigationFeatureFlagRequiredError){return{code:"ACCESS_DENIED",message:error2.message,retryable:false}}if(error2 instanceof AuthenticationError||error2 instanceof AuthRequiredError){return{code:"AUTH_REQUIRED",message:error2.message,retryable:false,details:{authSource:error2 instanceof AuthenticationError?error2.source:"local"}}}if(error2 instanceof CodeNavigationNetworkError){return{code:"NETWORK",message:error2.message,retryable:true}}if(error2 instanceof CodeNavigationValidationError){return{code:"INVALID_ARGUMENT",message:normalizeBackendMessage(error2.message),retryable:false}}if(error2 instanceof CodeNavigationBackendError){return classifyBackendError(error2)}if(error2 instanceof CodeNavigationGraphQLError){return{code:"BACKEND_ERROR",message:error2.message,retryable:false,details:error2.code?{graphqlCode:error2.code}:undefined}}if(error2 instanceof MalformedCodeNavigationResponseError){return{code:"PROTOCOL_ERROR",message:error2.message,retryable:false}}if(isInvalidArgumentError(error2)){return{code:"INVALID_ARGUMENT",message:error2.message,retryable:false}}if(error2 instanceof Error){return{code:"UNKNOWN",message:error2.message,retryable:false}}return{code:"UNKNOWN",message:"Unknown error",retryable:false}}function buildUpdateRequiredError(reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion){return{code:"UPDATE_REQUIRED",message:`Update required: ${reason}`,retryable:false,details:{reason,updateCommand:"npm i -g githits@latest",...currentVersion?{currentVersion}:{}}}}function classifyBackendError(error2){const details={};if(typeof error2.status==="number")details.status=error2.status;if(error2.graphqlCode)details.graphqlCode=error2.graphqlCode;const message=normalizeBackendMessage(error2.message);const build=(code,defaultRetryable)=>({code,message,retryable:error2.retryable??defaultRetryable,details:Object.keys(details).length>0?details:undefined});switch(error2.graphqlCode){case"TIMEOUT":return build("TIMEOUT",true);case"RATE_LIMITED":return build("RATE_LIMITED",true);case"UPSTREAM_ERROR":return build("BACKEND_ERROR",true);default:return build("BACKEND_ERROR",false)}}function normalizeBackendMessage(message){return message.replace(/extractable literal anchor/g,"extractable literal substring").replace(/at least one literal anchor/g,"at least one literal substring").replace(/literal prefix/g,"literal substring")}function isInvalidArgumentError(error2){if(!(error2 instanceof Error))return false;return error2.name.startsWith("Invalid")||error2.name.startsWith("Unsupported")}var CLI_AUTH_ERROR_MESSAGE="Authentication required. Run `githits login` to authenticate.";var CLI_LOCAL_AUTH_REMEDIATION="Run `githits login` to authenticate or set GITHITS_API_TOKEN.";var CLI_SERVER_AUTH_REMEDIATION="Re-authenticate with `githits login` or update GITHITS_API_TOKEN if set. If this persists, contact support@githits.com.";function formatMappedErrorForTerminal(mapped){if(mapped.code==="AUTH_REQUIRED"){if(mapped.message==="Authentication required."&&mapped.details?.authSource===undefined){return CLI_AUTH_ERROR_MESSAGE}return`${mapped.message} ${authRemediation(mapped)}`}if(mapped.code!=="UPDATE_REQUIRED"){return mapped.message}const detail=mapped.details??{};const updateCommand=typeof detail.updateCommand==="string"?detail.updateCommand:"npm i -g githits@latest";return[mapped.message,"","Update with:",` ${updateCommand}`].join(`
38
+ `)}}function buildSummaryHeader(envelope,options){const identity=buildIdentityLabel(envelope);const countValue=envelope.hasMore?`${envelope.files.length}+`:String(envelope.total);const counts=`${countValue} ${plural("file","files",envelope.files.length)}`;return colorize(`${identity} · ${counts}`,"bold",options.useColors)}function buildResolutionLine(envelope,options){const parts=[];const ref=envelope.resolution?.resolvedRef??envelope.indexedVersion;if(ref)parts.push(`indexed at ${ref}`);const commit=envelope.resolution?.commitSha;if(commit)parts.push(`commit ${commit.slice(0,7)}`);return dim(parts.join(" · "),options.useColors)}function appendTargetResolutionNotes(lines,envelope,options){const notes=buildTargetResolutionNotes(envelope.targetResolution);for(const note of notes)lines.push(dim(note,options.useColors))}function buildIdentityLabel(envelope){if(envelope.registry&&envelope.name){return`${envelope.name} · ${envelope.registry}`}if(envelope.repoUrl){return envelope.gitRef?`${envelope.repoUrl} @ ${envelope.gitRef}`:envelope.repoUrl}return"(unknown)"}function formatVerboseFileRow(file,pathWidth,options){const annotations=[];if(file.language)annotations.push(file.language);if(file.fileType)annotations.push(file.fileType);if(file.byteSize!=null)annotations.push(humanBytes(file.byteSize));const annotation=annotations.length?dim(`· ${annotations.join(" · ")}`,options.useColors):"";const paddedPath=padRight(file.path,pathWidth);return`${paddedPath} ${annotation}`.trimEnd()}function humanBytes(bytes){if(bytes<1024)return`${bytes} B`;if(bytes<1024*1024)return`${(bytes/1024).toFixed(1)} KB`;return`${(bytes/(1024*1024)).toFixed(1)} MB`}function plural(singular,pluralForm,count){return count===1?singular:pluralForm}function longestPathLength(entries){let max=0;for(const entry of entries){if(entry.path.length>max)max=entry.path.length}return max}function padRight(text,width){return text.length>=width?text:text+" ".repeat(width-text.length)}var SPINNER_FRAMES=["|","/","-","\\"];var FRAME_INTERVAL_MS=80;var MESSAGE_INTERVAL_MS=2000;function startSpinner(message,enabled=true,runtime={}){const stdoutIsTTY=runtime.stdoutIsTTY??process.stdout.isTTY;const stderrIsTTY=runtime.stderrIsTTY??process.stderr.isTTY;const writeStderr=runtime.writeStderr??((chunk)=>process.stderr.write(chunk));if(!enabled||!stdoutIsTTY||!stderrIsTTY){return{stop:()=>{}}}const messages=typeof message==="string"?[message]:message;const framesPerMessage=Math.round(MESSAGE_INTERVAL_MS/FRAME_INTERVAL_MS);const useColors=runtime.useColors??process.env.NO_COLOR===undefined;let frame=0;const render=()=>{const glyph=SPINNER_FRAMES[frame%SPINNER_FRAMES.length]??"|";const label=messages[Math.floor(frame/framesPerMessage)%messages.length]??"";frame+=1;writeStderr(`\r\x1B[2K${colorizeBrand(glyph,"primary",useColors)} ${label}`)};render();const interval=setInterval(render,FRAME_INTERVAL_MS);return{stop:()=>{clearInterval(interval);writeStderr("\r\x1B[2K")}}}var SPINNER_MESSAGES={example:["Searching real implementations...","Exploring open-source code...","Finding production patterns...","Grounding results..."],search:["Exploring repositories...","Tracing symbols...","Inspecting dependencies...","Scanning source code..."],code:["Inspecting source code...","Resolving symbols...","Reading dependency internals..."],docs:["Reading documentation...","Resolving references...","Collecting package docs..."]};function mapCodeNavigationError(error2){const mapped=classify(error2);debugLog("code-nav",{event:"error-classified",code:mapped.code,errorName:error2 instanceof Error?error2.name:typeof error2,detailKeys:mapped.details?Object.keys(mapped.details):[]});return mapped}function classify(error2){if(error2 instanceof ClientUpdateRequiredError){return buildUpdateRequiredError(error2.reason,error2.currentVersion)}if(error2 instanceof CodeNavigationVersionNotFoundError){const details={};if(error2.packageName)details.package=error2.packageName;if(error2.requestedVersion){details.requestedVersion=error2.requestedVersion}if(error2.latestIndexed)details.latestIndexed=error2.latestIndexed;if(error2.availableVersions&&error2.availableVersions.length>0){details.availableVersions=error2.availableVersions}return{code:"VERSION_NOT_FOUND",message:error2.message,retryable:false,details:Object.keys(details).length>0?details:undefined}}if(error2 instanceof CodeNavigationTargetNotFoundError){return{code:"NOT_FOUND",message:error2.message,retryable:false,details:error2.availableVersions?{availableVersions:error2.availableVersions}:undefined}}if(error2 instanceof CodeNavigationFileNotFoundError){return{code:"FILE_NOT_FOUND",message:error2.message,retryable:false,details:error2.filePath?{filePath:error2.filePath}:undefined}}if(error2 instanceof CodeNavigationIndexingError){const details={};if(error2.indexingRef)details.indexingRef=error2.indexingRef;if(error2.availableVersions&&error2.availableVersions.length>0){details.availableVersions=error2.availableVersions}if(error2.availableRefs&&error2.availableRefs.length>0){details.availableRefs=error2.availableRefs}if(error2.targetResolution){details.targetResolution=error2.targetResolution}return{code:"INDEXING",message:error2.message,retryable:true,details:Object.keys(details).length>0?details:undefined}}if(error2 instanceof CodeNavigationUnresolvableError){return{code:"UNRESOLVABLE",message:error2.message,retryable:false}}if(error2 instanceof CodeNavigationAccessError||error2 instanceof CodeNavigationFeatureFlagRequiredError){return{code:"ACCESS_DENIED",message:error2.message,retryable:false}}if(error2 instanceof AuthenticationError||error2 instanceof AuthRequiredError){return{code:"AUTH_REQUIRED",message:error2.message,retryable:false,details:{authSource:error2 instanceof AuthenticationError?error2.source:"local"}}}if(error2 instanceof CodeNavigationNetworkError){return{code:"NETWORK",message:error2.message,retryable:true}}if(error2 instanceof CodeNavigationValidationError){return{code:"INVALID_ARGUMENT",message:normalizeBackendMessage(error2.message),retryable:false}}if(error2 instanceof CodeNavigationBackendError){return classifyBackendError(error2)}if(error2 instanceof CodeNavigationGraphQLError){return{code:"BACKEND_ERROR",message:error2.message,retryable:false,details:error2.code?{graphqlCode:error2.code}:undefined}}if(error2 instanceof MalformedCodeNavigationResponseError){return{code:"PROTOCOL_ERROR",message:error2.message,retryable:false}}if(isInvalidArgumentError(error2)){return{code:"INVALID_ARGUMENT",message:error2.message,retryable:false}}if(error2 instanceof Error){return{code:"UNKNOWN",message:error2.message,retryable:false}}return{code:"UNKNOWN",message:"Unknown error",retryable:false}}function buildUpdateRequiredError(reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion){return{code:"UPDATE_REQUIRED",message:`Update required: ${reason}`,retryable:false,details:{reason,updateCommand:"npm i -g githits@latest",...currentVersion?{currentVersion}:{}}}}function classifyBackendError(error2){const details={};if(typeof error2.status==="number")details.status=error2.status;if(error2.graphqlCode)details.graphqlCode=error2.graphqlCode;const message=normalizeBackendMessage(error2.message);const build=(code,defaultRetryable)=>({code,message,retryable:error2.retryable??defaultRetryable,details:Object.keys(details).length>0?details:undefined});switch(error2.graphqlCode){case"TIMEOUT":return build("TIMEOUT",true);case"RATE_LIMITED":return build("RATE_LIMITED",true);case"REF_NOT_FOUND":return build("REF_NOT_FOUND",false);case"UPSTREAM_ERROR":return build("BACKEND_ERROR",true);default:return build("BACKEND_ERROR",false)}}function normalizeBackendMessage(message){return message.replace(/extractable literal anchor/g,"extractable literal substring").replace(/at least one literal anchor/g,"at least one literal substring").replace(/literal prefix/g,"literal substring")}function isInvalidArgumentError(error2){if(!(error2 instanceof Error))return false;return error2.name.startsWith("Invalid")||error2.name.startsWith("Unsupported")}var CLI_AUTH_ERROR_MESSAGE="Authentication required. Run `githits login` to authenticate.";var CLI_LOCAL_AUTH_REMEDIATION="Run `githits login` to authenticate or set GITHITS_API_TOKEN.";var CLI_SERVER_AUTH_REMEDIATION="Re-authenticate with `githits login` or update GITHITS_API_TOKEN if set. If this persists, contact support@githits.com.";function formatMappedErrorForTerminal(mapped){if(mapped.code==="AUTH_REQUIRED"){if(mapped.message==="Authentication required."&&mapped.details?.authSource===undefined){return CLI_AUTH_ERROR_MESSAGE}return`${mapped.message} ${authRemediation(mapped)}`}if(mapped.code!=="UPDATE_REQUIRED"){return mapped.message}const detail=mapped.details??{};const updateCommand=typeof detail.updateCommand==="string"?detail.updateCommand:"npm i -g githits@latest";return[mapped.message,"","Update with:",` ${updateCommand}`].join(`
39
39
  `)}function authRemediation(mapped){return mapped.details?.authSource==="server"?CLI_SERVER_AUTH_REMEDIATION:CLI_LOCAL_AUTH_REMEDIATION}function buildCliMappedErrorPayload(mapped){return{error:mapped.message,code:mapped.code,retryable:mapped.retryable??false,...mapped.details?{details:mapped.details}:{}}}function parseIntCliOption(raw,name,min,max){if(raw===undefined)return;if(!/^-?\d+$/.test(raw.trim())){throw new InvalidPackageSpecError(`${name} expects an integer between ${min} and ${max}. Got '${raw}'.`)}const parsed=Number.parseInt(raw,10);if(parsed<min||parsed>max){throw new InvalidPackageSpecError(`${name} expects an integer between ${min} and ${max}. Got ${parsed}.`)}return parsed}function resolveCliCodeNavTarget(spec,options){const hasSpec=Boolean(spec);const hasRepoUrl=Boolean(options.repoUrl);const hasGitRef=Boolean(options.gitRef);if(hasSpec&&(hasRepoUrl||hasGitRef)){throw new InvalidPackageSpecError("Provide either a package spec (e.g. `npm:express`) or `--repo-url` with optional `--git-ref`, not both.")}if(!hasSpec&&!hasRepoUrl){throw new InvalidPackageSpecError("A package spec (e.g. `npm:express`) or `--repo-url` is required.")}if(hasSpec){const parsed=parsePackageSpec(spec);return{registry:toPkgseerRegistry(parsed.registry),packageName:parsed.name,version:parsed.version}}return{repoUrl:options.repoUrl,gitRef:options.gitRef}}function formatIndexingError(mapped){if(mapped.code==="UPDATE_REQUIRED"){return formatMappedErrorForTerminal(mapped)}if(mapped.code!=="INDEXING")return formatMappedErrorForTerminal(mapped);const detail=mapped.details??{};const lines=[mapped.message];if(detail.indexingRef)lines.push(` indexingRef: ${detail.indexingRef}`);const versions=detail.availableVersions;if(versions&&versions.length>0){const shown=versions.slice(0,5).map((entry)=>entry.version??entry.ref).join(", ");const more=versions.length-5;const suffix=more>0?` (+${more} more)`:"";lines.push(` already-indexed versions: ${shown}${suffix}`)}const refs=detail.availableRefs;if(refs&&refs.length>0){const shown=refs.slice(0,5).map((entry)=>entry.ref).join(", ");const more=refs.length-5;const suffix=more>0?` (+${more} more)`:"";lines.push(` already-indexed refs: ${shown}${suffix}`)}return lines.join(`
40
40
  `)}function formatFileErrorWithFilesHint(mapped){if(mapped.code==="UPDATE_REQUIRED"){return formatMappedErrorForTerminal(mapped)}if(mapped.code==="FILE_NOT_FOUND"){return`${mapped.message}
41
41
  Use \`code files\` to list available paths.`}if(mapped.code==="NOT_FOUND"&&looksLikeMissingFileMessage(mapped.message)){return`${mapped.message}
42
- Use \`code files\` to list available paths.`}if(looksLikeMissingNavpackMessage(mapped.message)){return["Source index for this target is temporarily unavailable."," Retry with `--wait 60000`, use an already-indexed version/ref, or try again later."].join(`
42
+ Use \`code files\` to list available paths.`}if(mapped.code==="REF_NOT_FOUND"){return`${mapped.message}
43
+ Check that the repository URL and git ref exist and are publicly accessible.`}if(looksLikeMissingNavpackMessage(mapped.message)){return["Source index for this target is temporarily unavailable."," Retry with `--wait 60000`, use an already-indexed version/ref, or try again later."].join(`
43
44
  `)}if(mapped.code==="BACKEND_ERROR"){const retry=mapped.retryable?"Retry in a moment; if it persists, narrow the target or file an issue.":"Narrow the target (path, path-prefix, glob) and retry; if it persists, file an issue.";return`${mapped.message}
44
45
  ${retry}`}return formatIndexingError(mapped)}function looksLikeMissingFileMessage(message){const lower=message.toLowerCase();return lower.includes("file not found")||lower.includes("path not found")||lower.includes("path doesn't resolve")||lower.includes("path does not resolve")}function looksLikeMissingNavpackMessage(message){const lower=message.toLowerCase();return lower.includes("has no navpack for this ref")||lower.includes("navpack was pruned")||lower.includes("indexedrepository row still claims current state")}function handleCodeNavCommandError(error2,json,terminalRenderer,exitCode=1,mapMappedError=(mapped)=>mapped){const mapped=mapMappedError(mapCodeNavigationError(error2));if(json){console.error(JSON.stringify(buildCliMappedErrorPayload(mapped)));process.exit(exitCode)}console.error(terminalRenderer(mapped));process.exit(exitCode)}async function pkgFilesAction(firstArg,secondArg,options,deps){try{requireAuth(deps)}catch(error2){if(options.json)handleCodeNavCommandError(error2,true,formatIndexingError);throw error2}try{if(!deps.codeNavigationUrl||!deps.codeNavigationService){throw new InvalidPackageSpecError("Code navigation is not configured for this environment.")}const hasRepoUrl=Boolean(options.repoUrl);const{spec,pathPrefix}=resolvePositionals(firstArg,secondArg,hasRepoUrl);const target=resolveCliCodeNavTarget(spec,options);const limit=parseIntCliOption(options.limit,"--limit",1,1000);const wait=parseIntCliOption(options.wait,"--wait",0,MAX_WAIT_TIMEOUT_MS);const build=buildCliListFilesParams({target,path:options.path,pathPrefix,globs:options.glob,extensions:options.ext,fileTypes:options.fileType,languages:options.language,fileIntents:options.fileIntent,excludeFileIntents:options.excludeIntent,excludeDocFiles:options.excludeDocs,excludeTestFiles:options.excludeTests,includeHidden:options.hidden,limit,waitTimeoutMs:wait});const spinner=startSpinner(SPINNER_MESSAGES.code,!options.json);const result=await deps.codeNavigationService.listFiles(build.params).finally(()=>spinner.stop());const payload=buildListFilesSuccessPayload(result,{registry:target.registry?toPkgseerRegistryLowercase(target.registry):undefined,name:target.packageName,repoUrl:target.repoUrl,gitRef:target.gitRef,path:build.filterEcho.path,pathPrefix:build.filterEcho.pathPrefix,globs:build.filterEcho.globs,extensions:build.filterEcho.extensions,fileTypes:build.filterEcho.fileTypes,languages:build.filterEcho.languages,fileIntent:build.filterEcho.fileIntent,fileIntents:build.filterEcho.fileIntents,excludeFileIntents:build.filterEcho.excludeFileIntents,excludeDocFiles:build.filterEcho.excludeDocFiles,excludeTestFiles:build.filterEcho.excludeTestFiles,includeHidden:build.filterEcho.includeHidden,limit:build.filterEcho.limit,explicit:build.explicit});if(options.json){console.log(JSON.stringify(payload));return}const rendered=formatListFilesTerminal(payload,{verbose:options.verbose??false,useColors:shouldUseColors()});process.stdout.write(rendered.stdout);if(rendered.stderr)process.stderr.write(rendered.stderr)}catch(error2){handleCodeNavCommandError(error2,options.json??false,formatIndexingError)}}function collectRepeatable(value,previous){return[...previous??[],value]}function buildCliListFilesParams(input){try{return buildListFilesParams(input)}catch(error2){if(!(error2 instanceof InvalidPackageSpecError))throw error2;const rewritten=error2.message.replace(/^`path`/,"`--path`").replace(/`globs`/g,"`--glob`").replace(/`extensions`/g,"`--ext`").replace(/`file_types`/g,"`--file-type`").replace(/`languages`/g,"`--language`").replace(/`file_intent`/g,"`--file-intent`").replace(/`file_intents`/g,"`--file-intent`").replace(/`exclude_file_intents`/g,"`--exclude-intent`").replace(/`path_prefix`/g,"`[path-prefix]`");if(rewritten===error2.message)throw error2;throw new InvalidPackageSpecError(rewritten)}}var REGISTRY_SPEC_HINT=new RegExp(`^(${PKGSEER_REGISTRY_ARGS.join("|")}):`,"i");function resolvePositionals(firstArg,secondArg,hasRepoUrl){if(hasRepoUrl){if(secondArg!==undefined){throw new InvalidPackageSpecError("In --repo-url mode, pass only [path-prefix] — the package spec is replaced by --repo-url.")}if(firstArg&&REGISTRY_SPEC_HINT.test(firstArg)){throw new InvalidPackageSpecError(`'${firstArg}' looks like a package spec. Provide either a package spec or \`--repo-url\` with optional \`--git-ref\`, not both.`)}return{spec:undefined,pathPrefix:firstArg}}return{spec:firstArg,pathPrefix:secondArg}}var PKG_FILES_DESCRIPTION=`List files in an indexed dependency. Default returns up to 200
45
46
  entries; pass [path-prefix] to scope to a directory and --limit to
@@ -86,7 +87,7 @@ use --ext to narrow further (intersection).
86
87
  Default output is \`file:line:text\`, pipe-friendly like grep. Use -C / -A / -B
87
88
  for context, --verbose for grouped output, and --cursor to continue a paginated
88
89
  grep run. --symbol-field hydrates enclosing symbol metadata (appears under each
89
- match in --verbose output; full payload in --json).`;function registerCodeGrepCommand(pkgCommand){return pkgCommand.command("grep").summary("Deterministic text grep over indexed dependency source").description(PKG_GREP_DESCRIPTION).argument("[spec-or-pattern]","Spec mode: package spec (e.g. npm:express). Repo mode (with --repo-url): the pattern.").argument("[pattern-or-prefix]","Spec mode: the pattern. Repo mode: optional path-prefix.").argument("[path-prefix]","Spec mode only: optional path-prefix. Ignored with --repo-url.").option("--repo-url <url>","Repository URL addressing (defaults to the repo default branch)").option("--git-ref <ref>","Optional tag, commit, branch, or HEAD for --repo-url.").option("--path <path>","Exact file path to grep").option("--glob <glob>","Glob scope (repeatable)",collectRepeatable2,[]).option("--ext <ext>","Extension filter without leading dot (repeatable)",collectRepeatable2,[]).option("--regex","Interpret the pattern as RE2 regex").option("--case-sensitive","Enable ASCII case-sensitive matching").option("-C, --context <n>","Context lines before and after each match (0-10)").option("-B, --before-context <n>","Context lines before each match (0-10)").option("-A, --after-context <n>","Context lines after each match (0-10)").option("--exclude-docs","Skip files classified as documentation").option("--exclude-tests","Skip files classified as tests").option("--limit <n>","Max matches to return on this page (1-1000, default 50)").option("--per-file-limit <n>","Cap matches per file within this page (0-1000, 0 = unlimited)").option("--cursor <cursor>","Opaque nextCursor from a previous grep result").option("--symbol-field <field>",`Repeatable; surfaces in --json and under each --verbose match. ${GREP_REPO_SYMBOL_FIELDS_NOTE}`,collectRepeatable2,[]).option("--wait <ms>",`Indexing wait timeout (0-${MAX_WAIT_TIMEOUT_MS}, default ${DEFAULT_WAIT_TIMEOUT_MS})`).option("-v, --verbose","Render grouped output with file headers").option("--json","Emit the JSON envelope").action(async(arg1,arg2,arg3,options)=>{const{createContainer:createContainer2}=await import("./shared/chunk-q9yem3rk.js");const deps=await createContainer2();await pkgGrepAction(arg1,arg2,arg3,options,{codeNavigationService:deps.codeNavigationService,codeNavigationUrl:deps.codeNavigationUrl,hasValidToken:deps.hasValidToken,mcpUrl:deps.mcpUrl})})}function withReadFileRecovery(mapped,requestedPath){if(mapped.code!=="FILE_NOT_FOUND"&&mapped.code!=="NOT_FOUND"){return mapped}return{...mapped,details:{...mapped.details,action:buildReadFileNotFoundAction(requestedPath)}}}function buildReadFileNotFoundAction(requestedPath){const prefix=buildPathPrefixSuggestion(requestedPath);return"`code_read` reads files only, not directories. "+`Use \`code_files\` with \`path_prefix: ${JSON.stringify(prefix)}\` `+"to list candidate files, then pass an emitted `path` back to `code_read`."}function buildPathPrefixSuggestion(requestedPath){const trimmed=requestedPath.trim();if(trimmed==="")return"";if(trimmed.endsWith("/"))return trimmed;const slash=trimmed.lastIndexOf("/");const basename=slash===-1?trimmed:trimmed.slice(slash+1);if(!basename.includes("."))return`${trimmed}/`;return slash===-1?"":trimmed.slice(0,slash+1)}var WAIT_MIN3=0;var WAIT_MAX2=60000;function buildReadFileParams(input){const filePath=input.filePath?.trim()??"";if(!filePath){throw new InvalidPackageSpecError("`file_path` is required — pass the path to the file within the package or repo.")}if(filePath.endsWith("/")){throw new InvalidPackageSpecError(`\`file_path\` must be an exact file path, not a directory prefix. Use \`code_files\` with \`path_prefix: ${JSON.stringify(filePath)}\` to list files, then pass an emitted \`path\` to \`code_read\`.`)}const startLine=normaliseLine(input.startLine,"start_line");const endLine=normaliseLine(input.endLine,"end_line");if(startLine!==undefined&&endLine!==undefined&&startLine>endLine){throw new InvalidPackageSpecError(`Line range is reversed: start_line (${startLine}) must be ≤ end_line (${endLine}).`)}const waitTimeoutMs=normaliseWaitTimeoutMs2(input.waitTimeoutMs);return{params:{target:input.target,filePath,startLine,endLine,waitTimeoutMs}}}function normaliseLine(raw,name){if(raw===undefined)return;if(!Number.isInteger(raw)||raw<1){throw new InvalidPackageSpecError(`\`${name}\` must be a positive integer (lines are 1-indexed). Got ${raw}.`)}return raw}function normaliseWaitTimeoutMs2(raw){if(raw===undefined)return DEFAULT_WAIT_TIMEOUT_MS;if(!Number.isInteger(raw)||raw<WAIT_MIN3||raw>WAIT_MAX2){throw new InvalidPackageSpecError(`\`wait_timeout_ms\` must be an integer between ${WAIT_MIN3} and ${WAIT_MAX2}. Got ${raw}.`)}return raw}function buildReadFileSuccessPayload(result,options){const envelope={path:result.filePath??options.requestedFilePath};if(options.registry)envelope.registry=options.registry;if(options.name)envelope.name=options.name;if(options.repoUrl)envelope.repoUrl=options.repoUrl;if(options.gitRef)envelope.gitRef=options.gitRef;if(result.language!=null)envelope.language=result.language;if(result.totalLines!=null)envelope.totalLines=result.totalLines;if(result.startLine!=null)envelope.startLine=result.startLine;if(result.endLine!=null)envelope.endLine=result.endLine;if(result.isBinary){envelope.isBinary=true}else if(result.content!=null){envelope.content=result.content}const targetResolution=projectTargetResolution(result.targetResolution);if(targetResolution)envelope.targetResolution=targetResolution;return envelope}function formatReadFileTerminal(envelope,options){const verbose=options.verbose??false;if(envelope.isBinary){return formatBinary(envelope,options,verbose)}if(envelope.content==null){return formatNoContent(envelope,options,verbose)}if(!verbose){return envelope.content}return formatVerboseBody(envelope,options)}function formatBinary(envelope,options,verbose){const sentinel=dim("Binary file — cannot display as text.",options.useColors);if(verbose){return`${buildHeader(envelope,options)}
90
+ match in --verbose output; full payload in --json).`;function registerCodeGrepCommand(pkgCommand){return pkgCommand.command("grep").summary("Deterministic text grep over indexed dependency source").description(PKG_GREP_DESCRIPTION).argument("[spec-or-pattern]","Spec mode: package spec (e.g. npm:express). Repo mode (with --repo-url): the pattern.").argument("[pattern-or-prefix]","Spec mode: the pattern. Repo mode: optional path-prefix.").argument("[path-prefix]","Spec mode only: optional path-prefix. Ignored with --repo-url.").option("--repo-url <url>","Repository URL addressing (defaults to the repo default branch)").option("--git-ref <ref>","Optional tag, commit, branch, or HEAD for --repo-url.").option("--path <path>","Exact file path to grep").option("--glob <glob>","Glob scope (repeatable)",collectRepeatable2,[]).option("--ext <ext>","Extension filter without leading dot (repeatable)",collectRepeatable2,[]).option("--regex","Interpret the pattern as RE2 regex").option("--case-sensitive","Enable ASCII case-sensitive matching").option("-C, --context <n>","Context lines before and after each match (0-10)").option("-B, --before-context <n>","Context lines before each match (0-10)").option("-A, --after-context <n>","Context lines after each match (0-10)").option("--exclude-docs","Skip files classified as documentation").option("--exclude-tests","Skip files classified as tests").option("--limit <n>","Max matches to return on this page (1-1000, default 50)").option("--per-file-limit <n>","Cap matches per file within this page (0-1000, 0 = unlimited)").option("--cursor <cursor>","Opaque nextCursor from a previous grep result").option("--symbol-field <field>",`Repeatable; surfaces in --json and under each --verbose match. ${GREP_REPO_SYMBOL_FIELDS_NOTE}`,collectRepeatable2,[]).option("--wait <ms>",`Indexing wait timeout (0-${MAX_WAIT_TIMEOUT_MS}, default ${DEFAULT_WAIT_TIMEOUT_MS})`).option("-v, --verbose","Render grouped output with file headers").option("--json","Emit the JSON envelope").action(async(arg1,arg2,arg3,options)=>{const{createContainer:createContainer2}=await import("./shared/chunk-fj6xaw9r.js");const deps=await createContainer2();await pkgGrepAction(arg1,arg2,arg3,options,{codeNavigationService:deps.codeNavigationService,codeNavigationUrl:deps.codeNavigationUrl,hasValidToken:deps.hasValidToken,mcpUrl:deps.mcpUrl})})}function withReadFileRecovery(mapped,requestedPath){if(mapped.code!=="FILE_NOT_FOUND"&&mapped.code!=="NOT_FOUND"){return mapped}return{...mapped,details:{...mapped.details,action:buildReadFileNotFoundAction(requestedPath)}}}function buildReadFileNotFoundAction(requestedPath){const prefix=buildPathPrefixSuggestion(requestedPath);return"`code_read` reads files only, not directories. "+`Use \`code_files\` with \`path_prefix: ${JSON.stringify(prefix)}\` `+"to list candidate files, then pass an emitted `path` back to `code_read`."}function buildPathPrefixSuggestion(requestedPath){const trimmed=requestedPath.trim();if(trimmed==="")return"";if(trimmed.endsWith("/"))return trimmed;const slash=trimmed.lastIndexOf("/");const basename=slash===-1?trimmed:trimmed.slice(slash+1);if(!basename.includes("."))return`${trimmed}/`;return slash===-1?"":trimmed.slice(0,slash+1)}var WAIT_MIN3=0;var WAIT_MAX2=60000;function buildReadFileParams(input){const filePath=input.filePath?.trim()??"";if(!filePath){throw new InvalidPackageSpecError("`file_path` is required — pass the path to the file within the package or repo.")}if(filePath.endsWith("/")){throw new InvalidPackageSpecError(`\`file_path\` must be an exact file path, not a directory prefix. Use \`code_files\` with \`path_prefix: ${JSON.stringify(filePath)}\` to list files, then pass an emitted \`path\` to \`code_read\`.`)}const startLine=normaliseLine(input.startLine,"start_line");const endLine=normaliseLine(input.endLine,"end_line");if(startLine!==undefined&&endLine!==undefined&&startLine>endLine){throw new InvalidPackageSpecError(`Line range is reversed: start_line (${startLine}) must be ≤ end_line (${endLine}).`)}const waitTimeoutMs=normaliseWaitTimeoutMs2(input.waitTimeoutMs);return{params:{target:input.target,filePath,startLine,endLine,waitTimeoutMs}}}function normaliseLine(raw,name){if(raw===undefined)return;if(!Number.isInteger(raw)||raw<1){throw new InvalidPackageSpecError(`\`${name}\` must be a positive integer (lines are 1-indexed). Got ${raw}.`)}return raw}function normaliseWaitTimeoutMs2(raw){if(raw===undefined)return DEFAULT_WAIT_TIMEOUT_MS;if(!Number.isInteger(raw)||raw<WAIT_MIN3||raw>WAIT_MAX2){throw new InvalidPackageSpecError(`\`wait_timeout_ms\` must be an integer between ${WAIT_MIN3} and ${WAIT_MAX2}. Got ${raw}.`)}return raw}function buildReadFileSuccessPayload(result,options){const envelope={path:result.filePath??options.requestedFilePath};if(options.registry)envelope.registry=options.registry;if(options.name)envelope.name=options.name;if(options.repoUrl)envelope.repoUrl=options.repoUrl;if(options.gitRef)envelope.gitRef=options.gitRef;if(result.language!=null)envelope.language=result.language;if(result.totalLines!=null)envelope.totalLines=result.totalLines;if(result.startLine!=null)envelope.startLine=result.startLine;if(result.endLine!=null)envelope.endLine=result.endLine;if(result.isBinary){envelope.isBinary=true}else if(result.content!=null){envelope.content=result.content}const targetResolution=projectTargetResolution(result.targetResolution);if(targetResolution)envelope.targetResolution=targetResolution;return envelope}function formatReadFileTerminal(envelope,options){const verbose=options.verbose??false;if(envelope.isBinary){return formatBinary(envelope,options,verbose)}if(envelope.content==null){return formatNoContent(envelope,options,verbose)}if(!verbose){return envelope.content}return formatVerboseBody(envelope,options)}function formatBinary(envelope,options,verbose){const sentinel=dim("Binary file — cannot display as text.",options.useColors);if(verbose){return`${buildHeader(envelope,options)}
90
91
 
91
92
  ${sentinel}
92
93
  `}return`${sentinel}
@@ -131,8 +132,8 @@ Use page IDs from githits docs list, githits search --json, or MCP doc/search
131
132
  results. Default output is content-only for easy piping; pass --verbose for a
132
133
  metadata header. Use --lines for a bounded line range (e.g. \`--lines 10-40\`,
133
134
  \`--lines 10-\` for open-ended, or \`--lines -40\` for the first 40 lines) —
134
- useful when a page is too long to read whole.`;function registerDocsReadCommand(docsCommand){return docsCommand.command("read").summary("Read a documentation page by page ID").description(DOCS_READ_DESCRIPTION).argument("<page-id>","Documentation page ID from docs/search results").option("--lines <range>","Bounded line range, e.g. 10-40, 10-, or -40 (1-indexed inclusive)").option("-v, --verbose","Show metadata header before content").option("--json","Emit the JSON envelope").action(async(pageId,options)=>{const deps=await createContainer();await docsReadAction(pageId,options,{packageIntelligenceService:deps.packageIntelligenceService,codeNavigationUrl:deps.codeNavigationUrl,hasValidToken:deps.hasValidToken,mcpUrl:deps.mcpUrl})})}async function registerDocsCommandGroup(program,options={}){const registration=await resolveGatedCommandGroupRegistrationState(options);if(!registration.shouldRegister){return}const docsCommand=program.command("docs").summary("Browse and read package documentation").description("Browse and read package documentation across hosted docs and repository-backed docs. Docs are mixed by default; entries are source-badged and repo-backed pages also expose exact file follow-up metadata.");registerDocsListCommand(docsCommand);registerDocsReadCommand(docsCommand)}import{realpath}from"node:fs/promises";import{parse as parseToml}from"smol-toml";function createDoctorDependencies(){return{fs:new FileSystemServiceImpl,env:process.env,argv:process.argv,execPath:process.execPath,cwd:process.cwd(),platform:process.platform,arch:process.arch,nodeVersion:process.version,bunVersion:process.versions.bun,version,now:()=>new Date,realpath}}async function doctorAction(options,deps=createDoctorDependencies()){const report=await buildDoctorReport(deps);if(options.json){console.log(JSON.stringify(report,null,2));return}console.log(formatDoctorReport(report))}async function buildDoctorReport(deps){const fs=deps.fs;const config=await resolveAuthConfig(fs,deps.env,deps.platform);const activeFileStorageDir=getAuthFileStorageDirForEnv(fs,deps.env,deps.platform);const authFiles=await probeAuthFiles(fs,deps.env,activeFileStorageDir,[...deps.platform==="darwin"?[getLegacyMacAuthFileStorageDirForEnv(fs,deps.env)]:[],getLegacyAuthStorageDirForEnv(fs,deps.env,deps.platform)]);const report={schemaVersion:1,version:deps.version,currentTime:deps.now().toISOString(),platform:{platform:deps.platform,arch:deps.arch},runtime:await buildRuntimeReport(deps),environment:buildEnvironmentReport(deps.env),services:buildServicesReport(deps.env),config:{appConfigDir:getAppConfigDirForEnv(fs,deps.env,deps.platform),configPath:config.configPath,configFile:config.configFile,authStorageMode:config.authStorageMode},auth:{storageMode:config.authStorageMode,activeFileStorageDir,files:authFiles},recommendations:[]};report.recommendations=buildRecommendations(report);return report}function buildEnvironmentReport(env){return{home:envProbe(env.HOME),userProfile:envProbe(env.USERPROFILE),xdgConfigHome:envProbe(env.XDG_CONFIG_HOME),appData:envProbe(env.APPDATA),authStorageOverride:envProbe(env.GITHITS_AUTH_STORAGE),envApiToken:secretEnvProbe(env.GITHITS_API_TOKEN),httpProxy:secretEnvProbe(env.HTTP_PROXY??env.http_proxy),httpsProxy:secretEnvProbe(env.HTTPS_PROXY??env.https_proxy),noProxy:secretEnvProbe(env.NO_PROXY??env.no_proxy),nodeTlsRejectUnauthorized:secretEnvProbe(env.NODE_TLS_REJECT_UNAUTHORIZED)}}async function buildRuntimeReport(deps){const argv1=deps.argv[1];return{kind:deps.bunVersion?"bun":"node",nodeVersion:deps.nodeVersion,bunVersion:deps.bunVersion,execPath:deps.execPath,argv1:argv1?{status:"present",value:argv1}:{status:"missing"},argv1Realpath:argv1?await realpathProbe(argv1,deps.realpath):{status:"skipped",error:{message:"process.argv[1] is missing"}},cwd:deps.cwd,pathGithits:await resolvePathExecutable("githits",deps),npmExecPath:envProbe(deps.env.npm_execpath),npmUserAgent:envProbe(deps.env.npm_config_user_agent),bunInstall:envProbe(deps.env.BUN_INSTALL)}}function buildServicesReport(env){return{mcpUrl:serviceProbe(env.GITHITS_MCP_URL,DEFAULT_MCP_URL),apiUrl:serviceProbe(env.GITHITS_API_URL,DEFAULT_API_URL),codeNavigationUrl:serviceProbe(env.GITHITS_CODE_NAV_URL??env.PKGSEER_URL,DEFAULT_CODE_NAV_URL)}}async function resolveAuthConfig(fs,env,platform){const configPath=getAuthConfigPathForEnv(fs,env,platform);const envMode=env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{configPath,configFile:await filePresenceProbe(fs,configPath),authStorageMode:{status:"present",value:parseAuthStorageMode(envMode),source:"env"}}}catch(error2){return{configPath,configFile:await filePresenceProbe(fs,configPath),authStorageMode:toErrorProbe(error2,"env")}}}const primaryConfig=await readOptionalTextFile(fs,configPath);if(primaryConfig.status==="present"&&primaryConfig.value!==undefined){return parseConfigStorageMode(configPath,primaryConfig.value,"config")}if(primaryConfig.status!=="missing"){return{configPath,configFile:primaryConfig,authStorageMode:{status:"skipped",source:"config",error:{message:"Config file could not be read"}}}}if(platform==="darwin"){const legacyConfigPath=getLegacyMacAuthConfigPathForEnv(fs,env);const legacyConfig=await readOptionalTextFile(fs,legacyConfigPath);if(legacyConfig.status==="present"&&legacyConfig.value!==undefined){return parseConfigStorageMode(legacyConfigPath,legacyConfig.value,"legacy")}if(legacyConfig.status!=="missing"){return{configPath:legacyConfigPath,configFile:legacyConfig,authStorageMode:{status:"skipped",source:"legacy",error:{message:"Legacy macOS config file could not be read"}}}}}return{configPath,configFile:primaryConfig,authStorageMode:{status:"present",value:"keychain",source:"default"}}}function parseConfigStorageMode(configPath,contents,source){try{const parsed=parseToml(contents);const storage=parsed.auth?.storage;if(typeof storage!=="string"||storage.trim()===""){return{configPath,configFile:{status:"present",value:configPath,source},authStorageMode:{status:"present",value:"keychain",source:"default"}}}return{configPath,configFile:{status:"present",value:configPath,source},authStorageMode:{status:"present",value:parseAuthStorageMode(storage),source}}}catch(error2){return{configPath,configFile:{status:"invalid",value:configPath,source},authStorageMode:toErrorProbe(error2,source)}}}async function probeAuthFiles(fs,env,activeDir,legacyDirs){const uniqueDirs=[activeDir,...legacyDirs].filter((dir,index,dirs)=>dirs.indexOf(dir)===index);return Promise.all(uniqueDirs.map((dir,index)=>probeAuthFileDir(fs,env,dir,index===0?"file":"legacy")))}async function probeAuthFileDir(fs,env,dir,source){const authPath=fs.joinPath(dir,"auth.json");const clientPath=fs.joinPath(dir,"client.json");const metadataPath=fs.joinPath(dir,"metadata.json");const normalizedMcpUrl=normalizeBaseUrl(env.GITHITS_MCP_URL??DEFAULT_MCP_URL);const authFile=await readJsonFile(fs,authPath,isStoredAuthFile);const clientFile=await readJsonFile(fs,clientPath,isStoredClientFile);const metadataFile=await readJsonFile(fs,metadataPath,isStoredMetadataFile);const token=authFile.status==="present"&&authFile.value!==undefined?tokenProbe(authFile.value.tokens[normalizedMcpUrl]):dependentProbe(authFile,"auth.json could not be read");const client=clientFile.status==="present"&&clientFile.value!==undefined?clientProbe(clientFile.value.clients[normalizedMcpUrl]):dependentProbe(clientFile,"client.json could not be read");const metadata=metadataFile.status==="present"&&metadataFile.value!==undefined?metadataProbe(metadataFile.value.sessions[normalizedMcpUrl]):dependentProbe(metadataFile,"metadata.json could not be read");return{dir,source,authFile:fileProbeFromRead(authFile,authPath,source),clientFile:fileProbeFromRead(clientFile,clientPath,source),metadataFile:fileProbeFromRead(metadataFile,metadataPath,source),token,client,metadata}}function tokenProbe(token){if(!token)return{status:"missing",source:"file"};return{status:"present",source:"file",value:{createdAt:token.createdAt,expiresAt:token.expiresAt}}}function clientProbe(client){if(!client)return{status:"missing",source:"file"};return{status:"present",source:"file",value:{registeredAt:client.registeredAt}}}function metadataProbe(metadata){if(!metadata)return{status:"missing",source:"file"};return{status:"present",source:"file",value:metadata}}function dependentProbe(file,message){if(file.status==="missing")return{status:"missing",source:"file"};return{status:"skipped",source:"file",error:file.error??{message}}}function fileProbeFromRead(file,path,source){return{status:file.status,value:file.status==="missing"?undefined:path,source,error:file.error}}function buildRecommendations(report){const recommendations=[];if(report.environment.xdgConfigHome.status==="present"){recommendations.push("XDG_CONFIG_HOME is set. Compare `githits doctor --json` between the working and failing environments.")}if(report.environment.appData.status==="present"){recommendations.push("APPDATA is set. Compare `githits doctor --json` between the working and failing environments.")}if(report.auth.storageMode.value==="file"){const active=report.auth.files[0];const activeMissing=active?.token.status==="missing";const legacyPresent=report.auth.files.slice(1).some((entry)=>entry.token.status==="present");if(activeMissing&&legacyPresent){recommendations.push("The active file auth location has no token, but a legacy auth location has one.")}}if(report.auth.storageMode.status==="invalid"){recommendations.push("Fix the auth storage configuration before logging in again.")}if(report.environment.envApiToken.status==="present"){recommendations.push("GITHITS_API_TOKEN is set and takes precedence over stored OAuth credentials.")}return recommendations}function formatDoctorReport(report){const lines=[];lines.push("GitHits Doctor","");lines.push(`Version: ${report.version}`);lines.push(`Current time: ${report.currentTime}`);lines.push(`Platform: ${report.platform.platform} ${report.platform.arch}`,"");lines.push("Runtime:");lines.push(` Runtime: ${report.runtime.kind}`);lines.push(` Node: ${report.runtime.nodeVersion}`);if(report.runtime.bunVersion)lines.push(` Bun: ${report.runtime.bunVersion}`);lines.push(` Executable: ${report.runtime.execPath}`);lines.push(` CLI entrypoint: ${formatProbe(report.runtime.argv1)}`);lines.push(` CLI entrypoint realpath: ${formatProbe(report.runtime.argv1Realpath)}`);lines.push(` PATH githits: ${formatProbe(report.runtime.pathGithits)}`);lines.push(` Working directory: ${report.runtime.cwd}`,"");lines.push("Environment:");lines.push(` HOME: ${formatProbe(report.environment.home)}`);lines.push(` USERPROFILE: ${formatProbe(report.environment.userProfile)}`);lines.push(` XDG_CONFIG_HOME: ${formatProbe(report.environment.xdgConfigHome)}`);lines.push(` APPDATA: ${formatProbe(report.environment.appData)}`);lines.push(` GITHITS_AUTH_STORAGE: ${formatProbe(report.environment.authStorageOverride)}`);lines.push(` GITHITS_API_TOKEN: ${formatProbe(report.environment.envApiToken)}`);lines.push(` HTTP_PROXY: ${formatProbe(report.environment.httpProxy)}`);lines.push(` HTTPS_PROXY: ${formatProbe(report.environment.httpsProxy)}`);lines.push(` NO_PROXY: ${formatProbe(report.environment.noProxy)}`);lines.push(` NODE_TLS_REJECT_UNAUTHORIZED: ${formatProbe(report.environment.nodeTlsRejectUnauthorized)}`,"");lines.push("Services:");lines.push(` MCP URL: ${formatServiceProbe(report.services.mcpUrl)}`);lines.push(` API URL: ${formatServiceProbe(report.services.apiUrl)}`);lines.push(` Code navigation URL: ${formatServiceProbe(report.services.codeNavigationUrl)}`,"");lines.push("Config:");lines.push(` App config dir: ${report.config.appConfigDir}`);lines.push(` Config file: ${formatProbe(report.config.configFile)}`);lines.push(` Auth storage mode: ${formatProbe(report.config.authStorageMode)}`,"");lines.push("Auth:");lines.push(` Active file storage dir: ${report.auth.activeFileStorageDir}`);for(const entry of report.auth.files){if(entry.source==="legacy"&&!hasLegacyAuthEvidence(entry))continue;lines.push(` ${entry.source==="file"?"Active":"Legacy"} auth dir: ${entry.dir}`);lines.push(` auth.json: ${formatProbe(entry.authFile)}`);lines.push(` client.json: ${formatProbe(entry.clientFile)}`);lines.push(` metadata.json: ${formatProbe(entry.metadataFile)}`);lines.push(` token: ${formatTimedProbe(entry.token)}`);lines.push(` client: ${formatTimedProbe(entry.client)}`);lines.push(` metadata: ${formatTimedProbe(entry.metadata)}`)}if(report.recommendations.length>0){lines.push("","Recommendations:");for(const recommendation of report.recommendations){lines.push(` ${recommendation}`)}}return lines.join(`
135
- `)}function hasLegacyAuthEvidence(entry){return entry.authFile.status!=="missing"||entry.clientFile.status!=="missing"||entry.metadataFile.status!=="missing"||entry.token.status!=="missing"||entry.client.status!=="missing"||entry.metadata.status!=="missing"}function formatServiceProbe(probe){return probe.source==="default"?"default production":`overridden: ${probe.value}`}function formatProbe(probe){if(probe.status==="present")return String(probe.value??"present");if(probe.status==="missing")return"unset/missing";if(probe.error)return`${probe.status}: ${probe.error.message}`;return probe.status}function formatTimedProbe(probe){if(probe.status!=="present"||!probe.value||typeof probe.value!=="object"){return formatProbe(probe)}const entries=Object.entries(probe.value).map(([key,value])=>`${key}=${value}`).join(", ");return`present (${entries})`}function envProbe(value){const trimmed=value?.trim();return trimmed?{status:"present",value:trimmed,source:"env"}:{status:"missing",source:"env"}}function secretEnvProbe(value){const trimmed=value?.trim();return trimmed?{status:"present",value:"set",source:"env"}:{status:"missing",source:"env"}}function serviceProbe(value,_defaultValue){return value!==undefined?{source:"env",value}:{source:"default"}}async function filePresenceProbe(fs,path){try{return await fs.exists(path)?{status:"present",value:path,source:"file"}:{status:"missing",source:"file"}}catch(error2){return toErrorProbe(error2,"file")}}async function readOptionalTextFile(fs,path){try{if(!await fs.exists(path))return{status:"missing",source:"file"};return{status:"present",value:await fs.readFile(path),source:"file"}}catch(error2){return toFileReadErrorProbe(error2)}}async function readJsonFile(fs,path,isValid){const file=await readOptionalTextFile(fs,path);if(file.status!=="present"||file.value===undefined)return file;try{const parsed=JSON.parse(file.value);if(!isValid(parsed)){return{status:"invalid",source:"file",error:{message:"Unexpected JSON shape"}}}return{status:"present",value:parsed,source:"file"}}catch(error2){return toErrorProbe(error2,"file","invalid")}}function toFileReadErrorProbe(error2){const code=typeof error2==="object"&&error2!==null&&"code"in error2?String(error2.code):undefined;return{status:code==="EACCES"||code==="EPERM"?"unreadable":"error",source:"file",error:{code,message:error2 instanceof Error?error2.message:String(error2)}}}function toErrorProbe(error2,source,status="invalid"){const code=typeof error2==="object"&&error2!==null&&"code"in error2?String(error2.code):undefined;return{status,source,error:{code,message:error2 instanceof Error?error2.message:String(error2)}}}async function realpathProbe(path,resolveRealpath){try{return{status:"present",value:await resolveRealpath(path),source:"runtime"}}catch(error2){return toErrorProbe(error2,"runtime","error")}}async function resolvePathExecutable(name,deps){const pathValue=deps.env.PATH;if(!pathValue)return{status:"missing",source:"env"};const pathDelimiter=deps.platform==="win32"?";":":";for(const dir of pathValue.split(pathDelimiter)){if(!dir)continue;const candidate=deps.fs.joinPath(dir,name);try{if(await deps.fs.exists(candidate)){return{status:"present",value:candidate,source:"env"}}}catch(error2){return toErrorProbe(error2,"env","error")}}return{status:"missing",source:"env"}}function isStoredAuthFile(value){return hasVersionOne(value)&&typeof value.tokens==="object"}function isStoredClientFile(value){return hasVersionOne(value)&&typeof value.clients==="object"}function isStoredMetadataFile(value){return hasVersionOne(value)&&typeof value.sessions==="object"}function hasVersionOne(value){return typeof value==="object"&&value!==null&&value.version===1}var DOCTOR_DESCRIPTION=`Print redacted diagnostics for GitHits configuration and authentication.
135
+ useful when a page is too long to read whole.`;function registerDocsReadCommand(docsCommand){return docsCommand.command("read").summary("Read a documentation page by page ID").description(DOCS_READ_DESCRIPTION).argument("<page-id>","Documentation page ID from docs/search results").option("--lines <range>","Bounded line range, e.g. 10-40, 10-, or -40 (1-indexed inclusive)").option("-v, --verbose","Show metadata header before content").option("--json","Emit the JSON envelope").action(async(pageId,options)=>{const deps=await createContainer();await docsReadAction(pageId,options,{packageIntelligenceService:deps.packageIntelligenceService,codeNavigationUrl:deps.codeNavigationUrl,hasValidToken:deps.hasValidToken,mcpUrl:deps.mcpUrl})})}async function registerDocsCommandGroup(program,options={}){const registration=await resolveGatedCommandGroupRegistrationState(options);if(!registration.shouldRegister){return}const docsCommand=program.command("docs").summary("Browse and read package documentation").description("Browse and read package documentation across hosted docs and repository-backed docs. Docs are mixed by default; entries are source-badged and repo-backed pages also expose exact file follow-up metadata.");registerDocsListCommand(docsCommand);registerDocsReadCommand(docsCommand)}import{realpath}from"node:fs/promises";import{parse as parseToml}from"smol-toml";function createDoctorDependencies(){return{fs:new FileSystemServiceImpl,env:process.env,argv:process.argv,execPath:process.execPath,cwd:process.cwd(),platform:process.platform,arch:process.arch,nodeVersion:process.version,bunVersion:process.versions.bun,version,now:()=>new Date,realpath}}async function doctorAction(options,deps=createDoctorDependencies()){const report=await buildDoctorReport(deps);if(options.json){console.log(JSON.stringify(report,null,2));return}console.log(formatDoctorReport(report))}async function buildDoctorReport(deps){const fs=deps.fs;const config=await resolveAuthConfig(fs,deps.env,deps.platform);const activeFileStorageDir=getAuthFileStorageDirForEnv(fs,deps.env,deps.platform);const authFiles=await probeAuthFiles(fs,deps.env,activeFileStorageDir,[...deps.platform==="darwin"?[getLegacyMacAuthFileStorageDirForEnv(fs,deps.env)]:[],getLegacyAuthStorageDirForEnv(fs,deps.env,deps.platform)]);const report={schemaVersion:1,version:deps.version,currentTime:deps.now().toISOString(),platform:{platform:deps.platform,arch:deps.arch},runtime:await buildRuntimeReport(deps),environment:buildEnvironmentReport(deps.env),services:buildServicesReport(deps.env),config:{appConfigDir:getAppConfigDirForEnv(fs,deps.env,deps.platform),configPath:config.configPath,configFile:config.configFile,authStorageMode:config.authStorageMode},auth:{storageMode:config.authStorageMode,activeFileStorageDir,files:authFiles},recommendations:[]};report.recommendations=buildRecommendations(report);return report}function buildEnvironmentReport(env){return{home:envProbe(env.HOME),userProfile:envProbe(env.USERPROFILE),xdgConfigHome:envProbe(env.XDG_CONFIG_HOME),appData:envProbe(env.APPDATA),authStorageOverride:envProbe(env.GITHITS_AUTH_STORAGE),envApiToken:secretEnvProbe(env.GITHITS_API_TOKEN),httpProxy:secretEnvProbe(env.HTTP_PROXY??env.http_proxy),httpsProxy:secretEnvProbe(env.HTTPS_PROXY??env.https_proxy),noProxy:secretEnvProbe(env.NO_PROXY??env.no_proxy),nodeTlsRejectUnauthorized:secretEnvProbe(env.NODE_TLS_REJECT_UNAUTHORIZED)}}async function buildRuntimeReport(deps){const argv1=deps.argv[1];return{kind:deps.bunVersion?"bun":"node",nodeVersion:deps.nodeVersion,bunVersion:deps.bunVersion,execPath:deps.execPath,argv1:argv1?{status:"present",value:argv1}:{status:"missing"},argv1Realpath:argv1?await realpathProbe(argv1,deps.realpath):{status:"skipped",error:{message:"process.argv[1] is missing"}},cwd:deps.cwd,pathGithits:await resolvePathExecutable("githits",deps),npmExecPath:envProbe(deps.env.npm_execpath),npmUserAgent:envProbe(deps.env.npm_config_user_agent),bunInstall:envProbe(deps.env.BUN_INSTALL)}}function buildServicesReport(env){return{mcpUrl:serviceProbe(env.GITHITS_MCP_URL,DEFAULT_MCP_URL),apiUrl:serviceProbe(env.GITHITS_API_URL,DEFAULT_API_URL),codeNavigationUrl:serviceProbe(env.GITHITS_CODE_NAV_URL??env.PKGSEER_URL,DEFAULT_CODE_NAV_URL)}}async function resolveAuthConfig(fs,env,platform){const configPath=getAuthConfigPathForEnv(fs,env,platform);const envMode=env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{configPath,configFile:await filePresenceProbe(fs,configPath),authStorageMode:{status:"present",value:parseAuthStorageMode(envMode),source:"env"}}}catch(error2){return{configPath,configFile:await filePresenceProbe(fs,configPath),authStorageMode:toErrorProbe(error2,"env")}}}const primaryConfig=await readOptionalTextFile(fs,configPath);if(primaryConfig.status==="present"&&primaryConfig.value!==undefined){return parseConfigStorageMode(configPath,primaryConfig.value,"config")}if(primaryConfig.status!=="missing"){return{configPath,configFile:primaryConfig,authStorageMode:{status:"skipped",source:"config",error:{message:"Config file could not be read"}}}}if(platform==="darwin"){const legacyConfigPath=getLegacyMacAuthConfigPathForEnv(fs,env);const legacyConfig=await readOptionalTextFile(fs,legacyConfigPath);if(legacyConfig.status==="present"&&legacyConfig.value!==undefined){return parseConfigStorageMode(legacyConfigPath,legacyConfig.value,"legacy")}if(legacyConfig.status!=="missing"){return{configPath:legacyConfigPath,configFile:legacyConfig,authStorageMode:{status:"skipped",source:"legacy",error:{message:"Legacy macOS config file could not be read"}}}}}return{configPath,configFile:primaryConfig,authStorageMode:{status:"present",value:"keychain",source:"default"}}}function parseConfigStorageMode(configPath,contents,source){try{const parsed=parseToml(contents);const storage=parsed.auth?.storage;if(typeof storage!=="string"||storage.trim()===""){return{configPath,configFile:{status:"present",value:configPath,source},authStorageMode:{status:"present",value:"keychain",source:"default"}}}return{configPath,configFile:{status:"present",value:configPath,source},authStorageMode:{status:"present",value:parseAuthStorageMode(storage),source}}}catch(error2){return{configPath,configFile:{status:"invalid",value:configPath,source},authStorageMode:toErrorProbe(error2,source)}}}async function probeAuthFiles(fs,env,activeDir,legacyDirs){const uniqueDirs=[activeDir,...legacyDirs].filter((dir,index,dirs)=>dirs.indexOf(dir)===index);return Promise.all(uniqueDirs.map((dir,index)=>probeAuthFileDir(fs,env,dir,index===0?"file":"legacy")))}async function probeAuthFileDir(fs,env,dir,source){const authPath=fs.joinPath(dir,"auth.json");const clientPath=fs.joinPath(dir,"client.json");const metadataPath=fs.joinPath(dir,"metadata.json");const diagnosticsPath=fs.joinPath(dir,"diagnostics.json");const normalizedMcpUrl=normalizeBaseUrl(env.GITHITS_MCP_URL??DEFAULT_MCP_URL);const authFile=await readJsonFile(fs,authPath,isStoredAuthFile);const clientFile=await readJsonFile(fs,clientPath,isStoredClientFile);const metadataFile=await readJsonFile(fs,metadataPath,isStoredMetadataFile);const diagnosticsFile=await readJsonFile(fs,diagnosticsPath,isStoredDiagnosticsFile);const token=authFile.status==="present"&&authFile.value!==undefined?tokenProbe(authFile.value.tokens[normalizedMcpUrl]):dependentProbe(authFile,"auth.json could not be read");const client=clientFile.status==="present"&&clientFile.value!==undefined?clientProbe(clientFile.value.clients[normalizedMcpUrl]):dependentProbe(clientFile,"client.json could not be read");const metadata=metadataFile.status==="present"&&metadataFile.value!==undefined?metadataProbe(metadataFile.value.sessions[normalizedMcpUrl]):dependentProbe(metadataFile,"metadata.json could not be read");const lastClear=diagnosticsFile.status==="present"&&diagnosticsFile.value!==undefined?lastClearProbe(diagnosticsFile.value.events[normalizedMcpUrl]):dependentProbe(diagnosticsFile,"diagnostics.json could not be read");return{dir,source,authFile:fileProbeFromRead(authFile,authPath,source),clientFile:fileProbeFromRead(clientFile,clientPath,source),metadataFile:fileProbeFromRead(metadataFile,metadataPath,source),token,client,metadata,lastClear}}function tokenProbe(token){if(!token)return{status:"missing",source:"file"};return{status:"present",source:"file",value:{createdAt:token.createdAt,expiresAt:token.expiresAt}}}function clientProbe(client){if(!client)return{status:"missing",source:"file"};return{status:"present",source:"file",value:{registeredAt:client.registeredAt}}}function metadataProbe(metadata){if(!metadata)return{status:"missing",source:"file"};return{status:"present",source:"file",value:metadata}}function lastClearProbe(event){if(event===undefined)return{status:"missing",source:"file"};if(!isRecord(event))return invalidLastClearProbe();const{reason,at}=event;if(!isAuthClearReason(reason)||typeof at!=="string"||at.length===0){return invalidLastClearProbe()}return{status:"present",source:"file",value:{reason,at}}}function invalidLastClearProbe(){return{status:"invalid",source:"file",error:{message:"diagnostics.json has an unrecognized last-clear event"}}}function dependentProbe(file,message){if(file.status==="missing")return{status:"missing",source:"file"};return{status:"skipped",source:"file",error:file.error??{message}}}function fileProbeFromRead(file,path,source){return{status:file.status,value:file.status==="missing"?undefined:path,source,error:file.error}}function buildRecommendations(report){const recommendations=[];if(report.environment.xdgConfigHome.status==="present"){recommendations.push("XDG_CONFIG_HOME is set. Compare `githits doctor --json` between the working and failing environments.")}if(report.environment.appData.status==="present"){recommendations.push("APPDATA is set. Compare `githits doctor --json` between the working and failing environments.")}const activeAuth=report.auth.files[0];if(activeAuth?.token.status==="missing"&&activeAuth.lastClear.status==="present"&&activeAuth.lastClear.value&&!clearSupersededBySession(activeAuth.lastClear.value,activeAuth.metadata)){recommendations.push(lastClearRecommendation(activeAuth.lastClear.value))}if(report.auth.storageMode.value==="file"){const active=report.auth.files[0];const activeMissing=active?.token.status==="missing";const staleSessionEvidence=active?.client.status==="present"||active?.metadata.status==="present";const legacyPresent=report.auth.files.slice(1).some((entry)=>entry.token.status==="present");if(activeMissing&&staleSessionEvidence){recommendations.push("File auth token is missing but client/session metadata remains. Run `githits login` in this environment.")}if(activeMissing&&legacyPresent){recommendations.push("The active file auth location has no token, but a legacy auth location has one.")}}if(report.auth.storageMode.status==="invalid"){recommendations.push("Fix the auth storage configuration before logging in again.")}if(report.environment.envApiToken.status==="present"){recommendations.push("GITHITS_API_TOKEN is set and takes precedence over stored OAuth credentials.")}return recommendations}function formatDoctorReport(report){const lines=[];lines.push("GitHits Doctor","");lines.push(`Version: ${report.version}`);lines.push(`Current time: ${report.currentTime}`);lines.push(`Platform: ${report.platform.platform} ${report.platform.arch}`,"");lines.push("Runtime:");lines.push(` Runtime: ${report.runtime.kind}`);lines.push(` Node: ${report.runtime.nodeVersion}`);if(report.runtime.bunVersion)lines.push(` Bun: ${report.runtime.bunVersion}`);lines.push(` Executable: ${report.runtime.execPath}`);lines.push(` CLI entrypoint: ${formatProbe(report.runtime.argv1)}`);lines.push(` CLI entrypoint realpath: ${formatProbe(report.runtime.argv1Realpath)}`);lines.push(` PATH githits: ${formatProbe(report.runtime.pathGithits)}`);lines.push(` Working directory: ${report.runtime.cwd}`,"");lines.push("Environment:");lines.push(` HOME: ${formatProbe(report.environment.home)}`);lines.push(` USERPROFILE: ${formatProbe(report.environment.userProfile)}`);lines.push(` XDG_CONFIG_HOME: ${formatProbe(report.environment.xdgConfigHome)}`);lines.push(` APPDATA: ${formatProbe(report.environment.appData)}`);lines.push(` GITHITS_AUTH_STORAGE: ${formatProbe(report.environment.authStorageOverride)}`);lines.push(` GITHITS_API_TOKEN: ${formatProbe(report.environment.envApiToken)}`);lines.push(` HTTP_PROXY: ${formatProbe(report.environment.httpProxy)}`);lines.push(` HTTPS_PROXY: ${formatProbe(report.environment.httpsProxy)}`);lines.push(` NO_PROXY: ${formatProbe(report.environment.noProxy)}`);lines.push(` NODE_TLS_REJECT_UNAUTHORIZED: ${formatProbe(report.environment.nodeTlsRejectUnauthorized)}`,"");lines.push("Services:");lines.push(` MCP URL: ${formatServiceProbe(report.services.mcpUrl)}`);lines.push(` API URL: ${formatServiceProbe(report.services.apiUrl)}`);lines.push(` Code navigation URL: ${formatServiceProbe(report.services.codeNavigationUrl)}`,"");lines.push("Config:");lines.push(` App config dir: ${report.config.appConfigDir}`);lines.push(` Config file: ${formatProbe(report.config.configFile)}`);lines.push(` Auth storage mode: ${formatProbe(report.config.authStorageMode)}`,"");lines.push("Auth:");lines.push(` Active file storage dir: ${report.auth.activeFileStorageDir}`);for(const entry of report.auth.files){if(entry.source==="legacy"&&!hasLegacyAuthEvidence(entry))continue;lines.push(` ${entry.source==="file"?"Active":"Legacy"} auth dir: ${entry.dir}`);lines.push(` auth.json: ${formatProbe(entry.authFile)}`);lines.push(` client.json: ${formatProbe(entry.clientFile)}`);lines.push(` metadata.json: ${formatProbe(entry.metadataFile)}`);lines.push(` token: ${formatTimedProbe(entry.token)}`);lines.push(` client: ${formatTimedProbe(entry.client)}`);lines.push(` metadata: ${formatTimedProbe(entry.metadata)}`);lines.push(` last clear: ${formatTimedProbe(entry.lastClear)}`)}if(report.recommendations.length>0){lines.push("","Recommendations:");for(const recommendation of report.recommendations){lines.push(` ${recommendation}`)}}return lines.join(`
136
+ `)}function lastClearRecommendation(event){const when=`(last clear: ${event.reason} at ${event.at})`;switch(event.reason){case"terminal_invalid_refresh_token":return`Auth was cleared after refresh-token reuse or expiry ${when}. Run \`githits login\`. If this recurs, another agent or a stale CLI is likely refreshing the same credentials concurrently.`;case"terminal_invalid_client":return`Auth was cleared after the OAuth client registration was rejected ${when}. Run \`githits login\` to re-register.`;case"logout":return`Credentials were removed by \`githits logout\` ${when}. Run \`githits login\` to sign back in.`;default:return`Auth was last cleared ${when}. Run \`githits login\` if commands report authentication is required.`}}function clearSupersededBySession(lastClear,metadata){if(metadata.status!=="present"||!metadata.value)return false;const clearMs=Date.parse(lastClear.at);if(Number.isNaN(clearMs))return false;const sessionTimes=[metadata.value.createdAt,metadata.value.updatedAt].map((value)=>Date.parse(value)).filter((ms)=>!Number.isNaN(ms));if(sessionTimes.length===0)return false;return Math.max(...sessionTimes)>clearMs}function hasLegacyAuthEvidence(entry){return entry.authFile.status!=="missing"||entry.clientFile.status!=="missing"||entry.metadataFile.status!=="missing"||entry.token.status!=="missing"||entry.client.status!=="missing"||entry.metadata.status!=="missing"||entry.lastClear.status!=="missing"}function formatServiceProbe(probe){return probe.source==="default"?"default production":`overridden: ${probe.value}`}function formatProbe(probe){if(probe.status==="present")return String(probe.value??"present");if(probe.status==="missing")return"unset/missing";if(probe.error)return`${probe.status}: ${probe.error.message}`;return probe.status}function formatTimedProbe(probe){if(probe.status!=="present"||!probe.value||typeof probe.value!=="object"){return formatProbe(probe)}const entries=Object.entries(probe.value).map(([key,value])=>`${key}=${value}`).join(", ");return`present (${entries})`}function envProbe(value){const trimmed=value?.trim();return trimmed?{status:"present",value:trimmed,source:"env"}:{status:"missing",source:"env"}}function secretEnvProbe(value){const trimmed=value?.trim();return trimmed?{status:"present",value:"set",source:"env"}:{status:"missing",source:"env"}}function serviceProbe(value,_defaultValue){return value!==undefined?{source:"env",value}:{source:"default"}}async function filePresenceProbe(fs,path){try{return await fs.exists(path)?{status:"present",value:path,source:"file"}:{status:"missing",source:"file"}}catch(error2){return toErrorProbe(error2,"file")}}async function readOptionalTextFile(fs,path){try{if(!await fs.exists(path))return{status:"missing",source:"file"};return{status:"present",value:await fs.readFile(path),source:"file"}}catch(error2){return toFileReadErrorProbe(error2)}}async function readJsonFile(fs,path,isValid){const file=await readOptionalTextFile(fs,path);if(file.status!=="present"||file.value===undefined)return file;try{const parsed=JSON.parse(file.value);if(!isValid(parsed)){return{status:"invalid",source:"file",error:{message:"Unexpected JSON shape"}}}return{status:"present",value:parsed,source:"file"}}catch(error2){return toErrorProbe(error2,"file","invalid")}}function toFileReadErrorProbe(error2){const code=typeof error2==="object"&&error2!==null&&"code"in error2?String(error2.code):undefined;return{status:code==="EACCES"||code==="EPERM"?"unreadable":"error",source:"file",error:{code,message:error2 instanceof Error?error2.message:String(error2)}}}function toErrorProbe(error2,source,status="invalid"){const code=typeof error2==="object"&&error2!==null&&"code"in error2?String(error2.code):undefined;return{status,source,error:{code,message:error2 instanceof Error?error2.message:String(error2)}}}async function realpathProbe(path,resolveRealpath){try{return{status:"present",value:await resolveRealpath(path),source:"runtime"}}catch(error2){return toErrorProbe(error2,"runtime","error")}}async function resolvePathExecutable(name,deps){const pathValue=deps.env.PATH;if(!pathValue)return{status:"missing",source:"env"};const pathDelimiter=deps.platform==="win32"?";":":";for(const dir of pathValue.split(pathDelimiter)){if(!dir)continue;for(const candidate of getPathExecutableCandidates(name,dir,deps)){try{if(await deps.fs.exists(candidate)){return{status:"present",value:candidate,source:"env"}}}catch(error2){return toErrorProbe(error2,"env","error")}}}return{status:"missing",source:"env"}}function getPathExecutableCandidates(name,dir,deps){if(deps.platform!=="win32")return[deps.fs.joinPath(dir,name)];const names=new Set([name]);for(const ext of(deps.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map((ext2)=>ext2.trim()).filter((ext2)=>ext2.length>0)){names.add(`${name}${ext}`);names.add(`${name}${ext.toLowerCase()}`)}return Array.from(names,(candidate)=>deps.fs.joinPath(dir,candidate))}function isStoredAuthFile(value){return hasVersionOne(value)&&isRecord(value.tokens)}function isStoredClientFile(value){return hasVersionOne(value)&&isRecord(value.clients)}function isStoredMetadataFile(value){return hasVersionOne(value)&&isRecord(value.sessions)}function isStoredDiagnosticsFile(value){return hasVersionOne(value)&&isRecord(value.events)}function hasVersionOne(value){return isRecord(value)&&value.version===1}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var DOCTOR_DESCRIPTION=`Print redacted diagnostics for GitHits configuration and authentication.
136
137
 
137
138
  Doctor is intended for comparing environments when GitHits works in one
138
139
  terminal or agent but fails in another. It never prints token values or client
@@ -145,7 +146,7 @@ Examples:
145
146
  githits example "how to use express middleware" --lang javascript
146
147
  githits example "async file reading" -l python --license yolo
147
148
  githits example "react hooks patterns" -l typescript --explain
148
- githits example "react hooks patterns" -l typescript --json`;function registerExampleCommand(program){program.command("example").summary("Find real-world implementations from open-source code").description(EXAMPLE_DESCRIPTION).argument("<query>","Natural language example-search query").option("-l, --lang <language>","Optional programming language; omitted values are inferred by GitHits").addOption(new Option("--license <mode>","License filter mode").choices(["strict","yolo","custom"]).default(undefined)).option("--explain","Include AI-generated explanation").option("--json","Output as JSON for piping").action(async(query,options)=>{const deps=await loadContainer();await exampleAction(query,options,deps)})}async function loadContainer(){const{createContainer:createContainer2}=await import("./shared/chunk-q9yem3rk.js");return createContainer2()}import{Option as Option2}from"commander";async function feedbackAction(solutionId,options,deps){try{requireAuth(deps)}catch(error2){if(options.json&&error2 instanceof AuthRequiredError){console.error(JSON.stringify(buildAuthRequiredErrorPayload(error2)));process.exit(1)}throw error2}if(!options.accept&&!options.reject){console.error("Error: Specify either --accept or --reject.");process.exit(1)}const accepted=!!options.accept;try{const result=await deps.githitsService.submitFeedback({solutionId,accepted,feedbackText:options.message,toolName:options.tool});if(options.json){console.log(JSON.stringify({success:result.success,message:result.message}))}else{console.log(result.message)}}catch(error2){if(error2 instanceof AuthenticationError){const mapped={code:"AUTH_REQUIRED",message:error2.message,retryable:false,details:{authSource:error2.source}};if(options.json){console.error(JSON.stringify(buildCliMappedErrorPayload(mapped)))}else{console.error(formatMappedErrorForTerminal(mapped))}process.exit(1)}console.error(`Failed to submit feedback: ${error2 instanceof Error?error2.message:error2}`);process.exit(1)}}var FEEDBACK_DESCRIPTION=`Submit feedback on a tool result or the GitHits experience.
149
+ githits example "react hooks patterns" -l typescript --json`;function registerExampleCommand(program){program.command("example").summary("Find real-world implementations from open-source code").description(EXAMPLE_DESCRIPTION).argument("<query>","Natural language example-search query").option("-l, --lang <language>","Optional programming language; omitted values are inferred by GitHits").addOption(new Option("--license <mode>","License filter mode").choices(["strict","yolo","custom"]).default(undefined)).option("--explain","Include AI-generated explanation").option("--json","Output as JSON for piping").action(async(query,options)=>{const deps=await loadContainer();await exampleAction(query,options,deps)})}async function loadContainer(){const{createContainer:createContainer2}=await import("./shared/chunk-fj6xaw9r.js");return createContainer2()}import{Option as Option2}from"commander";async function feedbackAction(solutionId,options,deps){try{requireAuth(deps)}catch(error2){if(options.json&&error2 instanceof AuthRequiredError){console.error(JSON.stringify(buildAuthRequiredErrorPayload(error2)));process.exit(1)}throw error2}if(!options.accept&&!options.reject){console.error("Error: Specify either --accept or --reject.");process.exit(1)}const accepted=!!options.accept;try{const result=await deps.githitsService.submitFeedback({solutionId,accepted,feedbackText:options.message,toolName:options.tool});if(options.json){console.log(JSON.stringify({success:result.success,message:result.message}))}else{console.log(result.message)}}catch(error2){if(error2 instanceof AuthenticationError){const mapped={code:"AUTH_REQUIRED",message:error2.message,retryable:false,details:{authSource:error2.source}};if(options.json){console.error(JSON.stringify(buildCliMappedErrorPayload(mapped)))}else{console.error(formatMappedErrorForTerminal(mapped))}process.exit(1)}console.error(`Failed to submit feedback: ${error2 instanceof Error?error2.message:error2}`);process.exit(1)}}var FEEDBACK_DESCRIPTION=`Submit feedback on a tool result or the GitHits experience.
149
150
 
150
151
  Two modes:
151
152
  - Solution-tied: pass the [solution_id] from a prior 'githits example'
@@ -173,20 +174,18 @@ Examples:
173
174
  `}return`${JSON.stringify(config,null,2)}
174
175
  `}function getConfigObjectFormatName(format="json"){if(format==="yaml")return"YAML";if(format==="toml")return"TOML";return"JSON"}function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function deepEqual(left,right){if(Object.is(left,right)){return true}if(Array.isArray(left)&&Array.isArray(right)){if(left.length!==right.length){return false}for(let i=0;i<left.length;i++){if(!deepEqual(left[i],right[i])){return false}}return true}if(isPlainObject(left)&&isPlainObject(right)){const leftKeys=Object.keys(left).sort();const rightKeys=Object.keys(right).sort();if(!deepEqual(leftKeys,rightKeys)){return false}for(const key of leftKeys){if(!deepEqual(left[key],right[key])){return false}}return true}return false}function isStringArray(value){return Array.isArray(value)&&value.every((item)=>typeof item==="string")}function isGitHitsPackageToken(token){return token.toLowerCase()==="githits@latest"}function isLocalGitHitsInvocation(invocation){if(invocation.length===5){const[command,yesFlag,packageToken,subcommand,action]=invocation;return command==="npx"&&yesFlag==="-y"&&typeof packageToken==="string"&&isGitHitsPackageToken(packageToken)&&subcommand==="mcp"&&action==="start"}return false}function extractInvocation(config){if(!isPlainObject(config)){return null}const command=config.command;if(typeof command==="string"){const args=config.args;if(!isStringArray(args)){return null}return[command,...args]}if(isStringArray(command)){return[...command]}return null}function nonCommandFieldsEqual(existing,expected){for(const[key,value]of Object.entries(expected)){if(key==="command"||key==="args"){continue}if(!deepEqual(existing[key],value)){return false}}return true}function hasLegacyRemoteIndicators(existing,expected){if("url"in existing||"serverUrl"in existing){return true}if("type"in existing&&!("type"in expected)&&(existing.type==="http"||existing.type==="streamableHttp")){return true}return false}function isEquivalentConfiguredValue(existing,expected){if(deepEqual(existing,expected)){return true}if(!isPlainObject(existing)){return false}const expectedInvocation=extractInvocation(expected);const existingInvocation=extractInvocation(existing);if(!expectedInvocation||!existingInvocation){return false}if(!isLocalGitHitsInvocation(expectedInvocation)||!isLocalGitHitsInvocation(existingInvocation)){return false}if(hasLegacyRemoteIndicators(existing,expected)){return false}return nonCommandFieldsEqual(existing,expected)}function getMatchingServerKeys(servers,serverName){const normalizedTarget=serverName.toLowerCase();return Object.keys(servers).filter((key)=>key.toLowerCase()===normalizedTarget)}function mergeServerConfig(existingContent,serversKey,serverName,serverConfig,format="json"){if(format==="yaml"){return mergeYamlServerConfig(existingContent,serversKey,serverName,serverConfig)}const parsedConfig=parseConfigObjectForFormat(existingContent,format);if("error"in parsedConfig){return{status:"parse_error",error:parsedConfig.error}}const config=parsedConfig.value;if(!(serversKey in config)){config[serversKey]={}}const servers=config[serversKey];if(typeof servers!=="object"||servers===null||Array.isArray(servers)){return{status:"parse_error",error:`"${serversKey}" is not a ${getConfigObjectFormatName(format)} object`}}const serversObj=servers;const matchingKeys=getMatchingServerKeys(serversObj,serverName);if(matchingKeys.length===1&&matchingKeys[0]===serverName&&isEquivalentConfiguredValue(serversObj[serverName],serverConfig)){return{status:"already_configured"}}for(const key of matchingKeys){delete serversObj[key]}const hadExisting=matchingKeys.length>0;serversObj[serverName]=serverConfig;return{status:hadExisting?"updated":"added",content:renderConfigObjectForFormat(config,format)}}function removeServerConfig(existingContent,serversKey,serverName,format="json"){if(format==="yaml"){return removeYamlServerConfig(existingContent,serversKey,serverName)}const parsedConfig=parseConfigObjectForFormat(existingContent,format);if("error"in parsedConfig){return{status:"parse_error",error:parsedConfig.error}}const config=parsedConfig.value;const servers=config[serversKey];if(servers===undefined){return{status:"not_configured"}}if(typeof servers!=="object"||servers===null||Array.isArray(servers)){return{status:"parse_error",error:`"${serversKey}" is not a ${getConfigObjectFormatName(format)} object`}}const serversObj=servers;const matchingKeys=getMatchingServerKeys(serversObj,serverName);if(matchingKeys.length===0){return{status:"not_configured"}}for(const key of matchingKeys){delete serversObj[key]}return{status:"removed",content:renderConfigObjectForFormat(config,format)}}function formatUninstallPreview(config){if(config.method==="composite"){return config.steps.map(({step})=>formatUninstallPreview(step)).join(`
175
176
  `)}if(config.method==="cli"){return config.commands.map((cmd)=>`Will run: ${cmd.command} ${cmd.args.join(" ")}`).join(`
176
- `)}return`Will remove ${config.serverName} from ${config.configPath}`}async function isAlreadyConfigured(config,fs){try{const content=await fs.readFile(config.configPath);const parsedConfig=parseConfigObjectForFormat(content,config.format);if("error"in parsedConfig){return false}const parsed=parsedConfig.value;const servers=parsed[config.serversKey];if(typeof servers!=="object"||servers===null||Array.isArray(servers)){return false}const serversObj=servers;const matchingKeys=getMatchingServerKeys(serversObj,config.serverName);if(matchingKeys.length!==1||matchingKeys[0]!==config.serverName){return false}return isEquivalentConfiguredValue(serversObj[config.serverName],config.serverConfig)}catch{return false}}async function getConfigUninstallCheckStatus(config,fs){try{const content=await fs.readFile(config.configPath);const parsedConfig=parseConfigObjectForFormat(content,config.format);if("error"in parsedConfig){return{status:"failed",message:`Cannot parse ${config.configPath}: ${parsedConfig.error}. File left unchanged.`}}const servers=parsedConfig.value[config.serversKey];if(servers===undefined||servers===null){return{status:"not_configured"}}if(typeof servers!=="object"||servers===null||Array.isArray(servers)){return{status:"failed",message:`Cannot parse ${config.configPath}: "${config.serversKey}" is not a ${getConfigObjectFormatName(config.format)} object. File left unchanged.`}}const hasEntry=getMatchingServerKeys(servers,config.serverName).length>0;return{status:hasEntry?"configured":"not_configured"}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"not_configured"}}return{status:"failed",message:`Cannot read ${config.configPath}: ${err instanceof Error?err.message:String(err)}`}}}async function isSetupAlreadyConfigured(config,fs,execService,trace){if(config.method==="config-file"){return isAlreadyConfigured(config,fs)}if(config.method==="cli"){if(!config.checkCommand){return false}return isCliAlreadyConfigured(config.checkCommand,execService,trace)}for(const step of config.steps){if(!await isSetupAlreadyConfigured(step,fs,execService,trace)){return false}}return true}async function isCliAlreadyConfigured(check,execService,trace){return await getCliCheckStatus(check,execService,trace)==="configured"}async function getCliCheckStatus(check,execService,trace){const startedAt=Date.now();if(trace){traceProbeStart({agentId:trace.agentId,phase:trace.phase,command:check.command,args:check.args})}try{const result=await execService.exec(check.command,check.args,{timeoutMs:5000});if(trace){traceProbeEnd({agentId:trace.agentId,phase:trace.phase,startedAt,status:"end",exitCode:result.exitCode})}const combined=`${result.stdout} ${result.stderr}`;if(check.notConfiguredPattern?.test(combined)){return"not_configured"}if(check.requireExitCodeZero&&result.exitCode!==0){return"probe_failed"}if(check.configuredPattern){return check.configuredPattern.test(combined)?"configured":"not_configured"}if(check.notConfiguredPattern){return"configured"}return"not_configured"}catch(err){if(trace){traceProbeEnd({agentId:trace.agentId,phase:trace.phase,startedAt,status:err instanceof Error&&err.name==="ExecTimeoutError"?"timeout":"error"})}return"probe_failed"}}var ALREADY_EXISTS_PATTERNS=[/already exists/i,/already configured/i,/already added/i,/extension\s+"githits"\s+is\s+already\s+installed/i];var ALREADY_ABSENT_PATTERNS=[/(?:plugin|extension|server|mcp server)\s+["']?githits["']?\s+(?:was\s+)?not\s+found/i,/["']?githits["']?\s+(?:plugin|extension|server)?\s*(?:does\s+not\s+exist|is\s+not\s+installed|not\s+installed)/i,/(?:package\s+)?["']?pi-mcp-adapter["']?\s+(?:(?:is\s+)?not\s+installed|not\s+found)/i,/unknown\s+(?:plugin|extension|server)\s+["']?githits["']?/i,/marketplace\s+["']?githits-plugins["']?\s+(?:was\s+)?not\s+found/i];function isAlreadyConfiguredOutput(output){return ALREADY_EXISTS_PATTERNS.some((pattern)=>pattern.test(output))}function isAlreadyAbsentOutput(output){return ALREADY_ABSENT_PATTERNS.some((pattern)=>pattern.test(output))}async function executeCliCommand(cmd,execService){try{const result=await execService.exec(cmd.command,cmd.args);const combined=`${result.stdout} ${result.stderr}`;if(isAlreadyConfiguredOutput(combined)){return{status:"already_configured",message:`GitHits already configured via ${cmd.command}`}}if(result.exitCode===0){return{status:"success",message:"Configured successfully"}}const detail=result.stderr.trim()||result.stdout.trim();return{status:"failed",message:`Command exited with code ${result.exitCode}${detail?`: ${detail}`:""}`}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"failed",message:`"${cmd.command}" not found on PATH. Install it or configure manually.`}}return{status:"failed",message:`Failed to run command: ${err instanceof Error?err.message:String(err)}`}}}async function executeCliUninstallCommand(cmd,execService){try{const result=await execService.exec(cmd.command,cmd.args);const combined=`${result.stdout} ${result.stderr}`;if(isAlreadyAbsentOutput(combined)){return{status:"not_configured",message:`GitHits not configured via ${cmd.command}`}}if(result.exitCode===0){return{status:"removed",message:"Removed successfully"}}const detail=result.stderr.trim()||result.stdout.trim();return{status:"failed",message:`Command exited with code ${result.exitCode}${detail?`: ${detail}`:""}`}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"failed",message:`"${cmd.command}" not found on PATH. Install it or remove GitHits manually.`}}return{status:"failed",message:`Failed to run command: ${err instanceof Error?err.message:String(err)}`}}}async function executeCliSetup(setup,execService){let anyAlreadyConfigured=false;for(const cmd of setup.commands){const result=await executeCliCommand(cmd,execService);if(result.status==="failed"){return result}if(result.status==="already_configured"){anyAlreadyConfigured=true}}if(anyAlreadyConfigured){return{status:"already_configured",message:`GitHits already configured via ${setup.commands[0]?.command}`}}return{status:"success",message:"Configured successfully"}}async function executeCliUninstall(uninstall,execService){if(uninstall.commands.length===0){return{status:"failed",message:"No uninstall commands configured."}}let anyRemoved=false;let anyNotConfigured=false;const warnings=[];for(const cmd of uninstall.commands){const result=await executeCliUninstallCommand(cmd,execService);if(result.status==="failed"){if(anyRemoved){warnings.push(result.message);continue}return result}if(result.status==="removed"){anyRemoved=true}if(result.status==="not_configured"){if(anyRemoved){warnings.push(result.message);continue}anyNotConfigured=true}}if(anyRemoved){return{status:"removed",message:"Removed successfully",warnings:warnings.length>0?warnings:undefined}}if(anyNotConfigured){return{status:"not_configured",message:`GitHits not configured via ${uninstall.commands[0]?.command}`}}return{status:"removed",message:"Removed successfully"}}async function executeCompositeUninstall(uninstall,fs,execService){let anyRemoved=false;let anyNotConfigured=false;const warnings=[];for(const{step,failureMode}of uninstall.steps){const result=await executeUninstallStep(step,fs,execService);if(result.status==="removed"){anyRemoved=true;warnings.push(...result.warnings??[]);continue}if(result.status==="not_configured"){if(anyRemoved){warnings.push(result.message)}else{anyNotConfigured=true}continue}if(failureMode==="best-effort"&&anyRemoved){warnings.push(result.message);continue}return result}if(anyRemoved){return{status:"removed",message:"Removed successfully",warnings:warnings.length>0?warnings:undefined}}if(anyNotConfigured){return{status:"not_configured",message:"GitHits not configured"}}return{status:"not_configured",message:"GitHits not configured"}}async function executeUninstallStep(step,fs,execService){return step.method==="cli"?executeCliUninstall(step,execService):executeConfigFileUninstall(step,fs)}async function executeConfigFileSetup(setup,fs){try{const parentDir=fs.getDirname(setup.configPath);await fs.ensureDir(parentDir);let existingContent="";try{existingContent=await fs.readFile(setup.configPath)}catch(err){if(!(err instanceof Error)||!("code"in err)||err.code!=="ENOENT"){return{status:"failed",message:`Cannot read ${setup.configPath}: ${err instanceof Error?err.message:String(err)}`}}}const result=mergeServerConfig(existingContent,setup.serversKey,setup.serverName,setup.serverConfig,setup.format);if(result.status==="already_configured"){return{status:"already_configured",message:`GitHits already configured in ${setup.configPath}`}}if(result.status==="parse_error"){return{status:"failed",message:`Cannot parse ${setup.configPath}: ${result.error}. File left unchanged.`}}await fs.atomicWriteFile(setup.configPath,result.content);return{status:"success",message:"Configured successfully"}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="EACCES"){return{status:"failed",message:`Permission denied writing to ${setup.configPath}. Check file permissions.`}}return{status:"failed",message:`Failed to configure: ${err instanceof Error?err.message:String(err)}`}}}async function executeCompositeSetup(setup,fs,execService){let executedAny=false;for(const step of setup.steps){if(await isSetupAlreadyConfigured(step,fs,execService)){continue}executedAny=true;const result=step.method==="cli"?await executeCliSetup(step,execService):await executeConfigFileSetup(step,fs);if(result.status==="failed"){return result}}if(!executedAny){return{status:"already_configured",message:"GitHits already configured"}}return{status:"success",message:"Configured successfully"}}async function executeConfigFileUninstall(setup,fs){try{let existingContent="";try{existingContent=await fs.readFile(setup.configPath)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"not_configured",message:`GitHits not configured in ${setup.configPath}`}}return{status:"failed",message:`Cannot read ${setup.configPath}: ${err instanceof Error?err.message:String(err)}`}}const result=removeServerConfig(existingContent,setup.serversKey,setup.serverName,setup.format);if(result.status==="not_configured"){return{status:"not_configured",message:`GitHits not configured in ${setup.configPath}`}}if(result.status==="parse_error"){return{status:"failed",message:`Cannot parse ${setup.configPath}: ${result.error}. File left unchanged.`}}await fs.atomicWriteFile(setup.configPath,result.content);return{status:"removed",message:"Removed successfully"}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="EACCES"){return{status:"failed",message:`Permission denied writing to ${setup.configPath}. Check file permissions.`}}return{status:"failed",message:`Failed to uninstall: ${err instanceof Error?err.message:String(err)}`}}}var GITHITS_SERVER_NAME="GitHits";var GITHITS_MCP_COMMAND="npx";var GITHITS_MCP_ARGS=["-y","githits@latest","mcp","start"];var GITHITS_MCP_INVOCATION=[GITHITS_MCP_COMMAND,...GITHITS_MCP_ARGS];var CLAUDE_GITHITS_PLUGIN="githits";var CLAUDE_GITHITS_MARKETPLACE="githits-plugins";var CLAUDE_GITHITS_PLUGIN_REF=`${CLAUDE_GITHITS_PLUGIN}@${CLAUDE_GITHITS_MARKETPLACE}`;var CLAUDE_GITHITS_MARKETPLACE_SOURCE="githits-com/githits-cli";var BINARY_LOOKUP_TIMEOUT_MS=2000;var GLOBAL_BIN_PROBE_TIMEOUT_MS=3000;function getAppDataPath(fs,appName){const home=fs.getHomeDir();switch(process.platform){case"win32":return fs.joinPath(process.env.APPDATA??fs.joinPath(home,"AppData","Roaming"),appName);case"darwin":return fs.joinPath(home,"Library","Application Support",appName);default:return fs.joinPath(home,".config",appName)}}function getUserDataRoot(fs){const home=fs.getHomeDir();switch(process.platform){case"win32":return process.env.APPDATA??fs.joinPath(home,"AppData","Roaming");case"darwin":return fs.joinPath(home,"Library","Application Support");default:return process.env.XDG_DATA_HOME??fs.joinPath(home,".local","share")}}function getOpenCodeConfigDir(fs){if(process.platform==="win32"){return fs.joinPath(getUserDataRoot(fs),"opencode")}return fs.joinPath(fs.getHomeDir(),".config","opencode")}function expandHomePath(fs,path){if(path==="~"){return fs.getHomeDir()}if(path.startsWith("~/")){return fs.joinPath(fs.getHomeDir(),path.slice(2))}return path}function getPiAgentDir(fs){const configuredDir=process.env.PI_CODING_AGENT_DIR?.trim();if(configuredDir){return expandHomePath(fs,configuredDir)}return fs.joinPath(fs.getHomeDir(),".pi","agent")}function getPiMcpConfigPath(fs){return fs.joinPath(getPiAgentDir(fs),"mcp.json")}function getHermesHomeDir(fs){const configuredDir=process.env.HERMES_HOME?.trim();if(configuredDir){return expandHomePath(fs,configuredDir)}return fs.joinPath(fs.getHomeDir(),".hermes")}function getHermesConfigPath(fs){return fs.joinPath(getHermesHomeDir(fs),"config.yaml")}function getStandardMcpServerConfig(){return{command:GITHITS_MCP_COMMAND,args:[...GITHITS_MCP_ARGS]}}function getVsCodeMcpServerConfig(){return{type:"stdio",...getStandardMcpServerConfig()}}function getProjectPath(fs){return fs.getCwd()}function getProjectJsonConfig(fs,relativePath,serversKey,serverConfig=getStandardMcpServerConfig()){return{method:"config-file",configPath:fs.joinPath(getProjectPath(fs),...relativePath),serversKey,serverName:GITHITS_SERVER_NAME,serverConfig}}function getUnsupportedProjectSetup(reason){return{supported:false,reason}}function getAgentSetupConfig(agent,fs,scope="user",context){if(scope==="project"){if(agent.projectSetup?.supported){return agent.projectSetup.getSetupConfig(fs,context)}return null}return agent.getSetupConfig(fs,context)}function getProjectSetupUnsupportedReason(agent){if(agent.projectSetup?.supported){return null}return agent.projectSetup?.reason??"project-level MCP config not verified"}function getOpenCodeDesktopDetectPaths(fs){const userDataRoot=getUserDataRoot(fs);return[fs.joinPath(userDataRoot,"ai.opencode.desktop"),fs.joinPath(userDataRoot,"ai.opencode.desktop.beta"),fs.joinPath(userDataRoot,"ai.opencode.desktop.dev"),getOpenCodeConfigDir(fs)]}async function isExecutableAvailable(exec,executable){try{const lookupCommand=process.platform==="win32"?"where":"which";const result=await exec.exec(lookupCommand,[executable],{timeoutMs:BINARY_LOOKUP_TIMEOUT_MS});return result.exitCode===0}catch{return false}}async function resolveExecutableFromPath(exec,executable){return isExecutableAvailable(exec,executable)}var PI_GLOBAL_BIN_PROBES=[{command:"npm",args:["prefix","-g"],output:"prefix"},{command:"pnpm",args:["bin","-g"],output:"binDir"},{command:"bun",args:["pm","bin","-g"],output:"binDir"}];var PI_ADAPTER_CONFIGURED_PATTERN=/(?:^|\s|:)(?:npm:)?pi-mcp-adapter(?:[\s@:]|$)/i;function getPiExecutableNames(){return process.platform==="win32"?["pi.cmd","pi.exe","pi"]:["pi"]}async function runGlobalBinProbe(exec,probe){try{const result=await exec.exec(probe.command,[...probe.args],{timeoutMs:GLOBAL_BIN_PROBE_TIMEOUT_MS});if(result.exitCode!==0){return null}const probePath=result.stdout.split(/\r?\n/).map((line)=>line.trim()).find((line)=>line.length>0);if(!probePath){return null}if(probe.output==="prefix"&&process.platform!=="win32"){return fsJoinPathLike(probePath,"bin")}return probePath}catch{return null}}function fsJoinPathLike(base,child){return base.endsWith("/")?`${base}${child}`:`${base}/${child}`}async function detectPiExecutable(exec,fs){if(await resolveExecutableFromPath(exec,"pi")){return{command:"pi"}}for(const probe of PI_GLOBAL_BIN_PROBES){const binDir=await runGlobalBinProbe(exec,probe);if(!binDir){continue}for(const executableName of getPiExecutableNames()){const candidate=fs.joinPath(binDir,executableName);if(await fs.exists(candidate)){return{command:candidate}}}}return null}var claudeCode={name:"Claude Code",id:"claude-code",detectionMethod:"binary",setupMethod:"cli",detectBinary:async(exec)=>isExecutableAvailable(exec,"claude"),getSetupConfig:()=>({method:"cli",commands:[{command:"claude",args:["plugin","marketplace","add",CLAUDE_GITHITS_MARKETPLACE_SOURCE]},{command:"claude",args:["plugin","install",CLAUDE_GITHITS_PLUGIN_REF]}],checkCommand:{command:"claude",args:["plugin","list"],configuredPattern:/(^|\s)githits@githits-plugins\b/i}}),getUninstallConfig:()=>({method:"cli",commands:[{command:"claude",args:["plugin","uninstall",CLAUDE_GITHITS_PLUGIN]},{command:"claude",args:["plugin","marketplace","remove",CLAUDE_GITHITS_MARKETPLACE]}]}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".mcp.json"],"mcpServers")}};var cursor={name:"Cursor",id:"cursor",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".cursor")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".cursor","mcp.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".cursor","mcp.json"],"mcpServers")}};var windsurf={name:"Windsurf",id:"windsurf",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".codeium","windsurf")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".codeium","windsurf","mcp_config.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("project-level MCP config not verified for Windsurf")};var claudeDesktop={name:"Claude Desktop",id:"claude-desktop",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>{const appData=getAppDataPath(fs,"Claude");if(process.platform==="win32"){const home=fs.getHomeDir();const localAppData=process.env.LOCALAPPDATA??fs.joinPath(home,"AppData","Local");return[appData,fs.joinPath(localAppData,"Claude"),fs.joinPath(localAppData,"Programs","Claude")]}return[appData]},getSetupConfig:(fs)=>{const appData=getAppDataPath(fs,"Claude");return{method:"config-file",configPath:fs.joinPath(appData,"claude_desktop_config.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}},projectSetup:getUnsupportedProjectSetup("Claude Desktop uses user-level desktop config")};var codexCli={name:"Codex CLI",id:"codex-cli",detectionMethod:"binary",setupMethod:"cli",detectBinary:async(exec)=>isExecutableAvailable(exec,"codex"),getSetupConfig:()=>({method:"cli",commands:[{command:"codex",args:["mcp","add","githits","--",...GITHITS_MCP_INVOCATION]}],checkCommand:{command:"codex",args:["mcp","list"],configuredPattern:/^\s*githits\b/im}}),getUninstallConfig:()=>({method:"cli",commands:[{command:"codex",args:["mcp","remove","githits"]}]}),projectSetup:{supported:true,getSetupConfig:(fs)=>({method:"config-file",format:"toml",configPath:fs.joinPath(getProjectPath(fs),".codex","config.toml"),serversKey:"mcp_servers",serverName:"githits",serverConfig:getStandardMcpServerConfig()})}};var pi={name:"Pi",id:"pi",detectionMethod:"binary",setupMethod:"composite",detectCommand:detectPiExecutable,getSetupConfig:(fs,context)=>{const piCommand=context?.command??"pi";return{method:"composite",steps:[{method:"cli",commands:[{command:piCommand,args:["install","npm:pi-mcp-adapter"]}],checkCommand:{command:piCommand,args:["list"],configuredPattern:PI_ADAPTER_CONFIGURED_PATTERN}},{method:"config-file",configPath:getPiMcpConfigPath(fs),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:{...getStandardMcpServerConfig(),lifecycle:"eager"}}]}},getUninstallConfig:(fs,context)=>{const piCommand=context?.command??"pi";return{method:"composite",steps:[{failureMode:"required",step:{method:"config-file",configPath:getPiMcpConfigPath(fs),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:{}}},{failureMode:"required",step:{method:"cli",commands:[{command:piCommand,args:["remove","npm:pi-mcp-adapter"]}]}}]}},projectSetup:{supported:true,getSetupConfig:(fs,context)=>{const piCommand=context?.command??"pi";return{method:"composite",steps:[{method:"cli",commands:[{command:piCommand,args:["install","npm:pi-mcp-adapter"]}],checkCommand:{command:piCommand,args:["list"],configuredPattern:PI_ADAPTER_CONFIGURED_PATTERN}},getProjectJsonConfig(fs,[".mcp.json"],"mcpServers")]}}}};var vscode={name:"VS Code / Copilot",id:"vscode",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>{const appData=getAppDataPath(fs,"Code");return[appData]},getSetupConfig:(fs)=>{const appData=getAppDataPath(fs,"Code");return{method:"config-file",configPath:fs.joinPath(appData,"User","mcp.json"),serversKey:"servers",serverName:GITHITS_SERVER_NAME,serverConfig:getVsCodeMcpServerConfig()}},projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".vscode","mcp.json"],"servers",getVsCodeMcpServerConfig())}};var cline={name:"Cline",id:"cline",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".cline")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".cline","data","settings","cline_mcp_settings.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("Cline MCP settings are documented as user-level config; project MCP auto-load not verified")};var geminiCli={name:"Gemini CLI",id:"gemini-cli",detectionMethod:"binary",setupMethod:"cli",detectBinary:async(exec)=>isExecutableAvailable(exec,"gemini"),getSetupConfig:()=>({method:"cli",commands:[{command:"gemini",args:["extensions","install","--consent","https://github.com/githits-com/githits-cli"]}],checkCommand:{command:"gemini",args:["extensions","config","githits"],notConfiguredPattern:/not installed/i,requireExitCodeZero:true}}),getUninstallConfig:()=>({method:"cli",commands:[{command:"gemini",args:["extensions","uninstall","githits"]}]}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".gemini","settings.json"],"mcpServers")}};async function isGeminiExtensionInstalledFromFilesystem(fs){const extensionManifestPath=fs.joinPath(fs.getHomeDir(),".gemini","extensions","githits","gemini-extension.json");return fs.exists(extensionManifestPath)}var googleAntigravity={name:"Google Antigravity",id:"google-antigravity",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".gemini","antigravity")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".gemini","antigravity","mcp_config.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("Google Antigravity project-level MCP config not verified")};var openCode={name:"OpenCode",id:"opencode",detectionMethod:"hybrid",setupMethod:"config-file",detectPaths:(fs)=>getOpenCodeDesktopDetectPaths(fs),detectBinary:async(exec)=>isExecutableAvailable(exec,"opencode"),getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(getOpenCodeConfigDir(fs),"opencode.json"),serversKey:"mcp",serverName:GITHITS_SERVER_NAME,serverConfig:{type:"local",command:[...GITHITS_MCP_INVOCATION],enabled:true}}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,["opencode.json"],"mcp",{type:"local",command:[...GITHITS_MCP_INVOCATION],enabled:true})}};var hermesAgent={name:"Hermes Agent",id:"hermes-agent",detectionMethod:"hybrid",setupMethod:"config-file",detectPaths:(fs)=>[getHermesHomeDir(fs)],detectBinary:async(exec)=>isExecutableAvailable(exec,"hermes-agent"),getSetupConfig:(fs)=>({method:"config-file",format:"yaml",configPath:getHermesConfigPath(fs),serversKey:"mcp_servers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("Hermes Agent project-level MCP config not verified")};var agentDefinitions=[claudeCode,cursor,windsurf,vscode,cline,claudeDesktop,codexCli,pi,geminiCli,googleAntigravity,openCode,hermesAgent];async function scanSingleAgent(agent,fs,execService,scope){const scanStartedAt=Date.now();traceInit(`agent:start agent=${agent.id} scope=${scope}`);let detected=false;let setupContext;if(agent.detectCommand){const startedAt=Date.now();try{traceProbeStart({agentId:agent.id,phase:"detectCommand"});const resolvedCommand=await agent.detectCommand(execService,fs);traceProbeEnd({agentId:agent.id,phase:"detectCommand",startedAt,status:"end"});if(resolvedCommand){detected=true;setupContext={command:resolvedCommand.command}}}catch{traceProbeEnd({agentId:agent.id,phase:"detectCommand",startedAt,status:"error"});detected=false}}else if(agent.detectionMethod==="binary"&&agent.detectBinary){const startedAt=Date.now();try{traceProbeStart({agentId:agent.id,phase:"binary"});detected=await agent.detectBinary(execService);traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"end"})}catch{traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"error"});detected=false}}else if(agent.detectionMethod==="path"&&agent.detectPaths){const paths=agent.detectPaths(fs);for(const path of paths){if(await fs.isDirectory(path)){detected=true;break}}}else if(agent.detectionMethod==="hybrid"){let binaryDetected=false;let pathDetected=false;if(agent.detectBinary){const startedAt=Date.now();try{traceProbeStart({agentId:agent.id,phase:"binary"});binaryDetected=await agent.detectBinary(execService);traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"end"})}catch{traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"error"});binaryDetected=false}}if(!binaryDetected&&agent.detectPaths){const paths=agent.detectPaths(fs);for(const path of paths){if(await fs.isDirectory(path)){pathDetected=true;break}}}detected=binaryDetected||pathDetected}if(!detected){traceInit(`agent:end agent=${agent.id} status=not_detected elapsedMs=${Date.now()-scanStartedAt}`);return{status:"not_detected",agent}}const config=getAgentSetupConfig(agent,fs,scope,setupContext);if(!config){return{status:"unsupported",agent,reason:getProjectSetupUnsupportedReason(agent)??"project-level MCP config not verified"}}const scannedAgent={...agent,resolvedSetupConfig:config,resolvedSetupContext:setupContext};if(agent.id==="gemini-cli"&&config.method==="cli"){if(!config.checkCommand){return{status:"needs_setup",agent:scannedAgent}}const checkStatus=await getCliCheckStatus(config.checkCommand,execService,{agentId:agent.id,phase:"check"});let configured=checkStatus==="configured";if(!configured&&checkStatus==="probe_failed"){configured=await isGeminiExtensionInstalledFromFilesystem(fs)}const status=configured?"already_configured":"needs_setup";traceInit(`agent:end agent=${agent.id} status=${status} elapsedMs=${Date.now()-scanStartedAt}`);return{status,agent:scannedAgent}}if(await isSetupAlreadyConfigured(config,fs,execService,{agentId:agent.id,phase:"check"})){traceInit(`agent:end agent=${agent.id} status=already_configured elapsedMs=${Date.now()-scanStartedAt}`);return{status:"already_configured",agent:scannedAgent}}traceInit(`agent:end agent=${agent.id} status=needs_setup elapsedMs=${Date.now()-scanStartedAt}`);return{status:"needs_setup",agent:scannedAgent}}async function scanAgents(definitions,fs,execService,options={}){const result={needsSetup:[],alreadyConfigured:[],notDetected:[],unsupported:[]};let completed=0;const startedAt=Date.now();traceInit(`scan:start scope=${options.scope??"user"} total=${definitions.length}`);const outcomes=await Promise.all(definitions.map((agent)=>scanSingleAgent(agent,fs,execService,options.scope??"user").then((outcome)=>{completed+=1;options.onProgress?.({completed,total:definitions.length,agent:outcome.agent});return outcome})));for(const outcome of outcomes){if(outcome.status==="already_configured"){result.alreadyConfigured.push(outcome.agent)}else if(outcome.status==="needs_setup"){result.needsSetup.push(outcome.agent)}else if(outcome.status==="unsupported"){result.unsupported.push({agent:outcome.agent,reason:outcome.reason})}else{result.notDetected.push(outcome.agent)}}traceInit(`scan:end elapsedMs=${Date.now()-startedAt}`);return result}import{ExitPromptError}from"@inquirer/core";import{spawn}from"node:child_process";var WINDOWS_CMD_META_CHARS=/([()[\]%!^"`<>&|;, *?])/g;function escapeWindowsCommand(value){return value.replace(WINDOWS_CMD_META_CHARS,"^$1")}function escapeWindowsArgument(value){let arg=`${value}`;arg=arg.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\"");arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1");return`"${arg}"`.replace(WINDOWS_CMD_META_CHARS,"^$1")}function buildWindowsShellCommand(command,args){return[escapeWindowsCommand(command),...args.map(escapeWindowsArgument)].join(" ")}function isWindowsCommandNotFound(exitCode,stderr,platform=process.platform){return platform==="win32"&&exitCode!==0&&/^\s*'[^']+'\s+is not recognized as an internal or external command,/i.test(stderr)}function createCommandNotFoundError(command){const error2=new Error(`spawn ${command} ENOENT`);error2.code="ENOENT";error2.syscall="spawn";error2.path=command;return error2}function normalizeSpawnCommand(command,args,platform=process.platform){if(platform!=="win32"){return{command,args}}const shellCommand=buildWindowsShellCommand(command,args);return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${shellCommand}"`],windowsVerbatimArguments:true}}class ExecTimeoutError extends Error{command;args;timeoutMs;constructor(command,args,timeoutMs){super(`Command timed out after ${timeoutMs}ms: ${command} ${args.join(" ")}`);this.name="ExecTimeoutError";this.command=command;this.args=args;this.timeoutMs=timeoutMs}}class ExecServiceImpl{async exec(command,args,options={}){return new Promise((resolve,reject)=>{const spawnCommand=normalizeSpawnCommand(command,args);const child=spawn(spawnCommand.command,spawnCommand.args,{stdio:["ignore","pipe","pipe"],env:{...process.env},...spawnCommand.shell!==undefined&&{shell:spawnCommand.shell},...spawnCommand.windowsVerbatimArguments!==undefined&&{windowsVerbatimArguments:spawnCommand.windowsVerbatimArguments}});const stdoutChunks=[];const stderrChunks=[];let settled=false;let timeout;const settle=(fn)=>{if(settled){return}settled=true;if(timeout){clearTimeout(timeout)}fn()};if(options.timeoutMs!==undefined){timeout=setTimeout(()=>{settle(()=>{child.kill("SIGTERM");reject(new ExecTimeoutError(command,args,options.timeoutMs))})},options.timeoutMs)}child.stdout.on("data",(chunk)=>stdoutChunks.push(chunk));child.stderr.on("data",(chunk)=>stderrChunks.push(chunk));child.on("error",(error2)=>{settle(()=>reject(error2))});child.on("close",(code)=>{settle(()=>{const exitCode=code??1;const stderr=Buffer.concat(stderrChunks).toString("utf-8");if(isWindowsCommandNotFound(exitCode,stderr)){reject(createCommandNotFoundError(command));return}resolve({exitCode,stdout:Buffer.concat(stdoutChunks).toString("utf-8"),stderr})})})})}}import{checkbox,confirm,select}from"@inquirer/prompts";class PromptServiceImpl{async select(message,choices,defaultValue){return select({message,choices,default:defaultValue})}async checkbox(message,choices){return checkbox({message,choices})}async confirm(message,defaultValue){return confirm({message,default:defaultValue})}async confirm3(message,defaultValue){return select({message,default:defaultValue,choices:[{value:"yes",name:"Yes"},{value:"no",name:"No"},{value:"always",name:"Yes to all",description:"Skip confirmation for remaining agents"}]})}}var stdoutLoginOutput={write:(message)=>{console.log(message)}};var stderrLoginOutput={write:(message)=>{console.error(message)}};var TIMEOUT_MS=5*60*1000;var AUTH_TIMEOUT_MESSAGE="Authentication timed out after 5 minutes. The browser link has expired, so it will not work anymore. Run the same command again to try signing in again.";function randomPort(){return Math.floor(Math.random()*2000)+8000}async function preflightAuthPersistence(authStorage,mcpUrl){const probeUrl=`${mcpUrl.replace(/\/+$/,"")}/__githits_storage_probe__`;const probeClient={clientId:"__githits_storage_probe__",clientSecret:"__githits_storage_probe__",redirectUri:"http://127.0.0.1:1/callback",registeredAt:new Date(0).toISOString()};const probeTokens={accessToken:"__githits_storage_probe__",refreshToken:"__githits_storage_probe__",expiresAt:new Date(0).toISOString(),createdAt:new Date(0).toISOString()};try{await authStorage.saveAuthSession(probeUrl,probeClient,probeTokens);await authStorage.clearAuthSession(probeUrl);return null}catch(error2){await authStorage.clearAuthSession(probeUrl).catch(()=>{});const message=error2 instanceof Error?error2.message:String(error2);return{status:"failed",message:`Cannot persist OAuth credentials: ${message}`}}}async function loginFlow(options,deps,output=stdoutLoginOutput){const{authService,authStorage,browserService,mcpUrl}=deps;const existing=await authStorage.loadTokens(mcpUrl);if(options.port!==undefined&&(Number.isNaN(options.port)||options.port<1||options.port>65535)){return{status:"failed",message:"Invalid port number. Must be between 1 and 65535."}}if(existing&&!options.force){const isExpired=existing.expiresAt&&new Date(existing.expiresAt)<new Date;if(!isExpired){return{status:"already_authenticated",message:"Already logged in."}}output.write(`Token expired. Starting new login...
177
- `)}else if(existing&&options.force){output.write(`Re-authenticating (--force flag)...
178
- `)}if(!existing){await authStorage.clearClient(mcpUrl)}const persistenceError=await preflightAuthPersistence(authStorage,mcpUrl);if(persistenceError)return persistenceError;output.write("Discovering OAuth endpoints...");const metadata=await authService.discoverEndpoints(mcpUrl);let client=await authStorage.loadClient(mcpUrl);const hadStoredClient=client!==null;let shouldClearClientOnFailedAttempt=false;let port;let redirectUri;if(client){if(options.port){redirectUri=`http://127.0.0.1:${options.port}/callback`;if(redirectUri!==client.redirectUri){output.write("Registering CLI client with new port...");const registration=await authService.registerClient({registrationEndpoint:metadata.registrationEndpoint,redirectUri});client={clientId:registration.clientId,clientSecret:registration.clientSecret,redirectUri,registeredAt:new Date().toISOString()};shouldClearClientOnFailedAttempt=!hadStoredClient}port=options.port}else{redirectUri=client.redirectUri;const storedUrl=new URL(redirectUri);port=Number(storedUrl.port)||randomPort()}}else{port=options.port??randomPort();redirectUri=`http://127.0.0.1:${port}/callback`;output.write("Registering CLI client...");const registration=await authService.registerClient({registrationEndpoint:metadata.registrationEndpoint,redirectUri});client={clientId:registration.clientId,clientSecret:registration.clientSecret,redirectUri,registeredAt:new Date().toISOString()};shouldClearClientOnFailedAttempt=!hadStoredClient}const{verifier,challenge,state}=authService.generatePkceParams();const authUrl=authService.buildAuthUrl({authorizationEndpoint:metadata.authorizationEndpoint,clientId:client.clientId,redirectUri,state,codeChallenge:challenge});let callbackServer;try{callbackServer=await authService.startCallbackServer(port,state)}catch(error2){const msg=error2 instanceof Error?error2.message:String(error2);return{status:"failed",message:msg}}if(options.browser===false){output.write(`Open this URL in your browser:
177
+ `)}return`Will remove ${config.serverName} from ${config.configPath}`}async function isAlreadyConfigured(config,fs){try{const content=await fs.readFile(config.configPath);const parsedConfig=parseConfigObjectForFormat(content,config.format);if("error"in parsedConfig){return false}const parsed=parsedConfig.value;const servers=parsed[config.serversKey];if(typeof servers!=="object"||servers===null||Array.isArray(servers)){return false}const serversObj=servers;const matchingKeys=getMatchingServerKeys(serversObj,config.serverName);if(matchingKeys.length!==1||matchingKeys[0]!==config.serverName){return false}return isEquivalentConfiguredValue(serversObj[config.serverName],config.serverConfig)}catch{return false}}async function getConfigUninstallCheckStatus(config,fs){try{const content=await fs.readFile(config.configPath);const parsedConfig=parseConfigObjectForFormat(content,config.format);if("error"in parsedConfig){return{status:"failed",message:`Cannot parse ${config.configPath}: ${parsedConfig.error}. File left unchanged.`}}const servers=parsedConfig.value[config.serversKey];if(servers===undefined||servers===null){return{status:"not_configured"}}if(typeof servers!=="object"||servers===null||Array.isArray(servers)){return{status:"failed",message:`Cannot parse ${config.configPath}: "${config.serversKey}" is not a ${getConfigObjectFormatName(config.format)} object. File left unchanged.`}}const hasEntry=getMatchingServerKeys(servers,config.serverName).length>0;return{status:hasEntry?"configured":"not_configured"}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"not_configured"}}return{status:"failed",message:`Cannot read ${config.configPath}: ${err instanceof Error?err.message:String(err)}`}}}async function isSetupAlreadyConfigured(config,fs,execService,trace){if(config.method==="config-file"){return isAlreadyConfigured(config,fs)}if(config.method==="cli"){if(!config.checkCommand){return false}return isCliAlreadyConfigured(config.checkCommand,execService,trace)}for(const step of config.steps){if(!await isSetupAlreadyConfigured(step,fs,execService,trace)){return false}}return true}async function isCliAlreadyConfigured(check,execService,trace){return await getCliCheckStatus(check,execService,trace)==="configured"}async function getCliCheckStatus(check,execService,trace){const startedAt=Date.now();if(trace){traceProbeStart({agentId:trace.agentId,phase:trace.phase,command:check.command,args:check.args})}try{const result=await execService.exec(check.command,check.args,{timeoutMs:5000});if(trace){traceProbeEnd({agentId:trace.agentId,phase:trace.phase,startedAt,status:"end",exitCode:result.exitCode})}const combined=`${result.stdout} ${result.stderr}`;if(check.notConfiguredPattern?.test(combined)){return"not_configured"}if(check.requireExitCodeZero&&result.exitCode!==0){return"probe_failed"}if(check.configuredPattern){return check.configuredPattern.test(combined)?"configured":"not_configured"}if(check.notConfiguredPattern){return"configured"}return"not_configured"}catch(err){if(trace){traceProbeEnd({agentId:trace.agentId,phase:trace.phase,startedAt,status:err instanceof Error&&err.name==="ExecTimeoutError"?"timeout":"error"})}return"probe_failed"}}var ALREADY_EXISTS_PATTERNS=[/already exists/i,/already configured/i,/already added/i,/extension\s+"githits"\s+is\s+already\s+installed/i];var ALREADY_ABSENT_PATTERNS=[/(?:plugin|extension|server|mcp server)\s+["']?githits["']?\s+(?:was\s+)?not\s+found/i,/["']?githits["']?\s+(?:plugin|extension|server)?\s*(?:does\s+not\s+exist|is\s+not\s+installed|not\s+installed)/i,/(?:package\s+)?["']?pi-mcp-adapter["']?\s+(?:(?:is\s+)?not\s+installed|not\s+found)/i,/unknown\s+(?:plugin|extension|server)\s+["']?githits["']?/i,/marketplace\s+["']?githits-plugins["']?\s+(?:was\s+)?not\s+found/i];function isAlreadyConfiguredOutput(output){return ALREADY_EXISTS_PATTERNS.some((pattern)=>pattern.test(output))}function isAlreadyAbsentOutput(output){return ALREADY_ABSENT_PATTERNS.some((pattern)=>pattern.test(output))}async function executeCliCommand(cmd,execService){try{const result=await execService.exec(cmd.command,cmd.args);const combined=`${result.stdout} ${result.stderr}`;if(isAlreadyConfiguredOutput(combined)){return{status:"already_configured",message:`GitHits already configured via ${cmd.command}`}}if(result.exitCode===0){return{status:"success",message:"Configured successfully"}}const detail=result.stderr.trim()||result.stdout.trim();return{status:"failed",message:`Command exited with code ${result.exitCode}${detail?`: ${detail}`:""}`}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"failed",message:`"${cmd.command}" not found on PATH. Install it or configure manually.`}}return{status:"failed",message:`Failed to run command: ${err instanceof Error?err.message:String(err)}`}}}async function executeCliUninstallCommand(cmd,execService){try{const result=await execService.exec(cmd.command,cmd.args);const combined=`${result.stdout} ${result.stderr}`;if(isAlreadyAbsentOutput(combined)){return{status:"not_configured",message:`GitHits not configured via ${cmd.command}`}}if(result.exitCode===0){return{status:"removed",message:"Removed successfully"}}const detail=result.stderr.trim()||result.stdout.trim();return{status:"failed",message:`Command exited with code ${result.exitCode}${detail?`: ${detail}`:""}`}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"failed",message:`"${cmd.command}" not found on PATH. Install it or remove GitHits manually.`}}return{status:"failed",message:`Failed to run command: ${err instanceof Error?err.message:String(err)}`}}}async function executeCliSetup(setup,execService){let anyAlreadyConfigured=false;for(const cmd of setup.commands){const result=await executeCliCommand(cmd,execService);if(result.status==="failed"){return result}if(result.status==="already_configured"){anyAlreadyConfigured=true}}if(anyAlreadyConfigured){return{status:"already_configured",message:`GitHits already configured via ${setup.commands[0]?.command}`}}return{status:"success",message:"Configured successfully"}}async function executeCliUninstall(uninstall,execService){if(uninstall.commands.length===0){return{status:"failed",message:"No uninstall commands configured."}}let anyRemoved=false;let anyNotConfigured=false;const warnings=[];for(const cmd of uninstall.commands){const result=await executeCliUninstallCommand(cmd,execService);if(result.status==="failed"){if(anyRemoved){warnings.push(result.message);continue}return result}if(result.status==="removed"){anyRemoved=true}if(result.status==="not_configured"){if(anyRemoved){warnings.push(result.message);continue}anyNotConfigured=true}}if(anyRemoved){return{status:"removed",message:"Removed successfully",warnings:warnings.length>0?warnings:undefined}}if(anyNotConfigured){return{status:"not_configured",message:`GitHits not configured via ${uninstall.commands[0]?.command}`}}return{status:"removed",message:"Removed successfully"}}async function executeCompositeUninstall(uninstall,fs,execService){let anyRemoved=false;let anyNotConfigured=false;const warnings=[];for(const{step,failureMode}of uninstall.steps){const result=await executeUninstallStep(step,fs,execService);if(result.status==="removed"){anyRemoved=true;warnings.push(...result.warnings??[]);continue}if(result.status==="not_configured"){if(anyRemoved){warnings.push(result.message)}else{anyNotConfigured=true}continue}if(failureMode==="best-effort"&&anyRemoved){warnings.push(result.message);continue}return result}if(anyRemoved){return{status:"removed",message:"Removed successfully",warnings:warnings.length>0?warnings:undefined}}if(anyNotConfigured){return{status:"not_configured",message:"GitHits not configured"}}return{status:"not_configured",message:"GitHits not configured"}}async function executeUninstallStep(step,fs,execService){return step.method==="cli"?executeCliUninstall(step,execService):executeConfigFileUninstall(step,fs)}async function executeConfigFileSetup(setup,fs){try{const parentDir=fs.getDirname(setup.configPath);await fs.ensureDir(parentDir);let existingContent="";try{existingContent=await fs.readFile(setup.configPath)}catch(err){if(!(err instanceof Error)||!("code"in err)||err.code!=="ENOENT"){return{status:"failed",message:`Cannot read ${setup.configPath}: ${err instanceof Error?err.message:String(err)}`}}}const result=mergeServerConfig(existingContent,setup.serversKey,setup.serverName,setup.serverConfig,setup.format);if(result.status==="already_configured"){return{status:"already_configured",message:`GitHits already configured in ${setup.configPath}`}}if(result.status==="parse_error"){return{status:"failed",message:`Cannot parse ${setup.configPath}: ${result.error}. File left unchanged.`}}await fs.atomicWriteFile(setup.configPath,result.content);return{status:"success",message:"Configured successfully"}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="EACCES"){return{status:"failed",message:`Permission denied writing to ${setup.configPath}. Check file permissions.`}}return{status:"failed",message:`Failed to configure: ${err instanceof Error?err.message:String(err)}`}}}async function executeCompositeSetup(setup,fs,execService){let executedAny=false;for(const step of setup.steps){if(await isSetupAlreadyConfigured(step,fs,execService)){continue}executedAny=true;const result=step.method==="cli"?await executeCliSetup(step,execService):await executeConfigFileSetup(step,fs);if(result.status==="failed"){return result}}if(!executedAny){return{status:"already_configured",message:"GitHits already configured"}}return{status:"success",message:"Configured successfully"}}async function executeConfigFileUninstall(setup,fs){try{let existingContent="";try{existingContent=await fs.readFile(setup.configPath)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT"){return{status:"not_configured",message:`GitHits not configured in ${setup.configPath}`}}return{status:"failed",message:`Cannot read ${setup.configPath}: ${err instanceof Error?err.message:String(err)}`}}const result=removeServerConfig(existingContent,setup.serversKey,setup.serverName,setup.format);if(result.status==="not_configured"){return{status:"not_configured",message:`GitHits not configured in ${setup.configPath}`}}if(result.status==="parse_error"){return{status:"failed",message:`Cannot parse ${setup.configPath}: ${result.error}. File left unchanged.`}}await fs.atomicWriteFile(setup.configPath,result.content);return{status:"removed",message:"Removed successfully"}}catch(err){if(err instanceof Error&&"code"in err&&err.code==="EACCES"){return{status:"failed",message:`Permission denied writing to ${setup.configPath}. Check file permissions.`}}return{status:"failed",message:`Failed to uninstall: ${err instanceof Error?err.message:String(err)}`}}}var GITHITS_SERVER_NAME="GitHits";var GITHITS_MCP_COMMAND="npx";var GITHITS_MCP_ARGS=["-y","githits@latest","mcp","start"];var GITHITS_MCP_INVOCATION=[GITHITS_MCP_COMMAND,...GITHITS_MCP_ARGS];var CLAUDE_GITHITS_PLUGIN="githits";var CLAUDE_GITHITS_MARKETPLACE="githits-plugins";var CLAUDE_GITHITS_PLUGIN_REF=`${CLAUDE_GITHITS_PLUGIN}@${CLAUDE_GITHITS_MARKETPLACE}`;var CLAUDE_GITHITS_MARKETPLACE_SOURCE="githits-com/githits-cli";var BINARY_LOOKUP_TIMEOUT_MS=2000;var GLOBAL_BIN_PROBE_TIMEOUT_MS=3000;function getAppDataPath(fs,appName){const home=fs.getHomeDir();switch(process.platform){case"win32":return fs.joinPath(process.env.APPDATA??fs.joinPath(home,"AppData","Roaming"),appName);case"darwin":return fs.joinPath(home,"Library","Application Support",appName);default:return fs.joinPath(home,".config",appName)}}function getUserDataRoot(fs){const home=fs.getHomeDir();switch(process.platform){case"win32":return process.env.APPDATA??fs.joinPath(home,"AppData","Roaming");case"darwin":return fs.joinPath(home,"Library","Application Support");default:return process.env.XDG_DATA_HOME??fs.joinPath(home,".local","share")}}function getOpenCodeConfigDir(fs){if(process.platform==="win32"){return fs.joinPath(getUserDataRoot(fs),"opencode")}return fs.joinPath(fs.getHomeDir(),".config","opencode")}function expandHomePath(fs,path){if(path==="~"){return fs.getHomeDir()}if(path.startsWith("~/")){return fs.joinPath(fs.getHomeDir(),path.slice(2))}return path}function getPiAgentDir(fs){const configuredDir=process.env.PI_CODING_AGENT_DIR?.trim();if(configuredDir){return expandHomePath(fs,configuredDir)}return fs.joinPath(fs.getHomeDir(),".pi","agent")}function getPiMcpConfigPath(fs){return fs.joinPath(getPiAgentDir(fs),"mcp.json")}function getHermesHomeDir(fs){const configuredDir=process.env.HERMES_HOME?.trim();if(configuredDir){return expandHomePath(fs,configuredDir)}return fs.joinPath(fs.getHomeDir(),".hermes")}function getHermesConfigPath(fs){return fs.joinPath(getHermesHomeDir(fs),"config.yaml")}function getStandardMcpServerConfig(){return{command:GITHITS_MCP_COMMAND,args:[...GITHITS_MCP_ARGS]}}function getVsCodeMcpServerConfig(){return{type:"stdio",...getStandardMcpServerConfig()}}function getProjectPath(fs){return fs.getCwd()}function getProjectJsonConfig(fs,relativePath,serversKey,serverConfig=getStandardMcpServerConfig()){return{method:"config-file",configPath:fs.joinPath(getProjectPath(fs),...relativePath),serversKey,serverName:GITHITS_SERVER_NAME,serverConfig}}function getUnsupportedProjectSetup(reason){return{supported:false,reason}}function getAgentSetupConfig(agent,fs,scope="user",context){if(scope==="project"){if(agent.projectSetup?.supported){return agent.projectSetup.getSetupConfig(fs,context)}return null}return agent.getSetupConfig(fs,context)}function getProjectSetupUnsupportedReason(agent){if(agent.projectSetup?.supported){return null}return agent.projectSetup?.reason??"project-level MCP config not verified"}function getOpenCodeDesktopDetectPaths(fs){const userDataRoot=getUserDataRoot(fs);return[fs.joinPath(userDataRoot,"ai.opencode.desktop"),fs.joinPath(userDataRoot,"ai.opencode.desktop.beta"),fs.joinPath(userDataRoot,"ai.opencode.desktop.dev"),getOpenCodeConfigDir(fs)]}async function isExecutableAvailable(exec,executable){try{const lookupCommand=process.platform==="win32"?"where":"which";const result=await exec.exec(lookupCommand,[executable],{timeoutMs:BINARY_LOOKUP_TIMEOUT_MS});return result.exitCode===0}catch{return false}}async function resolveExecutableFromPath(exec,executable){return isExecutableAvailable(exec,executable)}var PI_GLOBAL_BIN_PROBES=[{command:"npm",args:["prefix","-g"],output:"prefix"},{command:"pnpm",args:["bin","-g"],output:"binDir"},{command:"bun",args:["pm","bin","-g"],output:"binDir"}];var PI_ADAPTER_CONFIGURED_PATTERN=/(?:^|\s|:)(?:npm:)?pi-mcp-adapter(?:[\s@:]|$)/i;function getPiExecutableNames(){return process.platform==="win32"?["pi.cmd","pi.exe","pi"]:["pi"]}async function runGlobalBinProbe(exec,probe){try{const result=await exec.exec(probe.command,[...probe.args],{timeoutMs:GLOBAL_BIN_PROBE_TIMEOUT_MS});if(result.exitCode!==0){return null}const probePath=result.stdout.split(/\r?\n/).map((line)=>line.trim()).find((line)=>line.length>0);if(!probePath){return null}if(probe.output==="prefix"&&process.platform!=="win32"){return fsJoinPathLike(probePath,"bin")}return probePath}catch{return null}}function fsJoinPathLike(base,child){return base.endsWith("/")?`${base}${child}`:`${base}/${child}`}async function detectPiExecutable(exec,fs){if(await resolveExecutableFromPath(exec,"pi")){return{command:"pi"}}for(const probe of PI_GLOBAL_BIN_PROBES){const binDir=await runGlobalBinProbe(exec,probe);if(!binDir){continue}for(const executableName of getPiExecutableNames()){const candidate=fs.joinPath(binDir,executableName);if(await fs.exists(candidate)){return{command:candidate}}}}return null}var claudeCode={name:"Claude Code",id:"claude-code",detectionMethod:"binary",setupMethod:"cli",detectBinary:async(exec)=>isExecutableAvailable(exec,"claude"),getSetupConfig:()=>({method:"cli",commands:[{command:"claude",args:["plugin","marketplace","add",CLAUDE_GITHITS_MARKETPLACE_SOURCE]},{command:"claude",args:["plugin","install",CLAUDE_GITHITS_PLUGIN_REF]}],checkCommand:{command:"claude",args:["plugin","list"],configuredPattern:/(^|\s)githits@githits-plugins\b/i}}),getUninstallConfig:()=>({method:"cli",commands:[{command:"claude",args:["plugin","uninstall",CLAUDE_GITHITS_PLUGIN]},{command:"claude",args:["plugin","marketplace","remove",CLAUDE_GITHITS_MARKETPLACE]}]}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".mcp.json"],"mcpServers")}};var cursor={name:"Cursor",id:"cursor",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".cursor")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".cursor","mcp.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".cursor","mcp.json"],"mcpServers")}};var windsurf={name:"Windsurf",id:"windsurf",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".codeium","windsurf")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".codeium","windsurf","mcp_config.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("project-level MCP config not verified for Windsurf")};var claudeDesktop={name:"Claude Desktop",id:"claude-desktop",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>{const appData=getAppDataPath(fs,"Claude");if(process.platform==="win32"){const home=fs.getHomeDir();const localAppData=process.env.LOCALAPPDATA??fs.joinPath(home,"AppData","Local");return[appData,fs.joinPath(localAppData,"Claude"),fs.joinPath(localAppData,"Programs","Claude")]}return[appData]},getSetupConfig:(fs)=>{const appData=getAppDataPath(fs,"Claude");return{method:"config-file",configPath:fs.joinPath(appData,"claude_desktop_config.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}},projectSetup:getUnsupportedProjectSetup("Claude Desktop uses user-level desktop config")};var codexCli={name:"Codex CLI",id:"codex-cli",detectionMethod:"binary",setupMethod:"cli",detectBinary:async(exec)=>isExecutableAvailable(exec,"codex"),getSetupConfig:()=>({method:"cli",commands:[{command:"codex",args:["mcp","add","githits","--",...GITHITS_MCP_INVOCATION]}],checkCommand:{command:"codex",args:["mcp","list"],configuredPattern:/^\s*githits\b/im}}),getUninstallConfig:()=>({method:"cli",commands:[{command:"codex",args:["mcp","remove","githits"]}]}),projectSetup:{supported:true,getSetupConfig:(fs)=>({method:"config-file",format:"toml",configPath:fs.joinPath(getProjectPath(fs),".codex","config.toml"),serversKey:"mcp_servers",serverName:"githits",serverConfig:getStandardMcpServerConfig()})}};var pi={name:"Pi",id:"pi",detectionMethod:"binary",setupMethod:"composite",detectCommand:detectPiExecutable,getSetupConfig:(fs,context)=>{const piCommand=context?.command??"pi";return{method:"composite",steps:[{method:"cli",commands:[{command:piCommand,args:["install","npm:pi-mcp-adapter"]}],checkCommand:{command:piCommand,args:["list"],configuredPattern:PI_ADAPTER_CONFIGURED_PATTERN}},{method:"config-file",configPath:getPiMcpConfigPath(fs),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:{...getStandardMcpServerConfig(),lifecycle:"eager"}}]}},getUninstallConfig:(fs,context)=>{const piCommand=context?.command??"pi";return{method:"composite",steps:[{failureMode:"required",step:{method:"config-file",configPath:getPiMcpConfigPath(fs),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:{}}},{failureMode:"required",step:{method:"cli",commands:[{command:piCommand,args:["remove","npm:pi-mcp-adapter"]}]}}]}},projectSetup:{supported:true,getSetupConfig:(fs,context)=>{const piCommand=context?.command??"pi";return{method:"composite",steps:[{method:"cli",commands:[{command:piCommand,args:["install","npm:pi-mcp-adapter"]}],checkCommand:{command:piCommand,args:["list"],configuredPattern:PI_ADAPTER_CONFIGURED_PATTERN}},getProjectJsonConfig(fs,[".mcp.json"],"mcpServers")]}}}};var vscode={name:"VS Code / Copilot",id:"vscode",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>{const appData=getAppDataPath(fs,"Code");return[appData]},getSetupConfig:(fs)=>{const appData=getAppDataPath(fs,"Code");return{method:"config-file",configPath:fs.joinPath(appData,"User","mcp.json"),serversKey:"servers",serverName:GITHITS_SERVER_NAME,serverConfig:getVsCodeMcpServerConfig()}},projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".vscode","mcp.json"],"servers",getVsCodeMcpServerConfig())}};var cline={name:"Cline",id:"cline",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".cline")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".cline","data","settings","cline_mcp_settings.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("Cline MCP settings are documented as user-level config; project MCP auto-load not verified")};var geminiCli={name:"Gemini CLI",id:"gemini-cli",detectionMethod:"binary",setupMethod:"cli",detectBinary:async(exec)=>isExecutableAvailable(exec,"gemini"),getSetupConfig:()=>({method:"cli",commands:[{command:"gemini",args:["extensions","install","--consent","https://github.com/githits-com/githits-cli"]}],checkCommand:{command:"gemini",args:["extensions","config","githits"],notConfiguredPattern:/not installed/i,requireExitCodeZero:true}}),getUninstallConfig:()=>({method:"cli",commands:[{command:"gemini",args:["extensions","uninstall","githits"]}]}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,[".gemini","settings.json"],"mcpServers")}};async function isGeminiExtensionInstalledFromFilesystem(fs){const extensionManifestPath=fs.joinPath(fs.getHomeDir(),".gemini","extensions","githits","gemini-extension.json");return fs.exists(extensionManifestPath)}var googleAntigravity={name:"Google Antigravity",id:"google-antigravity",detectionMethod:"path",setupMethod:"config-file",detectPaths:(fs)=>[fs.joinPath(fs.getHomeDir(),".gemini","antigravity")],getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(fs.getHomeDir(),".gemini","antigravity","mcp_config.json"),serversKey:"mcpServers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("Google Antigravity project-level MCP config not verified")};var openCode={name:"OpenCode",id:"opencode",detectionMethod:"hybrid",setupMethod:"config-file",detectPaths:(fs)=>getOpenCodeDesktopDetectPaths(fs),detectBinary:async(exec)=>isExecutableAvailable(exec,"opencode"),getSetupConfig:(fs)=>({method:"config-file",configPath:fs.joinPath(getOpenCodeConfigDir(fs),"opencode.json"),serversKey:"mcp",serverName:GITHITS_SERVER_NAME,serverConfig:{type:"local",command:[...GITHITS_MCP_INVOCATION],enabled:true}}),projectSetup:{supported:true,getSetupConfig:(fs)=>getProjectJsonConfig(fs,["opencode.json"],"mcp",{type:"local",command:[...GITHITS_MCP_INVOCATION],enabled:true})}};var hermesAgent={name:"Hermes Agent",id:"hermes-agent",detectionMethod:"hybrid",setupMethod:"config-file",detectPaths:(fs)=>[getHermesHomeDir(fs)],detectBinary:async(exec)=>isExecutableAvailable(exec,"hermes-agent"),getSetupConfig:(fs)=>({method:"config-file",format:"yaml",configPath:getHermesConfigPath(fs),serversKey:"mcp_servers",serverName:GITHITS_SERVER_NAME,serverConfig:getStandardMcpServerConfig()}),projectSetup:getUnsupportedProjectSetup("Hermes Agent project-level MCP config not verified")};var agentDefinitions=[claudeCode,cursor,windsurf,vscode,cline,claudeDesktop,codexCli,pi,geminiCli,googleAntigravity,openCode,hermesAgent];async function scanSingleAgent(agent,fs,execService,scope){const scanStartedAt=Date.now();traceInit(`agent:start agent=${agent.id} scope=${scope}`);let detected=false;let setupContext;if(agent.detectCommand){const startedAt=Date.now();try{traceProbeStart({agentId:agent.id,phase:"detectCommand"});const resolvedCommand=await agent.detectCommand(execService,fs);traceProbeEnd({agentId:agent.id,phase:"detectCommand",startedAt,status:"end"});if(resolvedCommand){detected=true;setupContext={command:resolvedCommand.command}}}catch{traceProbeEnd({agentId:agent.id,phase:"detectCommand",startedAt,status:"error"});detected=false}}else if(agent.detectionMethod==="binary"&&agent.detectBinary){const startedAt=Date.now();try{traceProbeStart({agentId:agent.id,phase:"binary"});detected=await agent.detectBinary(execService);traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"end"})}catch{traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"error"});detected=false}}else if(agent.detectionMethod==="path"&&agent.detectPaths){const paths=agent.detectPaths(fs);for(const path of paths){if(await fs.isDirectory(path)){detected=true;break}}}else if(agent.detectionMethod==="hybrid"){let binaryDetected=false;let pathDetected=false;if(agent.detectBinary){const startedAt=Date.now();try{traceProbeStart({agentId:agent.id,phase:"binary"});binaryDetected=await agent.detectBinary(execService);traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"end"})}catch{traceProbeEnd({agentId:agent.id,phase:"binary",startedAt,status:"error"});binaryDetected=false}}if(!binaryDetected&&agent.detectPaths){const paths=agent.detectPaths(fs);for(const path of paths){if(await fs.isDirectory(path)){pathDetected=true;break}}}detected=binaryDetected||pathDetected}if(!detected){traceInit(`agent:end agent=${agent.id} status=not_detected elapsedMs=${Date.now()-scanStartedAt}`);return{status:"not_detected",agent}}const config=getAgentSetupConfig(agent,fs,scope,setupContext);if(!config){return{status:"unsupported",agent,reason:getProjectSetupUnsupportedReason(agent)??"project-level MCP config not verified"}}const scannedAgent={...agent,resolvedSetupConfig:config,resolvedSetupContext:setupContext};if(agent.id==="gemini-cli"&&config.method==="cli"){if(!config.checkCommand){return{status:"needs_setup",agent:scannedAgent}}const checkStatus=await getCliCheckStatus(config.checkCommand,execService,{agentId:agent.id,phase:"check"});let configured=checkStatus==="configured";if(!configured&&checkStatus==="probe_failed"){configured=await isGeminiExtensionInstalledFromFilesystem(fs)}const status=configured?"already_configured":"needs_setup";traceInit(`agent:end agent=${agent.id} status=${status} elapsedMs=${Date.now()-scanStartedAt}`);return{status,agent:scannedAgent}}if(await isSetupAlreadyConfigured(config,fs,execService,{agentId:agent.id,phase:"check"})){traceInit(`agent:end agent=${agent.id} status=already_configured elapsedMs=${Date.now()-scanStartedAt}`);return{status:"already_configured",agent:scannedAgent}}traceInit(`agent:end agent=${agent.id} status=needs_setup elapsedMs=${Date.now()-scanStartedAt}`);return{status:"needs_setup",agent:scannedAgent}}async function scanAgents(definitions,fs,execService,options={}){const result={needsSetup:[],alreadyConfigured:[],notDetected:[],unsupported:[]};let completed=0;const startedAt=Date.now();traceInit(`scan:start scope=${options.scope??"user"} total=${definitions.length}`);const outcomes=await Promise.all(definitions.map((agent)=>scanSingleAgent(agent,fs,execService,options.scope??"user").then((outcome)=>{completed+=1;options.onProgress?.({completed,total:definitions.length,agent:outcome.agent});return outcome})));for(const outcome of outcomes){if(outcome.status==="already_configured"){result.alreadyConfigured.push(outcome.agent)}else if(outcome.status==="needs_setup"){result.needsSetup.push(outcome.agent)}else if(outcome.status==="unsupported"){result.unsupported.push({agent:outcome.agent,reason:outcome.reason})}else{result.notDetected.push(outcome.agent)}}traceInit(`scan:end elapsedMs=${Date.now()-startedAt}`);return result}import{ExitPromptError}from"@inquirer/core";import{spawn}from"node:child_process";var WINDOWS_CMD_META_CHARS=/([()[\]%!^"`<>&|;, *?])/g;function escapeWindowsCommand(value){return value.replace(WINDOWS_CMD_META_CHARS,"^$1")}function escapeWindowsArgument(value){let arg=`${value}`;arg=arg.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\"");arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1");return`"${arg}"`.replace(WINDOWS_CMD_META_CHARS,"^$1")}function buildWindowsShellCommand(command,args){return[escapeWindowsCommand(command),...args.map(escapeWindowsArgument)].join(" ")}function isWindowsCommandNotFound(exitCode,stderr,platform=process.platform){return platform==="win32"&&exitCode!==0&&/^\s*'[^']+'\s+is not recognized as an internal or external command,/i.test(stderr)}function createCommandNotFoundError(command){const error2=new Error(`spawn ${command} ENOENT`);error2.code="ENOENT";error2.syscall="spawn";error2.path=command;return error2}function normalizeSpawnCommand(command,args,platform=process.platform){if(platform!=="win32"){return{command,args}}const shellCommand=buildWindowsShellCommand(command,args);return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${shellCommand}"`],windowsVerbatimArguments:true}}class ExecTimeoutError extends Error{command;args;timeoutMs;constructor(command,args,timeoutMs){super(`Command timed out after ${timeoutMs}ms: ${command} ${args.join(" ")}`);this.name="ExecTimeoutError";this.command=command;this.args=args;this.timeoutMs=timeoutMs}}class ExecServiceImpl{async exec(command,args,options={}){return new Promise((resolve,reject)=>{const spawnCommand=normalizeSpawnCommand(command,args);const child=spawn(spawnCommand.command,spawnCommand.args,{stdio:["ignore","pipe","pipe"],env:{...process.env},...spawnCommand.shell!==undefined&&{shell:spawnCommand.shell},...spawnCommand.windowsVerbatimArguments!==undefined&&{windowsVerbatimArguments:spawnCommand.windowsVerbatimArguments}});const stdoutChunks=[];const stderrChunks=[];let settled=false;let timeout;const settle=(fn)=>{if(settled){return}settled=true;if(timeout){clearTimeout(timeout)}fn()};const timeoutMs=options.timeoutMs;if(timeoutMs!==undefined){timeout=setTimeout(()=>{settle(()=>{child.kill("SIGTERM");reject(new ExecTimeoutError(command,args,timeoutMs))})},timeoutMs)}child.stdout.on("data",(chunk)=>stdoutChunks.push(chunk));child.stderr.on("data",(chunk)=>stderrChunks.push(chunk));child.on("error",(error2)=>{settle(()=>reject(error2))});child.on("close",(code)=>{settle(()=>{const exitCode=code??1;const stderr=Buffer.concat(stderrChunks).toString("utf-8");if(isWindowsCommandNotFound(exitCode,stderr)){reject(createCommandNotFoundError(command));return}resolve({exitCode,stdout:Buffer.concat(stdoutChunks).toString("utf-8"),stderr})})})})}}import{checkbox,confirm,select}from"@inquirer/prompts";class PromptServiceImpl{async select(message,choices,defaultValue){return select({message,choices,default:defaultValue})}async checkbox(message,choices){return checkbox({message,choices})}async confirm(message,defaultValue){return confirm({message,default:defaultValue})}async confirm3(message,defaultValue){return select({message,default:defaultValue,choices:[{value:"yes",name:"Yes"},{value:"no",name:"No"},{value:"always",name:"Yes to all",description:"Skip confirmation for remaining agents"}]})}}var stdoutLoginOutput={write:(message)=>{console.log(message)}};var stderrLoginOutput={write:(message)=>{console.error(message)}};var TIMEOUT_MS=5*60*1000;var AUTH_TIMEOUT_MESSAGE="Authentication timed out after 5 minutes. The browser link has expired, so it will not work anymore. Run the same command again to try signing in again.";function randomPort(){return Math.floor(Math.random()*2000)+8000}async function preflightAuthPersistence(authStorage,mcpUrl){const probeUrl=`${mcpUrl.replace(/\/+$/,"")}/__githits_storage_probe__`;const probeClient={clientId:"__githits_storage_probe__",clientSecret:"__githits_storage_probe__",redirectUri:"http://127.0.0.1:1/callback",registeredAt:new Date(0).toISOString()};const probeTokens={accessToken:"__githits_storage_probe__",refreshToken:"__githits_storage_probe__",expiresAt:new Date(0).toISOString(),createdAt:new Date(0).toISOString()};try{await authStorage.saveAuthSession(probeUrl,probeClient,probeTokens);await authStorage.clearAuthSession(probeUrl);return null}catch(error2){await authStorage.clearAuthSession(probeUrl).catch(()=>{});const message=error2 instanceof Error?error2.message:String(error2);return{status:"failed",message:`Cannot persist OAuth credentials: ${message}`}}}async function loginFlow(options,deps,output=stdoutLoginOutput){const{authService,authStorage,browserService,mcpUrl}=deps;const existing=await authStorage.loadTokens(mcpUrl);if(options.port!==undefined&&(Number.isNaN(options.port)||options.port<1||options.port>65535)){return{status:"failed",message:"Invalid port number. Must be between 1 and 65535."}}if(existing&&!options.force){const isExpired=existing.expiresAt&&new Date(existing.expiresAt)<new Date;if(!isExpired){return{status:"already_authenticated",message:"Already logged in."}}output.write(`Starting sign-in...
178
+ `)}else if(existing&&options.force){output.write(`Signing in again...
179
+ `)}if(!existing){await authStorage.clearActiveClient(mcpUrl)}const persistenceError=await preflightAuthPersistence(authStorage,mcpUrl);if(persistenceError)return persistenceError;const metadata=await authService.discoverEndpoints(mcpUrl);let client=await authStorage.loadClient(mcpUrl);const hadStoredClient=client!==null;let shouldClearClientOnFailedAttempt=false;let port;let redirectUri;if(client){if(options.port){redirectUri=`http://127.0.0.1:${options.port}/callback`;if(redirectUri!==client.redirectUri){const registration=await authService.registerClient({registrationEndpoint:metadata.registrationEndpoint,redirectUri});client={clientId:registration.clientId,clientSecret:registration.clientSecret,redirectUri,registeredAt:new Date().toISOString()};shouldClearClientOnFailedAttempt=!hadStoredClient}port=options.port}else{redirectUri=client.redirectUri;const storedUrl=new URL(redirectUri);port=Number(storedUrl.port)||randomPort()}}else{port=options.port??randomPort();redirectUri=`http://127.0.0.1:${port}/callback`;const registration=await authService.registerClient({registrationEndpoint:metadata.registrationEndpoint,redirectUri});client={clientId:registration.clientId,clientSecret:registration.clientSecret,redirectUri,registeredAt:new Date().toISOString()};shouldClearClientOnFailedAttempt=!hadStoredClient}const{verifier,challenge,state}=authService.generatePkceParams();const authUrl=authService.buildAuthUrl({authorizationEndpoint:metadata.authorizationEndpoint,clientId:client.clientId,redirectUri,state,codeChallenge:challenge});let callbackServer;try{callbackServer=await authService.startCallbackServer(port,state)}catch(error2){const msg=error2 instanceof Error?error2.message:String(error2);return{status:"failed",message:msg}}if(options.browser===false){output.write(`Open this URL in your browser:
179
180
  `);output.write(` ${authUrl}
180
- `)}else{output.write("Opening browser...");try{await browserService.open(authUrl)}catch(error2){const msg=error2 instanceof Error?error2.message:String(error2);output.write(`Could not open browser automatically: ${msg}
181
+ `)}else{output.write("Opening browser for GitHits sign-in...");try{await browserService.open(authUrl)}catch(error2){const msg=error2 instanceof Error?error2.message:String(error2);output.write(`Could not open browser automatically: ${msg}
181
182
  `);output.write(`Open this URL in your browser:
182
183
  `);output.write(` ${authUrl}
183
- `)}}output.write(`Waiting for authentication...
184
- `);let timeoutId;const timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error(AUTH_TIMEOUT_MESSAGE)),TIMEOUT_MS)});let callback;try{callback=await Promise.race([callbackServer.result,timeoutPromise]);if(timeoutId)clearTimeout(timeoutId);await callbackServer.close().catch(()=>{})}catch(error2){if(timeoutId)clearTimeout(timeoutId);await callbackServer.close().catch(()=>{});if(shouldClearClientOnFailedAttempt){await authStorage.clearClient(mcpUrl).catch(()=>{})}const msg=error2 instanceof Error?error2.message:"Authentication failed";return{status:"failed",message:ensureTerminalPeriod(msg)}}if(callback.type!=="success"){await new Promise((r)=>setTimeout(r,2000));if(shouldClearClientOnFailedAttempt){await authStorage.clearClient(mcpUrl).catch(()=>{})}return{status:"failed",message:callback.message??"Authentication callback failed."}}let tokenResponse;try{tokenResponse=await authService.exchangeCodeForTokens({tokenEndpoint:metadata.tokenEndpoint,clientId:client.clientId,clientSecret:client.clientSecret,code:callback.code,codeVerifier:verifier,redirectUri})}catch(error2){try{await authStorage.clearClient(mcpUrl)}catch{}const msg=error2 instanceof Error?error2.message:String(error2);return{status:"failed",message:`Failed to complete authentication: ${msg}`}}const expiresAt=new Date(Date.now()+tokenResponse.expiresIn*1000).toISOString();await authStorage.saveAuthSession(mcpUrl,client,{accessToken:tokenResponse.accessToken,refreshToken:tokenResponse.refreshToken,expiresAt,createdAt:new Date().toISOString()});const hours=Math.round(tokenResponse.expiresIn/3600);return{status:"success",message:`Logged in successfully. Token expires in ${hours} hour${hours!==1?"s":""}.`}}async function loginAction(options,deps){const result=await loginFlow(options,deps,stdoutLoginOutput);if(result.status==="already_authenticated"){console.log(`Already logged in.
185
- `);console.log(` Environment: ${deps.mcpUrl}
186
- `);console.log("To re-authenticate, use `githits login --force`.");return}if(result.status==="failed"){console.error(`${result.message}
187
- `);printLoginRecoveryHint(result.message);process.exit(1)}console.log(`Logged in successfully.
188
- `);console.log(` Environment: ${deps.mcpUrl}`);console.log(result.message.replace("Logged in successfully. "," "));console.log(`
189
- You're ready to use githits with your AI assistant.`)}function printLoginRecoveryHint(message){console.log("Recovery steps:");if(message.includes("Authentication timed out")){console.log(" Run the same command again to open a fresh sign-in link.");console.log(" githits login --no-browser # if the browser did not open or you are on SSH");console.log(" githits logout && githits login # if sign-in keeps failing after a retry");return}console.log(" githits auth status");console.log(" githits login --force");if(message.includes("Cannot persist OAuth credentials")){console.log("If your system keychain is locked or unavailable, unlock it and retry.");console.log("For CI/automation, set GITHITS_API_TOKEN.");console.log("As a last resort, set GITHITS_AUTH_STORAGE=file to use plaintext file storage.")}}function printAutoLoginRecoveryHint(message){if(message.includes("Authentication timed out")){console.error("Run the same command again to open a fresh sign-in link.");console.error("If the browser did not open, run `githits login --no-browser` and follow the printed link.");console.error("If sign-in keeps failing after a retry, run `githits logout` and then run your command again.");return}console.error("Run the same command again to try signing in again.");console.error("Run `githits auth status` to check whether you are signed in.");if(message.includes("Cannot persist OAuth credentials")){console.error("If your system keychain is locked or unavailable, unlock it and try again.");console.error("For CI/automation, set GITHITS_API_TOKEN.")}}function ensureTerminalPeriod(message){return/[.!?]$/.test(message)?message:`${message}.`}var LOGIN_DESCRIPTION=`Authenticate with your GitHits account via browser.
184
+ `)}}output.write(`Waiting for sign-in to finish...
185
+ `);let timeoutId;const timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error(AUTH_TIMEOUT_MESSAGE)),TIMEOUT_MS)});let callback;try{callback=await Promise.race([callbackServer.result,timeoutPromise]);if(timeoutId)clearTimeout(timeoutId);await callbackServer.close().catch(()=>{})}catch(error2){if(timeoutId)clearTimeout(timeoutId);await callbackServer.close().catch(()=>{});if(shouldClearClientOnFailedAttempt){await authStorage.clearActiveClient(mcpUrl).catch(()=>{})}const msg=error2 instanceof Error?error2.message:"Authentication failed";return{status:"failed",message:ensureTerminalPeriod(msg)}}if(callback.type!=="success"){await new Promise((r)=>setTimeout(r,2000));if(shouldClearClientOnFailedAttempt){await authStorage.clearActiveClient(mcpUrl).catch(()=>{})}return{status:"failed",message:callback.message??"Authentication callback failed."}}let tokenResponse;try{tokenResponse=await authService.exchangeCodeForTokens({tokenEndpoint:metadata.tokenEndpoint,clientId:client.clientId,clientSecret:client.clientSecret,code:callback.code,codeVerifier:verifier,redirectUri})}catch(error2){try{await authStorage.clearActiveClient(mcpUrl)}catch{}const msg=error2 instanceof Error?error2.message:String(error2);return{status:"failed",message:`Failed to complete authentication: ${msg}`}}const expiresAt=new Date(Date.now()+tokenResponse.expiresIn*1000).toISOString();await authStorage.saveAuthSession(mcpUrl,client,{accessToken:tokenResponse.accessToken,refreshToken:tokenResponse.refreshToken,expiresAt,createdAt:new Date().toISOString()});return{status:"success",message:"Logged in successfully."}}async function loginAction(options,deps){const result=await loginFlow(options,deps,stdoutLoginOutput);if(result.status==="already_authenticated"){console.log(`Already logged in.
186
+ `);console.log("You're ready to use GitHits.");return}if(result.status==="failed"){console.error(`${result.message}
187
+ `);printLoginRecoveryHint(result.message);process.exit(1)}console.log(`${result.message}
188
+ `);console.log("You're ready to use GitHits.")}function printLoginRecoveryHint(message){console.log("Recovery steps:");if(message.includes("Authentication timed out")){console.log(" Run the same command again to open a fresh sign-in link.");console.log(" githits login --no-browser # if the browser did not open or you are on SSH");console.log(" githits logout && githits login # if sign-in keeps failing after a retry");return}console.log(" githits auth status");console.log(" githits login --force");if(message.includes("Cannot persist OAuth credentials")){console.log("If your system keychain is locked or unavailable, unlock it and retry.");console.log("For CI/automation, set GITHITS_API_TOKEN.");console.log("As a last resort, set GITHITS_AUTH_STORAGE=file to use plaintext file storage.")}}function printAutoLoginRecoveryHint(message){if(message.includes("Authentication timed out")){console.error("Run the same command again to open a fresh sign-in link.");console.error("If the browser did not open, run `githits login --no-browser` and follow the printed link.");console.error("If sign-in keeps failing after a retry, run `githits logout` and then run your command again.");return}console.error("Run the same command again to try signing in again.");console.error("Run `githits auth status` to check whether you are signed in.");if(message.includes("Cannot persist OAuth credentials")){console.error("If your system keychain is locked or unavailable, unlock it and try again.");console.error("For CI/automation, set GITHITS_API_TOKEN.")}}function ensureTerminalPeriod(message){return/[.!?]$/.test(message)?message:`${message}.`}var LOGIN_DESCRIPTION=`Authenticate with your GitHits account via browser.
190
189
 
191
190
  Opens your browser to complete authentication securely using OAuth.
192
191
  OAuth credentials are stored in the system keychain by default. If your
@@ -254,8 +253,7 @@ With a query, searches the top 5 backend-ranked matches by name, display name, o
254
253
  Examples:
255
254
  githits languages List all languages
256
255
  githits languages python Search by name
257
- githits languages type --json JSON output for piping`;function registerLanguagesCommand(program){program.command("languages").summary("List supported programming languages").description(LANGUAGES_DESCRIPTION).argument("[query]","Search by name, display name, or alias").option("--json","Output as JSON for piping").action(async(query,options)=>{const deps=await createContainer();await languagesAction(query,options,deps)})}async function logoutAction(deps){const{authStorage,mcpUrl}=deps;await authStorage.clearAuthSession(mcpUrl);console.log(`Logged out.
258
- `);console.log(` Environment: ${mcpUrl}`)}var LOGOUT_DESCRIPTION=`Remove stored credentials.
256
+ githits languages type --json JSON output for piping`;function registerLanguagesCommand(program){program.command("languages").summary("List supported programming languages").description(LANGUAGES_DESCRIPTION).argument("[query]","Search by name, display name, or alias").option("--json","Output as JSON for piping").action(async(query,options)=>{const deps=await createContainer();await languagesAction(query,options,deps)})}async function logoutAction(deps){const{authStorage,mcpUrl,authDiagnostics}=deps;await withTelemetrySpan("auth.clear",()=>authStorage.clearAuthSession(mcpUrl),{reason:"logout"});await authDiagnostics?.recordClear(mcpUrl,"logout");console.log("Logged out.")}var LOGOUT_DESCRIPTION=`Remove stored credentials.
259
257
 
260
258
  Clears all locally stored authentication data including tokens and
261
259
  client registrations. OAuth tokens expire naturally; this
@@ -454,7 +452,7 @@ Examples:
454
452
 
455
453
  Pass the searchRef returned by githits search when the initial request could
456
454
  not complete within the wait window. This can return progress, partial hits when
457
- the original request used --allow-partial, or final results.`;function registerSearchCommand(program){program.command("search").summary("Explore repository code, dependencies, docs and symbols").description(SEARCH_DESCRIPTION).argument("<query>","Search query").requiredOption("--in <target>","Search target: registry:name[@version] or https://github.com/org/repo[#ref]",collectRepeatable3,[]).addOption(new Option3("--source <source>","Restrict results to docs, code, or symbol; omit to let GitHits select the best sources").choices(["docs","code","symbol"]).argParser((value,previous)=>{if(previous!==undefined){throw new InvalidArgumentError("Pass --source at most once; omit it to let GitHits select the best sources.")}return value.toLowerCase()}).default(undefined)).addOption(new Option3("--kind <kind>","Precise symbol kind filter").choices([...knownSymbolKindList()])).addOption(new Option3("--category <category>","Broad symbol category filter").choices([...knownSymbolCategoryList()])).option("--path-prefix <prefix>","Repository path prefix filter").addOption(new Option3("--intent <intent>","File intent filter (omit to search across all intents)").choices(["production","test","benchmark","example","generated","fixture","build","vendor"])).option("--public","Filter to public symbols when supported").option("--name <name>","Structured name qualifier").option("--lang <language>","Structured language qualifier").option("--allow-partial","Include hits already available while indexing continues; a searchRef is still returned so search-status can fetch the rest").option("--limit <n>","Max results (1-100, default: 10)").option("--offset <n>","Result offset").option("--wait <seconds>","Max seconds to wait before returning a searchRef (0-60; default: 20)").option("--json","Output as JSON").action(async(query,options)=>{const deps=await loadContainer2();await searchAction(query,options,deps)});program.command("search-status").summary("Check the status of a previous search").description(SEARCH_STATUS_DESCRIPTION).argument("<search-ref>","Search reference returned by githits search").option("--json","Output as JSON").action(async(searchRef,options)=>{const deps=await loadContainer2();await searchStatusAction(searchRef,options,deps)})}async function registerUnifiedSearchCommands(program,options={}){const codeNavigationUrl=options.codeNavigationUrl??getCodeNavigationUrl();if(!codeNavigationUrl){return}registerSearchCommand(program)}function requireSearchService(deps){if(!deps.codeNavigationUrl||!deps.codeNavigationService){throw new InvalidArgumentError("Unified search is not configured for this environment.")}return deps.codeNavigationService}async function loadContainer2(){const{createContainer:createContainer2}=await import("./shared/chunk-q9yem3rk.js");return createContainer2()}function parseTargetSpecs(specs){if(!specs||specs.length===0){throw new InvalidArgumentError("Provide at least one --in target.")}for(const spec of specs){warnIfUnprefixedTargetSpec(spec)}return specs.map(parseUnifiedSearchTargetSpec)}function warnIfUnprefixedTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0)return;if(trimmed.startsWith("http://")||trimmed.startsWith("https://"))return;if(trimmed.includes(":"))return;console.error(`Warning: --in '${trimmed}' has no registry prefix; treating as 'npm:${trimmed}'. Pass 'npm:${trimmed}' explicitly to suppress this warning.`)}function parseSources(value){if(!value)return;switch(value){case"docs":return["DOCS"];case"code":return["CODE"];case"symbol":return["SYMBOL"];default:throw new InvalidArgumentError(`Unsupported source '${value}'.`)}}function parseOptionalInt(value,flag,min,max=Number.MAX_SAFE_INTEGER){return parseIntCliOption(value,flag,min,max)}function parseWaitMs(value){if(value===undefined)return;const match=/^(?<seconds>-?\d+)s?$/i.exec(value.trim());if(!match?.groups?.seconds){throw new InvalidArgumentError("--wait must be an integer between 0 and 60 seconds.")}const seconds=parseIntCliOption(match.groups.seconds,"--wait",0,60);if(seconds===undefined)return;return seconds*1000}function collectRepeatable3(value,previous){return[...previous,value]}function handleSearchError(error2,json,context="search"){const payload=buildUnifiedSearchErrorPayload(error2);if(json){console.error(JSON.stringify(payload))}else{console.error(formatSearchErrorTerminal(payload,context))}process.exit(1)}function formatSearchErrorTerminal(payload,context){if(payload.code==="AUTH_REQUIRED"){return formatMappedErrorForTerminal({code:"AUTH_REQUIRED",message:payload.error,retryable:false,details:payload.details})}if(context==="status"&&payload.code==="NOT_FOUND"){return`${payload.error}
455
+ the original request used --allow-partial, or final results.`;function registerSearchCommand(program){program.command("search").summary("Explore repository code, dependencies, docs and symbols").description(SEARCH_DESCRIPTION).argument("<query>","Search query").requiredOption("--in <target>","Search target: registry:name[@version] or https://github.com/org/repo[#ref]",collectRepeatable3,[]).addOption(new Option3("--source <source>","Restrict results to docs, code, or symbol; omit to let GitHits select the best sources").choices(["docs","code","symbol"]).argParser((value,previous)=>{if(previous!==undefined){throw new InvalidArgumentError("Pass --source at most once; omit it to let GitHits select the best sources.")}return value.toLowerCase()}).default(undefined)).addOption(new Option3("--kind <kind>","Precise symbol kind filter").choices([...knownSymbolKindList()])).addOption(new Option3("--category <category>","Broad symbol category filter").choices([...knownSymbolCategoryList()])).option("--path-prefix <prefix>","Repository path prefix filter").addOption(new Option3("--intent <intent>","File intent filter (omit to search across all intents)").choices(["production","test","benchmark","example","generated","fixture","build","vendor"])).option("--public","Filter to public symbols when supported").option("--name <name>","Structured name qualifier").option("--lang <language>","Structured language qualifier").option("--allow-partial","Include hits already available while indexing continues; a searchRef is still returned so search-status can fetch the rest").option("--limit <n>","Max results (1-100, default: 10)").option("--offset <n>","Result offset").option("--wait <seconds>","Max seconds to wait before returning a searchRef (0-60; default: 20)").option("--json","Output as JSON").action(async(query,options)=>{const deps=await loadContainer2();await searchAction(query,options,deps)});program.command("search-status").summary("Check the status of a previous search").description(SEARCH_STATUS_DESCRIPTION).argument("<search-ref>","Search reference returned by githits search").option("--json","Output as JSON").action(async(searchRef,options)=>{const deps=await loadContainer2();await searchStatusAction(searchRef,options,deps)})}async function registerUnifiedSearchCommands(program,options={}){const codeNavigationUrl=options.codeNavigationUrl??getCodeNavigationUrl();if(!codeNavigationUrl){return}registerSearchCommand(program)}function requireSearchService(deps){if(!deps.codeNavigationUrl||!deps.codeNavigationService){throw new InvalidArgumentError("Unified search is not configured for this environment.")}return deps.codeNavigationService}async function loadContainer2(){const{createContainer:createContainer2}=await import("./shared/chunk-fj6xaw9r.js");return createContainer2()}function parseTargetSpecs(specs){if(!specs||specs.length===0){throw new InvalidArgumentError("Provide at least one --in target.")}for(const spec of specs){warnIfUnprefixedTargetSpec(spec)}return specs.map(parseUnifiedSearchTargetSpec)}function warnIfUnprefixedTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0)return;if(trimmed.startsWith("http://")||trimmed.startsWith("https://"))return;if(trimmed.includes(":"))return;console.error(`Warning: --in '${trimmed}' has no registry prefix; treating as 'npm:${trimmed}'. Pass 'npm:${trimmed}' explicitly to suppress this warning.`)}function parseSources(value){if(!value)return;switch(value){case"docs":return["DOCS"];case"code":return["CODE"];case"symbol":return["SYMBOL"];default:throw new InvalidArgumentError(`Unsupported source '${value}'.`)}}function parseOptionalInt(value,flag,min,max=Number.MAX_SAFE_INTEGER){return parseIntCliOption(value,flag,min,max)}function parseWaitMs(value){if(value===undefined)return;const match=/^(?<seconds>-?\d+)s?$/i.exec(value.trim());if(!match?.groups?.seconds){throw new InvalidArgumentError("--wait must be an integer between 0 and 60 seconds.")}const seconds=parseIntCliOption(match.groups.seconds,"--wait",0,60);if(seconds===undefined)return;return seconds*1000}function collectRepeatable3(value,previous){return[...previous,value]}function handleSearchError(error2,json,context="search"){const payload=buildUnifiedSearchErrorPayload(error2);if(json){console.error(JSON.stringify(payload))}else{console.error(formatSearchErrorTerminal(payload,context))}process.exit(1)}function formatSearchErrorTerminal(payload,context){if(payload.code==="AUTH_REQUIRED"){return formatMappedErrorForTerminal({code:"AUTH_REQUIRED",message:payload.error,retryable:false,details:payload.details})}if(context==="status"&&payload.code==="NOT_FOUND"){return`${payload.error}
458
456
  Search sessions expire; run \`githits search ...\` to start a new one.`}return payload.error}function formatUnifiedSearchTerminal(payload){const lines=[];const useColors=shouldUseColors();const warnings=payload.warnings??payload.query.warnings;if(warnings&&warnings.length>0){for(const warning2 of warnings){lines.push(`Warning: ${warning2}`)}lines.push("")}if(!payload.completed){const statusText=formatSearchStatusTerminal({completed:false,searchRef:payload.searchRef??"",progress:payload.progress});if(payload.results.length===0){return statusText}lines.push(statusText);lines.push("");lines.push("Partial results:")}const sourceStatusNotes=formatSourceStatusNotes(payload.sourceStatus,warnings);if(payload.results.length===0){lines.push("No results.");if(sourceStatusNotes.length>0){lines.push("");lines.push(...sourceStatusNotes)}return lines.join(`
459
457
  `).trimEnd()}const{display,duplicatesFolded}=dedupeSearchResultsForDisplay(payload.results);const baseCount=`${display.length} result${display.length===1?"":"s"}`;const countSuffix=[payload.hasMore?" (more available)":"",duplicatesFolded>0?` (+${duplicatesFolded} near-duplicate folded)`:""].join("");const typeSummary=formatUnifiedSearchTypeSummary(display);lines.push(`${highlight(baseCount,useColors)}${dim(countSuffix,useColors)}${typeSummary?dim(` | ${typeSummary}`,useColors):""}`);lines.push("");for(const entry of display){const location=formatUnifiedSearchLocation(entry.locator);const header=formatUnifiedSearchHeader(entry,useColors,location,payload.query.raw);lines.push(header);const metadata=formatUnifiedSearchMetadata(entry,useColors);if(metadata.length>0){lines.push(...metadata)}if(entry.summary){lines.push(...formatUnifiedSearchSummary(entry.summary,entry.highlights?.summary,useColors))}lines.push("")}if(payload.nextOffset!==undefined){lines.push(dim(`Next offset: ${payload.nextOffset}`,useColors))}if(sourceStatusNotes.length>0){lines.push("");lines.push(...sourceStatusNotes)}return lines.join(`
460
458
  `).trimEnd()}function formatSearchStatusTerminal(payload){const status=payload.progress?.status;const lines=[formatSearchStatusHeadline(status),`searchRef: ${payload.searchRef}`];if(payload.progress){if(payload.progress.status){lines.push(`status: ${payload.progress.status.toLowerCase()}`)}if(typeof payload.progress.targetsReady==="number"&&typeof payload.progress.targetsTotal==="number"){lines.push(`targets ready: ${payload.progress.targetsReady}/${payload.progress.targetsTotal}`)}}if(status==="TIMEOUT"){lines.push("Search timed out before completion. Retry with a longer wait or start a new search.");return lines.join(`
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{version}from"./shared/chunk-33j95qx6.js";export{version};
1
+ import{version}from"./shared/chunk-y1k5vkfm.js";export{version};
@@ -0,0 +1 @@
1
+ import{clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer,loadAutoLoginAuthSessionMetadata,recordAuthFingerprint}from"./chunk-y3y83gbt.js";import"./chunk-y1k5vkfm.js";export{recordAuthFingerprint,loadAutoLoginAuthSessionMetadata,createContainer,createAuthStatusDependencies,createAuthCommandDependencies,clearAutoLoginAuthSessionMetadata};
@@ -1,2 +1,2 @@
1
- import{createRequire}from"node:module";var __require=createRequire(import.meta.url);var version="0.4.13";
1
+ import{createRequire}from"node:module";var __require=createRequire(import.meta.url);var version="0.4.15";
2
2
  export{__require,version};
@@ -1,4 +1,4 @@
1
- import{__require,version}from"./chunk-33j95qx6.js";import{createHash,randomBytes}from"node:crypto";function generateCodeVerifier(){return randomBytes(32).toString("base64url")}function generateCodeChallenge(verifier){return createHash("sha256").update(verifier).digest("base64url")}function generateState(){return randomBytes(32).toString("hex")}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}import{z}from"zod";function debugLog(area,payload){if(!isAreaEnabled(area))return;const line={ts:new Date().toISOString(),area,...payload};let text;try{text=JSON.stringify(line)}catch{text=JSON.stringify({ts:line.ts,area,error:"debug-log payload not serialisable"})}process.stderr.write(`${text}
1
+ import{__require,version}from"./chunk-y1k5vkfm.js";import{createHash,randomBytes}from"node:crypto";function generateCodeVerifier(){return randomBytes(32).toString("base64url")}function generateCodeChallenge(verifier){return createHash("sha256").update(verifier).digest("base64url")}function generateState(){return randomBytes(32).toString("hex")}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}import{z}from"zod";function debugLog(area,payload){if(!isAreaEnabled(area))return;const line={ts:new Date().toISOString(),area,...payload};let text;try{text=JSON.stringify(line)}catch{text=JSON.stringify({ts:line.ts,area,error:"debug-log payload not serialisable"})}process.stderr.write(`${text}
2
2
  `)}function isDebugAreaEnabled(area){return isAreaEnabled(area)}function isAreaEnabled(area){const raw=process.env.GITHITS_DEBUG;if(!raw||raw==="")return false;const scopes=raw.split(",").map((s)=>s.trim()).filter(Boolean);if(scopes.includes(area))return true;if(isExplicitOnlyArea(area))return false;return scopes.includes("*")}function isExplicitOnlyArea(area){return area==="code-nav-wire"}var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError extends Error{timeoutMs;constructor(timeoutMs,options){super(`Request timed out after ${timeoutMs}ms.`,options);this.name="FetchTimeoutError";this.timeoutMs=timeoutMs}}async function fetchWithTimeout(input,init={},options={}){const timeoutMs=options.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const timeoutSignal=AbortSignal.timeout(timeoutMs);const signal=init.signal?AbortSignal.any([init.signal,timeoutSignal]):timeoutSignal;const fetchFn=options.fetchFn??globalThis.fetch;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new FetchTimeoutError(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError}class PkgseerTransportError extends Error{constructor(message,options){super(message,options);this.name="PkgseerTransportError"}}function baseUrl(endpointUrl){return endpointUrl.replace(/\/+$/,"")}async function postPkgseerGraphql(request){const userAgent=request.userAgent??"githits-cli";const timeoutMs=request.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;let response;try{response=await fetchWithTimeout(`${baseUrl(request.endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.clientHeaders?.(),Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs})}catch(cause){debugLog("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true});throw new PkgseerTransportError("Network request failed before a response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");const parsedBody=parseJsonOrNull(responseBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}import{writeSync}from"node:fs";var ENABLED_VALUES=new Set(["1","true","yes","on"]);function isTelemetryEnabled(env=process.env){const raw=env.GITHITS_TELEMETRY?.trim().toLowerCase();if(!raw)return false;return ENABLED_VALUES.has(raw)}class TelemetryCollector{enabled;now;write;sessionStartMs;spans=[];activeSpans=new Map;nextId=1;flushed=false;constructor(options={}){this.enabled=isTelemetryEnabled(options.env);this.now=options.now??(()=>globalThis.performance.now());this.write=options.write??((text)=>writeSync(process.stderr.fd,text));this.sessionStartMs=this.now()}isEnabled(){return this.enabled}startSpan(name,attributes){if(!this.enabled)return;const span={id:this.nextId++,name,startMs:this.now(),attributes:sanitiseAttributes(attributes)};this.spans.push(span);this.activeSpans.set(span.id,span);return{id:span.id}}endSpan(handle,attributes){if(!this.enabled||!handle)return;const span=this.activeSpans.get(handle.id);if(!span||span.endMs!==undefined)return;span.endMs=this.now();span.attributes=mergeAttributes(span.attributes,attributes);this.activeSpans.delete(handle.id)}flush(exitCode=0){if(!this.enabled||this.flushed)return;const nowMs=this.now();for(const span of this.activeSpans.values()){if(span.endMs!==undefined)continue;span.endMs=nowMs;span.endedAtExit=true}this.activeSpans.clear();this.write(formatTelemetryReport(this.spans,this.sessionStartMs,nowMs,exitCode));this.flushed=true}}async function withTelemetrySpan(name,operation,attributes){const handle=telemetryCollector.startSpan(name,attributes);try{const result=await operation();telemetryCollector.endSpan(handle);return result}catch(error){telemetryCollector.endSpan(handle,{error:true});throw error}}function startTelemetrySpan(name,attributes){return telemetryCollector.startSpan(name,attributes)}function endTelemetrySpan(handle,attributes){telemetryCollector.endSpan(handle,attributes)}function flushTelemetry(exitCode=0){telemetryCollector.flush(exitCode)}var telemetryCollector=new TelemetryCollector;function sanitiseAttributes(attributes){if(!attributes)return;const entries=Object.entries(attributes).filter(([,value])=>value!==undefined);if(entries.length===0)return;return Object.fromEntries(entries)}function mergeAttributes(initial,extra){if(!initial&&!extra)return;return sanitiseAttributes({...initial??{},...extra??{}})}function formatTelemetryReport(spans,sessionStartMs,sessionEndMs,exitCode){const lines=["[githits telemetry]",`exit: ${exitCode}`,`total: ${formatMs(sessionEndMs-sessionStartMs)}`];const orderedSpans=[...spans].sort((left,right)=>{if(left.startMs!==right.startMs){return left.startMs-right.startMs}return left.id-right.id});for(const span of orderedSpans){const endMs=span.endMs??sessionEndMs;const details=[`start +${formatMs(span.startMs-sessionStartMs)}`];if(span.endedAtExit){details.push("ended-at-exit")}const attrs=formatAttributes(span.attributes);if(attrs){details.push(attrs)}lines.push(`- ${span.name}: ${formatMs(endMs-span.startMs)} (${details.join(", ")})`)}return`${lines.join(`
3
3
  `)}
4
4
  `}function formatAttributes(attributes){if(!attributes)return"";return Object.entries(attributes).map(([key,value])=>`${key}=${String(value)}`).join(" ")}function formatMs(value){return`${value.toFixed(1)}ms`}var AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}function parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail}catch{return body}return}class GitHitsServiceImpl{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params){return withTelemetrySpan("githits.search.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/search`,{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false})},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.text()})}async getLanguages(){return withTelemetrySpan("githits.languages.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/languages`,{headers:this.headers()},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.json()})}async searchLanguages(query,limit=5){return withTelemetrySpan("githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await fetchWithTimeout(`${this.apiUrl}/languages?${params.toString()}`,{headers:this.headers()},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.json()})}async submitFeedback(params){return withTelemetrySpan("githits.feedback.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/feedbacks`,{method:"POST",headers:this.headers(),body:JSON.stringify({...params.exampleId!==undefined&&{example_id:params.exampleId},...params.solutionId!==undefined&&{solution_id:params.solutionId},accepted:params.accepted,feedback_text:params.feedbackText??null,...params.toolName!==undefined&&{tool_name:params.toolName}})},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return{success:true,message:"Feedback submitted successfully"}})}headers(){return{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"}}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");switch(status){case 401:return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(parseDetail(body)||"Resource not found.");default:{if(status>=500){const detail=body?`: ${body}`:"";return new Error(`Server error (${status})${detail}`)}return new Error(body||`Request failed with status ${status}`)}}}}async function executeWithTokenRefresh(options){const token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;constructor(message,availableVersions){super(message);this.availableVersions=availableVersions;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
@@ -966,7 +966,7 @@ query ReadPackageDoc($pageId: String!) {
966
966
  baseUrl
967
967
  }
968
968
  }
969
- }`;class PackageIntelligenceServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withTelemetrySpan("pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){const status=response.status;const detail=parseDetail3(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";debugLog("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new PackageIntelligenceBackendError(isDebugAreaEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:break}return new PackageIntelligenceBackendError(message,undefined,code,retryable)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withTelemetrySpan("pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;return this.normaliseVulnerabilityReport(data)}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version:version2,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async packageDependencies(params){return withTelemetrySpan("pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withTelemetrySpan("pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeTransitive,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version:version2,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version2)=>({version:version2.version,severity:version2.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withTelemetrySpan("pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&&params.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined,metadata:entry.metadata??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withTelemetrySpan("pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withTelemetrySpan("pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,page:data.page?{id:data.page.id??undefined,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function parseDetail3(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}class RefreshingGitHitsService{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params){return this.withTokenRefresh((service)=>service.search(params))}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:async(token)=>{const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return value in registryMap}import{createHash as createHash2,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash2("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}var APP_DIR="githits";function getAppConfigDir(fs){return getAppConfigDirForEnv(fs,process.env,process.platform,fs.getHomeDir())}function getAppConfigDirForEnv(fs,env,platform,home=getHomeDirForEnv(fs,env,platform)){if(platform==="win32"){return fs.joinPath(env.APPDATA??fs.joinPath(home,"AppData","Roaming"),APP_DIR)}return fs.joinPath(env.XDG_CONFIG_HOME??fs.joinPath(home,".config"),APP_DIR)}function getAuthConfigPath(fs){return fs.joinPath(getAppConfigDir(fs),"config.toml")}function getAuthConfigPathForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"config.toml")}function getAuthFileStorageDir(fs){return fs.joinPath(getAppConfigDir(fs),"auth")}function getAuthFileStorageDirForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"auth")}function getHomeDirForEnv(fs,env,platform){if(platform==="win32"&&env.USERPROFILE)return env.USERPROFILE;if(platform!=="win32"&&env.HOME)return env.HOME;return fs.getHomeDir()}function getLegacyAuthStorageDir(fs){return fs.joinPath(fs.getHomeDir(),".githits")}function getLegacyAuthStorageDirForEnv(fs,env,platform){return fs.joinPath(getHomeDirForEnv(fs,env,platform),".githits")}function getLegacyMacAppConfigDir(fs){return fs.joinPath(fs.getHomeDir(),"Library","Application Support",APP_DIR)}function getLegacyMacAppConfigDirForEnv(fs,env){return fs.joinPath(getHomeDirForEnv(fs,env,"darwin"),"Library","Application Support",APP_DIR)}function getLegacyMacAuthConfigPath(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"config.toml")}function getLegacyMacAuthConfigPathForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"config.toml")}function getLegacyMacAuthFileStorageDir(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"auth")}function getLegacyMacAuthFileStorageDirForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"auth")}import{parse as parseToml}from"smol-toml";import{z as z3}from"zod";var AUTH_STORAGE_MODES=["keychain","file"];var AUTH_STORAGE_MODE_VALUES=new Set(AUTH_STORAGE_MODES);var CONFIG_SCHEMA=z3.object({auth:z3.object({storage:z3.string().optional()}).optional()}).passthrough();class AuthConfigError extends Error{constructor(message){super(message);this.name="AuthConfigError"}}function parseAuthStorageMode(value){const normalized=value.trim().toLowerCase();if(AUTH_STORAGE_MODE_VALUES.has(normalized)){return normalized}throw new AuthConfigError(`Invalid auth storage mode "${value}". Use "keychain" or "file". File mode stores OAuth credentials unencrypted on disk.`)}async function loadAuthConfig(fs){let configPath=getAuthConfigPath(fs);const envMode=process.env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{storage:parseAuthStorageMode(envMode),configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GITHITS_AUTH_STORAGE: ${error.message}`)}throw error}}if(!await fs.exists(configPath)){const legacyMacConfigPath=getLegacyMacAuthConfigPath(fs);if(process.platform==="darwin"&&await fs.exists(legacyMacConfigPath)){configPath=legacyMacConfigPath}else{return{storage:"keychain",configPath}}}let rawConfig;try{rawConfig=parseToml(await fs.readFile(configPath))}catch(error){const message=error instanceof Error?error.message:String(error);throw new AuthConfigError(`Cannot parse GitHits config at ${configPath}: ${message}`)}const parsed=CONFIG_SCHEMA.safeParse(rawConfig);if(!parsed.success){throw new AuthConfigError(`Invalid GitHits config at ${configPath}: ${z3.prettifyError(parsed.error)}`)}const configuredMode=parsed.data.auth?.storage;if(configuredMode===undefined||configuredMode.trim()===""){return{storage:"keychain",configPath}}try{return{storage:parseAuthStorageMode(configuredMode),configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GitHits config at ${configPath}: ${error.message}`)}throw error}}import{createServer}from"node:http";class AuthServiceImpl{fetchFn;fetchTimeoutMs;constructor(fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs}async discoverEndpoints(mcpBaseUrl){const url=`${mcpBaseUrl}/.well-known/oauth-authorization-server`;const response=await fetchWithTimeout(url,{},this.fetchOptions());if(!response.ok){throw new Error(`Failed to discover OAuth endpoints: ${response.status} ${response.statusText}`)}const data=await response.json();const authorizationEndpoint=data.authorization_endpoint;const tokenEndpoint=data.token_endpoint;const registrationEndpoint=data.registration_endpoint;if(!authorizationEndpoint||!tokenEndpoint||!registrationEndpoint){throw new Error("OAuth metadata missing required endpoints")}return{authorizationEndpoint,tokenEndpoint,registrationEndpoint}}async registerClient(params){const response=await fetchWithTimeout(params.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"GitHits CLI",redirect_uris:[params.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"})},this.fetchOptions());if(!response.ok){const error=await response.text();throw new Error(`Client registration failed: ${error}`)}const data=await response.json();if(!data.client_id||!data.client_secret){throw new Error("Client registration response missing required fields")}return{clientId:data.client_id,clientSecret:data.client_secret}}generatePkceParams(){const verifier=generateCodeVerifier();return{verifier,challenge:generateCodeChallenge(verifier),state:generateState()}}buildAuthUrl(params){const url=new URL(params.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",params.clientId);url.searchParams.set("redirect_uri",params.redirectUri);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method","S256");return url.toString()}startCallbackServer(port,expectedState){let closeTimer;const server=createServer();let callbackHandled=false;let resolved=false;const result=new Promise((resolve)=>{server.on("request",(req,res)=>{const address=server.address();const actualPort=typeof address==="object"&&address!==null?address.port:port;const url=new URL(req.url??"",`http://127.0.0.1:${actualPort}`);if(url.pathname==="/favicon.ico"){res.writeHead(204);res.end();return}if(url.pathname!=="/callback"){if(callbackHandled){sendHtmlResponse(res,200,successHtml("You're already signed in."));return}sendHtmlResponse(res,404,errorHtml("Invalid callback path.","Run `githits login` to start authentication."));return}const code=url.searchParams.get("code");const state=url.searchParams.get("state");const error=url.searchParams.get("error");const errorDescription=url.searchParams.get("error_description");const evaluation=evaluateCallback({code,state,error,errorDescription,expectedState});callbackHandled=true;sendHtmlResponse(res,evaluation.statusCode,evaluation.html);if(!resolved){resolved=true;resolve(evaluation.result)}if(closeTimer)clearTimeout(closeTimer);closeTimer=setTimeout(()=>closeServer(server),1500)})});return new Promise((resolve,reject)=>{const onError=(err)=>{reject(new Error(`Failed to start callback server: ${err.message}`))};server.once("error",onError);server.listen(port,"127.0.0.1",()=>{server.off("error",onError);server.on("error",()=>{});resolve({result,close:async()=>{if(closeTimer)clearTimeout(closeTimer);await closeServer(server)}})})})}async exchangeCodeForTokens(params){const body=new URLSearchParams({grant_type:"authorization_code",client_id:params.clientId,client_secret:params.clientSecret,code:params.code,code_verifier:params.codeVerifier,redirect_uri:params.redirectUri});const response=await fetchWithTimeout(params.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new Error(`Token exchange failed: ${error}`)}return parseTokenResponse(await response.json())}async refreshAccessToken(params){const body=new URLSearchParams({grant_type:"refresh_token",client_id:params.clientId,client_secret:params.clientSecret,refresh_token:params.refreshToken});const response=await fetchWithTimeout(params.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new Error(`Token refresh failed: ${error}`)}return parseRefreshTokenResponse(await response.json())}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}}function parseTokenResponse(data){const d=data;if(!d.access_token||!d.refresh_token){throw new Error("Token response missing required fields")}return{accessToken:d.access_token,refreshToken:d.refresh_token,expiresIn:d.expires_in||3600}}function parseRefreshTokenResponse(data){const d=data;if(!d.access_token){throw new Error("Token response missing required fields")}return{accessToken:d.access_token,refreshToken:typeof d.refresh_token==="string"?d.refresh_token:undefined,expiresIn:d.expires_in||3600}}function successHtml(title="You're signed in"){return`<!DOCTYPE html>
969
+ }`;class PackageIntelligenceServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withTelemetrySpan("pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){const status=response.status;const detail=parseDetail3(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";debugLog("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new PackageIntelligenceBackendError(isDebugAreaEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:break}return new PackageIntelligenceBackendError(message,undefined,code,retryable)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withTelemetrySpan("pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;return this.normaliseVulnerabilityReport(data)}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version:version2,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async packageDependencies(params){return withTelemetrySpan("pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withTelemetrySpan("pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeTransitive,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version:version2,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version2)=>({version:version2.version,severity:version2.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withTelemetrySpan("pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&&params.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined,metadata:entry.metadata??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withTelemetrySpan("pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withTelemetrySpan("pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,page:data.page?{id:data.page.id??undefined,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function parseDetail3(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}class RefreshingGitHitsService{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params){return this.withTokenRefresh((service)=>service.search(params))}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:async(token)=>{const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return value in registryMap}import{createHash as createHash2,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash2("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}var APP_DIR="githits";var USER_AUTH_STATE_DIR=".githits";function getAppConfigDir(fs){return getAppConfigDirForEnv(fs,process.env,process.platform,fs.getHomeDir())}function getAppConfigDirForEnv(fs,env,platform,home=getHomeDirForEnv(fs,env,platform)){if(platform==="win32"){return fs.joinPath(env.APPDATA??fs.joinPath(home,"AppData","Roaming"),APP_DIR)}return fs.joinPath(env.XDG_CONFIG_HOME??fs.joinPath(home,".config"),APP_DIR)}function getAuthConfigPath(fs){return fs.joinPath(getAppConfigDir(fs),"config.toml")}function getAuthConfigPathForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"config.toml")}function getAuthFileStorageDir(fs){return fs.joinPath(getAppConfigDir(fs),"auth")}function getAuthFileStorageDirForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"auth")}function getHomeDirForEnv(fs,env,platform){if(platform==="win32"&&env.USERPROFILE)return env.USERPROFILE;if(platform!=="win32"&&env.HOME)return env.HOME;return fs.getHomeDir()}function getLegacyAuthStorageDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyAuthStorageDirForEnv(fs,env,platform){return fs.joinPath(getHomeDirForEnv(fs,env,platform),USER_AUTH_STATE_DIR)}function getAuthLockDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyMacAppConfigDir(fs){return fs.joinPath(fs.getHomeDir(),"Library","Application Support",APP_DIR)}function getLegacyMacAppConfigDirForEnv(fs,env){return fs.joinPath(getHomeDirForEnv(fs,env,"darwin"),"Library","Application Support",APP_DIR)}function getLegacyMacAuthConfigPath(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"config.toml")}function getLegacyMacAuthConfigPathForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"config.toml")}function getLegacyMacAuthFileStorageDir(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"auth")}function getLegacyMacAuthFileStorageDirForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"auth")}import{parse as parseToml}from"smol-toml";import{z as z3}from"zod";var AUTH_STORAGE_MODES=["keychain","file"];var AUTH_STORAGE_MODE_VALUES=new Set(AUTH_STORAGE_MODES);var CONFIG_SCHEMA=z3.object({auth:z3.object({storage:z3.string().optional()}).optional()}).passthrough();class AuthConfigError extends Error{constructor(message){super(message);this.name="AuthConfigError"}}function parseAuthStorageMode(value){const normalized=value.trim().toLowerCase();if(AUTH_STORAGE_MODE_VALUES.has(normalized)){return normalized}throw new AuthConfigError(`Invalid auth storage mode "${value}". Use "keychain" or "file". File mode stores OAuth credentials unencrypted on disk.`)}async function loadAuthConfig(fs){let configPath=getAuthConfigPath(fs);const envMode=process.env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{storage:parseAuthStorageMode(envMode),configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GITHITS_AUTH_STORAGE: ${error.message}`)}throw error}}if(!await fs.exists(configPath)){const legacyMacConfigPath=getLegacyMacAuthConfigPath(fs);if(process.platform==="darwin"&&await fs.exists(legacyMacConfigPath)){configPath=legacyMacConfigPath}else{return{storage:"keychain",configPath}}}let rawConfig;try{rawConfig=parseToml(await fs.readFile(configPath))}catch(error){const message=error instanceof Error?error.message:String(error);throw new AuthConfigError(`Cannot parse GitHits config at ${configPath}: ${message}`)}const parsed=CONFIG_SCHEMA.safeParse(rawConfig);if(!parsed.success){throw new AuthConfigError(`Invalid GitHits config at ${configPath}: ${z3.prettifyError(parsed.error)}`)}const configuredMode=parsed.data.auth?.storage;if(configuredMode===undefined||configuredMode.trim()===""){return{storage:"keychain",configPath}}try{return{storage:parseAuthStorageMode(configuredMode),configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GitHits config at ${configPath}: ${error.message}`)}throw error}}var AUTH_FILE="auth.json";var CLIENT_FILE="client.json";var DIR_MODE=448;class AuthStorageImpl{fs;configDir;authPath;clientPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.authPath=fs.joinPath(this.configDir,AUTH_FILE);this.clientPath=fs.joinPath(this.configDir,CLIENT_FILE)}getStorageLocation(){return this.configDir}async loadTokens(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl2)]??null}async saveTokens(baseUrl2,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl2)];if(Object.keys(stored.tokens).length===0){await this.fs.deleteFile(this.authPath)}else{await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2))}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.clearTokensIfUnchanged(baseUrl2,expected)}async loadClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl2)]??null}async clearClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl2)];if(Object.keys(stored.clients).length===0){await this.fs.deleteFile(this.clientPath)}else{await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2))}}async saveClient(baseUrl2,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2))}clearActiveClient(baseUrl2){return this.clearClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}async loadAuthFile(){if(!await this.fs.exists(this.authPath))return null;try{const content=await this.fs.readFile(this.authPath);const data=JSON.parse(content);if(data.version!==1||!data.tokens)return null;return data}catch{return null}}async loadClientFile(){if(!await this.fs.exists(this.clientPath))return null;try{const content=await this.fs.readFile(this.clientPath);const data=JSON.parse(content);if(data.version!==1||!data.clients)return null;return data}catch{return null}}}function normalizeBaseUrl(url){return url.replace(/\/+$/,"")}function sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}async function clearAuthSessionBestEffort(clearTokens,clearClient){let firstError;try{await clearTokens()}catch(error){firstError=error}try{await clearClient()}catch(error){firstError??=error}if(firstError)throw firstError}var DIAGNOSTICS_FILE="diagnostics.json";var DIR_MODE2=448;var CLEAR_REASONS=new Set(["logout","terminal_invalid_refresh_token","terminal_invalid_client"]);class AuthDiagnosticsStorage{fs;configDir;diagnosticsPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.diagnosticsPath=fs.joinPath(this.configDir,DIAGNOSTICS_FILE)}async recordClear(baseUrl2,reason){try{const stored=await this.loadFile()??{version:1,events:{}};stored.events[normalizeBaseUrl(baseUrl2)]={reason,at:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE2);await this.fs.atomicWriteFile(this.diagnosticsPath,JSON.stringify(stored,null,2))}catch{}}async load(baseUrl2){const stored=await this.loadFile();if(!stored)return null;const event=stored.events[normalizeBaseUrl(baseUrl2)]??null;return isAuthClearEvent(event)?event:null}async loadFile(){if(!await this.fs.exists(this.diagnosticsPath))return null;try{const content=await this.fs.readFile(this.diagnosticsPath);const data=JSON.parse(content);if(!isRecord(data)||data.version!==1||!isRecord(data.events)){return null}return data}catch{return null}}}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isAuthClearReason(value){return typeof value==="string"&&CLEAR_REASONS.has(value)}function isAuthClearEvent(value){if(value===null||typeof value!=="object")return false;return isAuthClearReason(value.reason)&&typeof value.at==="string"&&value.at.length>0}import{createServer}from"node:http";class TokenRefreshError extends Error{status;body;oauthError;oauthErrorDescription;constructor(status,body){const details=parseOAuthErrorBody(body);const description=details.oauthErrorDescription??details.oauthError??body.trim();super(description?`Token refresh failed: ${description}`:`Token refresh failed with HTTP ${status}`);this.name="TokenRefreshError";this.status=status;this.body=body;this.oauthError=details.oauthError;this.oauthErrorDescription=details.oauthErrorDescription}}class AuthServiceImpl{fetchFn;fetchTimeoutMs;constructor(fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs}async discoverEndpoints(mcpBaseUrl){const url=`${mcpBaseUrl}/.well-known/oauth-authorization-server`;const response=await fetchWithTimeout(url,{},this.fetchOptions());if(!response.ok){throw new Error(`Failed to discover OAuth endpoints: ${response.status} ${response.statusText}`)}const data=await response.json();const authorizationEndpoint=data.authorization_endpoint;const tokenEndpoint=data.token_endpoint;const registrationEndpoint=data.registration_endpoint;if(!authorizationEndpoint||!tokenEndpoint||!registrationEndpoint){throw new Error("OAuth metadata missing required endpoints")}return{authorizationEndpoint,tokenEndpoint,registrationEndpoint}}async registerClient(params){const response=await fetchWithTimeout(params.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"GitHits CLI",redirect_uris:[params.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"})},this.fetchOptions());if(!response.ok){const error=await response.text();throw new Error(`Client registration failed: ${error}`)}const data=await response.json();if(!data.client_id||!data.client_secret){throw new Error("Client registration response missing required fields")}return{clientId:data.client_id,clientSecret:data.client_secret}}generatePkceParams(){const verifier=generateCodeVerifier();return{verifier,challenge:generateCodeChallenge(verifier),state:generateState()}}buildAuthUrl(params){const url=new URL(params.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",params.clientId);url.searchParams.set("redirect_uri",params.redirectUri);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method","S256");return url.toString()}startCallbackServer(port,expectedState){let closeTimer;const server=createServer();let callbackHandled=false;let resolved=false;const result=new Promise((resolve)=>{server.on("request",(req,res)=>{const address=server.address();const actualPort=typeof address==="object"&&address!==null?address.port:port;const url=new URL(req.url??"",`http://127.0.0.1:${actualPort}`);if(url.pathname==="/favicon.ico"){res.writeHead(204);res.end();return}if(url.pathname!=="/callback"){if(callbackHandled){sendHtmlResponse(res,200,successHtml("You're already signed in."));return}sendHtmlResponse(res,404,errorHtml("Invalid callback path.","Run `githits login` to start authentication."));return}const code=url.searchParams.get("code");const state=url.searchParams.get("state");const error=url.searchParams.get("error");const errorDescription=url.searchParams.get("error_description");const evaluation=evaluateCallback({code,state,error,errorDescription,expectedState});callbackHandled=true;sendHtmlResponse(res,evaluation.statusCode,evaluation.html);if(!resolved){resolved=true;resolve(evaluation.result)}if(closeTimer)clearTimeout(closeTimer);closeTimer=setTimeout(()=>closeServer(server),1500)})});return new Promise((resolve,reject)=>{const onError=(err)=>{reject(new Error(`Failed to start callback server: ${err.message}`))};server.once("error",onError);server.listen(port,"127.0.0.1",()=>{server.off("error",onError);server.on("error",()=>{});resolve({result,close:async()=>{if(closeTimer)clearTimeout(closeTimer);await closeServer(server)}})})})}async exchangeCodeForTokens(params){const body=new URLSearchParams({grant_type:"authorization_code",client_id:params.clientId,client_secret:params.clientSecret,code:params.code,code_verifier:params.codeVerifier,redirect_uri:params.redirectUri});const response=await fetchWithTimeout(params.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new Error(`Token exchange failed: ${error}`)}return parseTokenResponse(await response.json())}async refreshAccessToken(params){const body=new URLSearchParams({grant_type:"refresh_token",client_id:params.clientId,client_secret:params.clientSecret,refresh_token:params.refreshToken});const response=await fetchWithTimeout(params.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new TokenRefreshError(response.status,error)}return parseRefreshTokenResponse(await response.json())}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}}function classifyTerminalRefreshError(error){if(!(error instanceof TokenRefreshError))return;const oauthError=error.oauthError?.toLowerCase();const text=[error.oauthError,error.oauthErrorDescription,error.body,error.message].filter((part)=>typeof part==="string").join(" ").toLowerCase();if(oauthError==="invalid_client"||text.includes("client not found")||text.includes("client id not found")||text.includes("client_id not found")||text.includes("oauth client not found")||text.includes("client does not match")||text.includes("client authentication required")||text.includes("invalid client credentials")){return"invalid_client"}if(oauthError==="invalid_grant"&&(text.includes("invalid refresh token")||text.includes("refresh token already used")||text.includes("already used")||text.includes("session expired")||text.includes("session not found"))){return"invalid_refresh_token"}return}function parseOAuthErrorBody(body){try{const parsed=JSON.parse(body);return{oauthError:stringField(parsed.error),oauthErrorDescription:stringField(parsed.error_description)??stringField(parsed.errorDescription)??stringField(parsed.message)??stringField(parsed.msg)}}catch{return{oauthError:undefined,oauthErrorDescription:undefined}}}function stringField(value){return typeof value==="string"&&value.trim()?value:undefined}function parseTokenResponse(data){const d=data;if(!d.access_token||!d.refresh_token){throw new Error("Token response missing required fields")}return{accessToken:d.access_token,refreshToken:d.refresh_token,expiresIn:d.expires_in||3600}}function parseRefreshTokenResponse(data){const d=data;if(!d.access_token){throw new Error("Token response missing required fields")}return{accessToken:d.access_token,refreshToken:typeof d.refresh_token==="string"?d.refresh_token:undefined,expiresIn:d.expires_in||3600}}function successHtml(title="You're signed in"){return`<!DOCTYPE html>
970
970
  <html><head>
971
971
  <title>GitHits CLI</title>
972
972
  <meta charset="utf-8">
@@ -1288,7 +1288,7 @@ query ReadPackageDoc($pageId: String!) {
1288
1288
  });
1289
1289
  }
1290
1290
  })();
1291
- </script>`;var RETRY_CTA=ctaBlock("To try again, run these commands in your terminal:",["npx githits@latest logout","npx githits@latest login"]);var HELP_CTA=ctaBlock("Explore available commands with:",["npx githits@latest --help"]);function escapeHtml(text){return text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var AUTH_FILE="auth.json";var CLIENT_FILE="client.json";var DIR_MODE=448;class AuthStorageImpl{fs;configDir;authPath;clientPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.authPath=fs.joinPath(this.configDir,AUTH_FILE);this.clientPath=fs.joinPath(this.configDir,CLIENT_FILE)}getStorageLocation(){return this.configDir}async loadTokens(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl2)]??null}async saveTokens(baseUrl2,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl2)];if(Object.keys(stored.tokens).length===0){await this.fs.deleteFile(this.authPath)}else{await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2))}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async loadClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl2)]??null}async clearClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl2)];if(Object.keys(stored.clients).length===0){await this.fs.deleteFile(this.clientPath)}else{await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2))}}async saveClient(baseUrl2,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2))}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}async loadAuthFile(){if(!await this.fs.exists(this.authPath))return null;try{const content=await this.fs.readFile(this.authPath);const data=JSON.parse(content);if(data.version!==1||!data.tokens)return null;return data}catch{return null}}async loadClientFile(){if(!await this.fs.exists(this.clientPath))return null;try{const content=await this.fs.readFile(this.clientPath);const data=JSON.parse(content);if(data.version!==1||!data.clients)return null;return data}catch{return null}}}function normalizeBaseUrl(url){return url.replace(/\/+$/,"")}function sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}async function clearAuthSessionBestEffort(clearTokens,clearClient){let firstError;try{await clearTokens()}catch(error){firstError=error}try{await clearClient()}catch(error){firstError??=error}if(firstError)throw firstError}var METADATA_FILE="metadata.json";var DIR_MODE2=448;class AuthSessionMetadataStorage{fs;configDir;metadataPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.metadataPath=fs.joinPath(this.configDir,METADATA_FILE)}async load(baseUrl2){const stored=await this.loadFile();if(!stored)return null;const metadata=stored.sessions[normalizeBaseUrl(baseUrl2)]??null;return isAuthSessionMetadata(metadata)?metadata:null}async saveFromTokens(baseUrl2,tokens){const stored=await this.loadFile()??{version:1,sessions:{}};stored.sessions[normalizeBaseUrl(baseUrl2)]={createdAt:tokens.createdAt,expiresAt:tokens.expiresAt,updatedAt:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE2);await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2))}async clear(baseUrl2){const stored=await this.loadFile();if(!stored)return;delete stored.sessions[normalizeBaseUrl(baseUrl2)];if(Object.keys(stored.sessions).length===0){await this.fs.deleteFile(this.metadataPath);return}await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2))}async loadFile(){if(!await this.fs.exists(this.metadataPath))return null;try{const content=await this.fs.readFile(this.metadataPath);const data=JSON.parse(content);if(data.version!==1||!data.sessions)return null;return data}catch{return null}}}function isAuthSessionMetadata(value){if(value===null||typeof value!=="object")return false;return typeof value.createdAt==="string"&&value.createdAt.length>0&&typeof value.updatedAt==="string"&&value.updatedAt.length>0&&(value.expiresAt===null||typeof value.expiresAt==="string"&&value.expiresAt.length>0)}import open from"open";class BrowserServiceImpl{async open(url){await open(url)}}var WINDOWS_MAX_ENTRY_SIZE=1200;var CHUNKED_PREFIX="CHUNKED:";var MAX_CHUNK_COUNT=100;function chunkKey(account,writeId,index){return`${account}:chunk:${writeId}:${index}`}function parseChunkedSentinel(value){if(!value.startsWith(CHUNKED_PREFIX))return null;const rest=value.slice(CHUNKED_PREFIX.length);const colonIndex=rest.indexOf(":");if(colonIndex===-1)return null;const writeId=rest.slice(0,colonIndex);if(writeId.length===0)return null;const countStr=rest.slice(colonIndex+1);const count=Number(countStr);if(!Number.isInteger(count)||count<=0)return null;return{writeId,count}}function splitIntoChunks(value,maxSize){if(value.length===0)return[""];const chunks=[];for(let offset=0;offset<value.length;offset+=maxSize){chunks.push(value.slice(offset,offset+maxSize))}return chunks}function generateWriteId(){let id;do{id=Math.random().toString(36).slice(2,8)}while(id.length<6);return id}class ChunkingKeyringService{inner;maxEntrySize;constructor(inner,maxEntrySize=WINDOWS_MAX_ENTRY_SIZE){this.inner=inner;this.maxEntrySize=maxEntrySize}getPassword(service,account){const value=this.inner.getPassword(service,account);if(value===null)return null;if(!value.startsWith(CHUNKED_PREFIX))return value;const sentinel=parseChunkedSentinel(value);if(sentinel===null)return null;const chunks=[];for(let i=0;i<sentinel.count;i++){const chunk=this.inner.getPassword(service,chunkKey(account,sentinel.writeId,i));if(chunk===null){console.error(`Warning: Incomplete chunked keychain entry for "${account}" (missing chunk ${i} of ${sentinel.count}). Treating as missing.`);return null}chunks.push(chunk)}return chunks.join("")}setPassword(service,account,password){const oldValue=this.readOldSentinel(service,account);if(password.length<=this.maxEntrySize){this.inner.setPassword(service,account,password)}else{const chunks=splitIntoChunks(password,this.maxEntrySize);if(chunks.length>MAX_CHUNK_COUNT){throw new Error(`Value requires ${chunks.length} chunks, exceeding maximum of ${MAX_CHUNK_COUNT}. `+`This likely indicates a bug — credential data should not be this large.`)}const writeId=generateWriteId();for(const[i,chunk]of chunks.entries()){this.inner.setPassword(service,chunkKey(account,writeId,i),chunk)}this.inner.setPassword(service,account,`${CHUNKED_PREFIX}${writeId}:${chunks.length}`)}if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}}deletePassword(service,account){const oldValue=this.readOldSentinel(service,account);if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}return this.inner.deletePassword(service,account)}readOldSentinel(service,account){try{const value=this.inner.getPassword(service,account);if(value===null)return null;return parseChunkedSentinel(value)}catch{return null}}deleteChunkEntries(service,account,sentinel){for(let i=0;i<sentinel.count;i++){try{this.inner.deletePassword(service,chunkKey(account,sentinel.writeId,i))}catch{}}}}import{randomUUID as randomUUID2}from"node:crypto";import{mkdir,readdir,readFile,rename,stat,unlink,writeFile}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join}from"node:path";class FileSystemServiceImpl{async readFile(path){return readFile(path,"utf-8")}async writeFile(path,contents,mode){await writeFile(path,contents,{mode})}async deleteFile(path){try{await unlink(path)}catch(error){if(error.code!=="ENOENT"){throw error}}}async exists(path){try{await stat(path);return true}catch{return false}}async ensureDir(path,mode){await mkdir(path,{recursive:true,mode})}getHomeDir(){return homedir()}joinPath(...segments){return join(...segments)}getCwd(){return process.cwd()}getDirname(path){return dirname(path)}async readdir(path){return readdir(path)}async isDirectory(path){try{const stats=await stat(path);return stats.isDirectory()}catch{return false}}async atomicWriteFile(path,contents){const tmpPath=`${path}.${process.pid}.${randomUUID2()}.tmp`;let mode=384;try{const existing=await stat(path);mode=existing.mode&511}catch{}try{await writeFile(tmpPath,contents,{mode});await rename(tmpPath,path)}catch(error){try{await unlink(tmpPath)}catch{}throw error}}}var SERVICE_NAME="githits";var TOKEN_PREFIX="v1:tokens:";var CLIENT_PREFIX="v1:client:";function parseJsonOrNull2(json){if(json===null)return null;try{const parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function isValidTokenData(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.accessToken==="string"&&d.accessToken.length>0&&typeof d.refreshToken==="string"&&d.refreshToken.length>0&&typeof d.createdAt==="string"&&d.createdAt.length>0&&(d.expiresAt===null||typeof d.expiresAt==="string"&&d.expiresAt.length>0)}function isValidClientRegistration(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.clientId==="string"&&d.clientId.length>0&&typeof d.clientSecret==="string"&&d.clientSecret.length>0&&typeof d.redirectUri==="string"&&d.redirectUri.length>0&&typeof d.registeredAt==="string"&&d.registeredAt.length>0}class KeychainAuthStorage{keyring;constructor(keyring){this.keyring=keyring}async loadTokens(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidTokenData(data))return null;return data}async saveTokens(baseUrl2,data){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async loadClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidClientRegistration(data))return null;return data}async saveClient(baseUrl2,data){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async clearClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}getStorageLocation(){switch(process.platform){case"darwin":return"macOS Keychain (githits)";case"win32":return"Windows Credential Manager (githits)";default:return"System keychain (githits)"}}}import{Entry}from"@napi-rs/keyring";class KeychainUnavailableError extends Error{constructor(message,cause){super(message);this.name="KeychainUnavailableError";this.cause=cause}}function wrapKeyringError(error){const message=error instanceof Error?error.message:String(error);throw new KeychainUnavailableError(`System keychain unavailable: ${message}`,error)}class KeyringServiceImpl{getPassword(service,account){try{return new Entry(service,account).getPassword()}catch(error){wrapKeyringError(error)}}setPassword(service,account,password){try{new Entry(service,account).setPassword(password)}catch(error){wrapKeyringError(error)}}deletePassword(service,account){try{return new Entry(service,account).deleteCredential()}catch(error){wrapKeyringError(error)}}}import{AsyncLocalStorage}from"node:async_hooks";import{execFile}from"node:child_process";import{randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir2,readFile as readFile2,rm,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname2}from"node:path";import{promisify}from"node:util";var LOCK_DIR="auth.lock";var LOCK_TIMEOUT_MS=DEFAULT_FETCH_TIMEOUT_MS*2+1e4;var LOCK_RETRY_MS=25;var ORPHANED_LOCK_MS=5000;var OWNER_FILE="owner.json";var execFileAsync=promisify(execFile);class AuthStorageLockTimeoutError extends Error{constructor(message){super(message);this.name="AuthStorageLockTimeoutError"}}function withAuthStorageLock(storage,fn){return storage.withAuthStorageLock(fn)}class LockedAuthStorage{storage;lockPath;lockTimeoutMs;isOwnerAlive;lockContext=new AsyncLocalStorage;currentOwner=null;constructor(storage,fileSystemService,options={}){this.storage=storage;this.lockTimeoutMs=options.lockTimeoutMs??LOCK_TIMEOUT_MS;this.isOwnerAlive=options.isOwnerAlive??isOriginalProcessAlive;this.lockPath=fileSystemService.joinPath(getAppConfigDir(fileSystemService),LOCK_DIR)}loadTokens(baseUrl2){return this.storage.loadTokens(baseUrl2)}saveTokens(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveTokens(baseUrl2,data))}saveTokensIfUnchanged(baseUrl2,expected,data){return this.withAuthStorageLock(()=>this.storage.saveTokensIfUnchanged(baseUrl2,expected,data))}clearTokens(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearTokens(baseUrl2))}clearTokensIfUnchanged(baseUrl2,expected){return this.withAuthStorageLock(()=>this.storage.clearTokensIfUnchanged(baseUrl2,expected))}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}saveClient(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveClient(baseUrl2,data))}clearClient(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearClient(baseUrl2))}saveAuthSession(baseUrl2,client,tokens){return this.withAuthStorageLock(()=>this.storage.saveAuthSession(baseUrl2,client,tokens))}clearAuthSession(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearAuthSession(baseUrl2))}getStorageLocation(){return this.storage.getStorageLocation()}async withAuthStorageLock(fn){const ownerId=this.lockContext.getStore();if(ownerId&&this.currentOwner?.id===ownerId){return fn()}await this.acquireLock();const acquiredOwnerId=this.currentOwner?.id;try{return await this.lockContext.run(acquiredOwnerId??"",fn)}finally{await this.releaseLock()}}async acquireLock(){const processStartedAt=await getProcessStartedAt(process.pid);const startedAt=Date.now();await mkdir2(dirname2(this.lockPath),{recursive:true,mode:448});while(true){try{await mkdir2(this.lockPath,{recursive:false,mode:448});try{await this.writeOwner(processStartedAt)}catch(error){this.currentOwner=null;if(error.code==="EEXIST"){await sleep(LOCK_RETRY_MS);continue}await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return});throw error}return}catch(error){if(error.code!=="EEXIST")throw error;await this.reclaimStaleLock();if(Date.now()-startedAt>=this.lockTimeoutMs){throw new AuthStorageLockTimeoutError(`Timed out waiting for GitHits auth storage lock at ${this.lockPath}. If no githits process is running, remove this directory and retry.`)}await sleep(LOCK_RETRY_MS)}}}async writeOwner(processStartedAt){const owner={id:randomUUID3(),pid:process.pid,createdAt:new Date().toISOString(),processStartedAt};await writeFile2(this.ownerPath(),JSON.stringify(owner),{mode:384,flag:"wx"});this.currentOwner=owner}async reclaimStaleLock(){const owner=await this.readOwner();if(!owner){await this.reclaimOldOwnerlessLock();return}const ownerDead=!await this.isOwnerAlive(owner.pid,owner.processStartedAt);if(!ownerDead)return;const currentOwner=await this.readOwner();if(!currentOwner||currentOwner.id!==owner.id)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}async reclaimOldOwnerlessLock(){const createdAtMs=await lockCreatedAtMs(this.lockPath);if(Date.now()-createdAtMs<ORPHANED_LOCK_MS)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}async readOwner(){try{const raw=await readFile2(this.ownerPath(),"utf8");const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.pid!=="number"||typeof parsed.createdAt!=="string"||!(typeof parsed.processStartedAt==="string"||parsed.processStartedAt===null)){return null}return{id:parsed.id,pid:parsed.pid,createdAt:parsed.createdAt,processStartedAt:parsed.processStartedAt}}catch{return null}}async releaseLock(){const owner=this.currentOwner;this.currentOwner=null;if(!owner)return;const currentOwner=await this.readOwner();if(!currentOwner||currentOwner.id!==owner.id)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}ownerPath(){return`${this.lockPath}/${OWNER_FILE}`}}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}async function isOriginalProcessAlive(pid,processStartedAt){if(!isProcessAlive(pid))return false;if(!processStartedAt)return true;return await getProcessStartedAt(pid)===processStartedAt}function isProcessAlive(pid){if(pid<=0)return false;try{process.kill(pid,0);return true}catch(error){const code=error.code;return code==="EPERM"}}async function getProcessStartedAt(pid){try{if(process.platform==="win32"){const{stdout:stdout2}=await execFileAsync("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`]);return stdout2.trim()||null}const{stdout}=await execFileAsync("ps",["-p",String(pid),"-o","lstart="]);const parsed=Date.parse(stdout.trim());return Number.isNaN(parsed)?null:new Date(parsed).toISOString()}catch{return null}}async function lockCreatedAtMs(path){try{const{stat:stat2}=await import("node:fs/promises");return(await stat2(path)).mtimeMs}catch{return 0}}class AuthStoragePolicyError extends Error{constructor(message){super(message);this.name="AuthStoragePolicyError"}}function createFileAuthStorageGuidance(configPath){return`OAuth credentials were not saved to plaintext file storage.
1291
+ </script>`;var RETRY_CTA=ctaBlock("To try again, run these commands in your terminal:",["npx githits@latest logout","npx githits@latest login"]);var HELP_CTA=ctaBlock("Explore available commands with:",["npx githits@latest --help"]);function escapeHtml(text){return text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var METADATA_FILE="metadata.json";var DIR_MODE3=448;class AuthSessionMetadataStorage{fs;configDir;metadataPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.metadataPath=fs.joinPath(this.configDir,METADATA_FILE)}async load(baseUrl2){const stored=await this.loadFile();if(!stored)return null;const metadata=stored.sessions[normalizeBaseUrl(baseUrl2)]??null;return isAuthSessionMetadata(metadata)?metadata:null}async saveFromTokens(baseUrl2,tokens){const stored=await this.loadFile()??{version:1,sessions:{}};stored.sessions[normalizeBaseUrl(baseUrl2)]={createdAt:tokens.createdAt,expiresAt:tokens.expiresAt,updatedAt:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE3);await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2))}async clear(baseUrl2){const stored=await this.loadFile();if(!stored)return;delete stored.sessions[normalizeBaseUrl(baseUrl2)];if(Object.keys(stored.sessions).length===0){await this.fs.deleteFile(this.metadataPath);return}await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2))}async loadFile(){if(!await this.fs.exists(this.metadataPath))return null;try{const content=await this.fs.readFile(this.metadataPath);const data=JSON.parse(content);if(data.version!==1||!data.sessions)return null;return data}catch{return null}}}function isAuthSessionMetadata(value){if(value===null||typeof value!=="object")return false;return typeof value.createdAt==="string"&&value.createdAt.length>0&&typeof value.updatedAt==="string"&&value.updatedAt.length>0&&(value.expiresAt===null||typeof value.expiresAt==="string"&&value.expiresAt.length>0)}import open from"open";class BrowserServiceImpl{async open(url){await open(url)}}var WINDOWS_MAX_ENTRY_SIZE=1200;var CHUNKED_PREFIX="CHUNKED:";var MAX_CHUNK_COUNT=100;function chunkKey(account,writeId,index){return`${account}:chunk:${writeId}:${index}`}function parseChunkedSentinel(value){if(!value.startsWith(CHUNKED_PREFIX))return null;const rest=value.slice(CHUNKED_PREFIX.length);const colonIndex=rest.indexOf(":");if(colonIndex===-1)return null;const writeId=rest.slice(0,colonIndex);if(writeId.length===0)return null;const countStr=rest.slice(colonIndex+1);const count=Number(countStr);if(!Number.isInteger(count)||count<=0)return null;return{writeId,count}}function splitIntoChunks(value,maxSize){if(value.length===0)return[""];const chunks=[];for(let offset=0;offset<value.length;offset+=maxSize){chunks.push(value.slice(offset,offset+maxSize))}return chunks}function generateWriteId(){let id;do{id=Math.random().toString(36).slice(2,8)}while(id.length<6);return id}class ChunkingKeyringService{inner;maxEntrySize;constructor(inner,maxEntrySize=WINDOWS_MAX_ENTRY_SIZE){this.inner=inner;this.maxEntrySize=maxEntrySize}getPassword(service,account){const value=this.inner.getPassword(service,account);if(value===null)return null;if(!value.startsWith(CHUNKED_PREFIX))return value;const sentinel=parseChunkedSentinel(value);if(sentinel===null)return null;const chunks=[];for(let i=0;i<sentinel.count;i++){const chunk=this.inner.getPassword(service,chunkKey(account,sentinel.writeId,i));if(chunk===null){console.error(`Warning: Incomplete chunked keychain entry for "${account}" (missing chunk ${i} of ${sentinel.count}). Treating as missing.`);return null}chunks.push(chunk)}return chunks.join("")}setPassword(service,account,password){const oldValue=this.readOldSentinel(service,account);if(password.length<=this.maxEntrySize){this.inner.setPassword(service,account,password)}else{const chunks=splitIntoChunks(password,this.maxEntrySize);if(chunks.length>MAX_CHUNK_COUNT){throw new Error(`Value requires ${chunks.length} chunks, exceeding maximum of ${MAX_CHUNK_COUNT}. `+`This likely indicates a bug — credential data should not be this large.`)}const writeId=generateWriteId();for(const[i,chunk]of chunks.entries()){this.inner.setPassword(service,chunkKey(account,writeId,i),chunk)}this.inner.setPassword(service,account,`${CHUNKED_PREFIX}${writeId}:${chunks.length}`)}if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}}deletePassword(service,account){const oldValue=this.readOldSentinel(service,account);if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}return this.inner.deletePassword(service,account)}readOldSentinel(service,account){try{const value=this.inner.getPassword(service,account);if(value===null)return null;return parseChunkedSentinel(value)}catch{return null}}deleteChunkEntries(service,account,sentinel){for(let i=0;i<sentinel.count;i++){try{this.inner.deletePassword(service,chunkKey(account,sentinel.writeId,i))}catch{}}}}import{randomUUID as randomUUID2}from"node:crypto";import{mkdir,readdir,readFile,rename,stat,unlink,writeFile}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join}from"node:path";class FileSystemServiceImpl{async readFile(path){return readFile(path,"utf-8")}async writeFile(path,contents,mode){await writeFile(path,contents,{mode})}async deleteFile(path){try{await unlink(path)}catch(error){if(error.code!=="ENOENT"){throw error}}}async exists(path){try{await stat(path);return true}catch{return false}}async ensureDir(path,mode){await mkdir(path,{recursive:true,mode})}getHomeDir(){return homedir()}joinPath(...segments){return join(...segments)}getCwd(){return process.cwd()}getDirname(path){return dirname(path)}async readdir(path){return readdir(path)}async isDirectory(path){try{const stats=await stat(path);return stats.isDirectory()}catch{return false}}async atomicWriteFile(path,contents){const tmpPath=`${path}.${process.pid}.${randomUUID2()}.tmp`;let mode=384;try{const existing=await stat(path);mode=existing.mode&511}catch{}try{await writeFile(tmpPath,contents,{mode});await rename(tmpPath,path)}catch(error){try{await unlink(tmpPath)}catch{}throw error}}}var SERVICE_NAME="githits";var TOKEN_PREFIX="v1:tokens:";var CLIENT_PREFIX="v1:client:";function parseJsonOrNull2(json){if(json===null)return null;try{const parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function isValidTokenData(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.accessToken==="string"&&d.accessToken.length>0&&typeof d.refreshToken==="string"&&d.refreshToken.length>0&&typeof d.createdAt==="string"&&d.createdAt.length>0&&(d.expiresAt===null||typeof d.expiresAt==="string"&&d.expiresAt.length>0)}function isValidClientRegistration(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.clientId==="string"&&d.clientId.length>0&&typeof d.clientSecret==="string"&&d.clientSecret.length>0&&typeof d.redirectUri==="string"&&d.redirectUri.length>0&&typeof d.registeredAt==="string"&&d.registeredAt.length>0}class KeychainAuthStorage{keyring;constructor(keyring){this.keyring=keyring}async loadTokens(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidTokenData(data))return null;return data}async saveTokens(baseUrl2,data){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.clearTokensIfUnchanged(baseUrl2,expected)}async loadClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidClientRegistration(data))return null;return data}async saveClient(baseUrl2,data){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async clearClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}clearActiveClient(baseUrl2){return this.clearClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}getStorageLocation(){switch(process.platform){case"darwin":return"macOS Keychain (githits)";case"win32":return"Windows Credential Manager (githits)";default:return"System keychain (githits)"}}}import{Entry}from"@napi-rs/keyring";class KeychainUnavailableError extends Error{constructor(message,cause){super(message);this.name="KeychainUnavailableError";this.cause=cause}}function wrapKeyringError(error){const message=error instanceof Error?error.message:String(error);throw new KeychainUnavailableError(`System keychain unavailable: ${message}`,error)}class KeyringServiceImpl{getPassword(service,account){try{return new Entry(service,account).getPassword()}catch(error){wrapKeyringError(error)}}setPassword(service,account,password){try{new Entry(service,account).setPassword(password)}catch(error){wrapKeyringError(error)}}deletePassword(service,account){try{return new Entry(service,account).deleteCredential()}catch(error){wrapKeyringError(error)}}}import{AsyncLocalStorage}from"node:async_hooks";import{execFile}from"node:child_process";import{randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir2,readFile as readFile2,rm,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname2}from"node:path";import{promisify}from"node:util";var LOCK_DIR="auth.lock";var LOCK_TIMEOUT_MS=DEFAULT_FETCH_TIMEOUT_MS*2+1e4;var LOCK_RETRY_MS=25;var ORPHANED_LOCK_MS=5000;var OWNER_FILE="owner.json";var execFileAsync=promisify(execFile);class AuthStorageLockTimeoutError extends Error{constructor(message){super(message);this.name="AuthStorageLockTimeoutError"}}function withAuthStorageLock(storage,fn){return storage.withAuthStorageLock(fn)}class LockedAuthStorage{storage;lockPath;lockTimeoutMs;isOwnerAlive;lockContext=new AsyncLocalStorage;currentOwner=null;constructor(storage,fileSystemService,options={}){this.storage=storage;this.lockTimeoutMs=options.lockTimeoutMs??LOCK_TIMEOUT_MS;this.isOwnerAlive=options.isOwnerAlive??isOriginalProcessAlive;this.lockPath=fileSystemService.joinPath(getAuthLockDir(fileSystemService),LOCK_DIR)}loadTokens(baseUrl2){return this.storage.loadTokens(baseUrl2)}saveTokens(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveTokens(baseUrl2,data))}saveTokensIfUnchanged(baseUrl2,expected,data){return this.withAuthStorageLock(()=>this.storage.saveTokensIfUnchanged(baseUrl2,expected,data))}clearTokens(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearTokens(baseUrl2))}clearTokensIfUnchanged(baseUrl2,expected){return this.withAuthStorageLock(()=>this.storage.clearTokensIfUnchanged(baseUrl2,expected))}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.withAuthStorageLock(()=>this.storage.clearActiveTokensIfUnchanged(baseUrl2,expected))}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}saveClient(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveClient(baseUrl2,data))}clearClient(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearClient(baseUrl2))}clearActiveClient(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearActiveClient(baseUrl2))}saveAuthSession(baseUrl2,client,tokens){return this.withAuthStorageLock(()=>this.storage.saveAuthSession(baseUrl2,client,tokens))}clearAuthSession(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearAuthSession(baseUrl2))}getStorageLocation(){return this.storage.getStorageLocation()}async withAuthStorageLock(fn){const ownerId=this.lockContext.getStore();if(ownerId&&this.currentOwner?.id===ownerId){return fn()}await this.acquireLock();const acquiredOwnerId=this.currentOwner?.id;try{return await this.lockContext.run(acquiredOwnerId??"",fn)}finally{await this.releaseLock()}}async acquireLock(){const processStartedAt=await getProcessStartedAt(process.pid);const startedAt=Date.now();await mkdir2(dirname2(this.lockPath),{recursive:true,mode:448});while(true){try{await mkdir2(this.lockPath,{recursive:false,mode:448});try{await this.writeOwner(processStartedAt)}catch(error){this.currentOwner=null;const code=error.code;if(code==="EEXIST"||code==="ENOENT"){if(Date.now()-startedAt>=this.lockTimeoutMs){throw this.createLockTimeoutError()}await sleep(LOCK_RETRY_MS);continue}await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return});throw error}return}catch(error){if(error.code!=="EEXIST")throw error;await this.reclaimStaleLock();if(Date.now()-startedAt>=this.lockTimeoutMs){throw this.createLockTimeoutError()}await sleep(LOCK_RETRY_MS)}}}createLockTimeoutError(){return new AuthStorageLockTimeoutError(`Timed out waiting for GitHits auth storage lock at ${this.lockPath}. If no githits process is running, remove this directory and retry.`)}async writeOwner(processStartedAt){const owner={id:randomUUID3(),pid:process.pid,createdAt:new Date().toISOString(),processStartedAt};await writeFile2(this.ownerPath(),JSON.stringify(owner),{mode:384,flag:"wx"});this.currentOwner=owner}async reclaimStaleLock(){const owner=await this.readOwner();if(!owner){await this.reclaimOldOwnerlessLock();return}const ownerDead=!await this.isOwnerAlive(owner.pid,owner.processStartedAt);if(!ownerDead)return;const currentOwner=await this.readOwner();if(!currentOwner||currentOwner.id!==owner.id)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}async reclaimOldOwnerlessLock(){const createdAtMs=await lockCreatedAtMs(this.lockPath);if(Date.now()-createdAtMs<ORPHANED_LOCK_MS)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}async readOwner(){try{const raw=await readFile2(this.ownerPath(),"utf8");const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.pid!=="number"||typeof parsed.createdAt!=="string"||!(typeof parsed.processStartedAt==="string"||parsed.processStartedAt===null)){return null}return{id:parsed.id,pid:parsed.pid,createdAt:parsed.createdAt,processStartedAt:parsed.processStartedAt}}catch{return null}}async releaseLock(){const owner=this.currentOwner;this.currentOwner=null;if(!owner)return;const currentOwner=await this.readOwner();if(!currentOwner||currentOwner.id!==owner.id)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}ownerPath(){return`${this.lockPath}/${OWNER_FILE}`}}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}async function isOriginalProcessAlive(pid,processStartedAt){if(!isProcessAlive(pid))return false;if(!processStartedAt)return true;return await getProcessStartedAt(pid)===processStartedAt}function isProcessAlive(pid){if(pid<=0)return false;try{process.kill(pid,0);return true}catch(error){const code=error.code;return code==="EPERM"}}async function getProcessStartedAt(pid){try{if(process.platform==="win32"){const{stdout:stdout2}=await execFileAsync("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`]);return stdout2.trim()||null}const{stdout}=await execFileAsync("ps",["-p",String(pid),"-o","lstart="]);const parsed=Date.parse(stdout.trim());return Number.isNaN(parsed)?null:new Date(parsed).toISOString()}catch{return null}}async function lockCreatedAtMs(path){try{const{stat:stat2}=await import("node:fs/promises");return(await stat2(path)).mtimeMs}catch{return 0}}class AuthStoragePolicyError extends Error{constructor(message){super(message);this.name="AuthStoragePolicyError"}}function createFileAuthStorageGuidance(configPath){return`OAuth credentials were not saved to plaintext file storage.
1292
1292
 
1293
1293
  Options:
1294
1294
  1. Unlock or fix your system keychain.
@@ -1300,5 +1300,5 @@ Options:
1300
1300
 
1301
1301
  in ${configPath}, or run with GITHITS_AUTH_STORAGE=file.
1302
1302
 
1303
- Warning: file storage is plaintext. Use it only on machines where local file access is trusted.`}class ModeAwareFileAuthStorage{storage;mode;configPath;constructor(storage,mode,configPath="your GitHits config.toml"){this.storage=storage;this.mode=mode;this.configPath=configPath}loadTokens(baseUrl2){return this.storage.loadTokens(baseUrl2)}async saveTokens(baseUrl2,data){this.assertFileMode();await this.storage.saveTokens(baseUrl2,data)}async saveTokensIfUnchanged(baseUrl2,expected,data){this.assertFileMode();return this.storage.saveTokensIfUnchanged(baseUrl2,expected,data)}clearTokens(baseUrl2){return this.storage.clearTokens(baseUrl2)}clearTokensIfUnchanged(baseUrl2,expected){return this.storage.clearTokensIfUnchanged(baseUrl2,expected)}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}async saveClient(baseUrl2,data){this.assertFileMode();await this.storage.saveClient(baseUrl2,data)}clearClient(baseUrl2){return this.storage.clearClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){this.assertFileMode();await this.storage.saveAuthSession(baseUrl2,client,tokens)}clearAuthSession(baseUrl2){return this.storage.clearAuthSession(baseUrl2)}getStorageLocation(){return this.storage.getStorageLocation()}assertFileMode(){if(this.mode==="file")return;throw new AuthStoragePolicyError(createFileAuthStorageGuidance(this.configPath))}}class MigratingAuthStorage{primary;file;legacy;mode;configPath;onWarning;metadata;additionalLegacyStores;warnedFileModeKeychainExport=false;warnedAmbiguousPlaintext=false;constructor(primary,file,legacy,mode,configPath="your GitHits config.toml",onWarning=()=>{},metadata,additionalLegacyStores=[]){this.primary=primary;this.file=file;this.legacy=legacy;this.mode=mode;this.configPath=configPath;this.onWarning=onWarning;this.metadata=metadata;this.additionalLegacyStores=additionalLegacyStores}async loadTokens(baseUrl2){if(this.mode==="file"){return this.loadTokensFileMode(baseUrl2)}return this.loadTokensKeychainMode(baseUrl2)}async saveTokens(baseUrl2,data){if(this.mode==="file"){await this.file.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data);return}try{await this.primary.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.file.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearTokens(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async loadClient(baseUrl2){if(this.mode==="file"){return this.loadClientFileMode(baseUrl2)}return this.loadClientKeychainMode(baseUrl2)}async saveClient(baseUrl2,data){if(this.mode==="file"){await this.file.saveClient(baseUrl2,data);return}try{await this.primary.saveClient(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async clearClient(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearClient(baseUrl2));await this.clearBestEffort(()=>this.file.clearClient(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearClient(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearClient(baseUrl2))}if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async saveAuthSession(baseUrl2,client,tokens){if(this.mode==="file"){await this.file.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens);return}try{await this.primary.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens)}catch(error){throw this.toPolicyError(error)}}async clearAuthSession(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.file.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearAuthSession(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearAuthSession(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}getStorageLocation(){return this.mode==="file"?this.file.getStorageLocation():this.primary.getStorageLocation()}async loadTokensKeychainMode(baseUrl2){try{const primaryTokens=await this.primary.loadTokens(baseUrl2);if(primaryTokens){await this.saveMetadataBestEffort(baseUrl2,primaryTokens);return primaryTokens}}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);if(!candidate)return null;try{await this.primary.saveTokens(baseUrl2,candidate.data)}catch(error){if(error instanceof KeychainUnavailableError)return candidate.data;throw error}await this.clearMigratedPlaintext(baseUrl2,"tokens",candidate.source,candidate.storage,candidate.ambiguous);await this.saveMetadataBestEffort(baseUrl2,candidate.data);return candidate.data}async loadTokensFileMode(baseUrl2){const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);if(candidate){if(candidate.source==="legacy"){await this.file.saveTokens(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearTokens(baseUrl2))}await this.saveMetadataBestEffort(baseUrl2,candidate.data);return candidate.data}let primaryTokens=null;try{primaryTokens=await this.primary.loadTokens(baseUrl2)}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}if(!primaryTokens)return null;this.warnKeychainExport();await this.file.saveTokens(baseUrl2,primaryTokens);await this.saveMetadataBestEffort(baseUrl2,primaryTokens);return primaryTokens}async loadClientKeychainMode(baseUrl2){try{const primaryClient=await this.primary.loadClient(baseUrl2);if(primaryClient)return primaryClient}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}const candidate=await this.selectPlaintextClientCandidate(baseUrl2);if(!candidate)return null;try{await this.primary.saveClient(baseUrl2,candidate.data)}catch(error){if(error instanceof KeychainUnavailableError)return candidate.data;throw error}await this.clearMigratedPlaintext(baseUrl2,"client",candidate.source,candidate.storage,candidate.ambiguous);return candidate.data}async loadClientFileMode(baseUrl2){const candidate=await this.selectPlaintextClientCandidate(baseUrl2);if(candidate){if(candidate.source==="legacy"){await this.file.saveClient(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearClient(baseUrl2))}return candidate.data}let primaryClient=null;try{primaryClient=await this.primary.loadClient(baseUrl2)}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}if(!primaryClient)return null;this.warnKeychainExport();await this.file.saveClient(baseUrl2,primaryClient);return primaryClient}async selectPlaintextTokenCandidate(baseUrl2){const candidates=[];const fileTokens=await this.file.loadTokens(baseUrl2);if(fileTokens){candidates.push({data:fileTokens,source:"file",storage:this.file,timestamp:fileTokens.createdAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyTokens=await legacy.loadTokens(baseUrl2);if(legacyTokens){candidates.push({data:legacyTokens,source:"legacy",storage:legacy,timestamp:legacyTokens.createdAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}async selectPlaintextClientCandidate(baseUrl2){const candidates=[];const fileClient=await this.file.loadClient(baseUrl2);if(fileClient){candidates.push({data:fileClient,source:"file",storage:this.file,timestamp:fileClient.registeredAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyClient=await legacy.loadClient(baseUrl2);if(legacyClient){candidates.push({data:legacyClient,source:"legacy",storage:legacy,timestamp:legacyClient.registeredAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}selectNewestCandidate(candidates){if(candidates.length===0)return null;if(candidates.length===1)return candidates[0]??null;const parsed=candidates.map((candidate)=>({candidate,timestampMs:Date.parse(candidate.timestamp)}));if(parsed.some((entry)=>Number.isNaN(entry.timestampMs))){this.warnAmbiguousPlaintext();const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(selected)selected.ambiguous=true;return selected}const sorted=[...parsed].sort((a,b)=>b.timestampMs-a.timestampMs);const first=sorted[0];const second=sorted[1];if(!first)return candidates[0]??null;if(second&&first.timestampMs===second.timestampMs){this.warnAmbiguousPlaintext();const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(!selected)return null;selected.ambiguous=true;return selected}return first.candidate}async clearMigratedPlaintext(baseUrl2,kind,source,storage,ambiguous=false){if(!ambiguous){await this.clearPlaintextSource(this.file,baseUrl2,kind);for(const legacy of this.getLegacyStores()){await this.clearPlaintextSource(legacy,baseUrl2,kind)}return}if(source==="file"){await this.clearPlaintextSource(this.file,baseUrl2,kind);return}if(source==="legacy"){await this.clearPlaintextSource(storage,baseUrl2,kind)}}getLegacyStores(){return[...this.additionalLegacyStores,this.legacy]}async clearPlaintextSource(storage,baseUrl2,kind){await this.clearBestEffort(()=>kind==="tokens"?storage.clearTokens(baseUrl2):storage.clearClient(baseUrl2))}async clearBestEffort(fn){try{await fn();return}catch(error){return error}}async saveMetadataBestEffort(baseUrl2,tokens){await this.clearBestEffort(()=>this.metadata?.saveFromTokens(baseUrl2,tokens)??Promise.resolve())}toPolicyError(error){if(!(error instanceof KeychainUnavailableError))return error;return new AuthStoragePolicyError(`System keychain is unavailable. ${createFileAuthStorageGuidance(this.configPath)}`)}warnKeychainExport(){if(this.warnedFileModeKeychainExport)return;this.warnedFileModeKeychainExport=true;this.onWarning("Warning: auth.storage=file is exporting existing keychain credentials to plaintext file storage.")}warnAmbiguousPlaintext(){if(this.warnedAmbiguousPlaintext)return;this.warnedAmbiguousPlaintext=true;this.onWarning("Warning: multiple plaintext auth entries exist with ambiguous timestamps; using the new config auth path and leaving the other entry intact.")}sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}}var PROACTIVE_REFRESH_RATIO=0.9;function shouldRefreshToken(token,ratio,now){if(!token.expiresAt){return{expired:false,shouldRefresh:false}}const expiresAt=new Date(token.expiresAt).getTime();const nowMs=now.getTime();if(nowMs>=expiresAt){return{expired:true,shouldRefresh:true}}const createdAt=new Date(token.createdAt).getTime();const lifetime=expiresAt-createdAt;if(lifetime<=0){return{expired:false,shouldRefresh:false}}const threshold=createdAt+lifetime*ratio;return{expired:false,shouldRefresh:nowMs>=threshold}}async function refreshExpiredToken(authService,authStorage,mcpUrl){const manager=new TokenManager({authService,authStorage,mcpUrl});return manager.forceRefresh()}class TokenManager{authService;authStorage;mcpUrl;cachedToken=null;softRefreshPromise=null;forceRefreshPromise=null;constructor(deps){this.authService=deps.authService;this.authStorage=deps.authStorage;this.mcpUrl=deps.mcpUrl}async getToken(){return withTelemetrySpan("token-manager.get-token",async()=>{const activeForceRefresh=this.forceRefreshPromise;if(activeForceRefresh){return(await activeForceRefresh).accessToken}if(!this.cachedToken){const storedToken=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));const startedForceRefresh=this.forceRefreshPromise;if(startedForceRefresh){return(await startedForceRefresh).accessToken}if(!this.cachedToken){this.cachedToken=storedToken}if(!this.cachedToken)return}const currentToken=this.cachedToken.accessToken;const{expired,shouldRefresh}=shouldRefreshToken(this.cachedToken,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh){return currentToken}const refreshedToken=await this.refreshFromGetToken();if(refreshedToken){return refreshedToken}if(!expired){return currentToken}return})}async forceRefresh(){return withTelemetrySpan("token-manager.force-refresh",()=>this.refreshAfterAuthFailure())}async refreshFromGetToken(){const result=await this.softRefresh();return result.accessToken}async softRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;if(this.softRefreshPromise)return this.softRefreshPromise;this.softRefreshPromise=this.executeRefresh();try{return await this.softRefreshPromise}finally{this.softRefreshPromise=null}}async refreshAfterAuthFailure(){const result=await this.forceEndpointRefresh();return result.accessToken}async forceEndpointRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;this.forceRefreshPromise=(async()=>{const softResult=await this.softRefreshPromise?.catch(()=>{return});if(softResult?.accessToken&&softResult.refreshedViaEndpoint){return softResult}return this.executeRefresh()})();try{return await this.forceRefreshPromise}finally{this.forceRefreshPromise=null}}async executeRefresh(){return withAuthStorageLock(this.authStorage,()=>withTelemetrySpan("token-manager.refresh",async()=>{const candidate=await this.loadRefreshCandidate();if(!candidate)return refreshResult(undefined,false);if(candidate.externallyUpdated){const{shouldRefresh}=shouldRefreshToken(candidate.tokens,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh)return refreshResult(candidate.tokens.accessToken,false)}const tokens=candidate.tokens;const client=await withTelemetrySpan("token-manager.load-client",()=>this.authStorage.loadClient(this.mcpUrl));if(!client)return refreshResult(undefined,false);let response;try{const metadata=await withTelemetrySpan("token-manager.discover-endpoints",()=>this.authService.discoverEndpoints(this.mcpUrl));response=await withTelemetrySpan("token-manager.refresh-access-token",()=>this.authService.refreshAccessToken({tokenEndpoint:metadata.tokenEndpoint,clientId:client.clientId,clientSecret:client.clientSecret,refreshToken:tokens.refreshToken}))}catch{const reloadedToken=await this.loadExternallyUpdatedToken(tokens);if(reloadedToken)return refreshResult(reloadedToken.accessToken,false);const isExpired=tokens.expiresAt?new Date>=new Date(tokens.expiresAt):false;if(candidate.externallyUpdated&&!isExpired){return refreshResult(tokens.accessToken,false)}if(isExpired){const currentStoredTokens=await this.loadExternallyUpdatedToken(tokens);if(currentStoredTokens){return refreshResult(currentStoredTokens.accessToken,false)}const cleared=await withTelemetrySpan("token-manager.clear-tokens-if-unchanged",()=>this.authStorage.clearTokensIfUnchanged(this.mcpUrl,tokens));if(!cleared){const currentToken=await this.authStorage.loadTokens(this.mcpUrl);this.cachedToken=currentToken;return refreshResult(currentToken?.accessToken,false)}this.cachedToken=null}return refreshResult(undefined,false)}const newTokenData={accessToken:response.accessToken,refreshToken:response.refreshToken??tokens.refreshToken,expiresAt:new Date(Date.now()+response.expiresIn*1000).toISOString(),createdAt:new Date().toISOString()};const saved=await withTelemetrySpan("token-manager.save-tokens",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,tokens,newTokenData));if(!saved){return this.resolveSuccessfulRefreshConflict(tokens,response,newTokenData)}this.cachedToken=newTokenData;return refreshResult(response.accessToken,true)}))}async resolveSuccessfulRefreshConflict(refreshedFrom,response,newTokenData){const currentToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!currentToken){this.cachedToken=null;return refreshResult(undefined,false)}if(!response.refreshToken||currentToken.refreshToken!==refreshedFrom.refreshToken){this.cachedToken=currentToken;return refreshResult(currentToken.accessToken,false)}const saved=await withTelemetrySpan("token-manager.save-rotated-tokens-after-conflict",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,currentToken,newTokenData));if(saved){this.cachedToken=newTokenData;return refreshResult(newTokenData.accessToken,true)}const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false)}async loadRefreshCandidate(){const storedTokens=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!this.cachedToken){this.cachedToken=storedTokens;return storedTokens?{tokens:storedTokens,externallyUpdated:false}:null}if(!storedTokens){this.cachedToken=null;return null}if(!areSameTokenData(storedTokens,this.cachedToken)){this.cachedToken=storedTokens;return{tokens:storedTokens,externallyUpdated:true}}return{tokens:this.cachedToken,externallyUpdated:false}}async loadExternallyUpdatedToken(failedTokens){const storedTokens=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!storedTokens)return;if(areSameTokenData(storedTokens,failedTokens))return;this.cachedToken=storedTokens;return storedTokens}}function areSameTokenData(a,b){return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}function refreshResult(accessToken,refreshedViaEndpoint){return{accessToken,refreshedViaEndpoint}}var BASE_CLIENT_NAME="githits-cli";var USER_AGENT=`${BASE_CLIENT_NAME}/${version}`;async function createAuthStorage(fileSystemService){return withTelemetrySpan("container.create-auth-storage",async()=>{const authConfig=await loadAuthConfig(fileSystemService);return createAuthStorageForMode(fileSystemService,authConfig.storage,authConfig.configPath)})}function createAuthStorageForMode(fileSystemService,mode,configPath="your GitHits config.toml"){const fileStorage=new ModeAwareFileAuthStorage(new AuthStorageImpl(fileSystemService,getAuthFileStorageDir(fileSystemService)),mode,configPath);const legacyStorage=new AuthStorageImpl(fileSystemService,getLegacyAuthStorageDir(fileSystemService));const additionalLegacyStores=process.platform==="darwin"?[new AuthStorageImpl(fileSystemService,getLegacyMacAuthFileStorageDir(fileSystemService))]:[];const rawKeyring=new KeyringServiceImpl;const keyring=process.platform==="win32"?new ChunkingKeyringService(rawKeyring,WINDOWS_MAX_ENTRY_SIZE):rawKeyring;const keychainStorage=new KeychainAuthStorage(keyring);const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return new LockedAuthStorage(new MigratingAuthStorage(keychainStorage,fileStorage,legacyStorage,mode,configPath,(message)=>console.error(message),metadataStorage,additionalLegacyStores),fileSystemService)}async function loadAutoLoginAuthSessionMetadata(){const envToken=getEnvApiToken();if(envToken){const now=new Date().toISOString();return{createdAt:now,expiresAt:null,updatedAt:now}}const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return metadataStorage.load(getMcpUrl())}async function clearAutoLoginAuthSessionMetadata(){const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);await metadataStorage.clear(getMcpUrl())}async function createAuthCommandDependencies(){return withTelemetrySpan("container.create-auth-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:await createAuthStorage(fileSystemService),authService:new AuthServiceImpl,browserService:new BrowserServiceImpl,fileSystemService,mcpUrl:getMcpUrl(),apiUrl:getApiUrl(),envApiToken:getEnvApiToken()}})}async function createAuthStatusDependencies(){return withTelemetrySpan("container.create-auth-status",async()=>{const fileSystemService=new FileSystemServiceImpl;const envApiToken=getEnvApiToken();return{authStorage:envApiToken?createAuthStorageForMode(fileSystemService,"keychain"):await createAuthStorage(fileSystemService),authService:new AuthServiceImpl,browserService:new BrowserServiceImpl,fileSystemService,mcpUrl:getMcpUrl(),apiUrl:getApiUrl(),envApiToken}})}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}async function createContainer(options={}){return withTelemetrySpan("container.create",async()=>{const resolveStoredToken=options.resolveStoredToken??true;const mcpUrl=getMcpUrl();const apiUrl=getApiUrl();const codeNavigationUrl=getCodeNavigationUrl();const fileSystemService=new FileSystemServiceImpl;const authService=new AuthServiceImpl;const browserService=new BrowserServiceImpl;const clientHeaders=createClientHeaderBuilder({clientName:options.clientName??BASE_CLIENT_NAME,clientVersion:version,agentProvider:options.agentProvider});const serviceRuntime={clientHeaders,userAgent:USER_AGENT,clientVersion:version};const envToken=getEnvApiToken();if(envToken){const authStorage2=createAuthStorageForMode(fileSystemService,"keychain");const tokenProvider=createStaticTokenProvider(envToken);const codeNavigationService2=new CodeNavigationServiceImpl(codeNavigationUrl,tokenProvider,globalThis.fetch,serviceRuntime);const packageIntelligenceService2=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenProvider,globalThis.fetch,serviceRuntime);return{authStorage:authStorage2,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken:envToken,hasValidToken:true,envApiToken:envToken,codeNavigationUrl,codeNavigationService:codeNavigationService2,packageIntelligenceService:packageIntelligenceService2,githitsService:new GitHitsServiceImpl(apiUrl,envToken,undefined,undefined,serviceRuntime)}}const authStorage=await createAuthStorage(fileSystemService);const tokenManager=new TokenManager({authService,authStorage,mcpUrl});const apiToken=resolveStoredToken?await withTelemetrySpan("container.token.get",()=>tokenManager.getToken()):undefined;if(resolveStoredToken&&apiToken===undefined){await new AuthSessionMetadataStorage(fileSystemService).clear(mcpUrl)}const codeNavigationService=new CodeNavigationServiceImpl(codeNavigationUrl,tokenManager,globalThis.fetch,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenManager,globalThis.fetch,serviceRuntime);return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken,hasValidToken:apiToken!==undefined,envApiToken:undefined,codeNavigationUrl,codeNavigationService,packageIntelligenceService,githitsService:new RefreshingGitHitsService(apiUrl,tokenManager,undefined,serviceRuntime)}})}
1304
- export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,debugLog,isTelemetryEnabled,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,LOCAL_AUTHENTICATION_MISSING_MESSAGE,AuthenticationError,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getCodeNavigationUrl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,getAppConfigDirForEnv,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,AuthConfigError,parseAuthStorageMode,AuthStorageLockTimeoutError,AuthStoragePolicyError,normalizeBaseUrl,FileSystemServiceImpl,refreshExpiredToken,loadAutoLoginAuthSessionMetadata,clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer};
1303
+ Warning: file storage is plaintext. Use it only on machines where local file access is trusted.`}class ModeAwareFileAuthStorage{storage;mode;configPath;constructor(storage,mode,configPath="your GitHits config.toml"){this.storage=storage;this.mode=mode;this.configPath=configPath}loadTokens(baseUrl2){return this.storage.loadTokens(baseUrl2)}async saveTokens(baseUrl2,data){this.assertFileMode();await this.storage.saveTokens(baseUrl2,data)}async saveTokensIfUnchanged(baseUrl2,expected,data){this.assertFileMode();return this.storage.saveTokensIfUnchanged(baseUrl2,expected,data)}clearTokens(baseUrl2){return this.storage.clearTokens(baseUrl2)}clearTokensIfUnchanged(baseUrl2,expected){return this.storage.clearTokensIfUnchanged(baseUrl2,expected)}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.storage.clearActiveTokensIfUnchanged(baseUrl2,expected)}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}async saveClient(baseUrl2,data){this.assertFileMode();await this.storage.saveClient(baseUrl2,data)}clearClient(baseUrl2){return this.storage.clearClient(baseUrl2)}clearActiveClient(baseUrl2){return this.storage.clearActiveClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){this.assertFileMode();await this.storage.saveAuthSession(baseUrl2,client,tokens)}clearAuthSession(baseUrl2){return this.storage.clearAuthSession(baseUrl2)}getStorageLocation(){return this.storage.getStorageLocation()}assertFileMode(){if(this.mode==="file")return;throw new AuthStoragePolicyError(createFileAuthStorageGuidance(this.configPath))}}class MigratingAuthStorage{primary;file;legacy;mode;configPath;onWarning;metadata;additionalLegacyStores;warnedAmbiguousPlaintext=false;constructor(primary,file,legacy,mode,configPath="your GitHits config.toml",onWarning=()=>{},metadata,additionalLegacyStores=[]){this.primary=primary;this.file=file;this.legacy=legacy;this.mode=mode;this.configPath=configPath;this.onWarning=onWarning;this.metadata=metadata;this.additionalLegacyStores=additionalLegacyStores}async loadTokens(baseUrl2){if(this.mode==="file"){return this.loadTokensFileMode(baseUrl2)}return this.loadTokensKeychainMode(baseUrl2)}async saveTokens(baseUrl2,data){if(this.mode==="file"){await this.file.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data);return}try{await this.primary.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.file.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearTokens(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async clearActiveTokensIfUnchanged(baseUrl2,expected){const current=await this.currentActiveTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearTokens(baseUrl2));firstError??=error}const metadataError=await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());firstError??=metadataError;if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}return true}async loadClient(baseUrl2){if(this.mode==="file"){return this.loadClientFileMode(baseUrl2)}return this.loadClientKeychainMode(baseUrl2)}async saveClient(baseUrl2,data){if(this.mode==="file"){await this.file.saveClient(baseUrl2,data);return}try{await this.primary.saveClient(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async clearClient(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearClient(baseUrl2));await this.clearBestEffort(()=>this.file.clearClient(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearClient(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearClient(baseUrl2))}if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearActiveClient(baseUrl2){let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearClient(baseUrl2));firstError??=error}if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}}async saveAuthSession(baseUrl2,client,tokens){if(this.mode==="file"){await this.file.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens);return}try{await this.primary.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens)}catch(error){throw this.toPolicyError(error)}}async clearAuthSession(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.file.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearAuthSession(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearAuthSession(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}getStorageLocation(){return this.mode==="file"?this.file.getStorageLocation():this.primary.getStorageLocation()}async loadTokensKeychainMode(baseUrl2){try{const primaryTokens=await this.primary.loadTokens(baseUrl2);if(primaryTokens){await this.saveMetadataBestEffort(baseUrl2,primaryTokens);return primaryTokens}}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}return null}async loadTokensFileMode(baseUrl2){const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);if(candidate){if(candidate.source==="legacy"){await this.file.saveTokens(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearTokens(baseUrl2))}await this.saveMetadataBestEffort(baseUrl2,candidate.data);return candidate.data}return null}async loadClientKeychainMode(baseUrl2){try{const primaryClient=await this.primary.loadClient(baseUrl2);if(primaryClient)return primaryClient}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}return null}async loadClientFileMode(baseUrl2){const candidate=await this.selectPlaintextClientCandidate(baseUrl2);if(candidate){if(candidate.source==="legacy"){await this.file.saveClient(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearClient(baseUrl2))}return candidate.data}return null}async selectPlaintextTokenCandidate(baseUrl2){const candidates=[];const fileTokens=await this.file.loadTokens(baseUrl2);if(fileTokens){candidates.push({data:fileTokens,source:"file",storage:this.file,timestamp:fileTokens.createdAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyTokens=await legacy.loadTokens(baseUrl2);if(legacyTokens){candidates.push({data:legacyTokens,source:"legacy",storage:legacy,timestamp:legacyTokens.createdAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}async selectPlaintextClientCandidate(baseUrl2){const candidates=[];const fileClient=await this.file.loadClient(baseUrl2);if(fileClient){candidates.push({data:fileClient,source:"file",storage:this.file,timestamp:fileClient.registeredAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyClient=await legacy.loadClient(baseUrl2);if(legacyClient){candidates.push({data:legacyClient,source:"legacy",storage:legacy,timestamp:legacyClient.registeredAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}selectNewestCandidate(candidates){if(candidates.length===0)return null;if(candidates.length===1)return candidates[0]??null;const parsed=candidates.map((candidate)=>({candidate,timestampMs:Date.parse(candidate.timestamp)}));if(parsed.some((entry)=>Number.isNaN(entry.timestampMs))){this.warnAmbiguousPlaintext();const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(selected)selected.ambiguous=true;return selected}const sorted=[...parsed].sort((a,b)=>b.timestampMs-a.timestampMs);const first=sorted[0];const second=sorted[1];if(!first)return candidates[0]??null;if(second&&first.timestampMs===second.timestampMs){this.warnAmbiguousPlaintext();const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(!selected)return null;selected.ambiguous=true;return selected}return first.candidate}getLegacyStores(){return[...this.additionalLegacyStores,this.legacy]}activeStores(){return this.mode==="file"?[this.file,...this.getLegacyStores()]:[this.primary]}async currentActiveTokens(baseUrl2){if(this.mode==="file"){const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);return candidate?.data??null}try{return await this.primary.loadTokens(baseUrl2)}catch(error){if(error instanceof KeychainUnavailableError)return null;throw error}}async clearBestEffort(fn){try{await fn();return}catch(error){return error}}async saveMetadataBestEffort(baseUrl2,tokens){await this.clearBestEffort(()=>this.metadata?.saveFromTokens(baseUrl2,tokens)??Promise.resolve())}toPolicyError(error){if(!(error instanceof KeychainUnavailableError))return error;return new AuthStoragePolicyError(`System keychain is unavailable. ${createFileAuthStorageGuidance(this.configPath)}`)}warnAmbiguousPlaintext(){if(this.warnedAmbiguousPlaintext)return;this.warnedAmbiguousPlaintext=true;this.onWarning("Warning: multiple plaintext auth entries exist with ambiguous timestamps; using the new config auth path and leaving the other entry intact.")}sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}}var PROACTIVE_REFRESH_RATIO=0.9;function shouldRefreshToken(token,ratio,now){if(!token.expiresAt){return{expired:false,shouldRefresh:false}}const expiresAt=new Date(token.expiresAt).getTime();const nowMs=now.getTime();if(nowMs>=expiresAt){return{expired:true,shouldRefresh:true}}const createdAt=new Date(token.createdAt).getTime();const lifetime=expiresAt-createdAt;if(lifetime<=0){return{expired:false,shouldRefresh:false}}const threshold=createdAt+lifetime*ratio;return{expired:false,shouldRefresh:nowMs>=threshold}}async function refreshExpiredToken(authService,authStorage,mcpUrl){const manager=new TokenManager({authService,authStorage,mcpUrl});return manager.forceRefresh()}class TokenManager{authService;authStorage;mcpUrl;authDiagnostics;cachedToken=null;softRefreshPromise=null;forceRefreshPromise=null;constructor(deps){this.authService=deps.authService;this.authStorage=deps.authStorage;this.mcpUrl=deps.mcpUrl;this.authDiagnostics=deps.authDiagnostics}async getToken(){return withTelemetrySpan("token-manager.get-token",async()=>{const activeForceRefresh=this.forceRefreshPromise;if(activeForceRefresh){return(await activeForceRefresh).accessToken}if(!this.cachedToken){const storedToken=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));const startedForceRefresh=this.forceRefreshPromise;if(startedForceRefresh){return(await startedForceRefresh).accessToken}if(!this.cachedToken){this.cachedToken=storedToken}if(!this.cachedToken)return}const currentToken=this.cachedToken.accessToken;const{expired,shouldRefresh}=shouldRefreshToken(this.cachedToken,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh){return currentToken}const refresh=await this.refreshFromGetToken();if(refresh.accessToken){return refresh.accessToken}if(refresh.invalidatedCurrentToken){return}if(!expired){return currentToken}return})}async forceRefresh(){return withTelemetrySpan("token-manager.force-refresh",()=>this.refreshAfterAuthFailure())}refreshFromGetToken(){return this.softRefresh()}async softRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;if(this.softRefreshPromise)return this.softRefreshPromise;this.softRefreshPromise=this.executeRefresh();try{return await this.softRefreshPromise}finally{this.softRefreshPromise=null}}async refreshAfterAuthFailure(){const result=await this.forceEndpointRefresh();return result.accessToken}async forceEndpointRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;this.forceRefreshPromise=(async()=>{const softResult=await this.softRefreshPromise?.catch(()=>{return});if(softResult?.accessToken&&softResult.refreshedViaEndpoint){return softResult}return this.executeRefresh()})();try{return await this.forceRefreshPromise}finally{this.forceRefreshPromise=null}}async executeRefresh(){return withAuthStorageLock(this.authStorage,()=>withTelemetrySpan("token-manager.refresh",async()=>{const candidate=await this.loadRefreshCandidate();if(!candidate)return refreshResult(undefined,false);if(candidate.externallyUpdated){const{shouldRefresh}=shouldRefreshToken(candidate.tokens,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh)return refreshResult(candidate.tokens.accessToken,false)}const tokens=candidate.tokens;const client=await withTelemetrySpan("token-manager.load-client",()=>this.authStorage.loadClient(this.mcpUrl));if(!client)return refreshResult(undefined,false);let response;try{const metadata=await withTelemetrySpan("token-manager.discover-endpoints",()=>this.authService.discoverEndpoints(this.mcpUrl));response=await withTelemetrySpan("token-manager.refresh-access-token",()=>this.authService.refreshAccessToken({tokenEndpoint:metadata.tokenEndpoint,clientId:client.clientId,clientSecret:client.clientSecret,refreshToken:tokens.refreshToken}))}catch(error){const terminalFailure=classifyTerminalRefreshError(error);const reloadedToken=await this.loadExternallyUpdatedToken(tokens);if(reloadedToken)return refreshResult(reloadedToken.accessToken,false);const isExpired=tokens.expiresAt?new Date>=new Date(tokens.expiresAt):false;if(terminalFailure){return this.clearTerminalRefreshFailure(tokens,terminalFailure)}if(candidate.externallyUpdated&&!isExpired){return refreshResult(tokens.accessToken,false)}if(isExpired){const currentStoredTokens=await this.loadExternallyUpdatedToken(tokens);if(currentStoredTokens){return refreshResult(currentStoredTokens.accessToken,false)}const cleared=await withTelemetrySpan("token-manager.clear-tokens-if-unchanged",()=>this.authStorage.clearActiveTokensIfUnchanged(this.mcpUrl,tokens));if(!cleared){const currentToken=await this.authStorage.loadTokens(this.mcpUrl);this.cachedToken=currentToken;return refreshResult(currentToken?.accessToken,false)}this.cachedToken=null}return refreshResult(undefined,false)}const newTokenData={accessToken:response.accessToken,refreshToken:response.refreshToken??tokens.refreshToken,expiresAt:new Date(Date.now()+response.expiresIn*1000).toISOString(),createdAt:new Date().toISOString()};const saved=await withTelemetrySpan("token-manager.save-tokens",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,tokens,newTokenData));if(!saved){return this.resolveSuccessfulRefreshConflict(tokens,response,newTokenData)}this.cachedToken=newTokenData;return refreshResult(response.accessToken,true)}))}async resolveSuccessfulRefreshConflict(refreshedFrom,response,newTokenData){const currentToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!currentToken){this.cachedToken=null;return refreshResult(undefined,false)}if(!response.refreshToken||currentToken.refreshToken!==refreshedFrom.refreshToken){this.cachedToken=currentToken;return refreshResult(currentToken.accessToken,false)}const saved=await withTelemetrySpan("token-manager.save-rotated-tokens-after-conflict",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,currentToken,newTokenData));if(saved){this.cachedToken=newTokenData;return refreshResult(newTokenData.accessToken,true)}const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false)}async clearTerminalRefreshFailure(failedTokens,reason){const cleared=await withTelemetrySpan("token-manager.clear-terminal-refresh-failure",()=>this.authStorage.clearActiveTokensIfUnchanged(this.mcpUrl,failedTokens),{reason:`terminal_${reason}`});if(!cleared){const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false,!latestToken)}if(reason==="invalid_client"){await withTelemetrySpan("token-manager.clear-invalid-client",()=>this.authStorage.clearActiveClient(this.mcpUrl),{reason:"terminal_invalid_client"}).catch(()=>{return})}await this.authDiagnostics?.recordClear(this.mcpUrl,`terminal_${reason}`);this.cachedToken=null;return refreshResult(undefined,false,true)}async loadRefreshCandidate(){const storedTokens=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!this.cachedToken){this.cachedToken=storedTokens;return storedTokens?{tokens:storedTokens,externallyUpdated:false}:null}if(!storedTokens){this.cachedToken=null;return null}if(!areSameTokenData(storedTokens,this.cachedToken)){this.cachedToken=storedTokens;return{tokens:storedTokens,externallyUpdated:true}}return{tokens:this.cachedToken,externallyUpdated:false}}async loadExternallyUpdatedToken(failedTokens){const storedTokens=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!storedTokens)return;if(areSameTokenData(storedTokens,failedTokens))return;this.cachedToken=storedTokens;return storedTokens}}function areSameTokenData(a,b){return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}function refreshResult(accessToken,refreshedViaEndpoint,invalidatedCurrentToken=false){return{accessToken,refreshedViaEndpoint,invalidatedCurrentToken}}var BASE_CLIENT_NAME="githits-cli";var USER_AGENT=`${BASE_CLIENT_NAME}/${version}`;async function createAuthStorage(fileSystemService){return withTelemetrySpan("container.create-auth-storage",async()=>{const authConfig=await loadAuthConfig(fileSystemService);recordAuthFingerprint(authConfig.storage);return createAuthStorageForMode(fileSystemService,authConfig.storage,authConfig.configPath)})}function recordAuthFingerprint(mode,env=process.env){const handle=startTelemetrySpan("auth.fingerprint",{mode,platform:process.platform,homeSet:Boolean(env.HOME),xdgConfigHomeSet:Boolean(env.XDG_CONFIG_HOME),appDataSet:Boolean(env.APPDATA),userProfileSet:Boolean(env.USERPROFILE)});endTelemetrySpan(handle)}function createAuthStorageForMode(fileSystemService,mode,configPath="your GitHits config.toml"){const fileStorage=new ModeAwareFileAuthStorage(new AuthStorageImpl(fileSystemService,getAuthFileStorageDir(fileSystemService)),mode,configPath);const legacyStorage=new AuthStorageImpl(fileSystemService,getLegacyAuthStorageDir(fileSystemService));const additionalLegacyStores=process.platform==="darwin"?[new AuthStorageImpl(fileSystemService,getLegacyMacAuthFileStorageDir(fileSystemService))]:[];const rawKeyring=new KeyringServiceImpl;const keyring=process.platform==="win32"?new ChunkingKeyringService(rawKeyring,WINDOWS_MAX_ENTRY_SIZE):rawKeyring;const keychainStorage=new KeychainAuthStorage(keyring);const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return new LockedAuthStorage(new MigratingAuthStorage(keychainStorage,fileStorage,legacyStorage,mode,configPath,(message)=>console.error(message),metadataStorage,additionalLegacyStores),fileSystemService)}async function loadAutoLoginAuthSessionMetadata(){const envToken=getEnvApiToken();if(envToken){const now=new Date().toISOString();return{createdAt:now,expiresAt:null,updatedAt:now}}const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return metadataStorage.load(getMcpUrl())}async function clearAutoLoginAuthSessionMetadata(){const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);await metadataStorage.clear(getMcpUrl())}async function createAuthCommandDependencies(){return withTelemetrySpan("container.create-auth-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:await createAuthStorage(fileSystemService),authService:new AuthServiceImpl,browserService:new BrowserServiceImpl,fileSystemService,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpUrl(),apiUrl:getApiUrl(),envApiToken:getEnvApiToken()}})}async function createAuthStatusDependencies(){return withTelemetrySpan("container.create-auth-status",async()=>{const fileSystemService=new FileSystemServiceImpl;const envApiToken=getEnvApiToken();return{authStorage:envApiToken?createAuthStorageForMode(fileSystemService,"keychain"):await createAuthStorage(fileSystemService),authService:new AuthServiceImpl,browserService:new BrowserServiceImpl,fileSystemService,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpUrl(),apiUrl:getApiUrl(),envApiToken}})}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}async function createContainer(options={}){return withTelemetrySpan("container.create",async()=>{const resolveStoredToken=options.resolveStoredToken??true;const mcpUrl=getMcpUrl();const apiUrl=getApiUrl();const codeNavigationUrl=getCodeNavigationUrl();const fileSystemService=new FileSystemServiceImpl;const authService=new AuthServiceImpl;const browserService=new BrowserServiceImpl;const clientHeaders=createClientHeaderBuilder({clientName:options.clientName??BASE_CLIENT_NAME,clientVersion:version,agentProvider:options.agentProvider});const serviceRuntime={clientHeaders,userAgent:USER_AGENT,clientVersion:version};const envToken=getEnvApiToken();if(envToken){const authStorage2=createAuthStorageForMode(fileSystemService,"keychain");const tokenProvider=createStaticTokenProvider(envToken);const codeNavigationService2=new CodeNavigationServiceImpl(codeNavigationUrl,tokenProvider,globalThis.fetch,serviceRuntime);const packageIntelligenceService2=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenProvider,globalThis.fetch,serviceRuntime);return{authStorage:authStorage2,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken:envToken,hasValidToken:true,envApiToken:envToken,codeNavigationUrl,codeNavigationService:codeNavigationService2,packageIntelligenceService:packageIntelligenceService2,githitsService:new GitHitsServiceImpl(apiUrl,envToken,undefined,undefined,serviceRuntime)}}const authStorage=await createAuthStorage(fileSystemService);const tokenManager=new TokenManager({authService,authStorage,mcpUrl,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService)});const apiToken=resolveStoredToken?await withTelemetrySpan("container.token.get",()=>tokenManager.getToken()):undefined;if(resolveStoredToken&&apiToken===undefined){await new AuthSessionMetadataStorage(fileSystemService).clear(mcpUrl)}const codeNavigationService=new CodeNavigationServiceImpl(codeNavigationUrl,tokenManager,globalThis.fetch,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenManager,globalThis.fetch,serviceRuntime);return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken,hasValidToken:apiToken!==undefined,envApiToken:undefined,codeNavigationUrl,codeNavigationService,packageIntelligenceService,githitsService:new RefreshingGitHitsService(apiUrl,tokenManager,undefined,serviceRuntime)}})}
1304
+ export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,debugLog,isTelemetryEnabled,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,LOCAL_AUTHENTICATION_MISSING_MESSAGE,AuthenticationError,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getCodeNavigationUrl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,getAppConfigDirForEnv,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,AuthConfigError,parseAuthStorageMode,AuthStorageLockTimeoutError,AuthStoragePolicyError,normalizeBaseUrl,isAuthClearReason,FileSystemServiceImpl,refreshExpiredToken,recordAuthFingerprint,loadAutoLoginAuthSessionMetadata,clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "githits",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "Code examples from global open source for developers and AI assistants.",
5
5
  "mcpServers": {
6
6
  "githits": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "githits",
3
3
  "description": "CLI companion for GitHits - code examples from global open source for developers and AI assistants",
4
- "version": "0.4.13",
4
+ "version": "0.4.15",
5
5
  "type": "module",
6
6
  "workspaces": [
7
7
  "packages/*"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "githits",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "Code examples from global open source for developers and AI assistants",
5
5
  "author": {
6
6
  "name": "GitHits"
@@ -1 +0,0 @@
1
- import{clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer,loadAutoLoginAuthSessionMetadata}from"./chunk-ancbjszp.js";import"./chunk-33j95qx6.js";export{loadAutoLoginAuthSessionMetadata,createContainer,createAuthStatusDependencies,createAuthCommandDependencies,clearAutoLoginAuthSessionMetadata};