@githits/mcp 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-jh5qg990.js";import{EXTERNAL_CONTENT_POSTURE,PKG_VULNS_GUARDRAIL,PKG_INFO_GUARDRAIL,PKG_CHANGELOG_GUARDRAIL,PKG_UPGRADE_REVIEW_GUARDRAIL,CODE_READ_GUARDRAIL,CODE_GREP_GUARDRAIL,SEARCH_GUARDRAIL,KNOWN_REGISTRIES,UnsupportedRegistryError,InvalidPackageSpecError,InvalidArgumentError,parsePackageSpec,isKnownRegistry,LegacyRepositoryRefError,isRepositoryTargetSpec,parseRepositoryTargetSpec,isCanonicalRepositoryUrl,formatRepositoryTarget,formatRepositoryTargetLabel,buildInvalidTargetSpecError,terminalWidth,sanitizeTerminalText,wrapTerminalProse,projectTargetResolution,buildTargetResolutionNotes,buildRetryCandidateLine,buildSuggestedRefsLine,buildResolutionFromRetryCandidates,formatTargetResolutionIdentity,buildSourceCorrespondenceNotes,buildSourceCorrespondenceNote,toCodeNavigationRegistry,AuthRequiredError,mapSessionIdError,mapTermsAcceptanceError,shellQuote,shellQuoteExact,mapVersionRefRecovery,withVersionRefRecovery,mapCodeNavigationError,buildUpdateRequiredError,serviceRequestArgs,MAX_WAIT_TIMEOUT_MS,MAX_DISCOVERY_WAIT_TIMEOUT_MS,MCP_READ_DEFAULT_SPAN,MCP_READ_MAX_SPAN,formatProvenanceRow,formatSourceRow,renderSourceSection,sameRepositoryCommit,resolutionSourceFacts,formatRequestedIndexingExplanation,renderResolutionDetails,formatRequestedProvenance,formatPreparationRow,renderPreparationSection,formatPreparationRetry,indexingWaitMs,withIndexingRetryAction,formatMappedErrorText,READ_ONLY_TOOL_ANNOTATIONS,OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,textResult,errorResult,withErrorHandling,mcpMappedErrorResult,addLocalMcpAuthAction,throwIfCallerCancellation,createGetExampleTool2,colors,colorize,highlight,highlightMatch,highlightRanges,dim,mapPackageIntelligenceError,formatCompactNumber,createResearchTool2,parseUnifiedSearchTargetSpec,createResolveTargetTool2}from"./shared/chunk-v1gekdxc.js";import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2}from"./shared/chunk-07swxbg6.js";var GUIDE=`# GitHits
1
+ import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-99jxrjze.js";import{EXTERNAL_CONTENT_POSTURE,PKG_VULNS_GUARDRAIL,PKG_INFO_GUARDRAIL,PKG_CHANGELOG_GUARDRAIL,PKG_UPGRADE_REVIEW_GUARDRAIL,CODE_READ_GUARDRAIL,CODE_GREP_GUARDRAIL,SEARCH_GUARDRAIL,KNOWN_REGISTRIES,UnsupportedRegistryError,InvalidPackageSpecError,InvalidArgumentError,parsePackageSpec,isKnownRegistry,LegacyRepositoryRefError,isRepositoryTargetSpec,parseRepositoryTargetSpec,isCanonicalRepositoryUrl,formatRepositoryTarget,formatRepositoryTargetLabel,buildInvalidTargetSpecError,terminalWidth,sanitizeTerminalText,wrapTerminalProse,projectTargetResolution,buildTargetResolutionNotes,buildRetryCandidateLine,buildSuggestedRefsLine,buildResolutionFromRetryCandidates,formatTargetResolutionIdentity,buildSourceCorrespondenceNotes,buildSourceCorrespondenceNote,toCodeNavigationRegistry,AuthRequiredError,mapSessionIdError,mapTermsAcceptanceError,shellQuote,shellQuoteExact,mapVersionRefRecovery,withVersionRefRecovery,mapCodeNavigationError,buildUpdateRequiredError,serviceRequestArgs,MAX_WAIT_TIMEOUT_MS,MAX_DISCOVERY_WAIT_TIMEOUT_MS,MCP_READ_DEFAULT_SPAN,MCP_READ_MAX_SPAN,formatProvenanceRow,formatSourceRow,renderSourceSection,sameRepositoryCommit,resolutionSourceFacts,formatRequestedIndexingExplanation,renderResolutionDetails,formatRequestedProvenance,formatPreparationRow,renderPreparationSection,formatPreparationRetry,indexingWaitMs,withIndexingRetryAction,formatMappedErrorText,READ_ONLY_TOOL_ANNOTATIONS,OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,textResult,errorResult,withErrorHandling,mcpMappedErrorResult,addLocalMcpAuthAction,throwIfCallerCancellation,createGetExampleTool2,colors,colorize,highlight,highlightMatch,highlightRanges,dim,mapPackageIntelligenceError,formatCompactNumber,createResearchTool2,parseUnifiedSearchTargetSpec,createResolveTargetTool2}from"./shared/chunk-j3smtn4t.js";import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2}from"./shared/chunk-3rrwegcq.js";var GUIDE=`# GitHits
2
2
 
3
3
  GitHits answers questions about open-source code, documentation, and packages.
4
4
  Inputs leave this machine: never send private code, local paths, credentials,
@@ -115,7 +115,7 @@ ${EXTERNAL_CONTENT_POSTURE}`:GUIDE}function buildMcpInstructions(options={}){ret
115
115
  ${to}
116
116
  ${patch.slice(secondEnd+1)}`}function lower(value){return value.toLowerCase()}function buildCodeDiffCorrespondenceNotes(envelope){return["from","to"].flatMap((side)=>{const resolution=envelope[side];const note=buildSourceCorrespondenceNote({...envelope.target.kind==="package"?{registry:envelope.target.registry,packageName:envelope.target.name}:{},version:resolution.resolvedVersion,repoUrl:envelope.target.repoUrl,gitRef:resolution.ref,commitSha:resolution.commitSha,releaseCorrespondence:resolution.releaseCorrespondence},{sourceRole:side});return note?[note]:[]})}var MAX_FILE_ROWS=20;var MAX_PATCH_PREVIEW_BYTES=320;var UTF8_ENCODER=new TextEncoder;function formatCodeDiffMcpText(envelope){const lines=[`Code diff: ${formatTarget(envelope)}`,`Requested endpoints: ${safe(envelope.from.requested)} -> ${safe(envelope.to.requested)}`,`Resolved endpoints: ${formatResolution(envelope.from)} -> ${formatResolution(envelope.to)}`,`Scope: ${formatScope(envelope)}`,`Summary: ${formatSummary(envelope)}`,`Content: ${safe(envelope.contentCoverage)}`];for(const note of buildCodeDiffCorrespondenceNotes(envelope))lines.push(...wrapTerminalProse(note));appendWarnings(lines,envelope);const displayTruncatedPreviews=appendFiles(lines,envelope);lines.push(nextAction(envelope,displayTruncatedPreviews));return`${lines.join(`
117
117
  `)}
118
- `}function appendWarnings(lines,envelope){if(envelope.scope.status==="unknown"){lines.push("Warning: legacy unknown scope metadata; treat this diff as repository-wide, so unrelated paths may be included.")}if(!envelope.summary.inventoryComplete){lines.push("Warning: the authoritative file inventory is incomplete.")}if(envelope.summary.unprojectableFiles>0){lines.push(`Warning: ${envelope.summary.unprojectableFiles} matching path(s) could not be projected safely.`)}if(envelope.hasMoreFiles){lines.push(`Warning: more matching files exist than the ${envelope.files.length} returned.`)}if(envelope.contentCoverage==="partial"){lines.push("Warning: requested content is partial.")}else if(envelope.contentCoverage==="failed"){const failure=envelope.contentFailure;const detail=failure?` (${[failure.code,failure.stage,failure.limitKind].filter((value)=>Boolean(value)).map(safe).join(", ")})`:"";lines.push(`Warning: requested content failed after inventory completed${detail}.`)}const byteEscaped=envelope.files.filter((file)=>file.pathEncoding==="byte_escaped").length;if(byteEscaped>0){lines.push(`Warning: ${byteEscaped} path(s) are display-only byte escapes and cannot be reused as exact identities.`)}const filtered=envelope.files.filter((file)=>("contentSafety"in file)&&file.contentSafety.filtered).length;if(filtered>0){lines.push(`Warning: ${filtered} patch(es) were modified for content safety.`)}if(envelope.view==="patch"&&patchIsNotAuthoritative(envelope)){lines.push("Warning: patch content is not presented as authoritative or safely applicable; use inventory/stat evidence or JSON details.")}}function appendFiles(lines,envelope){if(envelope.files.length===0){lines.push(envelope.summary.filesChanged===0?"No changes between the requested endpoints.":"No file rows were returned; inspect the structured JSON evidence.");return 0}lines.push("Files:");const shown=envelope.files.slice(0,MAX_FILE_ROWS);let displayTruncatedPreviews=0;for(const file of shown){if(appendFile(lines,file,envelope.view))displayTruncatedPreviews+=1}if(envelope.files.length>shown.length){lines.push(` ... ${envelope.files.length-shown.length} additional file(s) omitted from compact text; use format=json for the complete list.`)}return displayTruncatedPreviews}function appendFile(lines,file,view){const path=safe(file.path);if(view==="name-only"){lines.push(` ${path}`);return false}const status="status"in file?safe(file.status):"unknown";let detail=`status=${status}`;if(view==="stat"||view==="patch"){const stat=file;detail+=`, content=${safe(stat.contentStatus)}`;if(stat.additions!==undefined||stat.deletions!==undefined){detail+=`, +${stat.additions??0}/-${stat.deletions??0}`}}lines.push(` ${path} [${detail}]`);if(view==="patch"){const patch=file;if(canShowPatch(patch)){const previewLines=formatPatchPreview(patch.patch??"",MAX_PATCH_PREVIEW_BYTES);if(previewLines.lines.length>0){const label=previewLines.truncated?"patch preview (truncated)":"patch preview";lines.push(` ${label}: ${previewLines.lines[0]}`);lines.push(...previewLines.lines.slice(1).map((line)=>` ${line}`))}return previewLines.truncated}else if(patch.contentOmissionReason){lines.push(` patch omitted: ${safe(patch.contentOmissionReason)}`)}}return false}function formatTarget(envelope){if(envelope.target.kind==="package"){return`${safe(envelope.target.registry)}:${safe(envelope.target.name)}`}return safe(envelope.target.repoUrl)}function formatResolution(resolution){const resolved=resolution.resolvedVersion?`, version ${safe(resolution.resolvedVersion)}`:"";return`${safe(resolution.ref)} (${safe(resolution.commitSha)}${resolved})`}function formatScope(envelope){const scope=envelope.scope;const roots=scope.fromSubpath||scope.toSubpath?`, roots ${safe(scope.fromSubpath||"?")} -> ${safe(scope.toSubpath||"?")}`:"";const glob=scope.pathGlob?`, glob ${safe(scope.pathGlob)}`:"";return`${safe(scope.status)}${roots}${glob}`}function formatSummary(envelope){const summary=envelope.summary;return`${summary.filesChanged} changed, ${summary.added} added, ${summary.deleted} deleted, ${summary.modified} modified`}function nextAction(envelope,displayTruncatedPreviews){const target=formatTarget(envelope);const from=safe(envelope.from.requested);const to=safe(envelope.to.requested);const needsScopeRecovery=envelope.scope.status==="unknown"||!envelope.summary.inventoryComplete||envelope.summary.unprojectableFiles>0||envelope.hasMoreFiles;const needsContentRecovery=envelope.contentCoverage==="partial"||envelope.contentCoverage==="failed"||envelope.view==="patch"&&patchIsNotAuthoritative(envelope);if(needsScopeRecovery||needsContentRecovery||displayTruncatedPreviews>0){const recovery=[];if(needsScopeRecovery){recovery.push("narrow `path_glob` or set `max_files` to a larger bound")}if(needsContentRecovery&&displayTruncatedPreviews===0){recovery.push('use view "stat" or format "json" for structured evidence')}if(displayTruncatedPreviews>0){recovery.push(`use format "json" for the full returned patch content (${displayTruncatedPreviews} preview${displayTruncatedPreviews===1?"":"s"} truncated); still subject to max_patch_bytes/backend coverage, and JSON cannot recover backend-omitted content`)}return`Next: call code_diff again with target ${target}, from "${from}", to "${to}"; ${recovery.join("; ")}. Raw diffs do not prove compatibility or upgrade safety.`}const nextView=envelope.view==="name-only"||envelope.view==="name-status"?"stat":envelope.view==="stat"?"patch":"stat";return`Next: call code_diff again with target ${target}, from "${from}", to "${to}", and view "${nextView}" as needed; raw diffs do not prove compatibility or upgrade safety.`}function patchIsNotAuthoritative(envelope){if(!envelope.summary.inventoryComplete||envelope.summary.unprojectableFiles>0||envelope.hasMoreFiles||envelope.contentCoverage!=="complete"){return true}return envelope.files.some((file)=>{if(!("contentSafety"in file))return true;return file.pathEncoding==="byte_escaped"||file.contentSafety.filtered||file.patch===undefined})}function canShowPatch(file){return file.pathEncoding==="utf8"&&file.contentSafety.filtered===false&&file.contentStatus==="patch"&&file.patch!==undefined}function safe(value){return sanitizeTerminalText(value).replace(/\s+/g," ").trim()}function formatPatchPreview(value,maxBytes){const sanitizedLines=value.split(/\r?\n/).map((line)=>sanitizeTerminalText(line));while(sanitizedLines.at(-1)==="")sanitizedLines.pop();const retained=[];let byteLength=0;for(const line of sanitizedLines){const separatorBytes=retained.length>0?1:0;const lineBytes=UTF8_ENCODER.encode(line).byteLength;const available=maxBytes-byteLength-separatorBytes;if(available<lineBytes){const truncated=truncateUtf8(line,Math.max(available,0));if(truncated)retained.push(truncated);return{lines:retained,truncated:true}}retained.push(line);byteLength+=separatorBytes+lineBytes}return{lines:retained,truncated:false}}function truncateUtf8(value,maxBytes){let result="";let byteLength=0;for(const character of value){const characterBytes=UTF8_ENCODER.encode(character).byteLength;if(byteLength+characterBytes>maxBytes)break;result+=character;byteLength+=characterBytes}return result}function parseCodeNavigationTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidArgumentError("Target spec cannot be empty.")}if(isRepositoryTargetSpec(trimmed)){return parseRepositoryTargetSpec(trimmed)}let parsed;try{parsed=parsePackageSpec(trimmed)}catch(error){if(error instanceof InvalidPackageSpecError||error instanceof UnsupportedRegistryError){throw buildInvalidTargetSpecError(trimmed,error.message)}throw error}return{registry:toCodeNavigationRegistry(parsed.registry),packageName:parsed.name,version:parsed.version}}var VIEW_TO_MODE={patch:"patches",stat:"stats","name-only":"inventory","name-status":"inventory"};var MAX_PATH_GLOB_BYTES=1024;var CODE_DIFF_MAX_FILES_MIN=1;var CODE_DIFF_MAX_FILES_MAX=300;var CODE_DIFF_MAX_PATCH_BYTES_MIN=1024;var CODE_DIFF_MAX_PATCH_BYTES_MAX=2097152;function buildCodeDiffMcpParams(input){const target=buildMcpTarget(input.target);const from=normaliseMcpEndpoint(input.from,"from");const to=normaliseMcpEndpoint(input.to,"to");return buildCodeDiffParamsFromParts(target,from,to,input)}function buildCodeDiffParamsFromParts(target,from,to,input){const view=normaliseView(input.view);const pathGlob=normalisePathGlob(input.pathGlob);const maxFiles=normaliseIntegerOption(input.maxFiles,"Maximum files",CODE_DIFF_MAX_FILES_MIN,CODE_DIFF_MAX_FILES_MAX);const maxPatchBytes=normaliseIntegerOption(input.maxPatchBytes,"Maximum patch bytes",CODE_DIFF_MAX_PATCH_BYTES_MIN,CODE_DIFF_MAX_PATCH_BYTES_MAX);if(maxPatchBytes!==undefined&&view!=="patch"){throw invalid("The maximum patch byte limit is valid only when the view is patch.")}const options=buildOptions({maxFiles,maxPatchBytes,pathGlob});const params={target,from,to,mode:VIEW_TO_MODE[view]};if(options!==undefined)params.options=options;return{params,view}}function buildMcpTarget(raw){return buildTargetFromRaw(raw,"mcpTarget")}function buildTargetFromRaw(raw,source){const parsed=parseTarget(raw);if((source==="target"||source==="mcpTarget")&&parsed.version){throw invalid(source==="target"?"Package targets must not include a version; put both versions in `range`.":"Package targets must not include a version; put both versions in the comparison endpoints.")}if(parsed.gitRef!==undefined){throw invalid(source==="target"||source==="repoUrl"?"Repository targets must not include a ref; put both refs in `range`.":"Repository targets must not include a ref; put both refs in the comparison endpoints.")}const hasPackageKeys=Object.hasOwn(parsed,"registry")||Object.hasOwn(parsed,"packageName");const hasRepoKey=Object.hasOwn(parsed,"repoUrl");if(source==="repoUrl"&&hasPackageKeys){throw invalid("Repository target must identify a repository, not a package.")}if(hasPackageKeys&&hasRepoKey){throw invalid("Diff target cannot combine package and repository keys.")}if(hasPackageKeys){if(!Object.hasOwn(parsed,"registry")||!Object.hasOwn(parsed,"packageName")||parsed.registry===undefined||parsed.packageName===undefined){throw invalid("Diff package target must include a registry and name.")}return{registry:parsed.registry,packageName:parsed.packageName}}if(hasRepoKey&&parsed.repoUrl!==undefined){return{repoUrl:parsed.repoUrl}}throw invalid("Diff target must be a package or repository target.")}function parseTarget(raw){try{return parseCodeNavigationTargetSpec(raw)}catch(error){if(error instanceof LegacyRepositoryRefError){throw invalid(error.message)}throw invalid(`Invalid Diff target. Expected an unversioned package target \`<registry>:<name>\` (for example \`npm:express\`; supported registries: ${KNOWN_REGISTRIES.join(", ")}) or an unversioned repository target (for example \`github:expressjs/express\`, \`codeberg:owner/repo\`, \`gitlab:group/subgroup/project\`, or \`launchpad:~owner/+git/repo\` (\`lp:PROJECT\` also accepted)).`)}}function normaliseMcpEndpoint(raw,name){if(typeof raw!=="string"||!raw.trim()){throw invalid(`Diff ${name} endpoint must not be empty.`)}return raw.trim()}function normaliseView(raw){if(raw===undefined)return"patch";if(typeof raw==="string"&&Object.hasOwn(VIEW_TO_MODE,raw)){return raw}throw invalid("Diff view must be patch, stat, name-only, or name-status.")}function normalisePathGlob(raw){if(raw===undefined)return;if(typeof raw!=="string"){throw invalid("Path glob must be a string when supplied.")}const pathGlob=raw;if(pathGlob.length===0){throw invalid("Path glob must not be empty when supplied.")}if(hasInvalidUtf16(pathGlob)){throw invalid("Path glob must be valid UTF-8.")}if(new TextEncoder().encode(pathGlob).byteLength>MAX_PATH_GLOB_BYTES){throw invalid(`Path glob must be at most ${MAX_PATH_GLOB_BYTES} UTF-8 bytes.`)}validatePathGlobGrammar(pathGlob);return pathGlob}function validatePathGlobGrammar(pathGlob){if(pathGlob===":"||pathGlob.startsWith(":(")||pathGlob.startsWith(":/")||pathGlob.startsWith(":!")||pathGlob.startsWith(":^")){throw invalid("Path glob does not support Git pathspec magic; pass one bounded glob.")}const components=[];let component=[];const characters=Array.from(pathGlob);for(let index=0;index<characters.length;index+=1){const character=characters[index];if(character===undefined)break;if(character==="/"){addGlobComponent(components,component);component=[];continue}if(character==="\\"){const escaped=characters[index+1];if(escaped===undefined||escaped==="/"){throw invalid("Path glob backslashes must escape one following non-slash character.")}component.push({char:escaped,escaped:true});index+=1;continue}if(character==="["||character==="]"||character==="{"||character==="}"||character==="!"){throw invalid("Path glob does not support unescaped brackets, braces, or `!`.")}component.push({char:character,escaped:false})}addGlobComponent(components,component);for(const tokens of components){const isGlobstar=tokens.length===2&&tokens.every(({char,escaped})=>char==="*"&&!escaped);if(isGlobstar)continue;let previous;for(const token of tokens){if(previous?.char==="*"&&!previous.escaped&&token.char==="*"&&!token.escaped){throw invalid("Path glob allows adjacent stars only as an exact `**` component.")}previous=token}}}function addGlobComponent(components,component){if(component.length===0){throw invalid("Path glob must use non-empty repository-relative components.")}const literal=component.map(({char})=>char).join("");if(literal==="."||literal===".."){throw invalid("Path glob must not contain `.` or `..` components.")}components.push(component)}function hasInvalidUtf16(value){for(let index=0;index<value.length;index+=1){const code=value.charCodeAt(index);if(code>=55296&&code<=56319){const next=value.charCodeAt(index+1);if(next>=56320&&next<=57343){index+=1;continue}return true}if(code>=56320&&code<=57343)return true}return false}function normaliseIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(!Number.isInteger(value)||value<minimum||value>maximum){throw invalid(`${name} must be an integer from ${minimum} through ${maximum}.`)}return value}function buildOptions(input){if(input.maxFiles===undefined&&input.maxPatchBytes===undefined&&input.pathGlob===undefined){return}const options={};if(input.maxFiles!==undefined)options.maxFiles=input.maxFiles;if(input.maxPatchBytes!==undefined){options.maxPatchBytes=input.maxPatchBytes}if(input.pathGlob!==undefined)options.pathGlob=input.pathGlob;return options}function invalid(message){return new InvalidPackageSpecError(message)}var schema={target:z.string().describe("One unversioned compact target string such as `npm:express`, `github:expressjs/express`, or `launchpad:~owner/+git/repo` (`lp:PROJECT` also accepted). Do not embed a version or ref."),from:z.string().describe("Required starting package version or public repository ref."),to:z.string().describe("Required ending package version or public repository ref."),view:z.enum(["name-status","name-only","stat","patch"]).optional().default("name-status").describe("Projection: `name-status` (default, bounded inventory), `name-only`, `stat`, or `patch`. `max_patch_bytes` is valid only for `patch`."),path_glob:z.string().optional().describe("Optional single non-empty repository-relative glob. Supports literals, `*`, `?`, whole-component `**`, and backslash escapes (for example `lib/**/*.js`); no braces, character classes, `!`, or Git pathspec magic."),max_files:z.number().int().min(1).max(300).optional().describe("Optional relevance-ranked returned-file bound from 1 through 300."),max_patch_bytes:z.number().int().min(1024).max(2097152).optional().describe("Optional aggregate patch-byte bound from 1024 through 2097152; patch view only."),format:z.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, fields are absent from text, or the full returned patch is required. Text patch previews are bounded at 320 UTF-8 bytes; JSON remains subject to backend limits and content coverage.")};var DESCRIPTION='Compare source across exact package versions or public repository refs. Pass an unversioned canonical `target`, with endpoints in `from` and `to`. Package targets return repository-wide diffs: sibling paths may appear, and a bounded result with no package paths does not prove the package unchanged. The default `name-status` view is bounded inventory; use `stat` for magnitude or `patch` for content. In `text`, patch previews are bounded at 320 UTF-8 bytes; use `format: "json"` for the exact full returned patch, still subject to `max_patch_bytes` and backend content coverage. Incomplete, filtered, byte-escaped, omitted, or unavailable patch evidence is not authoritative or safely applicable. Raw diffs never prove compatibility or upgrade safety. Do not include credentials, personal data, private code, or proprietary content in inputs.';function createCodeDiffTool(service){return{name:"code_diff",description:DESCRIPTION,schema,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const build=buildCodeDiffMcpParams({target:args.target,from:args.from,to:args.to,view:args.view??"name-status",pathGlob:args.path_glob,maxFiles:args.max_files,maxPatchBytes:args.max_patch_bytes});const result=await service.codeDiff(build.params,...serviceRequestArgs(context?.signal));const payload=buildCodeDiffSuccessPayload(result,{target:build.params.target,view:build.view});if(isTextFormat(args.format)){return textResult(formatCodeDiffMcpText(payload))}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);return mcpMappedErrorResult(mapCodeNavigationError(error),context,args.format,{recovery:{syntax:"mcp",tool:"code_diff",args}})}}}}function isTextFormat(format){return format===undefined||format==="text"}import{z as z2}from"zod";function grepPreparationReason(reason){switch(reason){case"repository_indexing":return"repository is being indexed";case"documentation_publishing":return"documentation is being prepared";case"no_grep_scopes":return"no searchable source or documentation is available";case"repository_not_found":return"repository was not found";case"package_not_found":return"package was not found";case"package_source_not_found":return"package source was not found";case"repository_ref_not_found":return"repository ref was not found";case"ref_not_found":return"repository ref was not found";case"package_source_ref_not_found":return"package source ref was not found";case"package_version_not_found":return"package source ref could not be resolved";case"package_version_unresolved":return"package version could not be resolved";case"repository_ref_ambiguous":return"repository ref is ambiguous";case"repository_legally_blocked":return"repository access is legally blocked";case"repository_resolution_error":return"repository resolution failed";case"repository_unavailable":return"repository is unavailable";case"package_source_unsupported":return"package source is unsupported";case"package_security_removed":return"package source was removed for security reasons";case"package_scope_unavailable":return"package source scope is unavailable";case"package_release_unusable":return"package release is unusable";case"no_site_pages":return"no searchable documentation pages are available";case"site_ambiguous":return"documentation site is ambiguous";case"site_not_indexed":return"documentation site is not indexed";case"site_no_docs":return"documentation site has no searchable pages";case"site_redirected":return"documentation site has moved";case"site_failed":return"documentation site preparation failed";case"site_v6_required":return"documentation site requires a publication format update";case"documentation_site_not_admitted":return"documentation site has not been admitted";case"documentation_source_resolution_required":return"documentation source must be resolved";case"documentation_site_no_docs":return"documentation site has no searchable pages";case"documentation_site_identity_blocked":return"documentation site identity needs resolution";case"documentation_site_failed":return"documentation site preparation failed";case"documentation_discovery":return"documentation sources are being discovered";case"documentation_unavailable":return"documentation is unavailable";case"starting_url_pending":return"requested documentation URL is being prepared";case"starting_url_missed_at_cap":return"requested documentation URL was not reached before the crawl limit";case"starting_url_absent_from_current_corpus":return"requested documentation URL is absent from the current corpus";default:return reason}}var MAX_TARGETS=20;var MAX_PATTERN_BYTES=200;var MAX_PATH_SELECTORS=1000;class InvalidGrepRequestError extends InvalidArgumentError{field;constructor(field,message){super(message);this.field=field;this.name="InvalidGrepRequestError"}}function buildGrepParams(input){if(!isRecord(input)){throw invalid2("request","A grep request is required.")}if(!Array.isArray(input.targets)||input.targets.length===0){throw invalid2("targets","`targets` must contain at least one target.")}if(input.targets.length>MAX_TARGETS){throw invalid2("targets",`Targets may contain at most ${MAX_TARGETS} entries.`)}if(typeof input.pattern!=="string"){throw invalid2("pattern","`pattern` must be a string.")}validateUnicode(input.pattern,"pattern","`pattern` must contain valid Unicode.");if(input.pattern.includes("\x00")){throw invalid2("pattern","`pattern` cannot contain NUL.")}const patternBytes=Buffer.byteLength(input.pattern,"utf8");if(patternBytes<1||patternBytes>MAX_PATTERN_BYTES){throw invalid2("pattern",`Pattern must be 1 to ${MAX_PATTERN_BYTES} UTF-8 bytes.`)}if(typeof input.includeDetailedFields!=="boolean"){throw invalid2("includeDetailedFields","`includeDetailedFields` must be a boolean.")}const patternType=normalizePatternType(input.patternType);const ignoreCase=normalizeBoolean(input.ignoreCase,"ignoreCase");const contextLinesBefore=normalizeGrepContextLines(input.contextLinesBefore,"contextLinesBefore");const contextLinesAfter=normalizeGrepContextLines(input.contextLinesAfter,"contextLinesAfter");const maxMatches=normalizeInteger(input.maxMatches,"maxMatches",1,1000);const waitTimeoutMs=normalizeInteger(input.waitTimeoutMs,"waitTimeoutMs",0,300000);const cursor=normalizeCursor(input.cursor);const targets=input.targets.map((targetInput,index)=>{const field=`targets[${index}]`;if(!isRecord(targetInput)||typeof targetInput.target!=="string"){throw invalid2(`${field}.target`,"Each target must include a string `target`.")}const target=targetInput.target;validateUnicode(target,`${field}.target`,"Target must contain valid Unicode.");if(target.trim().length===0){throw invalid2(`${field}.target`,"Target cannot be blank.")}const corpus=normalizeCorpus(targetInput.corpus,`${field}.corpus`);const pathSelectors=normalizePathSelectors(targetInput.pathSelectors,`${field}.pathSelectors`);if(isGrepSiteTarget(target)){if(targetInput.corpus!==undefined){throw invalid2(`${field}.corpus`,"Corpus cannot be used with a site target.")}if(pathSelectors.length>0){throw invalid2(`${field}.pathSelectors`,"Path selectors cannot be used with a site target.")}return{target}}return{target,corpus:corpus??"ALL",allowUnscoped:true,...pathSelectors.length>0?{pathSelectors}:{}}});return{targets,pattern:input.pattern,patternType,caseSensitive:!(ignoreCase??false),contextLinesBefore:contextLinesBefore??0,contextLinesAfter:contextLinesAfter??0,...maxMatches!==undefined?{maxMatches}:{},...cursor!==undefined?{cursor}:{},waitTimeoutMs:waitTimeoutMs??(cursor?0:DEFAULT_WAIT_TIMEOUT_MS),includeDetailedFields:input.includeDetailedFields}}function normalizePatternType(value){if(value===undefined||value==="regex")return"REGEX";if(value==="literal")return"LITERAL";throw invalid2("patternType","`patternType` must be `literal` or `regex`.")}function normalizeCorpus(value,field){if(value===undefined)return;if(typeof value!=="string"){throw invalid2(field,"Corpus must be `source`, `documentation`, or `all`.")}const normalized=value.toUpperCase();if(normalized==="SOURCE"||normalized==="DOCUMENTATION"||normalized==="ALL"){return normalized}throw invalid2(field,"Corpus must be `source`, `documentation`, or `all`.")}function normalizePathSelectors(value,field){if(value===undefined)return[];if(!Array.isArray(value)){throw invalid2(field,"Path selectors must be an array.")}if(value.length===0)return[];if(value.length>MAX_PATH_SELECTORS){throw invalid2(field,`A target may contain at most ${MAX_PATH_SELECTORS} path selectors.`)}return value.map((selector,index)=>{const itemField=`${field}[${index}]`;if(!isRecord(selector)){throw invalid2(itemField,"A path selector must be an object.")}const kind=normalizeSelectorKind(selector.kind,`${itemField}.kind`);if(typeof selector.value!=="string"){throw invalid2(`${itemField}.value`,"Selector value must be a string.")}const selectorValue=selector.value;validateUnicode(selectorValue,`${itemField}.value`,"Selector values must contain valid Unicode.");if(selectorValue.trim().length===0){throw invalid2(`${itemField}.value`,"Selector values cannot be blank.")}if(selectorValue.includes("\x00")){throw invalid2(`${itemField}.value`,"Selector values cannot contain NUL.")}return{kind,value:selectorValue}})}function normalizeSelectorKind(value,field){if(typeof value!=="string"){throw invalid2(field,"Selector kind must be `exact`, `prefix`, or `glob`.")}const normalized=value.toUpperCase();if(normalized==="EXACT"||normalized==="PREFIX"||normalized==="GLOB"){return normalized}throw invalid2(field,"Selector kind must be `exact`, `prefix`, or `glob`.")}function normalizeBoolean(value,field){if(value===undefined)return;if(typeof value!=="boolean"){throw invalid2(field,`${field} must be a boolean.`)}return value}function normalizeInteger(value,field,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isSafeInteger(value)||value<minimum||value>maximum){throw invalid2(field,`${field} must be a safe integer from ${minimum} to ${maximum}.`)}return value}function normalizeGrepContextLines(value,field){return normalizeInteger(value,field,0,10)}function normalizeCursor(value){if(value===undefined)return;if(typeof value!=="string"){throw invalid2("cursor","`cursor` must be a string.")}return value.trim().length===0?undefined:value}function isGrepSiteTarget(target){return target.trim().toLowerCase().startsWith("site:")}function validateUnicode(value,field,message){if(hasLoneSurrogate(value))throw invalid2(field,message)}function hasLoneSurrogate(value){for(let index=0;index<value.length;index+=1){const codeUnit=value.charCodeAt(index);if(codeUnit>=55296&&codeUnit<=56319){const nextCodeUnit=value.charCodeAt(index+1);if(!(nextCodeUnit>=56320&&nextCodeUnit<=57343))return true;index+=1}else if(codeUnit>=56320&&codeUnit<=57343){return true}}return false}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function invalid2(field,message){return new InvalidGrepRequestError(field,message)}function mapGrepError(error){const sessionError=mapSessionIdError(error);if(sessionError)return sessionError;const terms=mapTermsAcceptanceError(error);if(terms)return terms;if(error instanceof ClientUpdateRequiredError)return buildUpdateRequiredError(error.reason,error.currentVersion);if(error instanceof AuthenticationError2||error instanceof AuthRequiredError)return{code:"AUTH_REQUIRED",message:error.message,retryable:false,details:{authSource:error instanceof AuthenticationError2?error.source:"local"}};if(error instanceof InvalidGrepRequestError)return{code:"INVALID_ARGUMENT",message:error.message,retryable:false};if(error instanceof GrepAccessError2)return{code:"ACCESS_DENIED",message:error.message,retryable:false};if(error instanceof GrepNetworkError2)return{code:"NETWORK",message:error.message,retryable:true};if(error instanceof MalformedGrepResponseError2)return{code:"PROTOCOL_ERROR",message:error.message,retryable:false};if(error instanceof GrepBackendError2){const code=error.graphqlCode==="TIMEOUT"?"TIMEOUT":error.status===429?"RATE_LIMITED":"BACKEND_ERROR";return{code,message:error.message,retryable:error.retryable??(code==="TIMEOUT"||code==="RATE_LIMITED"||error.status!==undefined&&error.status>=500),details:{...error.status!==undefined?{status:error.status}:{},...error.graphqlCode?{graphqlCode:error.graphqlCode}:{}}}}if(error instanceof GrepGraphQLError2){const ext=error.extensions;const recovery=parseVersionRefRecovery(ext);if(recovery)return mapVersionRefRecovery(error.message,recovery);const graphqlCode=typeof ext.code==="string"?ext.code:undefined;const code=graphqlCode==="GREP_TARGET_PREPARATION_REQUIRED"?preparationErrorCode(ext.target_issues,ext.retryable):graphqlCode==="GREP_CURSOR_INVALID"||graphqlCode==="VALIDATION_ERROR"||graphqlCode==="INVALID_ARGUMENT"?"INVALID_ARGUMENT":graphqlCode==="GREP_BACKEND_PROTOCOL_ERROR"?"PROTOCOL_ERROR":graphqlCode==="TIMEOUT"?"TIMEOUT":graphqlCode==="RATE_LIMITED"?"RATE_LIMITED":"BACKEND_ERROR";const details={graphqlCode};if(Array.isArray(ext.target_issues)){details.targetIssues=ext.target_issues.slice(0,20).filter(isRecord2).map((issue)=>Object.fromEntries(Object.entries(issue).filter(([key])=>PUBLIC_ISSUE_KEYS.has(key))));const hints=details.targetIssues.flatMap((issue,index)=>{const target=typeof issue.target==="string"?issue.target:typeof issue.input_index==="number"?`Input ${issue.input_index}`:undefined;const translatedReason=typeof issue.reason==="string"?grepPreparationReason(issue.reason):undefined;const reason=translatedReason&&translatedReason!==issue.reason?translatedReason:code==="INDEXING"?"target is being prepared":"target is unavailable";const message=typeof issue.message==="string"?typeof issue.reason==="string"&&issue.message.endsWith(`Reason: ${issue.reason}.`)?reason:issue.message:undefined;const diagnostic=code==="INDEXING"?reason:graphqlCode==="GREP_TARGET_PREPARATION_REQUIRED"&&index===0?undefined:message!==undefined?typeof issue.message==="string"&&error.message.includes(issue.message)?undefined:message:reason;const path=typeof issue.file_path==="string"?`path ${issue.file_path}`:undefined;const text=[diagnostic,path].filter(Boolean).join("; ");return text?[`${target?`${target}: `:""}${text}`]:[]});if(hints.length)details.hint=hints.join(`
118
+ `}function appendWarnings(lines,envelope){if(envelope.scope.status==="unknown"){lines.push("Warning: legacy unknown scope metadata; treat this diff as repository-wide, so unrelated paths may be included.")}if(!envelope.summary.inventoryComplete){lines.push("Warning: the authoritative file inventory is incomplete.")}if(envelope.summary.unprojectableFiles>0){lines.push(`Warning: ${envelope.summary.unprojectableFiles} matching path(s) could not be projected safely.`)}if(envelope.hasMoreFiles){lines.push(`Warning: more matching files exist than the ${envelope.files.length} returned.`)}if(envelope.contentCoverage==="partial"){lines.push("Warning: requested content is partial.")}else if(envelope.contentCoverage==="failed"){const failure=envelope.contentFailure;const detail=failure?` (${[failure.code,failure.stage,failure.limitKind].filter((value)=>Boolean(value)).map(safe).join(", ")})`:"";lines.push(`Warning: requested content failed after inventory completed${detail}.`)}const byteEscaped=envelope.files.filter((file)=>file.pathEncoding==="byte_escaped").length;if(byteEscaped>0){lines.push(`Warning: ${byteEscaped} path(s) are display-only byte escapes and cannot be reused as exact identities.`)}const filtered=envelope.files.filter((file)=>("contentSafety"in file)&&file.contentSafety.filtered).length;if(filtered>0){lines.push(`Warning: ${filtered} patch(es) were modified for content safety.`)}if(envelope.view==="patch"&&patchIsNotAuthoritative(envelope)){lines.push("Warning: patch content is not presented as authoritative or safely applicable; use inventory/stat evidence or JSON details.")}}function appendFiles(lines,envelope){if(envelope.files.length===0){lines.push(envelope.summary.filesChanged===0?"No changes between the requested endpoints.":"No file rows were returned; inspect the structured JSON evidence.");return 0}lines.push("Files:");const shown=envelope.files.slice(0,MAX_FILE_ROWS);let displayTruncatedPreviews=0;for(const file of shown){if(appendFile(lines,file,envelope.view))displayTruncatedPreviews+=1}if(envelope.files.length>shown.length){lines.push(` ... ${envelope.files.length-shown.length} additional file(s) omitted from compact text; use format=json for the complete list.`)}return displayTruncatedPreviews}function appendFile(lines,file,view){const path=safe(file.path);if(view==="name-only"){lines.push(` ${path}`);return false}const status="status"in file?safe(file.status):"unknown";let detail=`status=${status}`;if(view==="stat"||view==="patch"){const stat=file;detail+=`, content=${safe(stat.contentStatus)}`;if(stat.additions!==undefined||stat.deletions!==undefined){detail+=`, +${stat.additions??0}/-${stat.deletions??0}`}}lines.push(` ${path} [${detail}]`);if(view==="patch"){const patch=file;if(canShowPatch(patch)){const previewLines=formatPatchPreview(patch.patch??"",MAX_PATCH_PREVIEW_BYTES);if(previewLines.lines.length>0){const label=previewLines.truncated?"patch preview (truncated)":"patch preview";lines.push(` ${label}: ${previewLines.lines[0]}`);lines.push(...previewLines.lines.slice(1).map((line)=>` ${line}`))}return previewLines.truncated}else if(patch.contentOmissionReason){lines.push(` patch omitted: ${safe(patch.contentOmissionReason)}`)}}return false}function formatTarget(envelope){if(envelope.target.kind==="package"){return`${safe(envelope.target.registry)}:${safe(envelope.target.name)}`}return safe(envelope.target.repoUrl)}function formatResolution(resolution){const resolved=resolution.resolvedVersion?`, version ${safe(resolution.resolvedVersion)}`:"";return`${safe(resolution.ref)} (${safe(resolution.commitSha)}${resolved})`}function formatScope(envelope){const scope=envelope.scope;const roots=scope.fromSubpath||scope.toSubpath?`, roots ${safe(scope.fromSubpath||"?")} -> ${safe(scope.toSubpath||"?")}`:"";const glob=scope.pathGlob?`, glob ${safe(scope.pathGlob)}`:"";return`${safe(scope.status)}${roots}${glob}`}function formatSummary(envelope){const summary=envelope.summary;return`${summary.filesChanged} changed, ${summary.added} added, ${summary.deleted} deleted, ${summary.modified} modified`}function nextAction(envelope,displayTruncatedPreviews){const target=formatTarget(envelope);const from=safe(envelope.from.requested);const to=safe(envelope.to.requested);const needsScopeRecovery=envelope.scope.status==="unknown"||!envelope.summary.inventoryComplete||envelope.summary.unprojectableFiles>0||envelope.hasMoreFiles;const needsContentRecovery=envelope.contentCoverage==="partial"||envelope.contentCoverage==="failed"||envelope.view==="patch"&&patchIsNotAuthoritative(envelope);if(needsScopeRecovery||needsContentRecovery||displayTruncatedPreviews>0){const recovery=[];if(needsScopeRecovery){recovery.push("narrow `path_glob` or set `max_files` to a larger bound")}if(needsContentRecovery&&displayTruncatedPreviews===0){recovery.push('use view "stat" or format "json" for structured evidence')}if(displayTruncatedPreviews>0){recovery.push(`use format "json" for the full returned patch content (${displayTruncatedPreviews} preview${displayTruncatedPreviews===1?"":"s"} truncated); still subject to max_patch_bytes/backend coverage, and JSON cannot recover backend-omitted content`)}return`Next: call code_diff again with target ${target}, from "${from}", to "${to}"; ${recovery.join("; ")}. Raw diffs do not prove compatibility or upgrade safety.`}const nextView=envelope.view==="name-only"||envelope.view==="name-status"?"stat":envelope.view==="stat"?"patch":"stat";return`Next: call code_diff again with target ${target}, from "${from}", to "${to}", and view "${nextView}" as needed; raw diffs do not prove compatibility or upgrade safety.`}function patchIsNotAuthoritative(envelope){if(!envelope.summary.inventoryComplete||envelope.summary.unprojectableFiles>0||envelope.hasMoreFiles||envelope.contentCoverage!=="complete"){return true}return envelope.files.some((file)=>{if(!("contentSafety"in file))return true;return file.pathEncoding==="byte_escaped"||file.contentSafety.filtered||file.patch===undefined})}function canShowPatch(file){return file.pathEncoding==="utf8"&&file.contentSafety.filtered===false&&file.contentStatus==="patch"&&file.patch!==undefined}function safe(value){return sanitizeTerminalText(value).replace(/\s+/g," ").trim()}function formatPatchPreview(value,maxBytes){const sanitizedLines=value.split(/\r?\n/).map((line)=>sanitizeTerminalText(line));while(sanitizedLines.at(-1)==="")sanitizedLines.pop();const retained=[];let byteLength=0;for(const line of sanitizedLines){const separatorBytes=retained.length>0?1:0;const lineBytes=UTF8_ENCODER.encode(line).byteLength;const available=maxBytes-byteLength-separatorBytes;if(available<lineBytes){const truncated=truncateUtf8(line,Math.max(available,0));if(truncated)retained.push(truncated);return{lines:retained,truncated:true}}retained.push(line);byteLength+=separatorBytes+lineBytes}return{lines:retained,truncated:false}}function truncateUtf8(value,maxBytes){let result="";let byteLength=0;for(const character of value){const characterBytes=UTF8_ENCODER.encode(character).byteLength;if(byteLength+characterBytes>maxBytes)break;result+=character;byteLength+=characterBytes}return result}function parseCodeNavigationTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidArgumentError("Target spec cannot be empty.")}if(isRepositoryTargetSpec(trimmed)){return parseRepositoryTargetSpec(trimmed)}let parsed;try{parsed=parsePackageSpec(trimmed)}catch(error){if(error instanceof InvalidPackageSpecError||error instanceof UnsupportedRegistryError){throw buildInvalidTargetSpecError(trimmed,error.message)}throw error}return{registry:toCodeNavigationRegistry(parsed.registry),packageName:parsed.name,version:parsed.version}}var VIEW_TO_MODE={patch:"patches",stat:"stats","name-only":"inventory","name-status":"inventory"};var MAX_PATH_GLOB_BYTES=1024;var CODE_DIFF_MAX_FILES_MIN=1;var CODE_DIFF_MAX_FILES_MAX=300;var CODE_DIFF_MAX_PATCH_BYTES_MIN=1024;var CODE_DIFF_MAX_PATCH_BYTES_MAX=2097152;function buildCodeDiffMcpParams(input){const target=buildMcpTarget(input.target);const from=normaliseMcpEndpoint(input.from,"from");const to=normaliseMcpEndpoint(input.to,"to");return buildCodeDiffParamsFromParts(target,from,to,input)}function buildCodeDiffParamsFromParts(target,from,to,input){const view=normaliseView(input.view);const pathGlob=normalisePathGlob(input.pathGlob);const maxFiles=normaliseIntegerOption(input.maxFiles,"Maximum files",CODE_DIFF_MAX_FILES_MIN,CODE_DIFF_MAX_FILES_MAX);const maxPatchBytes=normaliseIntegerOption(input.maxPatchBytes,"Maximum patch bytes",CODE_DIFF_MAX_PATCH_BYTES_MIN,CODE_DIFF_MAX_PATCH_BYTES_MAX);if(maxPatchBytes!==undefined&&view!=="patch"){throw invalid("The maximum patch byte limit is valid only when the view is patch.")}const options=buildOptions({maxFiles,maxPatchBytes,pathGlob});const params={target,from,to,mode:VIEW_TO_MODE[view]};if(options!==undefined)params.options=options;return{params,view}}function buildMcpTarget(raw){return buildTargetFromRaw(raw,"mcpTarget")}function buildTargetFromRaw(raw,source){const parsed=parseTarget(raw);if((source==="target"||source==="mcpTarget")&&parsed.version){throw invalid(source==="target"?"Package targets must not include a version; put both versions in `range`.":"Package targets must not include a version; put both versions in the comparison endpoints.")}if(parsed.gitRef!==undefined){throw invalid(source==="target"||source==="repoUrl"?"Repository targets must not include a ref; put both refs in `range`.":"Repository targets must not include a ref; put both refs in the comparison endpoints.")}const hasPackageKeys=Object.hasOwn(parsed,"registry")||Object.hasOwn(parsed,"packageName");const hasRepoKey=Object.hasOwn(parsed,"repoUrl");if(source==="repoUrl"&&hasPackageKeys){throw invalid("Repository target must identify a repository, not a package.")}if(hasPackageKeys&&hasRepoKey){throw invalid("Diff target cannot combine package and repository keys.")}if(hasPackageKeys){if(!Object.hasOwn(parsed,"registry")||!Object.hasOwn(parsed,"packageName")||parsed.registry===undefined||parsed.packageName===undefined){throw invalid("Diff package target must include a registry and name.")}return{registry:parsed.registry,packageName:parsed.packageName}}if(hasRepoKey&&parsed.repoUrl!==undefined){return{repoUrl:parsed.repoUrl}}throw invalid("Diff target must be a package or repository target.")}function parseTarget(raw){try{return parseCodeNavigationTargetSpec(raw)}catch(error){if(error instanceof LegacyRepositoryRefError){throw invalid(error.message)}throw invalid(`Invalid Diff target. Expected an unversioned package target \`<registry>:<name>\` (for example \`npm:express\`; supported registries: ${KNOWN_REGISTRIES.join(", ")}) or an unversioned repository target (for example \`github:expressjs/express\`, \`codeberg:owner/repo\`, \`gitlab:group/subgroup/project\`, or \`launchpad:~owner/+git/repo\` (\`lp:PROJECT\` also accepted)).`)}}function normaliseMcpEndpoint(raw,name){if(typeof raw!=="string"||!raw.trim()){throw invalid(`Diff ${name} endpoint must not be empty.`)}return raw.trim()}function normaliseView(raw){if(raw===undefined)return"patch";if(typeof raw==="string"&&Object.hasOwn(VIEW_TO_MODE,raw)){return raw}throw invalid("Diff view must be patch, stat, name-only, or name-status.")}function normalisePathGlob(raw){if(raw===undefined)return;if(typeof raw!=="string"){throw invalid("Path glob must be a string when supplied.")}const pathGlob=raw;if(pathGlob.length===0){throw invalid("Path glob must not be empty when supplied.")}if(hasInvalidUtf16(pathGlob)){throw invalid("Path glob must be valid UTF-8.")}if(new TextEncoder().encode(pathGlob).byteLength>MAX_PATH_GLOB_BYTES){throw invalid(`Path glob must be at most ${MAX_PATH_GLOB_BYTES} UTF-8 bytes.`)}validatePathGlobGrammar(pathGlob);return pathGlob}function validatePathGlobGrammar(pathGlob){if(pathGlob===":"||pathGlob.startsWith(":(")||pathGlob.startsWith(":/")||pathGlob.startsWith(":!")||pathGlob.startsWith(":^")){throw invalid("Path glob does not support Git pathspec magic; pass one bounded glob.")}const components=[];let component=[];const characters=Array.from(pathGlob);for(let index=0;index<characters.length;index+=1){const character=characters[index];if(character===undefined)break;if(character==="/"){addGlobComponent(components,component);component=[];continue}if(character==="\\"){const escaped=characters[index+1];if(escaped===undefined||escaped==="/"){throw invalid("Path glob backslashes must escape one following non-slash character.")}component.push({char:escaped,escaped:true});index+=1;continue}if(character==="["||character==="]"||character==="{"||character==="}"||character==="!"){throw invalid("Path glob does not support unescaped brackets, braces, or `!`.")}component.push({char:character,escaped:false})}addGlobComponent(components,component);for(const tokens of components){const isGlobstar=tokens.length===2&&tokens.every(({char,escaped})=>char==="*"&&!escaped);if(isGlobstar)continue;let previous;for(const token of tokens){if(previous?.char==="*"&&!previous.escaped&&token.char==="*"&&!token.escaped){throw invalid("Path glob allows adjacent stars only as an exact `**` component.")}previous=token}}}function addGlobComponent(components,component){if(component.length===0){throw invalid("Path glob must use non-empty repository-relative components.")}const literal=component.map(({char})=>char).join("");if(literal==="."||literal===".."){throw invalid("Path glob must not contain `.` or `..` components.")}components.push(component)}function hasInvalidUtf16(value){for(let index=0;index<value.length;index+=1){const code=value.charCodeAt(index);if(code>=55296&&code<=56319){const next=value.charCodeAt(index+1);if(next>=56320&&next<=57343){index+=1;continue}return true}if(code>=56320&&code<=57343)return true}return false}function normaliseIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(!Number.isInteger(value)||value<minimum||value>maximum){throw invalid(`${name} must be an integer from ${minimum} through ${maximum}.`)}return value}function buildOptions(input){if(input.maxFiles===undefined&&input.maxPatchBytes===undefined&&input.pathGlob===undefined){return}const options={};if(input.maxFiles!==undefined)options.maxFiles=input.maxFiles;if(input.maxPatchBytes!==undefined){options.maxPatchBytes=input.maxPatchBytes}if(input.pathGlob!==undefined)options.pathGlob=input.pathGlob;return options}function invalid(message){return new InvalidPackageSpecError(message)}var schema={target:z.string().describe("One unversioned compact target string such as `npm:express`, `github:expressjs/express`, or `launchpad:~owner/+git/repo` (`lp:PROJECT` also accepted). Do not embed a version or ref."),from:z.string().describe("Required starting package version or public repository ref."),to:z.string().describe("Required ending package version or public repository ref."),view:z.enum(["name-status","name-only","stat","patch"]).optional().default("name-status").describe("Projection: `name-status` (default, bounded inventory), `name-only`, `stat`, or `patch`. `max_patch_bytes` is valid only for `patch`."),path_glob:z.string().optional().describe("Optional single non-empty repository-relative glob. Supports literals, `*`, `?`, whole-component `**`, and backslash escapes (for example `lib/**/*.js`); no braces, character classes, `!`, or Git pathspec magic."),max_files:z.number().int().min(1).max(300).optional().describe("Optional relevance-ranked returned-file bound from 1 through 300."),max_patch_bytes:z.number().int().min(1024).max(2097152).optional().describe("Optional aggregate patch-byte bound from 1024 through 2097152; patch view only."),format:z.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, fields are absent from text, or the full returned patch is required. Text patch previews are bounded at 320 UTF-8 bytes; JSON remains subject to backend limits and content coverage.")};var DESCRIPTION='Compare source across exact package versions or public repository refs. Pass an unversioned canonical `target`, with endpoints in `from` and `to`. Package targets return repository-wide diffs: sibling paths may appear, and a bounded result with no package paths does not prove the package unchanged. The default `name-status` view is bounded inventory; use `stat` for magnitude or `patch` for content. In `text`, patch previews are bounded at 320 UTF-8 bytes; use `format: "json"` for the exact full returned patch, still subject to `max_patch_bytes` and backend content coverage. Incomplete, filtered, byte-escaped, omitted, or unavailable patch evidence is not authoritative or safely applicable. Raw diffs never prove compatibility or upgrade safety. Do not include credentials, personal data, private code, or proprietary content in inputs.';function createCodeDiffTool(service){return{name:"code_diff",description:DESCRIPTION,schema,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const build=buildCodeDiffMcpParams({target:args.target,from:args.from,to:args.to,view:args.view??"name-status",pathGlob:args.path_glob,maxFiles:args.max_files,maxPatchBytes:args.max_patch_bytes});const result=await service.codeDiff(build.params,...serviceRequestArgs(context?.signal));const payload=buildCodeDiffSuccessPayload(result,{target:build.params.target,view:build.view});if(isTextFormat(args.format)){return textResult(formatCodeDiffMcpText(payload))}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);return mcpMappedErrorResult(mapCodeNavigationError(error),context,args.format,{recovery:{syntax:"mcp",tool:"code_diff",args}})}}}}function isTextFormat(format){return format===undefined||format==="text"}import{z as z2}from"zod";function grepPreparationReason(reason){switch(reason){case"repository_indexing":return"repository is being indexed";case"documentation_publishing":return"documentation is being prepared";case"no_grep_scopes":return"no searchable source or documentation is available";case"repository_not_found":return"repository was not found";case"package_not_found":return"package was not found";case"package_source_not_found":return"package source was not found";case"repository_ref_not_found":return"repository ref was not found";case"ref_not_found":return"repository ref was not found";case"package_source_ref_not_found":return"package source ref was not found";case"package_version_not_found":return"package source ref could not be resolved";case"package_version_unresolved":return"package version could not be resolved";case"repository_ref_ambiguous":return"repository ref is ambiguous";case"repository_legally_blocked":return"repository access is legally blocked";case"repository_resolution_error":return"repository resolution failed";case"repository_unavailable":return"repository is unavailable";case"package_source_unsupported":return"package source is unsupported";case"package_security_removed":return"package source was removed for security reasons";case"package_scope_unavailable":return"package source scope is unavailable";case"package_release_unusable":return"package release is unusable";case"no_site_pages":return"no searchable documentation pages are available";case"site_ambiguous":return"documentation site is ambiguous";case"site_not_indexed":return"documentation site is not indexed";case"site_no_docs":return"documentation site has no searchable pages";case"site_redirected":return"documentation site has moved";case"site_failed":return"documentation site preparation failed";case"site_v6_required":return"documentation site requires a publication format update";case"documentation_site_not_admitted":return"documentation site has not been admitted";case"documentation_source_resolution_required":return"documentation source must be resolved";case"documentation_site_no_docs":return"documentation site has no searchable pages";case"documentation_site_identity_blocked":return"documentation site identity needs resolution";case"documentation_site_failed":return"documentation site preparation failed";case"documentation_discovery":return"documentation sources are being discovered";case"documentation_unavailable":return"documentation is unavailable";case"starting_url_pending":return"requested documentation URL is being prepared";case"starting_url_missed_at_cap":return"requested documentation URL was not reached before the crawl limit";case"starting_url_absent_from_current_corpus":return"requested documentation URL is absent from the current corpus";default:return reason}}var GREP_CONTEXT_MAX=10;var MAX_TARGETS=20;var MAX_PATTERN_BYTES=200;var MAX_PATH_SELECTORS=1000;class InvalidGrepRequestError extends InvalidArgumentError{field;constructor(field,message){super(message);this.field=field;this.name="InvalidGrepRequestError"}}function buildGrepParams(input){if(!isRecord(input)){throw invalid2("request","A grep request is required.")}if(!Array.isArray(input.targets)||input.targets.length===0){throw invalid2("targets","`targets` must contain at least one target.")}if(input.targets.length>MAX_TARGETS){throw invalid2("targets",`Targets may contain at most ${MAX_TARGETS} entries.`)}if(typeof input.pattern!=="string"){throw invalid2("pattern","`pattern` must be a string.")}validateUnicode(input.pattern,"pattern","`pattern` must contain valid Unicode.");if(input.pattern.includes("\x00")){throw invalid2("pattern","`pattern` cannot contain NUL.")}const patternBytes=Buffer.byteLength(input.pattern,"utf8");if(patternBytes<1||patternBytes>MAX_PATTERN_BYTES){throw invalid2("pattern",`Pattern must be 1 to ${MAX_PATTERN_BYTES} UTF-8 bytes.`)}if(typeof input.includeDetailedFields!=="boolean"){throw invalid2("includeDetailedFields","`includeDetailedFields` must be a boolean.")}const patternType=normalizePatternType(input.patternType);const ignoreCase=normalizeBoolean(input.ignoreCase,"ignoreCase");const contextLinesBefore=normalizeGrepContextLines(input.contextLinesBefore,"contextLinesBefore");const contextLinesAfter=normalizeGrepContextLines(input.contextLinesAfter,"contextLinesAfter");const maxMatches=normalizeInteger(input.maxMatches,"maxMatches",1,1000);const waitTimeoutMs=normalizeInteger(input.waitTimeoutMs,"waitTimeoutMs",0,300000);const cursor=normalizeCursor(input.cursor);const targets=input.targets.map((targetInput,index)=>{const field=`targets[${index}]`;if(!isRecord(targetInput)||typeof targetInput.target!=="string"){throw invalid2(`${field}.target`,"Each target must include a string `target`.")}const target=targetInput.target;validateUnicode(target,`${field}.target`,"Target must contain valid Unicode.");if(target.trim().length===0){throw invalid2(`${field}.target`,"Target cannot be blank.")}const corpus=normalizeCorpus(targetInput.corpus,`${field}.corpus`);const pathSelectors=normalizePathSelectors(targetInput.pathSelectors,`${field}.pathSelectors`);if(isGrepSiteTarget(target)){if(targetInput.corpus!==undefined){throw invalid2(`${field}.corpus`,"Corpus cannot be used with a site target.")}if(pathSelectors.length>0){throw invalid2(`${field}.pathSelectors`,"Path selectors cannot be used with a site target.")}return{target}}return{target,corpus:corpus??"ALL",allowUnscoped:true,...pathSelectors.length>0?{pathSelectors}:{}}});return{targets,pattern:input.pattern,patternType,caseSensitive:!(ignoreCase??false),contextLinesBefore:contextLinesBefore??0,contextLinesAfter:contextLinesAfter??0,...maxMatches!==undefined?{maxMatches}:{},...cursor!==undefined?{cursor}:{},waitTimeoutMs:waitTimeoutMs??(cursor?0:DEFAULT_WAIT_TIMEOUT_MS),includeDetailedFields:input.includeDetailedFields}}function normalizePatternType(value){if(value===undefined||value==="regex")return"REGEX";if(value==="literal")return"LITERAL";throw invalid2("patternType","`patternType` must be `literal` or `regex`.")}function normalizeCorpus(value,field){if(value===undefined)return;if(typeof value!=="string"){throw invalid2(field,"Corpus must be `source`, `documentation`, or `all`.")}const normalized=value.toUpperCase();if(normalized==="SOURCE"||normalized==="DOCUMENTATION"||normalized==="ALL"){return normalized}throw invalid2(field,"Corpus must be `source`, `documentation`, or `all`.")}function normalizePathSelectors(value,field){if(value===undefined)return[];if(!Array.isArray(value)){throw invalid2(field,"Path selectors must be an array.")}if(value.length===0)return[];if(value.length>MAX_PATH_SELECTORS){throw invalid2(field,`A target may contain at most ${MAX_PATH_SELECTORS} path selectors.`)}return value.map((selector,index)=>{const itemField=`${field}[${index}]`;if(!isRecord(selector)){throw invalid2(itemField,"A path selector must be an object.")}const kind=normalizeSelectorKind(selector.kind,`${itemField}.kind`);if(typeof selector.value!=="string"){throw invalid2(`${itemField}.value`,"Selector value must be a string.")}const selectorValue=selector.value;validateUnicode(selectorValue,`${itemField}.value`,"Selector values must contain valid Unicode.");if(selectorValue.trim().length===0){throw invalid2(`${itemField}.value`,"Selector values cannot be blank.")}if(selectorValue.includes("\x00")){throw invalid2(`${itemField}.value`,"Selector values cannot contain NUL.")}return{kind,value:selectorValue}})}function normalizeSelectorKind(value,field){if(typeof value!=="string"){throw invalid2(field,"Selector kind must be `exact`, `prefix`, or `glob`.")}const normalized=value.toUpperCase();if(normalized==="EXACT"||normalized==="PREFIX"||normalized==="GLOB"){return normalized}throw invalid2(field,"Selector kind must be `exact`, `prefix`, or `glob`.")}function normalizeBoolean(value,field){if(value===undefined)return;if(typeof value!=="boolean"){throw invalid2(field,`${field} must be a boolean.`)}return value}function normalizeInteger(value,field,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isSafeInteger(value)||value<minimum||value>maximum){throw invalid2(field,`${field} must be a safe integer from ${minimum} to ${maximum}.`)}return value}function normalizeGrepContextLines(value,field){return normalizeInteger(value,field,0,GREP_CONTEXT_MAX)}function normalizeCursor(value){if(value===undefined)return;if(typeof value!=="string"){throw invalid2("cursor","`cursor` must be a string.")}return value.trim().length===0?undefined:value}function isGrepSiteTarget(target){return target.trim().toLowerCase().startsWith("site:")}function validateUnicode(value,field,message){if(hasLoneSurrogate(value))throw invalid2(field,message)}function hasLoneSurrogate(value){for(let index=0;index<value.length;index+=1){const codeUnit=value.charCodeAt(index);if(codeUnit>=55296&&codeUnit<=56319){const nextCodeUnit=value.charCodeAt(index+1);if(!(nextCodeUnit>=56320&&nextCodeUnit<=57343))return true;index+=1}else if(codeUnit>=56320&&codeUnit<=57343){return true}}return false}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function invalid2(field,message){return new InvalidGrepRequestError(field,message)}function mapGrepError(error){const sessionError=mapSessionIdError(error);if(sessionError)return sessionError;const terms=mapTermsAcceptanceError(error);if(terms)return terms;if(error instanceof ClientUpdateRequiredError)return buildUpdateRequiredError(error.reason,error.currentVersion);if(error instanceof AuthenticationError2||error instanceof AuthRequiredError)return{code:"AUTH_REQUIRED",message:error.message,retryable:false,details:{authSource:error instanceof AuthenticationError2?error.source:"local"}};if(error instanceof InvalidGrepRequestError)return{code:"INVALID_ARGUMENT",message:error.message,retryable:false};if(error instanceof GrepAccessError2)return{code:"ACCESS_DENIED",message:error.message,retryable:false};if(error instanceof GrepNetworkError2)return{code:"NETWORK",message:error.message,retryable:true};if(error instanceof MalformedGrepResponseError2)return{code:"PROTOCOL_ERROR",message:error.message,retryable:false};if(error instanceof GrepBackendError2){const code=error.graphqlCode==="TIMEOUT"?"TIMEOUT":error.status===429?"RATE_LIMITED":"BACKEND_ERROR";return{code,message:error.message,retryable:error.retryable??(code==="TIMEOUT"||code==="RATE_LIMITED"||error.status!==undefined&&error.status>=500),details:{...error.status!==undefined?{status:error.status}:{},...error.graphqlCode?{graphqlCode:error.graphqlCode}:{}}}}if(error instanceof GrepGraphQLError2){const ext=error.extensions;const recovery=parseVersionRefRecovery(ext);if(recovery)return mapVersionRefRecovery(error.message,recovery);const graphqlCode=typeof ext.code==="string"?ext.code:undefined;const code=graphqlCode==="GREP_TARGET_PREPARATION_REQUIRED"?preparationErrorCode(ext.target_issues,ext.retryable):graphqlCode==="GREP_CURSOR_INVALID"||graphqlCode==="VALIDATION_ERROR"||graphqlCode==="INVALID_ARGUMENT"?"INVALID_ARGUMENT":graphqlCode==="GREP_BACKEND_PROTOCOL_ERROR"?"PROTOCOL_ERROR":graphqlCode==="TIMEOUT"?"TIMEOUT":graphqlCode==="RATE_LIMITED"?"RATE_LIMITED":"BACKEND_ERROR";const details={graphqlCode};if(Array.isArray(ext.target_issues)){details.targetIssues=ext.target_issues.slice(0,20).filter(isRecord2).map((issue)=>Object.fromEntries(Object.entries(issue).filter(([key])=>PUBLIC_ISSUE_KEYS.has(key))));const hints=details.targetIssues.flatMap((issue,index)=>{const target=typeof issue.target==="string"?issue.target:typeof issue.input_index==="number"?`Input ${issue.input_index}`:undefined;const translatedReason=typeof issue.reason==="string"?grepPreparationReason(issue.reason):undefined;const reason=translatedReason&&translatedReason!==issue.reason?translatedReason:code==="INDEXING"?"target is being prepared":"target is unavailable";const message=typeof issue.message==="string"?typeof issue.reason==="string"&&issue.message.endsWith(`Reason: ${issue.reason}.`)?reason:issue.message:undefined;const diagnostic=code==="INDEXING"?reason:graphqlCode==="GREP_TARGET_PREPARATION_REQUIRED"&&index===0?undefined:message!==undefined?typeof issue.message==="string"&&error.message.includes(issue.message)?undefined:message:reason;const path=typeof issue.file_path==="string"?`path ${issue.file_path}`:undefined;const text=[diagnostic,path].filter(Boolean).join("; ");return text?[`${target?`${target}: `:""}${text}`]:[]});if(hints.length)details.hint=hints.join(`
119
119
  `)}if(graphqlCode==="GREP_CURSOR_INVALID")details.hint="Restart explicitly without the cursor, using the same targets and controls.";return{code,message:error.message,retryable:typeof ext.retryable==="boolean"?ext.retryable:code==="INDEXING"||code==="TIMEOUT"||code==="RATE_LIMITED",details}}return{code:"UNKNOWN",message:error instanceof Error?error.message:"Unknown error",retryable:false}}function preparationErrorCode(issues,retryable){if(!Array.isArray(issues)||issues.length===0)return"UNRESOLVABLE";for(const issue of issues){const code=isRecord2(issue)?preparationIssueCode(issue):"UNRESOLVABLE";if(code!=="INDEXING")return code}return retryable===false?"UNRESOLVABLE":"INDEXING"}function preparationIssueCode(issue){switch(issue.reason){case"repository_indexing":case"documentation_publishing":case"documentation_discovery":case"site_v6_required":case"starting_url_pending":return issue.retryable===false?"UNRESOLVABLE":"INDEXING";case"repository_not_found":case"package_not_found":case"package_source_not_found":return"NOT_FOUND";case"repository_ref_not_found":case"ref_not_found":return"REF_NOT_FOUND";case"package_version_not_found":case"package_version_unresolved":case"package_source_ref_not_found":return"VERSION_NOT_FOUND";case"repository_ref_ambiguous":case"site_ambiguous":return"INVALID_ARGUMENT";case"repository_resolution_error":case"repository_unavailable":return"BACKEND_ERROR";case"no_grep_scopes":case"no_site_pages":case"repository_legally_blocked":case"package_source_unsupported":case"package_security_removed":case"package_scope_unavailable":case"package_release_unusable":case"site_not_indexed":case"site_no_docs":case"site_redirected":case"site_failed":case"documentation_site_not_admitted":case"documentation_source_resolution_required":case"documentation_site_no_docs":case"documentation_site_identity_blocked":case"documentation_site_failed":case"documentation_unavailable":case"starting_url_missed_at_cap":case"starting_url_absent_from_current_corpus":return"UNRESOLVABLE";default:return typeof issue.reason==="string"&&issue.reason.trim()&&issue.retryable===true&&typeof issue.progress_ref==="string"&&issue.progress_ref.trim()?"INDEXING":"UNRESOLVABLE"}}var PUBLIC_ISSUE_KEYS=new Set(["input_index","target","reason","retryable","progress_ref","file_path","repo_url","git_ref","requested_ref","available_refs","available_versions","message","suggested_refs","published_versions","published_versions_truncated","suggested_site_targets","registry","package"]);function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function summarizeGrepPathWarnings(warnings){return[...new Set(warnings.map((warning)=>{const suggestion=warning.suggestions.find((entry)=>entry.target===warning.target);return`Path is prefixed with package path ${JSON.stringify(warning.repositorySubpath)}.${suggestion?` Did you mean ${JSON.stringify(suggestion.path)}?`:""}`.replace(/[\u007f-\u009f]/g,(character)=>`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`)}))]}function projectGrepResult(result){const projected=parseGrepResult({...result,indexingEstimates:result.indexingEstimates??[],targetResolutions:result.targetResolutions===undefined?[]:result.targetResolutions});if(result.indexingEstimates===undefined)delete projected.indexingEstimates;if(result.targetResolutions===undefined)delete projected.targetResolutions;return{...projected,pathWarnings:summarizeGrepPathWarnings(projected.pathWarnings)}}function appendSearchGrepFooter(lines,footer,useColors){for(const[label,body]of[["Read:",footer.read],["More results:",footer.more],["Follow-up:",footer.followUp]]){if(!body?.length)continue;lines.push("",useColors?`${colors.bold}${label}${colors.reset}`:label,...body.map((line)=>` ${line}`))}}function footerAction(value,useColors){return dim(value,useColors)}function footerProse(value,width){return wrapTerminalProse(value,Math.max(20,width)-2)}function formatGrepText(result,options={}){const lines=[];const prose=(value)=>{lines.push(...wrap(escapeText(value),options.width??80))};const groups=groupFiles(result.hits);const isPreparing=(reason)=>["repository_indexing","documentation_publishing"].includes(reason);const scopeCoverageGap=result.targets.some(hasPageCoverageGap);const pageCoverageGap=scopeCoverageGap||result.unavailableTargets.length>0||!["COMPLETE","RESUMABLE_LIMIT"].includes(result.traversal);const omissionsOnly=result.unavailableTargets.length>0&&!scopeCoverageGap&&!["FAILED","CURSOR_EXPIRED"].includes(result.traversal);const preparationOnly=omissionsOnly&&result.unavailableTargets.every((target)=>target.retryable&&isPreparing(target.reason));const nothingSearched=(result.targets.length>0||result.unavailableTargets.length>0)&&result.targets.every((scope)=>scope.filesScanned===0&&(scope.traversal==="FAILED"||!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness)));const matchingLines=new Set(result.hits.map((hit)=>JSON.stringify([...fileIdentity(hit),hit.line]))).size;const kinds=new Set(result.hits.map((hit)=>hit.__typename));const noun=kinds.size>1?"files/pages":kinds.has("GrepSiteHit")?`page${groups.length===1?"":"s"}`:`file${groups.length===1?"":"s"}`;prose(result.hits.length?`Found ${result.totalMatches} match${result.totalMatches===1?"":"es"} on ${matchingLines} line${matchingLines===1?"":"s"} in ${groups.length} ${noun}.`:result.nextCursor?preparationOnly?"No matches on this page; some requested content is still being prepared.":pageCoverageGap?"No matches on this page; some requested content could not be searched.":"No matches on this page.":preparationOnly?`No matches available yet; ${nothingSearched?"requested":"some requested"} content is still being prepared.`:nothingSearched?"None of the requested content could be searched.":isExhaustive(result)?"No matches found.":"No matches returned; some requested content could not be searched.");if(options.useColors)lines[0]=`${colors.bold}${lines[0]}${colors.reset}`;if(result.targets.length){lines.push("","Sources:");const matchedScopes=new Set(result.hits.map((hit)=>hit.targetIndex));for(const source of formatSources(result.targets,matchedScopes,isExhaustive(result)))prose(` - ${source}`)}const repositoryHits=new Set(result.hits.filter((hit)=>hit.__typename==="GrepRepositoryHit").map((hit)=>hit.targetIndex));const searchedInputs=new Set(result.targets.filter((scope)=>scope.kind==="REPOSITORY"&&(scope.readiness==="CURRENT"||scope.readiness==="STALE"||repositoryHits.has(scope.targetIndex))).flatMap((scope)=>scope.requestedInputIndices));const correspondence=new Set((result.targetResolutions??[]).flatMap((entry)=>buildSourceCorrespondenceNotes(entry.targetResolution,searchedInputs.has(entry.inputIndex)?"served":"selected")));for(const note of correspondence)prose(note);const pending=result.unavailableTargets.filter((entry)=>entry.retryable&&isPreparing(entry.reason));const attached=new Set;if(pending.length||result.indexingEstimates?.length)lines.push("","Preparing:");for(const entry of result.indexingEstimates??[]){prose(` - ${formatPreparationRow(entry)}`);const inputs=pending.filter((omitted)=>entry.targets.includes(omitted.target)&&entry.kind===(omitted.reason==="repository_indexing"?"REPOSITORY":"DOCUMENTATION"));for(const omitted of inputs)attached.add(omitted);for(const target of new Set(inputs.map((omitted)=>omitted.target))){const targetInputs=inputs.filter((omitted)=>omitted.target===target);const needsAlias=inputs.length>1||entry.targets.length>1||Boolean(entry.repositoryUrl&&entry.commitSha)||targetInputs.some((omitted)=>Boolean(omitted.suggestedSiteTargets?.length));if(needsAlias)prose(` Requested: ${target}`);for(const omitted of targetInputs)for(const suggested of omitted.suggestedSiteTargets??[])prose(` Search hosted documentation instead: ${suggested}`)}if(entry.repositoryUrl&&entry.commitSha){const remaining=entry.targets.filter((target)=>!inputs.some((input)=>input.target===target));if(remaining.length)prose(` Requested: ${remaining.join(", ")}`)}}for(const omitted of pending.filter((entry)=>!attached.has(entry))){prose(` - ${formatProvenanceRow(omitted.target,[omitted.reason==="repository_indexing"?"indexing":"preparing documentation"])}`);for(const target of omitted.suggestedSiteTargets??[])prose(` Search hosted documentation instead: ${target}`)}const otherOmissions=result.unavailableTargets.filter((entry)=>!pending.includes(entry));if(otherOmissions.length)lines.push("","Not searched:");for(const omitted of otherOmissions){prose(` - ${omitted.target}: ${grepPreparationReason(omitted.reason)}; ${omitted.retryable?"you can retry":"do not retry unchanged"}${omitted.reason==="no_grep_scopes"&&!omitted.retryable&&!omitted.suggestedSiteTargets?.length?"; choose a different package, repository or site target":""}`);for(const target of omitted.suggestedSiteTargets??[])prose(` Search hosted documentation instead: ${target}`)}for(const scope of result.targets)renderCoverage(scope,prose);if(result.traversal==="CURSOR_EXPIRED")prose("Cursor expired; the search could not continue.");else if(result.traversal!=="COMPLETE"&&(!result.nextCursor||result.traversal!=="RESUMABLE_LIMIT")&&(result.unavailableTargets.length===0||result.traversal==="FAILED")&&!result.targets.some((scope)=>!["COMPLETE","RESUMABLE_LIMIT"].includes(scope.traversal)||!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness)))prose(result.nextCursor?`${result.hits.length?"Some requested content could not be searched; the":"The"} service did not explain why or whether retrying would help.`:"The search did not finish, and no continuation cursor was returned. The service did not explain why the full search stopped or whether retrying would help.");if(result.pathWarnings.length)lines.push("");for(const warning of summarizeGrepPathWarnings(result.pathWarnings))lines.push(`Warning: ${escapeControls(warning)}`);for(const[index,group]of groups.entries()){const first=group.first;const target=first.read.target;const path=first.read.path!==null?` ${quoteLocator(first.read.path,options.syntax)}`:"";const display=first.__typename==="GrepSiteHit"&&first.pageUrl!==first.read.target?` [page: ${escapeText(first.pageUrl)}]`:"";lines.push("",`[${index+1}] ${quoteLocator(target,options.syntax)}${path}${display}`);const rows=groupRows(group.hits);const gutter=Math.max(...rows.map((row)=>String(row.number).length));const hasContext=rows.some((row)=>!row.match);let previous;for(const row of rows){if(hasContext&&previous!==undefined&&row.number>previous+1)lines.push("--");lines.push(`${String(row.number).padStart(gutter)}${row.match?":":"-"} ${renderSlice(row,options.useColors??false)}`);previous=row.number}if(group.hits.some((hit)=>hit.contentSafety.filtered))prose("Safety normalization applied; physical source coordinates remain in JSON.")}const read=[];const more=[];const followUp=[];const proseLines=(value)=>footerProse(escapeText(value),options.width??80);const operand=(value)=>footerAction(value,options.useColors===true);if(groups.length){if(kinds.has("GrepRepositoryHit"))read.push(operand(options.syntax==="mcp"?"Files: read target=$target path=$path start_line=$start end_line=$end":"Files: githits read --lines $start-$end -- $target $path"));if(kinds.has("GrepSiteHit"))read.push(operand(options.syntax==="mcp"?"Pages: read target=$url start_line=$start end_line=$end":"Pages: githits read --lines $start-$end -- $url"))}if(result.nextCursor)more.push(...proseLines("Repeat the original grep, adding:"),operand(options.syntax==="mcp"?`cursor=${JSON.stringify(result.nextCursor)}`:`--cursor ${shellQuoteExact(result.nextCursor)}`));const cursorOption=options.syntax==="mcp"?"cursor":"--cursor";if(result.traversal==="CURSOR_EXPIRED"){followUp.push(...proseLines(`To restart the full search, repeat the original grep and omit ${cursorOption}.`))}else{const retryableOmissions=result.unavailableTargets.filter((target)=>target.retryable);const retryableScopes=result.targets.filter((scope)=>scope.retryable&&hasPageCoverageGap(scope));if(retryableOmissions.length||retryableScopes.length){const indices=new Set([...retryableOmissions.map((target)=>target.inputIndex),...retryableScopes.flatMap((scope)=>scope.requestedInputIndices)]);const requestedTargets=options.requestedTargets;const targets=requestedTargets?requestedTargets.flatMap((target,index)=>indices.has(index)?[`${quoteLocator(target,options.syntax)}${requestedTargets.indexOf(target)!==requestedTargets.lastIndexOf(target)?` (target ${index+1})`:""}`]:[]):[...new Set([...retryableOmissions.map((target)=>target.target),...retryableScopes.map((scope)=>scope.target)])].map((target)=>quoteLocator(target,options.syntax));followUp.push(...proseLines(requestedTargets?"Repeat the same pattern and options for:":"Repeat the original grep inputs for these sources:"),...targets.map((target)=>operand(` ${target}`)));if(pending.length){const wait=indexingWaitMs(result.indexingEstimates);const waitOption=options.syntax==="mcp"?`wait_timeout_ms=${wait}`:`--wait ${wait}`;followUp.push(...proseLines(`Omit ${cursorOption}; set ${waitOption} to wait up to ${wait/1000}s for preparation.`))}else{followUp.push(...proseLines(`Omit ${cursorOption} to start a new search.`))}}}appendSearchGrepFooter(lines,{read,more,followUp},options.useColors===true);return lines.join(`
120
120
  `)}function renderCoverage(scope,prose){const prefix=`${scope.kind==="REPOSITORY"?"Repository":"Hosted docs"} ${scope.target}`;const notes=[];if(scope.readiness==="UNSPECIFIED"&&scope.traversal!=="RESUMABLE_LIMIT")notes.push("source readiness unknown");else if(scope.readiness!=="UNSPECIFIED"&&scope.readiness!=="CURRENT")notes.push(readinessNote(scope));if(scope.traversal!=="COMPLETE"&&scope.traversal!=="RESUMABLE_LIMIT")notes.push(traversalNote(scope));if(hasPageCoverageGap(scope))notes.push(scope.retryable?"you can retry":"do not retry unchanged");const details=[];if(scope.publicMessage)details.push(`Reason: ${scope.publicMessage}${scope.errorCode?` [${scope.errorCode}]`:""}`);else if(scope.errorCode)details.push(`Error: ${scope.errorCode}.`);else if(scope.traversal==="FAILED")details.push("No further failure details were provided.");if(notes.length||details.length){if(scope.readiness==="STALE"&&scope.commitSha)details.push(...scope.repoUrl?scope.requestedRef?[`Requested ref: ${scope.requestedRef}.`]:[]:[`Served ${scope.commitSha}${scope.requestedRef?`; requested ${scope.requestedRef}`:""}.`]);if(scope.filesScanned!==null&&scope.filesInScope!==null&&scope.filesScanned!==scope.filesInScope)details.push(`Searched ${scope.filesScanned} of ${scope.filesInScope} file${scope.filesInScope===1?"":"s"}.`)}if(scope.binaryFilesSkipped)details.push(`Skipped ${scope.binaryFilesSkipped} binary file${scope.binaryFilesSkipped===1?"":"s"}.`);if(scope.filesTooLargeSkipped)details.push(`Skipped ${scope.filesTooLargeSkipped} oversized file${scope.filesTooLargeSkipped===1?"":"s"}.`);for(const issue of scope.fileIssues??[])details.push(`File issue ${issue.filePath}${issue.line>0?`:${issue.line}`:" (aggregate)"}; ${issue.code}${issue.contentSafety.filtered?"; safety normalization applied":""}.`);if(scope.fileIssuesOmitted)details.push(`${scope.fileIssuesOmitted} additional file issue(s) omitted.`);if(notes.length||details.length){const note=notes.join("; ");prose(`${prefix}:${note?` ${note}${/[.!?]$/.test(note)?"":"."}`:""}`);for(const detail of details)prose(` ${detail}`)}}function readinessNote(scope){switch(scope.readiness){case"STALE":return"stale snapshot";case"NOT_AVAILABLE":return"unavailable";case"MISSING_REF":return"requested ref missing";case"READER_OPEN_FAILED":return"could not open repository reader";case"INCOMPLETE":return"incomplete index";case"RESOURCE_LIMIT":return"resource limit reached";case"VERSION_UNSUPPORTED":return"unsupported documentation version";case"READ_FAILED":return"could not read documentation";default:return scope.readiness}}function traversalNote(scope){switch(scope.traversal){case"FAILED":return"search failed";case"CURSOR_EXPIRED":return"cursor expired";default:return"incomplete search"}}function isExhaustive(result){return result.traversal==="COMPLETE"&&result.unavailableTargets.length===0&&result.targets.every((scope)=>!hasCoverageGap(scope))}function hasPageCoverageGap(scope){return scope.readiness!=="CURRENT"&&!(scope.readiness==="UNSPECIFIED"&&scope.traversal==="RESUMABLE_LIMIT")||!["COMPLETE","RESUMABLE_LIMIT"].includes(scope.traversal)||scope.errorCode!==null||Boolean(scope.binaryFilesSkipped||scope.filesTooLargeSkipped||scope.fileIssues?.length||scope.fileIssuesOmitted)}function hasCoverageGap(scope){return scope.readiness!=="CURRENT"||scope.traversal!=="COMPLETE"||hasPageCoverageGap(scope)}function formatSources(scopes,matchedScopes,exhaustive){const sources=new Map;for(const scope of scopes){let target=scope.target;let identity=JSON.stringify([scope.kind,scope.target]);const hostedDocumentation=scope.kind==="SITE"&&Boolean(scope.canonicalSite);if(scope.kind==="SITE"&&scope.canonicalSite){target=`site:${scope.canonicalSite.replace(/^https?:\/\//i,"").replace(/\/$/,"")}`;identity=JSON.stringify([scope.kind,scope.canonicalSite])}const qualifiers=[];if(scope.kind==="REPOSITORY"&&scope.repoUrl&&scope.commitSha){if(scope.corpus==="SOURCE")qualifiers.push("source files");if(scope.corpus==="DOCUMENTATION")qualifiers.push("repository docs");identity=JSON.stringify([scope.kind,scope.repoUrl,scope.commitSha,scope.corpus])}if(scope.readiness==="STALE")qualifiers.push("older snapshot");const unsearched=!matchedScopes.has(scope.targetIndex)&&scope.filesScanned===0&&(scope.traversal==="FAILED"||!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness));if(unsearched)qualifiers.push("not searched");if(scope.readiness==="UNSPECIFIED"&&scope.traversal==="RESUMABLE_LIMIT")qualifiers.push("not reached on this page");identity=JSON.stringify([identity,scope.readiness,scope.traversal,scope.filesScanned,scope.filesInScope,scope.errorCode,scope.binaryFilesSkipped,scope.filesTooLargeSkipped,scope.fileIssues,scope.fileIssuesOmitted,scope.urlPrefixes]);const source=sources.get(identity)??{facts:{target,identity:scope.kind==="REPOSITORY"?{repoUrl:scope.repoUrl,commitSha:scope.commitSha}:undefined,qualifiers},requested:new Set,matched:false,hostedDocumentation};if(scope.kind==="REPOSITORY"&&scope.commitSha&&scope.requestedRef&&/^[a-f0-9]{40}$/i.test(scope.requestedRef)&&scope.requestedRef.toLowerCase()!==scope.commitSha.toLowerCase())source.requested.add(scope.target);source.matched||=matchedScopes.has(scope.targetIndex);sources.set(identity,source)}return[...sources.values()].map((source)=>formatSourceRow({...source.facts,qualifiers:[...source.facts.qualifiers??[],...source.requested.size?[`requested: ${[...source.requested].join(", ")}`]:[],...!source.matched&&!source.facts.qualifiers?.some((qualifier)=>["not searched","not reached on this page"].includes(qualifier))?[exhaustive?"no results":"no matches returned"]:[],...source.hostedDocumentation?["hosted documentation"]:[]]}))}function quoteLocator(value,syntax){if(/^[A-Za-z0-9_./:@%+=-][A-Za-z0-9_./:@%#+=-]*$/.test(value))return value;return syntax==="mcp"?JSON.stringify(value):shellQuoteExact(value)}function fileIdentity(hit){return[hit.targetIndex,hit.__typename,hit.read.target,hit.read.path]}function groupFiles(hits){const groups=new Map;for(const hit of hits){const key=JSON.stringify(fileIdentity(hit));const group=groups.get(key);if(group)group.hits.push(hit);else groups.set(key,{first:hit,hits:[hit]})}return[...groups.values()]}function groupRows(hits){const rows=new Map;const add=(number,slice,span)=>{const key=JSON.stringify([number,slice.startByte,slice.endByte,slice.content]);const row=rows.get(key);if(row){if(span){row.match=true;row.spans.push(span)}}else rows.set(key,{number,slice,match:span!==undefined,spans:span?[span]:[]})};for(const hit of hits){hit.contextBeforeSlices.forEach((slice,index)=>{add(hit.line-hit.contextBeforeSlices.length+index,slice)});add(hit.line,hit.lineSlice,{start:hit.matchStartByte,end:hit.matchEndByte});hit.contextAfterSlices.forEach((slice,index)=>{add(hit.line+index+1,slice)})}return[...rows.values()].sort((a,b)=>a.number-b.number||a.slice.startByte-b.slice.startByte||a.slice.endByte-b.slice.endByte)}function renderSlice(row,useColors){const{slice}=row;let content;if(!useColors)content=escapeSource(slice.content);else{const bytes=new TextEncoder().encode(slice.content);const decoder=new TextDecoder("utf-8",{ignoreBOM:true});const merged=[];for(const span of[...row.spans].sort((a,b)=>a.start-b.start||a.end-b.end)){if(span.start===span.end)continue;const previous=merged[merged.length-1];if(previous&&span.start<=previous.end)previous.end=Math.max(previous.end,span.end);else merged.push({...span})}let cursor=0;content="";for(const span of merged){content+=escapeSource(decoder.decode(bytes.subarray(cursor,span.start)));content+=highlightMatch(escapeSource(decoder.decode(bytes.subarray(span.start,span.end))),true);cursor=span.end}content+=escapeSource(decoder.decode(bytes.subarray(cursor)))}return`${slice.startByte>0?"[...] ":""}${content}${slice.endByte<slice.originalLineBytes?" [...]":""}`}function escapeText(value){return escapeControls(value.replace(/\\/g,"\\\\"))}function escapeSource(value){return escapeControls(value,true)}function escapeControls(value,preserveTabs=false){return value.replace(/[\u0000-\u001f\u007f-\u009f]/g,(character)=>preserveTabs&&character==="\t"?character:`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`)}function wrap(text,width){const lines=[];const prefix=text.match(/^ *(?:- )?/)?.[0]??"";const indent=" ".repeat(prefix.length);let current=prefix;for(const word of text.slice(prefix.length).split(" ")){const hasWord=current.length>indent.length;if(hasWord&&terminalWidth(`${current} ${word}`)>width){lines.push(current);current=`${indent}${word}`}else current=hasWord?`${current} ${word}`:`${current}${word}`}if(current)lines.push(current);return lines}var targetSchema=z2.object({target:z2.string().describe("Package `npm:express@5.2.1`, repository `github:expressjs/express@v5.2.1` or `launchpad:~owner/+git/repo@ref` (`lp:PROJECT` also accepted), or hosted docs `site:expressjs.com/en/5x`."),corpus:z2.enum(["source","documentation","all"]).optional().describe("Filters repository files (default all); selected hosted docs are unaffected. Omit for sites."),path_selectors:z2.array(z2.object({kind:z2.enum(["exact","prefix","glob"]),value:z2.string()})).optional().describe("OR-ed file scopes relative to the package/repository root. Empty applies no path filter; corpus still applies. Hosted docs are unaffected; omit for sites.")});var schema2={targets:z2.array(targetSchema).min(1).max(20).describe("One to 20 ordered package, repository, or site targets."),pattern:z2.string().describe("RE2 regex (default), or text with pattern_type literal (1-200 UTF-8 bytes). No lookaround or backreferences; multi-file regex needs a literal anchor."),pattern_type:z2.enum(["regex","literal"]).optional().describe("Regex (default) or literal substring matching."),ignore_case:z2.boolean().optional().describe("true ignores case with Unicode folding; false (default) is case-sensitive."),context_lines_before:z2.number().int().min(0).max(10).optional().describe("Lines before each match (0-10; default 0)."),context_lines_after:z2.number().int().min(0).max(10).optional().describe("Lines after each match (0-10; default 0)."),max_matches:z2.number().int().min(1).max(1000).optional().describe("Maximum occurrences across all scopes on this page (default 100)."),cursor:z2.string().optional().describe("Continue with the same ordered targets, pattern, and matching controls. Empty starts page one. Hosted pages can change between grep and read."),wait_timeout_ms:z2.number().int().min(0).max(300000).optional().describe(`First-page preparation wait in milliseconds (default ${DEFAULT_WAIT_TIMEOUT_MS}). Continuation never waits.`),format:z2.enum(["text","json"]).default("text").describe("Omit for text: grouped matches, read locators, and coverage. Use json only when code consumes raw hit and scope fields.")};var DESCRIPTION2="Find regex or literal matches across source and documentation. "+"Search ordered package, repository, and site targets; packages include selected hosted docs. "+"Defaults: RE2 regex, case-sensitive, zero context. "+"Use `list` for paths, `search` for topics, and `read` for more context. "+"Text groups matches by file/page with read locators. "+"Indexed matches may be partial; coverage limits and a continuation cursor remain visible."+`
121
121
 
@@ -124,13 +124,13 @@ ${CODE_GREP_GUARDRAIL}`;function createGrepTool(service){return{name:"grep",desc
124
124
  `)}function formatSourceReadAction(target,syntax){return syntax==="mcp"?`read target=${JSON.stringify(target)} path=$path`:`read -- ${shellQuoteExact(target)} $path`}function formatSiteReadGuidance(target,syntax){return syntax==="mcp"?`Read pages: read target=${JSON.stringify(target)} path=$path`:`Read pages: read -- ${shellQuoteExact(target)} $path`}function formatPath(entry,inventoryKind){if(inventoryKind==="SITE"){return formatSitePath(entry)}if(entry.kind==="PAGE"&&entry.read?.target!==undefined){return escapePath(entry.read.target)}const path=entry.kind==="DIRECTORY"&&!entry.path.endsWith("/")?`${entry.path}/`:entry.path;return escapePath(path)}function formatSitePath(entry){if(entry.kind==="PAGE"&&entry.read!==null&&entry.read!==undefined){if(isSiteReadAction(entry.read.target,entry.read.path)){return escapePath(entry.read.path)}return escapePath(entry.read.target)}const path=entry.kind==="DIRECTORY"&&!entry.path.endsWith("/")?`${entry.path}/`:entry.path;return escapePath(path)}function findSharedSiteReadTarget(result){if(result.inventoryKind!=="SITE")return;let sharedTarget;for(const entry of result.entries){if(entry.kind!=="PAGE"||entry.read===null||entry.read===undefined||!isSiteReadAction(entry.read.target,entry.read.path)){continue}if(sharedTarget===undefined){sharedTarget=entry.read.target}else if(entry.read.target!==sharedTarget){return}}return sharedTarget}function isSiteReadAction(target,path){return target.startsWith("site:")&&path!==null}function escapePath(path){return escapeLineValue(path)}function escapeLineValue(value){let escaped="";for(const character of value){if(character==="\\"){escaped+="\\\\";continue}const shortEscape=SHORT_ESCAPES.get(character);if(shortEscape!==undefined){escaped+=shortEscape;continue}const codePoint=character.codePointAt(0)??0;if(codePoint<=31||codePoint>=127&&codePoint<=159||codePoint===8232||codePoint===8233||codePoint>=55296&&codePoint<=57343){escaped+=`\\u${codePoint.toString(16).padStart(4,"0")}`;continue}escaped+=character}return escaped}var SHORT_ESCAPES=new Map([["\b","\\b"],["\t","\\t"],[`
125
125
  `,"\\n"],["\f","\\f"],["\r","\\r"]]);var LIST_INTENTS=["PRODUCTION","TEST","BENCHMARK","EXAMPLE","GENERATED","FIXTURE","BUILD","VENDOR"];var schema3={target:z3.string().describe("Known package such as `npm:express@5.2.1`, repository such as `github:expressjs/express` or `launchpad:~owner/+git/repo` (`lp:PROJECT` also accepted), or hosted docs site such as `site:expressjs.com`."),paths:z3.array(z3.string()).max(1000).optional().describe("Target-relative literal paths and globs form a union for packages, repositories, and sites. Site paths with one leading `/` stay within the supplied target; `/` alone selects its root. Omit or pass `[]` to browse the root."),recursive:z3.boolean().optional().describe("Expand selected directories to descendant leaves. Without this, selected directories show immediate children. Glob depth is independent of recursion."),file_types:z3.array(z3.string()).max(64).optional().describe("Source inventories only; classifications such as `source` or `doc`, case-insensitive. Select file extensions with a `paths` glob such as `lib/**/*.js`."),languages:z3.array(z3.string()).max(64).optional().describe("Source inventories only; language names such as `javascript`, `typescript`, or `rust`, case-insensitive."),intents:z3.array(z3.enum(LIST_INTENTS)).max(64).optional().describe("Source inventories only; filter by file intent: PRODUCTION, TEST, BENCHMARK, EXAMPLE, GENERATED, FIXTURE, BUILD, or VENDOR."),limit:z3.number().int().min(1).max(500).optional().describe("Maximum entries to return (1-500)."),after:z3.string().optional().describe("Opaque `nextCursor` from a prior list response. Reuse the same target, paths, filters, recursion, and limit; empty is omitted."),wait_timeout_ms:z3.number().int().min(0).max(300000).optional().describe(`Maximum wait for indexing in milliseconds (0-300000; default ${DEFAULT_WAIT_TIMEOUT_MS}).`),format:z3.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or follows read and continuation guidance. Set `json` for exact entry kinds or actions, or when code consumes the raw response instead of the model by parsing or filtering it programmatically.")};var DESCRIPTION3="List files and documentation paths in a known package, repository, or site. "+"Use it to browse structure or find an exact path before `read`; use `search` "+`for topics.
126
126
 
127
- `+"Package targets cover one package-owned "+"tree; repository targets cover the whole snapshot. Both include source and "+"documentation. Hosted docs use an explicit `site:` target supplied by the "+"user or a docs search result. `paths` are target-relative literals or globs for every target and "+"form a union; omit them for the root. Directories show immediate children "+"unless `recursive` expands them; glob depth is independent of recursion. "+"In site text, a path without trailing `/` is a page even when its source URL ended in `/`. "+"Keep text for model use, including read and continuation guidance; use JSON "+"for exact entry kinds or actions and programmatic consumption.";function createListTool(service){return{name:"list",description:DESCRIPTION3,schema:schema3,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{let builtParams;try{builtParams=buildListParams({target:args.target,paths:args.paths,recursive:args.recursive,fileTypes:args.file_types,languages:args.languages,intents:args.intents,limit:args.limit,after:args.after,waitTimeoutMs:args.wait_timeout_ms,includeDetailedFields:args.format==="json",includeTargetProvenance:true});const result=await service.list(builtParams,...serviceRequestArgs(context?.signal));const payload=projectListResult(result);if(args.format!=="json"){return textResult(formatListText(payload,{useColors:false,syntax:"mcp",hasAfter:builtParams.after!==undefined}))}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapListError(error,{hasAfter:builtParams?.after!==undefined});return mcpMappedErrorResult(withIndexingRetryAction(mapped,"list","mcp",{maxWaitMs:MAX_DISCOVERY_WAIT_TIMEOUT_MS,hasAfter:builtParams?.after!==undefined}),context,args.format,{recovery:{syntax:"mcp",tool:"list",args},indexingTarget:args.target,indexingOutcome:args.target.startsWith("site:")?"No pages available yet.":"No files available yet."})}}}}import{z as z4}from"zod";function normaliseChangelogChanges(raw){const value=raw?.trim().toLowerCase()||"all";if(value!=="actionable"&&value!=="important"&&value!=="all"){throw new InvalidPackageSpecError("changes must be actionable, important (actionable + should know), or all.")}return value}var PACKAGE_ONLY_MESSAGE="`pkg_changelog` is package-only. Use a `registry:name` target such as `npm:express`, not a repository or site coordinate.";function parsePackageChangelogTarget(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidPackageSpecError("Package spec cannot be empty. Expected <registry>:<name>[@<version> or @<from>..<to>].")}if(isNonPackageChangelogTarget(trimmed)){throw new InvalidPackageSpecError(PACKAGE_ONLY_MESSAGE)}const parsed=parsePackageSpec(trimmed);if(parsed.version===undefined){return{mode:"latest",registry:parsed.registry,name:parsed.name}}return classifyVersionSuffix(parsed.registry,parsed.name,parsed.version)}function classifyVersionSuffix(registry,name,suffix){if(suffix.includes("...")){throw new InvalidPackageSpecError(`Invalid changelog interval '${suffix}'. Use '..' between endpoints; '...' is not supported.`)}if(!suffix.includes("..")){return{mode:"exact",registry,name,version:suffix}}const parts=suffix.split("..");if(parts.length!==2){throw new InvalidPackageSpecError(`Invalid changelog interval '${suffix}'. Expected at most one '..' between endpoints.`)}const fromVersion=emptyToUndefined(parts[0]);const toVersion=emptyToUndefined(parts[1]);if(fromVersion===undefined&&toVersion===undefined){throw new InvalidPackageSpecError("Empty changelog interval '@..' is not supported. Provide a from bound, a to bound, or both.")}if(fromVersion===undefined){return{mode:"latest",registry,name,toVersion}}return{mode:"range",registry,name,fromVersion,toVersion}}function emptyToUndefined(value){if(value===undefined)return;const trimmed=value.trim();return trimmed.length>0?trimmed:undefined}function isNonPackageChangelogTarget(spec){if(isRepositoryTargetSpec(spec))return true;const lower=spec.toLowerCase();return lower.startsWith("site:")||lower.startsWith("http:")||lower.startsWith("https:")}function normalisePackageVersion(raw,registry,options={}){if(raw===undefined)return;const version=raw.trim();if(version.length===0)return;if(registry==="GO"){if(/^[0-9]/.test(version))return`v${version}`;if(/^v[0-9]/.test(version))return version}if(options.rejectLeadingV===true&&registry!=="SWIFT"&&/^v[0-9]/i.test(version)){const fieldName=options.fieldName??"version";throw new InvalidPackageSpecError(`Invalid ${fieldName} '${version}': it looks like a git tag. Use the canonical package version without a leading 'v' (for example '${version.slice(1)}').`)}return version}function buildPackageChangelogParams(input){const target=input.target?.trim()??"";if(target.length===0){throw new InvalidPackageSpecError("`pkg changelog` requires a package spec (e.g. `npm:express`).")}const parsed=parsePackageChangelogTarget(target);const registry=toPkgseerRegistry2(parsed.registry);const flagFrom=normaliseBound(input.fromVersion,registry,"--from");const flagTo=normaliseBound(input.toVersion,registry,"--to");const limit=normaliseLimit(input.limit);const view=input.view??"statements";const changes=view==="statements"?normaliseChangelogChanges(input.changes):undefined;const statementTiers=changes==="actionable"?["MUST_ACT"]:changes==="important"?["MUST_ACT","SHOULD_KNOW"]:undefined;const explicitChanges=changes!==undefined&&Boolean(input.changes?.trim());if(parsed.mode==="exact"){rejectExactConflicts(flagFrom,flagTo,limit);const version=normaliseBound(parsed.version,registry,"version");if(version===undefined){throw new InvalidPackageSpecError("Selected-release target is missing a version.")}return{mode:"exact",changes,params:{registry,packageName:parsed.name,version,view,statementTiers},explicitFilterFields:new Set(explicitChanges?["version","changes"]:["version"])}}const inlineFrom=parsed.mode==="range"?normaliseBound(parsed.fromVersion,registry,"from version"):undefined;const inlineTo=normaliseBound(parsed.toVersion,registry,"to version");if(inlineFrom!==undefined&&flagFrom!==undefined){throw new InvalidPackageSpecError("Positional range already contains a from version. Drop `--from`, or use a bare package target with `--from`.")}if(inlineTo!==undefined&&flagTo!==undefined){throw new InvalidPackageSpecError("Positional target already contains a to version. Drop `--to`, or use a bare package target with `--to`.")}const fromVersion=inlineFrom??flagFrom;const toVersion=inlineTo??flagTo;const mode=fromVersion!==undefined?"range":"latest";if(fromVersion!==undefined&&limit!==undefined){throw new InvalidPackageSpecError("`--limit` / `limit` is a latest-mode input; drop `--limit` for range mode, or drop `--from` / the from bound to cap by count instead.")}const explicit=new Set;if(explicitChanges)explicit.add("changes");if(fromVersion!==undefined)explicit.add("fromVersion");if(toVersion!==undefined)explicit.add("toVersion");if(limit!==undefined)explicit.add("limit");return{mode,changes,params:{registry,packageName:parsed.name,fromVersion,toVersion,limit,view,statementTiers},explicitFilterFields:explicit}}function rejectExactConflicts(fromVersion,toVersion,limit){const extras=[];if(fromVersion!==undefined)extras.push("`--from`");if(toVersion!==undefined)extras.push("`--to`");if(limit!==undefined)extras.push("`limit`");if(extras.length===0)return;throw new InvalidPackageSpecError(`Inline single-release target already selects one release; drop ${joinList(extras)}.`)}function joinList(items){if(items.length===1)return items.join("");if(items.length===2)return`${items[0]} and ${items[1]}`;return`${items.slice(0,-1).join(", ")}, and ${items.at(-1)}`}function normaliseBound(raw,registry,fieldName){return normalisePackageVersion(raw,registry,{rejectLeadingV:true,fieldName})}function normaliseLimit(raw){if(raw===undefined)return;if(!Number.isInteger(raw)||raw<1||raw>50){throw new InvalidPackageSpecError(`\`limit\` must be an integer between 1 and 50. Got ${raw}.`)}return raw}function resolvePackageChangelogView(input){const fullNotes=input.verbatim===true||input.verbose===true;if(input.omitBodies&&fullNotes)throw new InvalidPackageSpecError("--no-body / omit_bodies cannot be combined with --verbatim / verbatim or its --verbose / verbose alias.");if(input.omitBodies)return{view:"timeline"};if(fullNotes)return{view:"verbatim"};if(!input.json&&input.bodyLines!==undefined){if(!Number.isInteger(input.bodyLines)||input.bodyLines<1||input.bodyLines>50)throw new InvalidPackageSpecError(`body_lines must be an integer between 1 and 50. Got ${input.bodyLines}.`);return{view:"verbatim",bodyPreviewLines:input.bodyLines}}return{view:"statements"}}function releaseNoteText(text,reference){const plain=safeRiskText(text.split(/\r?\n/).map((line)=>line.replace(/^\s*(?:>\s*)+/,"").replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/,"").replace(/\[!([A-Z]+)\]/g,"$1:")).join(" ")).replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1").replace(/\[(S?\d+)\](?!\()/g,"($1)");return plain.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<>]+)/g,(_match,label,linkedUrl,bareUrl)=>{if(linkedUrl)return`${label??""} ${reference(linkedUrl)}`.trim();const rawUrl=bareUrl??"";const url=rawUrl.replace(/[.,;:!?)]*$/,"");return`${reference(url)}${rawUrl.slice(url.length)}`}).replace(/\s+/g," ").trim()}var RISK_KIND_LABELS={removes_or_renames_api:"removal",changes_behavior_or_default:"behavior",raises_runtime_or_platform_requirement:"runtime/platform",changes_packaging_or_module_format:"packaging/modules",deprecates_without_removal:"deprecation",security_fix:"security fix",notable_change:"notable change"};var PENDING_CLASSIFICATION_MESSAGE="Classification is still running or may have failed. Rerun in a few seconds to a minute to fill not-assessed versions from completed stored labels, without rerunning the model.";function safeRiskText(value){return sanitizeTerminalText(value.replace(/\s+/g," ")).trim()}function buildPackageChangelogSuccessPayload(report,options){const items=report.entries.map((entry)=>{const lean={version:entry.version??null};if(entry.normalizedVersion!=null){lean.normalizedVersion=entry.normalizedVersion}if(entry.publishedAt!=null){lean.publishedAt=entry.publishedAt}if(entry.htmlUrl!=null){lean.htmlUrl=entry.htmlUrl}if(options.view==="verbatim"&&entry.body!=null){lean.body=entry.body}if(options.mode==="exact"&&entry.hasChangelog!==undefined){lean.hasChangelog=entry.hasChangelog}return lean});const envelope={mode:options.mode,entries:{count:items.length,items}};if(options.view==="statements"&&report.statements){envelope.statements=normaliseChangelogStatements(report.statements)}if(report.source)envelope.source=report.source;if(options.registry)envelope.registry=options.registry;if(options.name)envelope.name=options.name;const filter=buildFilterBlock(options);if(filter)envelope.filter=filter;return envelope}function normaliseChangelogStatements(statements){return{...statements,count:statements.items.length,items:statements.items.map((item)=>({...item,...item.source?{source:item.source.toLowerCase()}:{},classification:item.classification===null?null:{...item.classification,tier:item.classification.tier.toLowerCase(),...item.classification.kind?{kind:item.classification.kind.toLowerCase()}:{}}})),coverage:statements.coverage.map((c)=>({...c,status:c.status.toLowerCase()}))}}function buildFilterBlock(options){const{explicitFilterFields}=options;if(explicitFilterFields.size===0)return;const filter={};if(options.explicitFilterFields.has("changes")&&options.changes)filter.changes=options.changes;if(explicitFilterFields.has("fromVersion")&&options.fromVersion){filter.fromVersion=options.fromVersion}if(explicitFilterFields.has("toVersion")&&options.toVersion){filter.toVersion=options.toVersion}if(explicitFilterFields.has("limit")&&options.limit!==undefined){filter.limit=options.limit}if(explicitFilterFields.has("version")&&options.version){filter.version=options.version}return Object.keys(filter).length>0?filter:undefined}function formatPackageChangelogTerminal(envelope,options){const width=Number.isFinite(options.terminalWidth)?Math.max(20,Math.floor(options.terminalWidth)):80;const lines=[];const prose=(text,indent="")=>{lines.push(...wrapTerminalProse(`${indent}${text}`,width,indent))};const identity=envelope.registry&&envelope.name?`${envelope.registry}:${envelope.name}`:"(unknown package)";lines.push(...wrapTerminalProse(sanitizeTerminalText(`${identity} | ${modeSummary(envelope)} | ${envelope.entries.count} release${envelope.entries.count===1?"":"s"}`),width).map((line)=>colorize(line,"bold",options.useColors)));const statements=envelope.statements;if(statements){lines.push("",highlight("Changes (classified by agent)",options.useColors));const c=statements.coverage;prose(`${statements.count} ${envelope.filter?.changes&&envelope.filter.changes!=="all"?"matching ":""}statements of ${statements.totalCount} parsed | versions: ${c.filter((v)=>v.status==="classified").length} classified | ${c.filter((v)=>v.status==="not_assessed").length} not assessed | ${c.filter((v)=>v.status==="without_notes").length} without notes | ${c.filter((v)=>v.status==="unparseable").length} without parsed statements`," ");if(statements.items.some((item)=>item.classification?.tier==="must_act"||item.classification?.tier==="should_know"||item.classification?.tier==="no_impact"))prose("! requires action | kind tags: should know | plain: no impact identified"," ");const pending=c.reduce((sum,v)=>sum+v.statementsNotAssessed,0);const oversize=c.reduce((sum,v)=>sum+v.statementsUnclassified,0);if(envelope.filter?.changes&&envelope.filter.changes!=="all")prose(`Filter excludes ${pending} not-assessed and ${oversize} too-long-to-classify statements.`," ");if(pending)prose("Classification is still in progress or failed. Rerun in a few seconds to a minute to fill stored answers."," ");if(c.some((v)=>v.status==="without_notes"||v.status==="unparseable"))prose("Missing or unparseable notes are not evidence of no risk."," ")}if(!envelope.entries.items.length)lines.push("","No releases in this selection.");for(const entry of envelope.entries.items){lines.push("");lines.push(...wrapTerminalProse(sanitizeTerminalText(`${entry.version??"(unversioned)"}${entry.publishedAt?` (${formatDate(entry.publishedAt)})`:""}`),width).map((line)=>highlight(line,options.useColors)));if(!statements){if(entry.htmlUrl)prose(sanitizeTerminalText(entry.htmlUrl)," ");if(entry.body!==undefined)renderOriginalNotes(lines,entry.body,options);else if(entry.hasChangelog===false)lines.push(" No release notes available.");continue}const items=statements.items.filter((item)=>item.version===entry.version);if(!items.length){if(entry.htmlUrl)prose(sanitizeTerminalText(entry.htmlUrl)," ");const coverage=statements.coverage.find((v)=>v.version===entry.version);prose(coverage?.status==="without_notes"?"No release notes available.":coverage?.status==="unparseable"?"Notes contain no parsed statements.":"No statements match this filter."," ");continue}lines.push(...formatChangelogVersionStatements(items,options))}return`${lines.join(`
127
+ `+"Package targets cover one package-owned "+"tree; repository targets cover the whole snapshot. Both include source and "+"documentation. Hosted docs use an explicit `site:` target supplied by the "+"user or a docs search result. `paths` are target-relative literals or globs for every target and "+"form a union; omit them for the root. Directories show immediate children "+"unless `recursive` expands them; glob depth is independent of recursion. "+"In site text, a path without trailing `/` is a page even when its source URL ended in `/`. "+"Keep text for model use, including read and continuation guidance; use JSON "+"for exact entry kinds or actions and programmatic consumption.";function createListTool(service){return{name:"list",description:DESCRIPTION3,schema:schema3,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{let builtParams;try{builtParams=buildListParams({target:args.target,paths:args.paths,recursive:args.recursive,fileTypes:args.file_types,languages:args.languages,intents:args.intents,limit:args.limit,after:args.after,waitTimeoutMs:args.wait_timeout_ms,includeDetailedFields:args.format==="json",includeTargetProvenance:true});const result=await service.list(builtParams,...serviceRequestArgs(context?.signal));const payload=projectListResult(result);if(args.format!=="json"){return textResult(formatListText(payload,{useColors:false,syntax:"mcp",hasAfter:builtParams.after!==undefined}))}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapListError(error,{hasAfter:builtParams?.after!==undefined});return mcpMappedErrorResult(withIndexingRetryAction(mapped,"list","mcp",{maxWaitMs:MAX_DISCOVERY_WAIT_TIMEOUT_MS,hasAfter:builtParams?.after!==undefined}),context,args.format,{recovery:{syntax:"mcp",tool:"list",args},indexingTarget:args.target,indexingOutcome:args.target.startsWith("site:")?"No pages available yet.":"No files available yet."})}}}}import{z as z4}from"zod";function normaliseChangelogChanges(raw){const value=raw?.trim().toLowerCase()||"all";if(value!=="actionable"&&value!=="important"&&value!=="all"){throw new InvalidPackageSpecError("changes must be actionable, important (actionable + should know), or all.")}return value}var PACKAGE_ONLY_MESSAGE="`pkg_changelog` is package-only. Use a `registry:name` target such as `npm:express`, not a repository or site coordinate.";function parsePackageChangelogTarget(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidPackageSpecError("Package spec cannot be empty. Expected <registry>:<name>[@<version> or @<from>..<to>].")}if(isNonPackageChangelogTarget(trimmed)){throw new InvalidPackageSpecError(PACKAGE_ONLY_MESSAGE)}const parsed=parsePackageSpec(trimmed);if(parsed.version===undefined){return{mode:"latest",registry:parsed.registry,name:parsed.name}}return classifyVersionSuffix(parsed.registry,parsed.name,parsed.version)}function classifyVersionSuffix(registry,name,suffix){if(suffix.includes("...")){throw new InvalidPackageSpecError(`Invalid changelog interval '${suffix}'. Use '..' between endpoints; '...' is not supported.`)}if(!suffix.includes("..")){return{mode:"exact",registry,name,version:suffix}}const parts=suffix.split("..");if(parts.length!==2){throw new InvalidPackageSpecError(`Invalid changelog interval '${suffix}'. Expected at most one '..' between endpoints.`)}const fromVersion=emptyToUndefined(parts[0]);const toVersion=emptyToUndefined(parts[1]);if(fromVersion===undefined&&toVersion===undefined){throw new InvalidPackageSpecError("Empty changelog interval '@..' is not supported. Provide a from bound, a to bound, or both.")}if(fromVersion===undefined){return{mode:"latest",registry,name,toVersion}}return{mode:"range",registry,name,fromVersion,toVersion}}function emptyToUndefined(value){if(value===undefined)return;const trimmed=value.trim();return trimmed.length>0?trimmed:undefined}function isNonPackageChangelogTarget(spec){if(isRepositoryTargetSpec(spec))return true;const lower=spec.toLowerCase();return lower.startsWith("site:")||lower.startsWith("http:")||lower.startsWith("https:")}function normalisePackageVersion(raw,registry,options={}){if(raw===undefined)return;const version=raw.trim();if(version.length===0)return;if(registry==="GO"){if(/^[0-9]/.test(version))return`v${version}`;if(/^v[0-9]/.test(version))return version}if(options.rejectLeadingV===true&&registry!=="SWIFT"&&/^v[0-9]/i.test(version)){const fieldName=options.fieldName??"version";throw new InvalidPackageSpecError(`Invalid ${fieldName} '${version}': it looks like a git tag. Use the canonical package version without a leading 'v' (for example '${version.slice(1)}').`)}return version}function buildPackageChangelogParams(input){const target=input.target?.trim()??"";if(target.length===0){throw new InvalidPackageSpecError("`pkg changelog` requires a package spec (e.g. `npm:express`).")}const parsed=parsePackageChangelogTarget(target);const registry=toPkgseerRegistry2(parsed.registry);const flagFrom=normaliseBound(input.fromVersion,registry,"--from");const flagTo=normaliseBound(input.toVersion,registry,"--to");const limit=normaliseLimit(input.limit);const view=input.view??"statements";const changes=view==="statements"?normaliseChangelogChanges(input.changes):undefined;const statementTiers=changes==="actionable"?["MUST_ACT"]:changes==="important"?["MUST_ACT","SHOULD_KNOW"]:undefined;const explicitChanges=changes!==undefined&&Boolean(input.changes?.trim());if(parsed.mode==="exact"){rejectExactConflicts(flagFrom,flagTo,limit);const version=normaliseBound(parsed.version,registry,"version");if(version===undefined){throw new InvalidPackageSpecError("Selected-release target is missing a version.")}return{mode:"exact",changes,params:{registry,packageName:parsed.name,version,view,statementTiers},explicitFilterFields:new Set(explicitChanges?["version","changes"]:["version"])}}const inlineFrom=parsed.mode==="range"?normaliseBound(parsed.fromVersion,registry,"from version"):undefined;const inlineTo=normaliseBound(parsed.toVersion,registry,"to version");if(inlineFrom!==undefined&&flagFrom!==undefined){throw new InvalidPackageSpecError("Positional range already contains a from version. Drop `--from`, or use a bare package target with `--from`.")}if(inlineTo!==undefined&&flagTo!==undefined){throw new InvalidPackageSpecError("Positional target already contains a to version. Drop `--to`, or use a bare package target with `--to`.")}const fromVersion=inlineFrom??flagFrom;const toVersion=inlineTo??flagTo;const mode=fromVersion!==undefined?"range":"latest";if(fromVersion!==undefined&&limit!==undefined){throw new InvalidPackageSpecError("`--limit` / `limit` is a latest-mode input; drop `--limit` for range mode, or drop `--from` / the from bound to cap by count instead.")}const explicit=new Set;if(explicitChanges)explicit.add("changes");if(fromVersion!==undefined)explicit.add("fromVersion");if(toVersion!==undefined)explicit.add("toVersion");if(limit!==undefined)explicit.add("limit");return{mode,changes,params:{registry,packageName:parsed.name,fromVersion,toVersion,limit,view,statementTiers},explicitFilterFields:explicit}}function rejectExactConflicts(fromVersion,toVersion,limit){const extras=[];if(fromVersion!==undefined)extras.push("`--from`");if(toVersion!==undefined)extras.push("`--to`");if(limit!==undefined)extras.push("`limit`");if(extras.length===0)return;throw new InvalidPackageSpecError(`Inline single-release target already selects one release; drop ${joinList(extras)}.`)}function joinList(items){if(items.length===1)return items.join("");if(items.length===2)return`${items[0]} and ${items[1]}`;return`${items.slice(0,-1).join(", ")}, and ${items.at(-1)}`}function normaliseBound(raw,registry,fieldName){return normalisePackageVersion(raw,registry,{rejectLeadingV:true,fieldName})}function normaliseLimit(raw){if(raw===undefined)return;if(!Number.isInteger(raw)||raw<1||raw>50){throw new InvalidPackageSpecError(`\`limit\` must be an integer between 1 and 50. Got ${raw}.`)}return raw}function resolvePackageChangelogView(input){const fullNotes=input.verbatim===true||input.verbose===true;if(input.omitBodies&&fullNotes)throw new InvalidPackageSpecError("--no-body / omit_bodies cannot be combined with --verbatim / verbatim or its --verbose / verbose alias.");if(input.omitBodies)return{view:"timeline"};if(fullNotes)return{view:"verbatim"};if(!input.json&&input.bodyLines!==undefined){if(!Number.isInteger(input.bodyLines)||input.bodyLines<1||input.bodyLines>50)throw new InvalidPackageSpecError(`body_lines must be an integer between 1 and 50. Got ${input.bodyLines}.`);return{view:"verbatim",bodyPreviewLines:input.bodyLines}}return{view:"statements"}}function releaseNoteText(text,reference){const plain=safeRiskText(text.split(/\r?\n/).map((line)=>line.replace(/^\s*(?:>\s*)+/,"").replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/,"").replace(/\[!([A-Z]+)\]/g,"$1:")).join(" ")).replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1").replace(/\[(S?\d+)\](?!\()/g,"($1)");return plain.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<>]+)/g,(_match,label,linkedUrl,bareUrl)=>{if(linkedUrl)return`${label??""} ${reference(linkedUrl)}`.trim();const rawUrl=bareUrl??"";const url=rawUrl.replace(/[.,;:!?)]*$/,"");return`${reference(url)}${rawUrl.slice(url.length)}`}).replace(/\s+/g," ").trim()}var RISK_KIND_LABELS={removes_or_renames_api:"removal",changes_behavior_or_default:"behavior",raises_runtime_or_platform_requirement:"runtime/platform",changes_packaging_or_module_format:"packaging/modules",deprecates_without_removal:"deprecation",security_fix:"security fix",notable_change:"notable change"};var PENDING_CLASSIFICATION_MESSAGE="Classification is still running or may have failed. Rerun in a few seconds to a minute to fill not-assessed versions from completed stored labels, without rerunning the model.";function safeRiskText(value){return sanitizeTerminalText(value.replace(/\s+/g," ")).trim()}function buildPackageChangelogSuccessPayload(report,options){const items=report.entries.map((entry)=>{const lean={version:entry.version??null};if(entry.normalizedVersion!=null){lean.normalizedVersion=entry.normalizedVersion}if(entry.publishedAt!=null){lean.publishedAt=entry.publishedAt}if(entry.htmlUrl!=null){lean.htmlUrl=entry.htmlUrl}if(options.view==="verbatim"&&entry.body!=null){lean.body=entry.body}if(options.mode==="exact"&&entry.hasChangelog!==undefined){lean.hasChangelog=entry.hasChangelog}return lean});const envelope={mode:options.mode,entries:{count:items.length,items}};if(options.view==="statements"&&report.statements){envelope.statements=normaliseChangelogStatements(report.statements)}if(report.source)envelope.source=report.source;if(options.registry)envelope.registry=options.registry;if(options.name)envelope.name=options.name;const filter=buildFilterBlock(options);if(filter)envelope.filter=filter;return envelope}function normaliseChangelogStatements(statements){return{...statements,count:statements.items.length,items:statements.items.map((item)=>{const{commits,...statement}=omitDuplicateFullText(item);const commit=commits?.[0];return{...statement,...item.context?{context:omitDuplicateFullText(item.context)}:{},...commit?{commits:[commit.url??commit.sha]}:{},...commits&&commits.length>1?{commitsOmitted:commits.length-1}:{},...item.source?{source:item.source.toLowerCase()}:{},classification:item.classification===null?null:{...item.classification,tier:item.classification.tier.toLowerCase(),...item.classification.kind?{kind:item.classification.kind.toLowerCase()}:{}}}}),coverage:statements.coverage.map(({generation,...c})=>({...c,status:c.status.toLowerCase(),...generation?{generation:{status:generation.status.toLowerCase(),...generation.reason!=null?{reason:generation.reason}:{}}}:{}}))}}function omitDuplicateFullText(value){const{fullText,...rest}=value;return{...rest,...fullText!==undefined&&fullText!==value.text?{fullText}:{}}}function buildFilterBlock(options){const{explicitFilterFields}=options;if(explicitFilterFields.size===0)return;const filter={};if(options.explicitFilterFields.has("changes")&&options.changes)filter.changes=options.changes;if(explicitFilterFields.has("fromVersion")&&options.fromVersion){filter.fromVersion=options.fromVersion}if(explicitFilterFields.has("toVersion")&&options.toVersion){filter.toVersion=options.toVersion}if(explicitFilterFields.has("limit")&&options.limit!==undefined){filter.limit=options.limit}if(explicitFilterFields.has("version")&&options.version){filter.version=options.version}return Object.keys(filter).length>0?filter:undefined}function formatPackageChangelogTerminal(envelope,options){const width=Number.isFinite(options.terminalWidth)?Math.max(20,Math.floor(options.terminalWidth)):80;const lines=[];const prose=(text,indent="")=>{lines.push(...wrapTerminalProse(`${indent}${text}`,width,indent))};const identity=envelope.registry&&envelope.name?`${envelope.registry}:${envelope.name}`:"(unknown package)";lines.push(...wrapTerminalProse(sanitizeTerminalText(`${identity} | ${modeSummary(envelope)} | ${envelope.entries.count} release${envelope.entries.count===1?"":"s"}`),width).map((line)=>colorize(line,"bold",options.useColors)));const statements=envelope.statements;if(statements){lines.push("",highlight("Changes (classified by agent)",options.useColors));const c=statements.coverage;prose(`${statements.count} ${envelope.filter?.changes&&envelope.filter.changes!=="all"?"matching ":""}statements of ${statements.totalCount} parsed | versions: ${c.filter((v)=>v.status==="classified").length} classified | ${c.filter((v)=>v.status==="not_assessed").length} not assessed | ${c.filter((v)=>v.status==="without_notes").length} without notes | ${c.filter((v)=>v.status==="unparseable").length} without parsed statements`," ");if(statements.items.some((item)=>item.classification?.tier==="must_act"||item.classification?.tier==="should_know"||item.classification?.tier==="no_impact"))prose("! requires action | kind tags: should know | plain: no impact identified"," ");const pending=c.reduce((sum,v)=>sum+v.statementsNotAssessed,0);const oversize=c.reduce((sum,v)=>sum+v.statementsUnclassified,0);if(envelope.filter?.changes&&envelope.filter.changes!=="all")prose(`Filter excludes ${pending} not-assessed and ${oversize} too-long-to-classify statements.`," ");if(pending)prose("Classification is still in progress or failed. Rerun in a few seconds to a minute to fill stored answers."," ");if(c.some((v)=>v.status==="without_notes"||v.status==="unparseable"))prose("Missing or unparseable notes are not evidence of no risk."," ")}if(!envelope.entries.items.length)lines.push("","No releases in this selection.");for(const entry of envelope.entries.items){lines.push("");lines.push(...wrapTerminalProse(sanitizeTerminalText(`${entry.version??"(unversioned)"}${entry.publishedAt?` (${formatDate(entry.publishedAt)})`:""}`),width).map((line)=>highlight(line,options.useColors)));if(!statements){if(entry.htmlUrl)prose(sanitizeTerminalText(entry.htmlUrl)," ");if(entry.body!==undefined)renderOriginalNotes(lines,entry.body,options);else if(entry.hasChangelog===false)lines.push(" No release notes available.");continue}const items=statements.items.filter((item)=>item.version===entry.version);const coverage=statements.coverage.find((v)=>v.version===entry.version);lines.push(...formatChangelogGeneration(coverage,options));if(!items.length){if(entry.htmlUrl)prose(sanitizeTerminalText(entry.htmlUrl)," ");if(coverage?.generation?.status==="generated"&&coverage.statementsTotal===0)continue;prose(coverage?.generation&&coverage.statementsTotal>0?"No statements match this filter.":coverage?.status==="without_notes"?"No release notes available.":coverage?.status==="unparseable"?"Notes contain no parsed statements.":"No statements match this filter."," ");continue}lines.push(...formatChangelogVersionStatements(items,options))}return`${lines.join(`
128
128
  `)}
129
- `}function formatChangelogVersionStatements(items,options){const lines=[];const width=Math.max(20,options.terminalWidth??80);const prose=(text,indent="")=>{lines.push(...wrapTerminalProse(`${indent}${text}`,width,indent))};let sourceIndex;let heading;for(const item of items){if(sourceIndex!==item.sourceIndex){sourceIndex=item.sourceIndex;heading=undefined;const source=noteSourceLabel(item.source);prose(`${source}${item.url?`: ${sanitizeTerminalText(item.url)}`:" (source URL unavailable)"}`," ")}if(item.heading!==heading){heading=item.heading;if(heading)prose(sanitizeTerminalText(heading)," ")}if(item.context){if(item.context.heading&&item.context.heading!==heading)prose(`Context for next statement - ${sanitizeTerminalText(item.context.heading)}`," ");else prose("Context for next statement"," ");renderStatementText(lines,item.context.text," ",width);if(item.context.textTruncated)prose(`Context truncated; ${options.fullStatementHint??"use --json for full text"}.`," ")}const classification=item.classification;const tier=classification?.tier;const kind=classification?.kind?RISK_KIND_LABELS[classification.kind]:undefined;const annotation=tier==="no_impact"?undefined:tier==="unclassified"?"[too long to classify - read it]":!classification?"[not assessed]":kind?`[${tier==="must_act"?"!":""}${kind}]`:tier==="must_act"?"[!]":"[should know]";const start=lines.length;renderStatementText(lines,options.compactNonAction&&tier!=="must_act"&&Array.from(item.text).length>240?`${Array.from(item.text).slice(0,240).join("")}...`:item.text,` * ${annotation?`${annotation} `:""}${classification?.ambiguous?"(uncertain) ":""}`,width);if(annotation&&lines[start]?.startsWith(` * ${annotation}`)){const styled=classification?.ambiguous||!classification?dim(annotation,options.useColors):colorize(annotation,tier==="must_act"?"red":tier==="should_know"?"yellow":"cyan",options.useColors);lines[start]=` * ${styled}${lines[start].slice(6+annotation.length)}`}if(classification?.ambiguous&&lines[start])lines[start]=lines[start].replace("(uncertain)",dim("(uncertain)",options.useColors));if(options.compactNonAction&&tier!=="must_act"&&Array.from(item.text).length>240)prose("Excerpt; use verbose for the full bounded quote."," ");if(item.textTruncated)prose(`Statement truncated; ${options.fullStatementHint??"use --json for full text"}.`," ")}return lines}function renderStatementText(lines,text,prefix,width){const raw=text.split(`
129
+ `}function formatChangelogGeneration(coverage,options){const generation=coverage?.generation;if(!generation)return[];const lines=[];const prose=(text)=>{lines.push(...wrapTerminalProse(` ${sanitizeTerminalText(text)}`,Math.max(20,options.terminalWidth??80)," "))};if(generation.status==="generated"){if(coverage.statementsTotal===0)prose("No actionable statements (generated from commits).")}else{const reason=generation.reason?` (${generation.reason})`:"";prose(generation.status==="pending"?`Generation pending${reason}; retry later.`:`Generation unavailable${reason}.`)}return lines}function formatChangelogVersionStatements(items,options){const lines=[];const width=Math.max(20,options.terminalWidth??80);const prose=(text,indent="")=>{lines.push(...wrapTerminalProse(`${indent}${text}`,width,indent))};let sourceIndex;let heading;for(const item of items){if(sourceIndex!==item.sourceIndex){sourceIndex=item.sourceIndex;heading=undefined;const source=noteSourceLabel(item.source);prose(item.source==="generated"?"(generated from commits)":`${source}${item.url?`: ${sanitizeTerminalText(item.url)}`:" (source URL unavailable)"}`," ")}if(item.heading!==heading){heading=item.heading;if(heading)prose(sanitizeTerminalText(heading)," ")}if(item.context){if(item.context.heading&&item.context.heading!==heading)prose(`Context for next statement - ${sanitizeTerminalText(item.context.heading)}`," ");else prose("Context for next statement"," ");renderStatementText(lines,item.context.text," ",width);if(item.context.textTruncated)prose(`Context truncated; ${options.fullStatementHint??"use --json for full text"}.`," ")}const classification=item.classification;const tier=classification?.tier;const kind=classification?.kind?RISK_KIND_LABELS[classification.kind]:undefined;const annotation=tier==="no_impact"?undefined:tier==="unclassified"?"[too long to classify - read it]":!classification?"[not assessed]":kind?`[${tier==="must_act"?"!":""}${kind}]`:tier==="must_act"?"[!]":"[should know]";const start=lines.length;renderStatementText(lines,options.compactNonAction&&tier!=="must_act"&&Array.from(item.text).length>240?`${Array.from(item.text).slice(0,240).join("")}...`:item.text,` * ${annotation?`${annotation} `:""}${classification?.ambiguous?"(uncertain) ":""}`,width);if(annotation&&lines[start]?.startsWith(` * ${annotation}`)){const styled=classification?.ambiguous||!classification?dim(annotation,options.useColors):colorize(annotation,tier==="must_act"?"red":tier==="should_know"?"yellow":"cyan",options.useColors);lines[start]=` * ${styled}${lines[start].slice(6+annotation.length)}`}if(classification?.ambiguous&&lines[start])lines[start]=lines[start].replace("(uncertain)",dim("(uncertain)",options.useColors));if(options.compactNonAction&&tier!=="must_act"&&Array.from(item.text).length>240)prose("Excerpt; use verbose for the full bounded quote."," ");if(item.textTruncated)prose(`Statement truncated; ${options.fullStatementHint??"use --json for full text"}.`," ")}return lines}function renderStatementText(lines,text,prefix,width){const raw=text.split(`
130
130
  `);const first=sanitizeTerminalText((raw[0]??"").replace(/\t/g," "));const contentIndent=first.match(/^ *(?:[-*+]|\d+[.)]) +/)?.[0].length??0;let fenced=false;raw.forEach((line,index)=>{const safe=sanitizeTerminalText(line.replace(/\t/g," "));const content=index===0?safe.replace(/^\s*(?:[-*+] |\d+[.)] )/,""):safe;if(!content.trim()){lines.push("");return}const leading=safe.match(/^ */)?.[0]??"";const indent=index===0?prefix:` ${leading}`;const value=index===0?content:content.trimStart();const isFence=value.startsWith("```")||value.startsWith("~~~");const nestedBullet=/^(?:[-*+]|\d+[.)]) +/.test(value.trimStart());const indentedCode=leading.length>=contentIndent+4&&!nestedBullet;if(fenced||isFence||indentedCode)lines.push(`${indent}${value}`);else lines.push(...wrapTerminalProse(`${indent}${value}`,width,index===0?" ":`${indent}${nestedBullet?" ":""}`));if(isFence)fenced=!fenced})}function renderOriginalNotes(lines,body,options){if(!body.trim()){lines.push(" (empty release notes)");return}const bodyLines=body.split(`
131
131
  `);const cap=options.bodyPreviewLines??bodyLines.length;for(const line of bodyLines.slice(0,cap))lines.push(` ${sanitizeTerminalText(line.replace(/\t/g," "))}`);if(bodyLines.length>cap)lines.push(` ... (+${bodyLines.length-cap} more lines - ${options.fullBodyHint??"use --verbatim for full original notes"})`)}function modeSummary(envelope){if(envelope.mode==="exact")return`exact ${envelope.entries.items[0]?.version??envelope.filter?.version??""}`.trim();if(envelope.mode==="range")return`range (${envelope.filter?.fromVersion??"earliest"}, ${envelope.filter?.toVersion??"latest"}] (start excluded; end included)`;return envelope.filter?.toVersion?`latest up to ${envelope.filter.toVersion}`:"latest"}function formatDate(iso){return/^\d{4}-\d{2}-\d{2}/.test(iso)?iso.slice(0,10):iso}function noteSourceLabel(source){if(source==="releases")return"Release notes";if(source==="changelog_file")return"Changelog";if(source==="hexdocs")return"HexDocs";if(source==="registry_release_notes")return"Registry notes";return source?sanitizeTerminalText(source):"Notes"}var schema4={target:z4.string().describe(`Package registry:name[@version|@from..to], for example npm:express@5.2.1; omit the version for latest. Ranges exclude from and include to: @4.21.2..5.2.1 returns releases after 4.21.2 through 5.2.1. Use @from alone for the starting release's own notes. Open bounds from.. and ..to are accepted. Package-only; repository and site targets are rejected. Registries: ${PKGSEER_REGISTRY_LIST2}.`),limit:z4.number().optional().describe("Latest-mode and upper-cap (`@..to`) count (1-50, default 10). Do not pass with exact `@version` or lower-bound range targets (`@from..to`, `@from..`)."),changes:z4.string().optional().describe("Statements: actionable (MUST_ACT, including uncertain), important (actionable + SHOULD_KNOW), or all (default, including no impact identified, too-long and unassessed statements). Filters before pagination. Coverage includes every selected release. Ignored outside the default statement view."),omit_bodies:z4.boolean().optional().describe("Show only the version/date/URL timeline, skipping parsing and classification. Cannot combine with verbatim:true or verbose:true."),verbatim:z4.boolean().optional().describe("Show full original notes instead of parsed statements, including bodies in JSON. Skips classification. Cannot combine with omit_bodies:true."),verbose:z4.boolean().optional().describe("Deprecated alias for verbatim:true, in text and JSON. Overrides body_lines; cannot combine with omit_bodies:true."),body_lines:z4.number().optional().describe("Deprecated text-only original-note preview request and line cap (1-50). Ignored for format=json, omit_bodies:true, verbatim:true and verbose:true. Omit for the default statement view."),format:z4.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text. JSON includes full statement text and per-item provenance by default; verbatim:true includes original markdown bodies.")};var DESCRIPTION_BASE="Find release notes and changelog history for a package. Default "+"latest mode returns up to ten entries; source ordering may interleave maintained release lines. "+"Pin `registry:name@version` for one selected release, or `registry:name@from..to` for releases after from through to (from excluded, to included). "+"`limit` applies only to latest and upper-cap targets. "+"A selected release without notes succeeds with `hasChangelog: false`. "+"Empty latest or range selections succeed with no entries. "+"Default text shows all parsed statements with available agent classifications, including no-impact and unassessed statements, in source order. `changes` filters statements; all matching pages are retrieved. `verbatim:true` shows original full notes; `omit_bodies:true` shows only the timeline. Original-note and timeline views skip classification and ignore `changes`.";var DESCRIPTION4=`${DESCRIPTION_BASE}
132
132
 
133
- ${PKG_CHANGELOG_GUARDRAIL}`;function createPackageChangelogTool(service){return{name:"pkg_changelog",description:DESCRIPTION4,schema:schema4,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const textFormat=isTextFormat2(args.format);const{view,bodyPreviewLines}=resolvePackageChangelogView({omitBodies:args.omit_bodies,verbatim:args.verbatim,verbose:args.verbose,bodyLines:args.body_lines,json:!textFormat});const{params,mode,explicitFilterFields,changes}=buildPackageChangelogParams({target:args.target,limit:args.limit,view,changes:args.changes});const report=await service.packageChangelog({...params,includeJsonFields:!textFormat},...serviceRequestArgs(context?.signal));const payload=buildPackageChangelogSuccessPayload(report,{registry:toPkgseerRegistryLowercase2(params.registry),name:params.packageName,mode,changes,explicitFilterFields,view,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,version:params.version});if(textFormat){return textResult(formatPackageChangelogTerminal(payload,{useColors:false,bodyPreviewLines,fullStatementHint:'pass format="json" for full text',fullBodyHint:"pass verbatim=true for full original notes"}).trimEnd())}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_changelog",args}})}}}}function isTextFormat2(format){return format===undefined||format==="text"}import{z as z5}from"zod";var SUPPORTED_DEPS_REGISTRY_ARGS=PKGSEER_REGISTRY_ARGS;var SUPPORTED_DEPS_REGISTRIES_LIST=SUPPORTED_DEPS_REGISTRY_ARGS.join(", ");var SUPPORTED_VULN_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","packagist","rubygems","go","swift"];var SUPPORTED_VULN_REGISTRIES=new Set(SUPPORTED_VULN_REGISTRY_ARGS.map(toPkgseerRegistry2));var SUPPORTED_VULN_REGISTRIES_LIST=SUPPORTED_VULN_REGISTRY_ARGS.join(", ");var SUPPORTED_VULN_REGISTRIES_HUMAN="npm, pypi, hex, crates, nuget, maven, packagist, rubygems, go, and swift";function supportsVulnerabilitiesRegistry(registry){return SUPPORTED_VULN_REGISTRIES.has(registry)}var LIFECYCLES=["runtime","development","build","peer","optional"];var LIFECYCLE_ORDER={runtime:0,development:1,build:2,peer:3,optional:4};function buildPackageDependenciesParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registryArg=parsePkgseerRegistryArg(input.registry??"");if(!registryArg){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const registry=toPkgseerRegistry2(registryArg);const version=normalisePackageVersion(input.version,registry,{rejectLeadingV:true});const canonicalLifecycles=resolveLifecycles(input.lifecycle);const wireLifecycles=canonicalLifecycles.filter((entry)=>entry!=="runtime"&&entry!=="all");const maxDepth=input.maxDepth;if(maxDepth!==undefined){if(!Number.isInteger(maxDepth)||maxDepth<1||maxDepth>10){throw new InvalidPackageSpecError(`Transitive depth must be an integer between 1 and 10. Got ${maxDepth}.`)}}return{canonicalLifecycles,wireLifecycles,params:{registry,packageName:trimmedName,version,includeTransitive:input.includeIssues===true?true:input.includeTransitive,includeTransitiveDetails:input.includeTransitiveDetails,includeGroups:input.includeGroups,includeDependencyIssues:input.includeIssues,maxDepth,lifecycle:wireLifecycles.length>0?wireLifecycles:undefined}}}function resolveLifecycles(raw){if(raw===undefined)return[];const tokens=Array.isArray(raw)?raw.flatMap((entry)=>entry.split(",")):raw.split(",");const seen=new Set;for(const token of tokens){const trimmed=token.trim();if(trimmed.length===0)continue;const lower=trimmed.toLowerCase();if(!isLifecycleInput(lower)){throw new InvalidPackageSpecError(`Unknown lifecycle '${trimmed}'. Expected one of: ${LIFECYCLES.join(", ")}, all.`)}seen.add(lower)}if(seen.has("all")&&seen.size>1){throw new InvalidPackageSpecError("lifecycle=all cannot be combined with other lifecycle values.")}return Array.from(seen).sort(lifecycleInputSort)}function isLifecycle(value){return LIFECYCLES.includes(value)}function isLifecycleInput(value){return value==="all"||isLifecycle(value)}function lifecycleInputSort(a,b){if(a==="all")return b==="all"?0:1;if(b==="all")return-1;return LIFECYCLE_ORDER[a]-LIFECYCLE_ORDER[b]}function buildPackageDependenciesSuccessPayload(report,options={}){const pkg=report.package;const payload={registry:lowerRegistry(pkg.registry),name:pkg.name,version:pkg.version};if(pkg.registryRepository)payload.registryRepository=pkg.registryRepository;const requestedEcho=deriveRequestedVersion(options.requestedVersion,pkg.version);if(requestedEcho!==undefined){payload.requestedVersion=requestedEcho}const bundle=report.dependencies;const graph=bundle?.transitive?.dependencyGraph??null;const directVersionByName=graph?buildDirectVersionLookup(graph):null;const directArray=bundle?.direct;if(directArray!==undefined){const items=directArray.map((entry)=>buildDirect(entry,directVersionByName));payload.runtime={count:items.length,items}}const groupsInfo=report.dependencyGroups;if(groupsInfo!==undefined&&shouldEmitGroups(options.canonicalLifecycles)){const groupItems=sortGroups(groupsInfo.groups.map(buildGroup).filter((group)=>{if(!options.canonicalLifecycles)return false;if(options.canonicalLifecycles.includes("all"))return true;return options.canonicalLifecycles.includes(group.lifecycle)}));const groupsBlock={items:groupItems};if(groupsInfo.primaryGroup&&groupItems.some((group)=>group.name===groupsInfo.primaryGroup)){groupsBlock.primaryGroup=groupsInfo.primaryGroup}if(groupsInfo.environmentMarkers&&groupsInfo.environmentMarkers.length>0){groupsBlock.environmentMarkers=groupsInfo.environmentMarkers.map((m)=>projectEnvironmentMarker(m))}payload.groups=groupsBlock}if(options.includeTransitive){const transitive=bundle?.transitive;if(transitive){const block={};if(transitive.totalEdges!==undefined){block.edges=transitive.totalEdges}if(transitive.uniquePackagesCount!==undefined){block.uniquePackages=transitive.uniquePackagesCount}if(options.maxDepth!==undefined){block.depth=options.maxDepth}const packages=buildTransitivePackages(transitive.uniqueDependencies,graph,options.includeImporters??false);if(packages&&packages.length>0){block.packages=packages}if(transitive.dependencyConflicts&&transitive.dependencyConflicts.length>0){block.conflicts=transitive.dependencyConflicts.map((c)=>projectTransitiveConflict(c,graph,payload))}if(transitive.circularDependencyCycles&&transitive.circularDependencyCycles.length>0){block.circularDependencies=transitive.circularDependencyCycles.map((c)=>({cycle:c.circularPath.slice()}))}payload.transitive=block}}const issueSummary=bundle?.transitive?.dependencyIssues;if(options.includeIssues===true&&issueSummary){payload.issues=projectDependencyIssues(issueSummary,graph,payload,options.maxDepth)}if(options.canonicalLifecycles&&options.canonicalLifecycles.length>0){payload.filter={lifecycles:options.canonicalLifecycles.slice()}}return payload}function projectDependencyIssues(issues,graph,payload,maxDepth){return{total:issues.totalCount,scope:maxDepth===undefined?{mode:"full"}:{mode:"depth_limited",maxDepth},deprecated:{count:issues.deprecatedCount,items:issues.deprecatedPackages.map(projectDeprecatedIssue)},outdated:{count:issues.outdatedCount,items:issues.outdatedPackages.map(projectOutdatedIssue)},duplicates:{count:issues.duplicateCount,items:issues.duplicatePackages.map(projectDuplicateIssue)},conflicts:{count:issues.conflictCount,items:issues.conflicts.map((conflict)=>projectIssueConflict(conflict,graph,payload))}}}function projectDeprecatedIssue(issue){return{registry:lowerRegistry(issue.registry),name:issue.name,versions:issue.versions.slice(),reasons:issue.reasons.map((reason)=>{const out={version:reason.version};if(reason.reason!==undefined)out.reason=reason.reason;return out})}}function projectOutdatedIssue(issue){const out={registry:lowerRegistry(issue.registry),name:issue.name,severity:issue.severity,versions:issue.versions.map((version)=>({version:version.version,severity:version.severity}))};if(issue.latestVersion!==undefined){out.latestVersion=issue.latestVersion}if(issue.repositoryUrl!==undefined){out.repositoryUrl=issue.repositoryUrl}return out}function projectDuplicateIssue(issue){const out={name:issue.name,versions:issue.versions.slice()};if(issue.registry!==undefined){out.registry=lowerRegistry(issue.registry)}return out}function projectTransitiveConflict(conflict,graph,payload){return{name:conflict.packageName,requiredVersions:conflict.requiredVersions.slice().sort(),requirements:projectConflictRequirements(conflict.conflictingEdges,graph,payload)}}function projectIssueConflict(conflict,graph,payload){const out={name:conflict.name,versions:conflict.versions.slice(),requiredVersions:conflict.requiredVersions.slice(),requirements:projectConflictRequirements(conflict.conflictingEdges,graph,payload)};if(conflict.registry!==undefined){out.registry=lowerRegistry(conflict.registry)}return out}function projectConflictRequirements(edges,graph,payload){return edges.map((edge)=>({constraint:edge.versionConstraint,dependencyType:edge.dependencyType,importer:edge.fromIndex===undefined||edge.fromIndex===null?{registry:payload.registry,name:payload.name,version:payload.version,root:true}:projectGraphNode(graph,edge.fromIndex),target:projectGraphNode(graph,edge.toIndex)}))}function projectGraphNode(graph,index){const node=graph.nodes[index];const identity={registry:lowerRegistry(node.registry),name:node.name};if(node.version!==undefined)identity.version=node.version;return identity}function shouldEmitGroups(lifecycles){if(!lifecycles||lifecycles.length===0)return false;return lifecycles.some((entry)=>entry!=="runtime")}function projectEnvironmentMarker(marker){const out={};if(marker.type!==undefined)out.type=marker.type;if(marker.value!==undefined)out.value=marker.value;if(marker.raw!==undefined)out.raw=marker.raw;return out}function buildDirect(entry,directVersionByName){const lean={name:entry.name};if(entry.versionConstraint)lean.constraint=entry.versionConstraint;const resolved=directVersionByName?.get(entry.name);if(resolved)lean.version=resolved;return lean}function buildDirectVersionLookup(graph){const rootIdx=findRootNodeIdx(graph);const out=new Map;for(const edge of graph.edges){const fromRoot=edge.fromIndex===undefined||edge.fromIndex===null||edge.fromIndex===rootIdx;if(!fromRoot)continue;const node=graph.nodes[edge.toIndex];if(!node?.version)continue;if(!out.has(node.name)){out.set(node.name,node.version)}}return out.size>0?out:null}function findRootNodeIdx(graph){const incoming=new Set;for(const e of graph.edges)incoming.add(e.toIndex);let root=null;for(let i=0;i<graph.nodes.length;i++){if(!incoming.has(i)){if(root!==null)return null;root=i}}return root}function buildTransitivePackages(uniqueDependencies,graph,includeImporters){if(!uniqueDependencies||uniqueDependencies.length===0)return null;const incoming=includeImporters&&graph?buildIncomingEdgeMap(graph):null;const out=[];for(const entry of uniqueDependencies){const[name,version]=parseNameAtVersion(entry);if(!name)continue;const record={name};if(version)record.version=version;if(includeImporters&&graph&&incoming){const nodeIdx=findNodeIdx(graph,name,version);if(nodeIdx!==null){const edges=incoming.get(nodeIdx)??[];const importers=buildImportersFromEdges(graph,edges);if(importers.length>0)record.importers=importers}}out.push(record)}return out}function parseNameAtVersion(raw){const trimmed=raw.trim();if(!trimmed)return[null,undefined];const atIdx=trimmed.lastIndexOf("@");if(atIdx<=0)return[trimmed,undefined];return[trimmed.slice(0,atIdx),trimmed.slice(atIdx+1)]}function buildIncomingEdgeMap(graph){const map=new Map;for(const edge of graph.edges){const list=map.get(edge.toIndex);if(list)list.push(edge);else map.set(edge.toIndex,[edge])}return map}function findNodeIdx(graph,name,version){let fallback=null;for(let i=0;i<graph.nodes.length;i++){const n=graph.nodes[i];if(!n)continue;if(n.name!==name)continue;if(version&&n.version===version)return i;if(!version&&!n.version)return i;if(fallback===null)fallback=i}return fallback}function buildImportersFromEdges(graph,edges){const seen=new Set;const out=[];for(const edge of edges){if(edge.fromIndex===undefined||edge.fromIndex===null)continue;const from=graph.nodes[edge.fromIndex];if(!from)continue;const key=`${from.name}\x00${from.version??""}\x00${edge.constraint??""}`;if(seen.has(key))continue;seen.add(key);const importer={name:from.name};if(from.version)importer.version=from.version;if(edge.constraint)importer.constraint=edge.constraint;out.push(importer)}out.sort((a,b)=>{if(a.name!==b.name)return a.name<b.name?-1:1;const av=a.version??"";const bv=b.version??"";if(av!==bv)return av<bv?-1:1;const ac=a.constraint??"";const bc=b.constraint??"";return ac<bc?-1:ac>bc?1:0});return out}function buildGroup(group){const lean={name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,selectionMode:group.selectionMode,items:group.dependencies.map((dep)=>{const entry={name:dep.name};if(dep.constraint)entry.constraint=dep.constraint;return entry})};if(group.conditionValue)lean.conditionValue=group.conditionValue;if(group.exclusiveGroup)lean.exclusiveGroup=group.exclusiveGroup;if(group.fallbackPriority!==undefined){lean.fallbackPriority=group.fallbackPriority}if(group.compatibleWith&&group.compatibleWith.length>0){lean.compatibleWith=group.compatibleWith.slice()}if(group.defaultEnabled!==undefined){lean.defaultEnabled=group.defaultEnabled}return lean}var LIFECYCLE_ORDER2={runtime:0,development:1,build:2,peer:3,optional:4};function sortGroups(groups){return groups.slice().sort((a,b)=>{const la=LIFECYCLE_ORDER2[a.lifecycle]??99;const lb=LIFECYCLE_ORDER2[b.lifecycle]??99;if(la!==lb)return la-lb;if(a.lifecycle==="optional"){const ad=a.defaultEnabled===true?0:1;const bd=b.defaultEnabled===true?0:1;if(ad!==bd)return ad-bd}return a.name<b.name?-1:a.name>b.name?1:0})}function deriveRequestedVersion(requested,resolved){if(requested===undefined)return;const trimmed=requested.trim();if(trimmed.length===0)return;if(trimmed===resolved)return;return trimmed}function lowerRegistry(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function formatPackageDependenciesTerminal(report,options={}){const verbose=options.verbose??false;const payload=buildPackageDependenciesSuccessPayload(report,{requestedVersion:options.requestedVersion,canonicalLifecycles:options.canonicalLifecycles??["all"],includeTransitive:options.includeTransitive,maxDepth:options.maxDepth,includeImporters:verbose,includeIssues:options.includeIssues});const useColors=options.useColors??false;const terminalWidth=resolveIssueTerminalWidth(options.terminalWidth);const showGroups=options.showGroups??false;const includeTransitive=options.includeTransitive??false;const blocks=[];blocks.push(formatHeaderBlock(payload,useColors,showGroups,options));if(includeTransitive){blocks.push(formatTransitiveDepsList(payload,verbose,useColors));const issues=formatConflictsAndCycles(payload,verbose,useColors,terminalWidth);if(issues)blocks.push(issues)}else if(!showGroups){blocks.push(formatDirectDepsList(payload,verbose,useColors))}if(showGroups){blocks.push(formatGroupsBlock(payload,verbose,useColors))}const dependencyIssues=formatDependencyIssues(payload.issues,verbose,useColors,options.issuesDetailHint,terminalWidth);if(dependencyIssues)blocks.push(dependencyIssues);return`${blocks.filter((b)=>b.length>0).join(`
133
+ ${PKG_CHANGELOG_GUARDRAIL}`;function createPackageChangelogTool(service){return{name:"pkg_changelog",description:DESCRIPTION4,schema:schema4,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const textFormat=isTextFormat2(args.format);const{view,bodyPreviewLines}=resolvePackageChangelogView({omitBodies:args.omit_bodies,verbatim:args.verbatim,verbose:args.verbose,bodyLines:args.body_lines,json:!textFormat});const{params,mode,explicitFilterFields,changes}=buildPackageChangelogParams({target:args.target,limit:args.limit,view,changes:args.changes});const report=await service.packageChangelog({...params,includeJsonFields:!textFormat},...serviceRequestArgs(context?.signal));const payload=buildPackageChangelogSuccessPayload(report,{registry:toPkgseerRegistryLowercase2(params.registry),name:params.packageName,mode,changes,explicitFilterFields,view,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,version:params.version});if(textFormat){return textResult(formatPackageChangelogTerminal(payload,{useColors:false,bodyPreviewLines,fullStatementHint:'pass format="json" for full text',fullBodyHint:"pass verbatim=true for full original notes"}).trimEnd())}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_changelog",args}})}}}}function isTextFormat2(format){return format===undefined||format==="text"}import{z as z5}from"zod";var SUPPORTED_DEPS_REGISTRY_ARGS=PKGSEER_REGISTRY_ARGS;var SUPPORTED_DEPS_REGISTRIES_LIST=SUPPORTED_DEPS_REGISTRY_ARGS.join(", ");var SUPPORTED_VULN_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","packagist","rubygems","go","swift","pub"];var SUPPORTED_VULN_REGISTRIES=new Set(SUPPORTED_VULN_REGISTRY_ARGS.map(toPkgseerRegistry2));var SUPPORTED_VULN_REGISTRIES_LIST=SUPPORTED_VULN_REGISTRY_ARGS.join(", ");var SUPPORTED_VULN_REGISTRIES_HUMAN=`${SUPPORTED_VULN_REGISTRY_ARGS.slice(0,-1).join(", ")}, and ${SUPPORTED_VULN_REGISTRY_ARGS[SUPPORTED_VULN_REGISTRY_ARGS.length-1]}`;function supportsVulnerabilitiesRegistry(registry){return SUPPORTED_VULN_REGISTRIES.has(registry)}var LIFECYCLES=["runtime","development","build","peer","optional"];var LIFECYCLE_ORDER={runtime:0,development:1,build:2,peer:3,optional:4};function buildPackageDependenciesParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registryArg=parsePkgseerRegistryArg(input.registry??"");if(!registryArg){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const registry=toPkgseerRegistry2(registryArg);const version=normalisePackageVersion(input.version,registry,{rejectLeadingV:true});const canonicalLifecycles=resolveLifecycles(input.lifecycle);const wireLifecycles=canonicalLifecycles.filter((entry)=>entry!=="runtime"&&entry!=="all");const maxDepth=input.maxDepth;if(maxDepth!==undefined){if(!Number.isInteger(maxDepth)||maxDepth<1||maxDepth>10){throw new InvalidPackageSpecError(`Transitive depth must be an integer between 1 and 10. Got ${maxDepth}.`)}}return{canonicalLifecycles,wireLifecycles,params:{registry,packageName:trimmedName,version,includeTransitive:input.includeIssues===true?true:input.includeTransitive,includeTransitiveDetails:input.includeTransitiveDetails,includeGroups:input.includeGroups,includeDependencyIssues:input.includeIssues,maxDepth,lifecycle:wireLifecycles.length>0?wireLifecycles:undefined}}}function resolveLifecycles(raw){if(raw===undefined)return[];const tokens=Array.isArray(raw)?raw.flatMap((entry)=>entry.split(",")):raw.split(",");const seen=new Set;for(const token of tokens){const trimmed=token.trim();if(trimmed.length===0)continue;const lower=trimmed.toLowerCase();if(!isLifecycleInput(lower)){throw new InvalidPackageSpecError(`Unknown lifecycle '${trimmed}'. Expected one of: ${LIFECYCLES.join(", ")}, all.`)}seen.add(lower)}if(seen.has("all")&&seen.size>1){throw new InvalidPackageSpecError("lifecycle=all cannot be combined with other lifecycle values.")}return Array.from(seen).sort(lifecycleInputSort)}function isLifecycle(value){return LIFECYCLES.includes(value)}function isLifecycleInput(value){return value==="all"||isLifecycle(value)}function lifecycleInputSort(a,b){if(a==="all")return b==="all"?0:1;if(b==="all")return-1;return LIFECYCLE_ORDER[a]-LIFECYCLE_ORDER[b]}function buildPackageDependenciesSuccessPayload(report,options={}){const pkg=report.package;const payload={registry:lowerRegistry(pkg.registry),name:pkg.name,version:pkg.version};if(pkg.registryRepository)payload.registryRepository=pkg.registryRepository;const requestedEcho=deriveRequestedVersion(options.requestedVersion,pkg.version);if(requestedEcho!==undefined){payload.requestedVersion=requestedEcho}const bundle=report.dependencies;const graph=bundle?.transitive?.dependencyGraph??null;const directVersionByName=graph?buildDirectVersionLookup(graph):null;const directArray=bundle?.direct;if(directArray!==undefined){const items=directArray.map((entry)=>buildDirect(entry,directVersionByName));payload.runtime={count:items.length,items}}const groupsInfo=report.dependencyGroups;if(groupsInfo!==undefined&&shouldEmitGroups(options.canonicalLifecycles)){const groupItems=sortGroups(groupsInfo.groups.map(buildGroup).filter((group)=>{if(!options.canonicalLifecycles)return false;if(options.canonicalLifecycles.includes("all"))return true;return options.canonicalLifecycles.includes(group.lifecycle)}));const groupsBlock={items:groupItems};if(groupsInfo.primaryGroup&&groupItems.some((group)=>group.name===groupsInfo.primaryGroup)){groupsBlock.primaryGroup=groupsInfo.primaryGroup}if(groupsInfo.environmentMarkers&&groupsInfo.environmentMarkers.length>0){groupsBlock.environmentMarkers=groupsInfo.environmentMarkers.map((m)=>projectEnvironmentMarker(m))}payload.groups=groupsBlock}if(options.includeTransitive){const transitive=bundle?.transitive;if(transitive){const block={};if(transitive.totalEdges!==undefined){block.edges=transitive.totalEdges}if(transitive.uniquePackagesCount!==undefined){block.uniquePackages=transitive.uniquePackagesCount}if(options.maxDepth!==undefined){block.depth=options.maxDepth}const packages=buildTransitivePackages(transitive.uniqueDependencies,graph,options.includeImporters??false);if(packages&&packages.length>0){block.packages=packages}if(transitive.dependencyConflicts&&transitive.dependencyConflicts.length>0){block.conflicts=transitive.dependencyConflicts.map((c)=>projectTransitiveConflict(c,graph,payload))}if(transitive.circularDependencyCycles&&transitive.circularDependencyCycles.length>0){block.circularDependencies=transitive.circularDependencyCycles.map((c)=>({cycle:c.circularPath.slice()}))}payload.transitive=block}}const issueSummary=bundle?.transitive?.dependencyIssues;if(options.includeIssues===true&&issueSummary){payload.issues=projectDependencyIssues(issueSummary,graph,payload,options.maxDepth)}if(options.canonicalLifecycles&&options.canonicalLifecycles.length>0){payload.filter={lifecycles:options.canonicalLifecycles.slice()}}return payload}function projectDependencyIssues(issues,graph,payload,maxDepth){return{total:issues.totalCount,scope:maxDepth===undefined?{mode:"full"}:{mode:"depth_limited",maxDepth},deprecated:{count:issues.deprecatedCount,items:issues.deprecatedPackages.map(projectDeprecatedIssue)},outdated:{count:issues.outdatedCount,items:issues.outdatedPackages.map(projectOutdatedIssue)},duplicates:{count:issues.duplicateCount,items:issues.duplicatePackages.map(projectDuplicateIssue)},conflicts:{count:issues.conflictCount,items:issues.conflicts.map((conflict)=>projectIssueConflict(conflict,graph,payload))}}}function projectDeprecatedIssue(issue){return{registry:lowerRegistry(issue.registry),name:issue.name,versions:issue.versions.slice(),reasons:issue.reasons.map((reason)=>{const out={version:reason.version};if(reason.reason!==undefined)out.reason=reason.reason;return out})}}function projectOutdatedIssue(issue){const out={registry:lowerRegistry(issue.registry),name:issue.name,severity:issue.severity,versions:issue.versions.map((version)=>({version:version.version,severity:version.severity}))};if(issue.latestVersion!==undefined){out.latestVersion=issue.latestVersion}if(issue.repositoryUrl!==undefined){out.repositoryUrl=issue.repositoryUrl}return out}function projectDuplicateIssue(issue){const out={name:issue.name,versions:issue.versions.slice()};if(issue.registry!==undefined){out.registry=lowerRegistry(issue.registry)}return out}function projectTransitiveConflict(conflict,graph,payload){return{name:conflict.packageName,requiredVersions:conflict.requiredVersions.slice().sort(),requirements:projectConflictRequirements(conflict.conflictingEdges,graph,payload)}}function projectIssueConflict(conflict,graph,payload){const out={name:conflict.name,versions:conflict.versions.slice(),requiredVersions:conflict.requiredVersions.slice(),requirements:projectConflictRequirements(conflict.conflictingEdges,graph,payload)};if(conflict.registry!==undefined){out.registry=lowerRegistry(conflict.registry)}return out}function projectConflictRequirements(edges,graph,payload){return edges.map((edge)=>({constraint:edge.versionConstraint,dependencyType:edge.dependencyType,importer:edge.fromIndex===undefined||edge.fromIndex===null?{registry:payload.registry,name:payload.name,version:payload.version,root:true}:projectGraphNode(graph,edge.fromIndex),target:projectGraphNode(graph,edge.toIndex)}))}function projectGraphNode(graph,index){const node=graph.nodes[index];const identity={registry:lowerRegistry(node.registry),name:node.name};if(node.version!==undefined)identity.version=node.version;return identity}function shouldEmitGroups(lifecycles){if(!lifecycles||lifecycles.length===0)return false;return lifecycles.some((entry)=>entry!=="runtime")}function projectEnvironmentMarker(marker){const out={};if(marker.type!==undefined)out.type=marker.type;if(marker.value!==undefined)out.value=marker.value;if(marker.raw!==undefined)out.raw=marker.raw;return out}function buildDirect(entry,directVersionByName){const lean={name:entry.name};if(entry.versionConstraint)lean.constraint=entry.versionConstraint;const resolved=directVersionByName?.get(entry.name);if(resolved)lean.version=resolved;return lean}function buildDirectVersionLookup(graph){const rootIdx=findRootNodeIdx(graph);const out=new Map;for(const edge of graph.edges){const fromRoot=edge.fromIndex===undefined||edge.fromIndex===null||edge.fromIndex===rootIdx;if(!fromRoot)continue;const node=graph.nodes[edge.toIndex];if(!node?.version)continue;if(!out.has(node.name)){out.set(node.name,node.version)}}return out.size>0?out:null}function findRootNodeIdx(graph){const incoming=new Set;for(const e of graph.edges)incoming.add(e.toIndex);let root=null;for(let i=0;i<graph.nodes.length;i++){if(!incoming.has(i)){if(root!==null)return null;root=i}}return root}function buildTransitivePackages(uniqueDependencies,graph,includeImporters){if(!uniqueDependencies||uniqueDependencies.length===0)return null;const incoming=includeImporters&&graph?buildIncomingEdgeMap(graph):null;const out=[];for(const entry of uniqueDependencies){const[name,version]=parseNameAtVersion(entry);if(!name)continue;const record={name};if(version)record.version=version;if(graph){const match=findNodeMatch(graph,name,version);if(match!==null){record.registry=lowerRegistry(match.registry);if(incoming){const edges=incoming.get(match.index)??[];const importers=buildImportersFromEdges(graph,edges);if(importers.length>0)record.importers=importers}}}out.push(record)}return out}function parseNameAtVersion(raw){const trimmed=raw.trim();if(!trimmed)return[null,undefined];const atIdx=trimmed.lastIndexOf("@");if(atIdx<=0)return[trimmed,undefined];return[trimmed.slice(0,atIdx),trimmed.slice(atIdx+1)]}function buildIncomingEdgeMap(graph){const map=new Map;for(const edge of graph.edges){const list=map.get(edge.toIndex);if(list)list.push(edge);else map.set(edge.toIndex,[edge])}return map}function findNodeMatch(graph,name,version){let match=null;for(let i=0;i<graph.nodes.length;i++){const n=graph.nodes[i];if(!n)continue;if(n.name!==name||n.version!==version)continue;if(match!==null)return null;match={index:i,registry:n.registry}}return match}function buildImportersFromEdges(graph,edges){const seen=new Set;const out=[];for(const edge of edges){if(edge.fromIndex===undefined||edge.fromIndex===null)continue;const from=graph.nodes[edge.fromIndex];if(!from)continue;const registry=lowerRegistry(from.registry);const key=`${from.name}\x00${registry}\x00${from.version??""}\x00${edge.constraint??""}`;if(seen.has(key))continue;seen.add(key);const importer={registry,name:from.name};if(from.version)importer.version=from.version;if(edge.constraint)importer.constraint=edge.constraint;out.push(importer)}out.sort((a,b)=>{if(a.name!==b.name)return a.name<b.name?-1:1;const ar=a.registry??"";const br=b.registry??"";if(ar!==br)return ar<br?-1:1;const av=a.version??"";const bv=b.version??"";if(av!==bv)return av<bv?-1:1;const ac=a.constraint??"";const bc=b.constraint??"";return ac<bc?-1:ac>bc?1:0});return out}function buildGroup(group){const lean={name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,selectionMode:group.selectionMode,items:group.dependencies.map((dep)=>{const entry={name:dep.name};if(dep.constraint)entry.constraint=dep.constraint;return entry})};if(group.conditionValue)lean.conditionValue=group.conditionValue;if(group.exclusiveGroup)lean.exclusiveGroup=group.exclusiveGroup;if(group.fallbackPriority!==undefined){lean.fallbackPriority=group.fallbackPriority}if(group.compatibleWith&&group.compatibleWith.length>0){lean.compatibleWith=group.compatibleWith.slice()}if(group.defaultEnabled!==undefined){lean.defaultEnabled=group.defaultEnabled}return lean}var LIFECYCLE_ORDER2={runtime:0,development:1,build:2,peer:3,optional:4};function sortGroups(groups){return groups.slice().sort((a,b)=>{const la=LIFECYCLE_ORDER2[a.lifecycle]??99;const lb=LIFECYCLE_ORDER2[b.lifecycle]??99;if(la!==lb)return la-lb;if(a.lifecycle==="optional"){const ad=a.defaultEnabled===true?0:1;const bd=b.defaultEnabled===true?0:1;if(ad!==bd)return ad-bd}return a.name<b.name?-1:a.name>b.name?1:0})}function deriveRequestedVersion(requested,resolved){if(requested===undefined)return;const trimmed=requested.trim();if(trimmed.length===0)return;if(trimmed===resolved)return;return trimmed}function lowerRegistry(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function formatPackageDependenciesTerminal(report,options={}){const verbose=options.verbose??false;const includeImporters=verbose||options.includeImporters===true;const payload=buildPackageDependenciesSuccessPayload(report,{requestedVersion:options.requestedVersion,canonicalLifecycles:options.canonicalLifecycles??["all"],includeTransitive:options.includeTransitive,maxDepth:options.maxDepth,includeImporters,includeIssues:options.includeIssues});const useColors=options.useColors??false;const terminalWidth=resolveIssueTerminalWidth(options.terminalWidth);const showGroups=options.showGroups??false;const includeTransitive=options.includeTransitive??false;const blocks=[];blocks.push(formatHeaderBlock(payload,useColors,showGroups,options));if(includeTransitive){blocks.push(formatTransitiveDepsList(payload,includeImporters,useColors));const issues=formatConflictsAndCycles(payload,verbose,useColors,terminalWidth);if(issues)blocks.push(issues)}else if(!showGroups){blocks.push(formatDirectDepsList(payload,verbose,useColors))}if(showGroups){blocks.push(formatGroupsBlock(payload,verbose,useColors))}const dependencyIssues=formatDependencyIssues(payload,verbose,useColors,options.issuesDetailHint,terminalWidth);if(dependencyIssues)blocks.push(dependencyIssues);return`${blocks.filter((b)=>b.length>0).join(`
134
134
 
135
135
  `)}
136
136
  `}function formatHeaderBlock(payload,useColors,showGroups,options){const name=colorize(payload.name,"bold",useColors);const lines=[`${name} @ ${payload.version} | ${payload.registry}`];if(payload.requestedVersion){lines.push(dim(`(requested ${payload.requestedVersion})`,useColors))}lines.push(formatSummaryRow(payload,useColors,showGroups,options));return lines.join(`
@@ -138,18 +138,18 @@ ${PKG_CHANGELOG_GUARDRAIL}`;function createPackageChangelogTool(service){return{
138
138
  ${hiddenLine}`}function collectHiddenGroupNames(payload){const groups=payload.groups;if(!groups)return[];return groups.items.filter((g)=>g.lifecycle!=="runtime").map((g)=>g.name)}function formatDirectDepsList(payload,verbose,useColors){const runtime=payload.runtime;if(!runtime||runtime.count===0)return"";const sorted=sortAlphabetically(runtime.items,(i)=>i.name);const lines=["Runtime dependencies:",""];if(!verbose){lines.push(...sorted.map((item)=>` ${formatDepLabel(item)}`));return lines.join(`
139
139
  `)}const rootLabel=`${payload.name}@${payload.version}`;lines.push(...sorted.map((item)=>{const head=` ${formatDepLabel(item)}`;const constraintLabel=item.constraint??"*";const line=dim(` - ${constraintLabel} required by ${rootLabel}`,useColors);return`${head}
140
140
  ${line}`}));return lines.join(`
141
- `)}function formatDepLabel(item){if(item.version)return`${item.name}@${item.version}`;if(item.constraint)return`${item.name} ${item.constraint}`;return item.name}function formatTransitiveDepsList(payload,verbose,useColors){const packages=payload.transitive?.packages??[];if(packages.length===0)return"";const sorted=[...packages].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);const lines=["Transitive packages:",""];if(!verbose){lines.push(...sorted.map((pkg)=>` ${formatPackageLabel(pkg)}`));return lines.join(`
142
- `)}lines.push(...sorted.map((pkg)=>{const head=` ${formatPackageLabel(pkg)}`;const importers=pkg.importers??[];if(importers.length===0)return head;const bullets=formatImporterBullets(importers,useColors);return`${head}
141
+ `)}function formatDepLabel(item){if(item.version)return`${item.name}@${item.version}`;if(item.constraint)return`${item.name} ${item.constraint}`;return item.name}function formatTransitiveDepsList(payload,verbose,useColors){const packages=payload.transitive?.packages??[];if(packages.length===0)return"";const sorted=[...packages].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);const lines=["Transitive packages:",""];if(!verbose){lines.push(...sorted.map((pkg)=>` ${formatPackageLabel(pkg,payload.registry)}`));return lines.join(`
142
+ `)}lines.push(...sorted.map((pkg)=>{const head=` ${formatPackageLabel(pkg,payload.registry)}`;const importers=pkg.importers??[];if(importers.length===0)return head;const bullets=formatImporterBullets(importers,useColors,payload.registry);return`${head}
143
143
  ${bullets}`}));return lines.join(`
144
- `)}function formatPackageLabel(pkg){return pkg.version?`${pkg.name}@${pkg.version}`:pkg.name}function formatImporterBullets(importers,useColors){const byConstraint=new Map;for(const i of importers){const key=i.constraint??"*";const label=i.version?`${i.name}@${i.version}`:i.name;const list=byConstraint.get(key);if(list){if(!list.includes(label))list.push(label)}else{byConstraint.set(key,[label])}}const constraints=[...byConstraint.keys()].sort((a,b)=>a<b?-1:a>b?1:0);return constraints.map((constraint)=>{const labels=byConstraint.get(constraint)??[];labels.sort();return dim(` - ${constraint} required by ${labels.join(", ")}`,useColors)}).join(`
145
- `)}function formatDependencyIssues(issues,verbose,useColors,detailHint,terminalWidth){if(!issues)return"";const scope=issues.scope.mode==="full"?"full graph":`max depth ${issues.scope.maxDepth}`;const countLine=formatDependencyIssueCounts(issues);const count=verbose?{lines:wrapIssueEvidence(countLine,terminalWidth),truncated:false}:boundCompactIssueLines([countLine],terminalWidth);const lines=[`${colorize("Dependency issues","yellow",useColors)}: ${issues.total} (${scope})`,...count.lines];if(issues.total===0&&issueCategoryEvidenceCount(issues)===0){lines.push("No dependency issues detected.");return lines.join(`
146
- `)}if(verbose){lines.push(...formatVerboseIssueCategories(issues,useColors,terminalWidth));return lines.join(`
147
- `)}const compact=formatCompactIssueCategories(issues,useColors,terminalWidth);compact.truncated||=count.truncated;lines.push(...compact.lines);if(compact.truncated&&detailHint){lines.push(...wrapIssueEvidence(detailHint,terminalWidth))}return lines.join(`
148
- `)}function formatDependencyIssueCounts(issues){return` Deprecated ${issues.deprecated.count} | Outdated ${issues.outdated.count} | Duplicates ${issues.duplicates.count} | Conflicts ${issues.conflicts.count}`}function issueCategoryEvidenceCount(issues){return issues.deprecated.items.length+issues.outdated.items.length+issues.duplicates.items.length+issues.conflicts.items.length}function formatCompactIssueCategories(issues,useColors,terminalWidth){const lines=[];let truncated=false;const appendBounded=(values)=>{const bounded=boundCompactIssueLines(values,terminalWidth);lines.push(...bounded.lines);truncated||=bounded.truncated};const deprecated=sortIssueItems(issues.deprecated.items);if(deprecated.length>0){const shown=deprecated.slice(0,3);lines.push(colorize("Deprecated dependencies:","yellow",useColors));appendBounded(shown.map((item)=>` - ${formatDeprecatedIssue(item)}`));truncated||=issueCategoryTruncated(issues.deprecated.count,deprecated.length,shown.length)}else{truncated||=issues.deprecated.count>0}const outdated=sortIssueItems(issues.outdated.items);if(outdated.length>0){const shown=outdated.slice(0,3);lines.push(colorize("Outdated dependencies:","yellow",useColors));appendBounded(shown.map((item)=>` - ${formatOutdatedIssue(item)}`));truncated||=issueCategoryTruncated(issues.outdated.count,outdated.length,shown.length)}else{truncated||=issues.outdated.count>0}const duplicates=sortIssueItems(issues.duplicates.items);if(duplicates.length>0){const shown=duplicates.slice(0,3);lines.push(colorize("Duplicate dependencies:","yellow",useColors));appendBounded(shown.map((item)=>` - ${formatDuplicateIssue(item)}`));truncated||=issueCategoryTruncated(issues.duplicates.count,duplicates.length,shown.length)}else{truncated||=issues.duplicates.count>0}const conflicts=sortIssueItems(issues.conflicts.items);if(conflicts.length>0){lines.push(colorize("Conflicts:","yellow",useColors));for(const conflict of conflicts.slice(0,3)){const formatted=formatCompactIssueConflict(conflict,terminalWidth);lines.push(...formatted.lines);truncated||=formatted.truncated}truncated||=issueCategoryTruncated(issues.conflicts.count,conflicts.length,Math.min(3,conflicts.length))}else{truncated||=issues.conflicts.count>0}return{lines,truncated}}function resolveIssueTerminalWidth(width){return typeof width==="number"&&Number.isFinite(width)&&width>0?Math.max(1,Math.floor(width)):80}function boundCompactIssueLines(values,width){let truncated=false;const lines=values.map((value)=>{if(terminalWidth(value)<=width)return value;truncated=true;const suffix=width>=3?"...":".".repeat(width);return`${truncateIssueText(value,width-suffix.length)}${suffix}`});return{lines,truncated}}function truncateIssueText(value,width){let result="";for(const character of value){if(terminalWidth(result+character)>width)break;result+=character}return result}function wrapIssueEvidence(value,width){if(terminalWidth(value)<=width)return[value];const prefix=value.match(/^\s*-\s/)?.[0]??value.match(/^\s*/)?.[0]??"";const continuation=prefix.endsWith("- ")?`${prefix.slice(0,-2)} `:prefix;const words=value.slice(prefix.length).split(/\s+/).filter(Boolean);const lines=[];let firstLine=true;let current=truncateIssueText(prefix,width);for(const word of words){const separator=current===prefix?"":" ";if(terminalWidth(current+separator+word)<=width){current+=`${separator}${word}`;continue}const startsWithBullet=current===prefix&&firstLine;if(current!==prefix)lines.push(current);current=truncateIssueText(startsWithBullet?prefix:continuation,width);firstLine=false;for(const character of Array.from(word)){if(terminalWidth(current+character)>width){lines.push(current);current=`${truncateIssueText(continuation,width)}${character}`}else{current+=character}}}if(current!==prefix)lines.push(current);return lines}function issueCategoryTruncated(backendCount,itemCount,shownCount){return Math.max(backendCount,itemCount)>shownCount}function formatVerboseIssueCategories(issues,useColors,terminalWidth){const lines=[];const deprecated=sortIssueItems(issues.deprecated.items);if(deprecated.length>0){lines.push(colorize("Deprecated dependencies:","yellow",useColors));for(const item of deprecated){lines.push(...wrapIssueEvidence(` - ${formatDeprecatedIssue(item)}`,terminalWidth))}}const outdated=sortIssueItems(issues.outdated.items);if(outdated.length>0){lines.push(colorize("Outdated dependencies:","yellow",useColors));for(const item of outdated){lines.push(...wrapIssueEvidence(` - ${formatOutdatedIssue(item)}`,terminalWidth))}}const duplicates=sortIssueItems(issues.duplicates.items);if(duplicates.length>0){lines.push(colorize("Duplicate dependencies:","yellow",useColors));for(const item of duplicates){lines.push(...wrapIssueEvidence(` - ${formatDuplicateIssue(item)}`,terminalWidth))}}const conflicts=sortIssueItems(issues.conflicts.items);if(conflicts.length>0){lines.push(colorize("Issue conflicts:","yellow",useColors));for(const conflict of conflicts){lines.push(...wrapIssueEvidence(` - ${formatIssueConflict(conflict)}`,terminalWidth));for(const line of formatConflictRequirements(conflict.requirements).lines){lines.push(...wrapIssueEvidence(line,terminalWidth))}}}return lines}function formatDeprecatedIssue(issue){const versions=issue.versions.join(", ");const versionsByReason=new Map;for(const reason of issue.reasons){if(reason.reason===undefined)continue;const matchingVersions=versionsByReason.get(reason.reason);if(matchingVersions)matchingVersions.push(reason.version);else versionsByReason.set(reason.reason,[reason.version])}const reasons=[...versionsByReason.entries()].map(([reason,matchingVersions])=>`${matchingVersions.join(", ")}: ${reason}`).join("; ");return`${issue.name} [${versions}]${reasons?` - ${reasons}`:""}`}function formatOutdatedIssue(issue){const versions=issue.versions.map((version)=>`${version.version} (${version.severity})`).join(", ");const latest=issue.latestVersion===undefined?"":` (latest ${issue.latestVersion})`;return`${issue.name} [${versions}]${latest}`}function formatDuplicateIssue(issue){return`${issue.name} [${issue.versions.join(", ")}]`}function formatIssueConflict(conflict){const versions=conflict.versions.length>0?` [${conflict.versions.join(", ")}]`:"";const constraints=conflict.requiredVersions.join(", ");return`${conflict.name}${versions}: ${constraints}`}function formatCompactIssueConflict(conflict,terminalWidth){const requirements=formatConflictRequirements(conflict.requirements,{maxGroups:3,maxImporters:3});const bounded=boundCompactIssueLines([` - ${formatIssueConflict(conflict)}`,...requirements.lines],terminalWidth);return{lines:bounded.lines,truncated:requirements.truncated||bounded.truncated}}function sortIssueItems(items){return items.slice().sort((a,b)=>{if(a.name!==b.name)return a.name<b.name?-1:1;const ar=a.registry??"";const br=b.registry??"";return ar<br?-1:ar>br?1:0})}function formatConflictRequirements(requirements,limits={}){const byConstraint=new Map;for(const requirement of requirements){const existing=byConstraint.get(requirement.constraint);if(existing)existing.push(requirement);else byConstraint.set(requirement.constraint,[requirement])}const lines=[];const constraints=[...byConstraint.keys()].sort();const maxGroups=limits.maxGroups??Number.POSITIVE_INFINITY;const maxImporters=limits.maxImporters??Number.POSITIVE_INFINITY;let truncated=constraints.length>maxGroups;for(const constraint of constraints.slice(0,maxGroups)){const entries=byConstraint.get(constraint)??[];const dependencyTypes=new Set(entries.map((entry)=>entry.dependencyType));const includeDependencyType=dependencyTypes.size>1;const seen=new Set;const importers=[];for(const entry of entries){const importer=entry.importer;const label=importer.version?`${importer.name}@${importer.version}`:importer.name;const key=`${label}\x00${entry.dependencyType}`;if(seen.has(key))continue;seen.add(key);importers.push({label,dependencyType:entry.dependencyType})}importers.sort((a,b)=>{if(a.label!==b.label)return a.label<b.label?-1:1;return a.dependencyType<b.dependencyType?-1:a.dependencyType>b.dependencyType?1:0});const labels=importers.slice(0,maxImporters).map((importer)=>includeDependencyType?`${importer.label} (${importer.dependencyType})`:importer.label);truncated||=importers.length>maxImporters;lines.push(` - ${constraint} required by ${labels.join(", ")}`)}return{lines,truncated}}function formatConflictsAndCycles(payload,verbose,useColors,terminalWidth){const t=payload.transitive;if(!t)return"";const conflicts=t.conflicts??[];const cycles=t.circularDependencies??[];const lines=[];if(conflicts.length===0&&cycles.length===0){lines.push(dim("No version conflicts or circular dependencies detected.",useColors));return lines.join(`
149
- `)}if(!verbose)return"";if(conflicts.length>0){lines.push(colorize(`Conflicts (${conflicts.length}):`,"yellow",useColors));const nameWidth=Math.max(...conflicts.map((c)=>c.name.length));const sorted=[...conflicts].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(const c of sorted){if(c.requirements.length>0){lines.push(...wrapIssueEvidence(` ${c.name}: ${c.requiredVersions.join(", ")}`,terminalWidth));for(const line of formatConflictRequirements(c.requirements).lines){lines.push(...wrapIssueEvidence(line,terminalWidth))}continue}const padded=`${c.name}:`.padEnd(nameWidth+2);lines.push(` ${padded} ${c.requiredVersions.join(", ")}`)}}if(cycles.length>0){if(conflicts.length>0)lines.push("");lines.push(colorize(`Circular dependencies (${cycles.length}):`,"red",useColors));for(const c of cycles)lines.push(` ${c.cycle.join(" -> ")}`)}return lines.join(`
144
+ `)}function formatPackageLabel(pkg,headerRegistry){const label=pkg.version?`${pkg.name}@${pkg.version}`:pkg.name;return pkg.registry&&pkg.registry!==headerRegistry?`${label} (${pkg.registry})`:label}function formatImporterBullets(importers,useColors,headerRegistry){const byConstraint=new Map;for(const i of importers){const key=i.constraint??"*";const label=formatPackageLabel(i,headerRegistry);const list=byConstraint.get(key);if(list){if(!list.includes(label))list.push(label)}else{byConstraint.set(key,[label])}}const constraints=[...byConstraint.keys()].sort((a,b)=>a<b?-1:a>b?1:0);return constraints.map((constraint)=>{const labels=byConstraint.get(constraint)??[];labels.sort();return dim(` - ${constraint} required by ${labels.join(", ")}`,useColors)}).join(`
145
+ `)}function formatDependencyIssues(payload,verbose,useColors,detailHint,terminalWidth){const issues=payload.issues;if(!issues)return"";const scope=issues.scope.mode==="full"?"full graph":`max depth ${issues.scope.maxDepth}`;const countLine=formatDependencyIssueCounts(issues);const count=verbose?{lines:wrapIssueEvidence(countLine,terminalWidth),truncated:false}:boundCompactIssueLines([countLine],terminalWidth);const lines=[`${colorize("Dependency issues","yellow",useColors)}: ${issues.total} (${scope})`,...count.lines];if(issues.total===0&&issueCategoryEvidenceCount(issues)===0){lines.push("No dependency issues detected.");return lines.join(`
146
+ `)}if(verbose){lines.push(...formatVerboseIssueCategories(issues,useColors,terminalWidth,payload.registry));return lines.join(`
147
+ `)}const compact=formatCompactIssueCategories(issues,useColors,terminalWidth,payload.registry);compact.truncated||=count.truncated;lines.push(...compact.lines);if(compact.truncated&&detailHint){lines.push(...wrapIssueEvidence(detailHint,terminalWidth))}return lines.join(`
148
+ `)}function formatDependencyIssueCounts(issues){return` Deprecated ${issues.deprecated.count} | Outdated ${issues.outdated.count} | Duplicates ${issues.duplicates.count} | Conflicts ${issues.conflicts.count}`}function issueCategoryEvidenceCount(issues){return issues.deprecated.items.length+issues.outdated.items.length+issues.duplicates.items.length+issues.conflicts.items.length}function formatCompactIssueCategories(issues,useColors,terminalWidth,headerRegistry){const lines=[];let truncated=false;const appendBounded=(values)=>{const bounded=boundCompactIssueLines(values,terminalWidth);lines.push(...bounded.lines);truncated||=bounded.truncated};const deprecated=sortIssueItems(issues.deprecated.items);if(deprecated.length>0){const shown=deprecated.slice(0,3);lines.push(colorize("Deprecated dependencies:","yellow",useColors));appendBounded(shown.map((item)=>` - ${formatDeprecatedIssue(item)}`));truncated||=issueCategoryTruncated(issues.deprecated.count,deprecated.length,shown.length)}else{truncated||=issues.deprecated.count>0}const outdated=sortIssueItems(issues.outdated.items);if(outdated.length>0){const shown=outdated.slice(0,3);lines.push(colorize("Outdated dependencies:","yellow",useColors));appendBounded(shown.map((item)=>` - ${formatOutdatedIssue(item)}`));truncated||=issueCategoryTruncated(issues.outdated.count,outdated.length,shown.length)}else{truncated||=issues.outdated.count>0}const duplicates=sortIssueItems(issues.duplicates.items);if(duplicates.length>0){const shown=duplicates.slice(0,3);lines.push(colorize("Duplicate dependencies:","yellow",useColors));appendBounded(shown.map((item)=>` - ${formatDuplicateIssue(item)}`));truncated||=issueCategoryTruncated(issues.duplicates.count,duplicates.length,shown.length)}else{truncated||=issues.duplicates.count>0}const conflicts=sortIssueItems(issues.conflicts.items);if(conflicts.length>0){lines.push(colorize("Conflicts:","yellow",useColors));for(const conflict of conflicts.slice(0,3)){const formatted=formatCompactIssueConflict(conflict,terminalWidth,headerRegistry);lines.push(...formatted.lines);truncated||=formatted.truncated}truncated||=issueCategoryTruncated(issues.conflicts.count,conflicts.length,Math.min(3,conflicts.length))}else{truncated||=issues.conflicts.count>0}return{lines,truncated}}function resolveIssueTerminalWidth(width){return typeof width==="number"&&Number.isFinite(width)&&width>0?Math.max(1,Math.floor(width)):80}function boundCompactIssueLines(values,width){let truncated=false;const lines=values.map((value)=>{if(terminalWidth(value)<=width)return value;truncated=true;const suffix=width>=3?"...":".".repeat(width);return`${truncateIssueText(value,width-suffix.length)}${suffix}`});return{lines,truncated}}function truncateIssueText(value,width){let result="";for(const character of value){if(terminalWidth(result+character)>width)break;result+=character}return result}function wrapIssueEvidence(value,width){if(terminalWidth(value)<=width)return[value];const prefix=value.match(/^\s*-\s/)?.[0]??value.match(/^\s*/)?.[0]??"";const continuation=prefix.endsWith("- ")?`${prefix.slice(0,-2)} `:prefix;const words=value.slice(prefix.length).split(/\s+/).filter(Boolean);const lines=[];let firstLine=true;let current=truncateIssueText(prefix,width);for(const word of words){const separator=current===prefix?"":" ";if(terminalWidth(current+separator+word)<=width){current+=`${separator}${word}`;continue}const startsWithBullet=current===prefix&&firstLine;if(current!==prefix)lines.push(current);current=truncateIssueText(startsWithBullet?prefix:continuation,width);firstLine=false;for(const character of Array.from(word)){if(terminalWidth(current+character)>width){lines.push(current);current=`${truncateIssueText(continuation,width)}${character}`}else{current+=character}}}if(current!==prefix)lines.push(current);return lines}function issueCategoryTruncated(backendCount,itemCount,shownCount){return Math.max(backendCount,itemCount)>shownCount}function formatVerboseIssueCategories(issues,useColors,terminalWidth,headerRegistry){const lines=[];const deprecated=sortIssueItems(issues.deprecated.items);if(deprecated.length>0){lines.push(colorize("Deprecated dependencies:","yellow",useColors));for(const item of deprecated){lines.push(...wrapIssueEvidence(` - ${formatDeprecatedIssue(item)}`,terminalWidth))}}const outdated=sortIssueItems(issues.outdated.items);if(outdated.length>0){lines.push(colorize("Outdated dependencies:","yellow",useColors));for(const item of outdated){lines.push(...wrapIssueEvidence(` - ${formatOutdatedIssue(item)}`,terminalWidth))}}const duplicates=sortIssueItems(issues.duplicates.items);if(duplicates.length>0){lines.push(colorize("Duplicate dependencies:","yellow",useColors));for(const item of duplicates){lines.push(...wrapIssueEvidence(` - ${formatDuplicateIssue(item)}`,terminalWidth))}}const conflicts=sortIssueItems(issues.conflicts.items);if(conflicts.length>0){lines.push(colorize("Issue conflicts:","yellow",useColors));for(const conflict of conflicts){lines.push(...wrapIssueEvidence(` - ${formatIssueConflict(conflict)}`,terminalWidth));for(const line of formatConflictRequirements(conflict.requirements,{headerRegistry}).lines){lines.push(...wrapIssueEvidence(line,terminalWidth))}}}return lines}function formatDeprecatedIssue(issue){const versions=issue.versions.join(", ");const versionsByReason=new Map;for(const reason of issue.reasons){if(reason.reason===undefined)continue;const matchingVersions=versionsByReason.get(reason.reason);if(matchingVersions)matchingVersions.push(reason.version);else versionsByReason.set(reason.reason,[reason.version])}const reasons=[...versionsByReason.entries()].map(([reason,matchingVersions])=>`${matchingVersions.join(", ")}: ${reason}`).join("; ");return`${issue.name} [${versions}]${reasons?` - ${reasons}`:""}`}function formatOutdatedIssue(issue){const versions=issue.versions.map((version)=>`${version.version} (${version.severity})`).join(", ");const latest=issue.latestVersion===undefined?"":` (latest ${issue.latestVersion})`;return`${issue.name} [${versions}]${latest}`}function formatDuplicateIssue(issue){return`${issue.name} [${issue.versions.join(", ")}]`}function formatIssueConflict(conflict){const versions=conflict.versions.length>0?` [${conflict.versions.join(", ")}]`:"";const constraints=conflict.requiredVersions.join(", ");return`${conflict.name}${versions}: ${constraints}`}function formatCompactIssueConflict(conflict,terminalWidth,headerRegistry){const requirements=formatConflictRequirements(conflict.requirements,{headerRegistry,maxGroups:3,maxImporters:3});const bounded=boundCompactIssueLines([` - ${formatIssueConflict(conflict)}`,...requirements.lines],terminalWidth);return{lines:bounded.lines,truncated:requirements.truncated||bounded.truncated}}function sortIssueItems(items){return items.slice().sort((a,b)=>{if(a.name!==b.name)return a.name<b.name?-1:1;const ar=a.registry??"";const br=b.registry??"";return ar<br?-1:ar>br?1:0})}function formatConflictRequirements(requirements,limits){const byConstraint=new Map;for(const requirement of requirements){const existing=byConstraint.get(requirement.constraint);if(existing)existing.push(requirement);else byConstraint.set(requirement.constraint,[requirement])}const lines=[];const constraints=[...byConstraint.keys()].sort();const maxGroups=limits.maxGroups??Number.POSITIVE_INFINITY;const maxImporters=limits.maxImporters??Number.POSITIVE_INFINITY;let truncated=constraints.length>maxGroups;for(const constraint of constraints.slice(0,maxGroups)){const entries=byConstraint.get(constraint)??[];const dependencyTypes=new Set(entries.map((entry)=>entry.dependencyType));const includeDependencyType=dependencyTypes.size>1;const seen=new Set;const importers=[];for(const entry of entries){const importer=entry.importer;const label=formatPackageLabel(importer,limits.headerRegistry);const key=`${label}\x00${entry.dependencyType}`;if(seen.has(key))continue;seen.add(key);importers.push({label,dependencyType:entry.dependencyType})}importers.sort((a,b)=>{if(a.label!==b.label)return a.label<b.label?-1:1;return a.dependencyType<b.dependencyType?-1:a.dependencyType>b.dependencyType?1:0});const labels=importers.slice(0,maxImporters).map((importer)=>includeDependencyType?`${importer.label} (${importer.dependencyType})`:importer.label);truncated||=importers.length>maxImporters;lines.push(` - ${constraint} required by ${labels.join(", ")}`)}return{lines,truncated}}function formatConflictsAndCycles(payload,verbose,useColors,terminalWidth){const t=payload.transitive;if(!t)return"";const conflicts=t.conflicts??[];const cycles=t.circularDependencies??[];const lines=[];if(conflicts.length===0&&cycles.length===0){lines.push(dim("No version conflicts or circular dependencies detected.",useColors));return lines.join(`
149
+ `)}if(!verbose)return"";if(conflicts.length>0){lines.push(colorize(`Conflicts (${conflicts.length}):`,"yellow",useColors));const nameWidth=Math.max(...conflicts.map((c)=>c.name.length));const sorted=[...conflicts].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(const c of sorted){if(c.requirements.length>0){lines.push(...wrapIssueEvidence(` ${c.name}: ${c.requiredVersions.join(", ")}`,terminalWidth));for(const line of formatConflictRequirements(c.requirements,{headerRegistry:payload.registry}).lines){lines.push(...wrapIssueEvidence(line,terminalWidth))}continue}const padded=`${c.name}:`.padEnd(nameWidth+2);lines.push(` ${padded} ${c.requiredVersions.join(", ")}`)}}if(cycles.length>0){if(conflicts.length>0)lines.push("");lines.push(colorize(`Circular dependencies (${cycles.length}):`,"red",useColors));for(const c of cycles)lines.push(` ${c.cycle.join(" -> ")}`)}return lines.join(`
150
150
  `)}function formatGroupsBlock(payload,verbose,useColors){const groups=payload.groups;const lines=[];if(!groups||groups.items.length===0){lines.push(payload.filter?`No dependency groups matched lifecycle filter: ${payload.filter.lifecycles.join(", ")}.`:"No dependency groups available.");return lines.join(`
151
151
  `)}const summary=summariseGroupsByLifecycle(groups.items);const groupNoun=groups.items.length===1?"group":"groups";lines.push("Dependency groups:");lines.push("");lines.push(colorize(`${groups.items.length} ${groupNoun} (${summary}):`,"bold",useColors));lines.push("");if(verbose&&groups.environmentMarkers&&groups.environmentMarkers.length>0){lines.push(dim(`environmentMarkers (${groups.environmentMarkers.length}):`,useColors));for(const marker of groups.environmentMarkers){lines.push(dim(` ${formatEnvironmentMarker(marker)}`,useColors))}lines.push("")}for(const group of groups.items){const heading=formatGroupHeading(group,payload.registry);lines.push(` ${colorize(heading,"bold",useColors)}`);if(verbose){const metaLines=formatGroupMeta(group);for(const meta of metaLines){lines.push(` ${dim(meta,useColors)}`)}}const deps=sortAlphabetically(dedupeGroupItems(group.items),(d)=>d.name);if(deps.length===0){lines.push(` ${dim("(no dependencies)",useColors)}`)}else{const nameWidth=Math.max(...deps.map((d)=>d.name.length));for(const dep of deps){lines.push(` ${formatGroupDependencyRow(dep,group,payload,nameWidth)}`)}}lines.push("")}return lines.join(`
152
- `).trimEnd()}function formatGroupDependencyRow(dep,group,payload,nameWidth){const constraint=dep.constraint??"";if(group.lifecycle!=="runtime"){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const resolvedVersion=payload.runtime?.items.find((item)=>item.name===dep.name)?.version;if(!resolvedVersion){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const versionedName=`${dep.name}@${resolvedVersion}`.padEnd(nameWidth);return`${versionedName} ${constraint}`.trimEnd()}function formatEnvironmentMarker(marker){if(marker.type&&marker.value)return`${marker.type}: ${marker.value}`;if(marker.value)return marker.value;if(marker.type)return marker.type;return marker.raw??"(empty marker)"}function formatGroupHeading(group,registry){if(group.conditionType==="always"){return group.name}const displayCondition=displayConditionType(group.conditionType,registry);const showValue=group.conditionValue!==undefined&&group.conditionValue.toLowerCase()!==group.name.toLowerCase();const tail=showValue?`${displayCondition}: ${group.conditionValue}`:displayCondition;return`${group.name} (${group.lifecycle}, ${tail})`}function displayConditionType(conditionType,registry){if(conditionType==="feature"&&registry==="pypi")return"extra";return conditionType}function formatGroupMeta(group){const rows=[];if(group.selectionMode!=="required"){rows.push(`selectionMode: ${group.selectionMode}`)}if(group.defaultEnabled!==undefined){rows.push(`defaultEnabled: ${group.defaultEnabled}`)}if(group.exclusiveGroup){rows.push(`exclusiveGroup: ${group.exclusiveGroup}`)}if(group.fallbackPriority!==undefined){rows.push(`fallbackPriority: ${group.fallbackPriority}`)}if(group.compatibleWith&&group.compatibleWith.length>0){rows.push(`compatibleWith: ${group.compatibleWith.join(", ")}`)}return rows}function dedupeGroupItems(items){const seen=new Set;const out=[];for(const item of items){const key=`${item.name}\x00${item.constraint??""}`;if(seen.has(key))continue;seen.add(key);out.push(item)}return out}function summariseGroupsByLifecycle(groups){const counts=new Map;for(const g of groups){counts.set(g.lifecycle,(counts.get(g.lifecycle)??0)+1)}const parts=[];for(const lc of["runtime","development","build","peer","optional"]){const n=counts.get(lc);if(n&&n>0)parts.push(`${n} ${lc}`)}return parts.join(", ")||"0"}function sortAlphabetically(items,key){return items.slice().sort((a,b)=>{const ka=key(a);const kb=key(b);return ka<kb?-1:ka>kb?1:0})}var schema5={target:z5.string().describe("Package registry:name[@version], for example npm:express@5.2.1; omit the version for latest. Go accepts versions with or without v; other registries reject v-prefixed git tags except Swift."),lifecycle:z5.union([z5.string(),z5.array(z5.string())]).optional().describe("Lifecycle breadth. Omit for runtime-only. Use `runtime` for explicit runtime-only, a concrete non-runtime lifecycle (`development`, `build`, `peer`, `optional`) for runtime plus matching groups, or `all` for runtime plus all available groups. Accepts a single value, a comma-separated string, or an array; `all` cannot be combined with other values. Uppercase is tolerated."),include_importers:z5.boolean().optional().describe("When true, each entry in `transitive.packages[]` also carries an `importers` array — every upstream package that pulls it in, with that importer's own resolved version and the constraint it declared. Off by default because adding provenance roughly quadruples the envelope size on heavy graphs. If `max_depth` is omitted, this also requests the full transitive block."),include_issues:z5.boolean().optional().describe("When true, computes deprecated, outdated, duplicate, and conflict analysis across the resolved dependency graph. Without `max_depth`, this traverses the full graph; set `max_depth` to bound analysis cost and scope. Off by default; JSON exposes complete issue rows for direct code consumption."),max_depth:z5.number().int().min(1).max(10).optional().describe("Add a `transitive` block and cap traversal at this depth (1-10). Omit for direct output unless `include_importers` is true; `include_issues` can still analyze the full graph."),format:z5.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text. JSON includes complete issue rows.")};var DESCRIPTION5="Inspect what a package depends on, directly or transitively. Lists direct runtime "+"dependencies with resolved versions; non-runtime groups are omitted by default. "+"Opt into transitive footprint, per-package provenance, or issue analysis with "+"the corresponding fields; full-graph analysis is not local application lockfile "+"or reachability evidence. Supports "+`${SUPPORTED_DEPS_REGISTRIES_LIST}.`;function createPackageDependenciesTool(service){return{name:"pkg_deps",description:DESCRIPTION5,schema:schema5,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());const includeIssues=args.include_issues;const includeTransitiveOutput=args.max_depth!==undefined||args.include_importers===true;const wireMaxDepth=includeTransitiveOutput||includeIssues===true?args.max_depth:1;const{params,canonicalLifecycles}=buildPackageDependenciesParams({registry:target.registry,packageName:target.name,version:target.version,includeTransitive:true,maxDepth:wireMaxDepth,lifecycle:args.lifecycle,includeIssues});const showGroups=canonicalLifecycles.length>0&&!canonicalLifecycles.every((item)=>item==="runtime");const textFormat=isTextFormat3(args.format);const report=await service.packageDependencies({...params,includeTransitiveDetails:includeTransitiveOutput,includeGroups:showGroups||textFormat},...serviceRequestArgs(context?.signal));if(textFormat){const textLifecycles=canonicalLifecycles.length>0?canonicalLifecycles:["all"];return textResult(formatPackageDependenciesTerminal(report,{useColors:false,requestedVersion:params.version,canonicalLifecycles:textLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,showGroups,hiddenGroupsHint:'pass lifecycle="all".',includeIssues,issuesDetailHint:'Pass format: "json" for complete issue details.'}).trimEnd())}const payload=buildPackageDependenciesSuccessPayload(report,{requestedVersion:params.version,canonicalLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,includeImporters:args.include_importers??false,includeIssues});return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_deps",args}})}}}}function isTextFormat3(format){return format===undefined||format==="text"}import{z as z6}from"zod";function buildPackageSummaryParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registry=parsePkgseerRegistryArg(input.registry??"");if(!registry){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}return{params:{registry:toPkgseerRegistry2(registry),packageName:trimmedName}}}function toIsoDate(iso){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;return parsed.toISOString().slice(0,10)}var MINUTE=60;var HOUR=60*MINUTE;var DAY=24*HOUR;var MONTH=30*DAY;var YEAR=365*DAY;function toRelativeDate(iso,now=new Date){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;const deltaSeconds=Math.floor((now.getTime()-parsed.getTime())/1000);if(deltaSeconds<0){return toIsoDate(iso)}if(deltaSeconds<MINUTE)return"just now";if(deltaSeconds<HOUR)return formatUnit(deltaSeconds,MINUTE,"minute");if(deltaSeconds<DAY)return formatUnit(deltaSeconds,HOUR,"hour");if(deltaSeconds<MONTH)return formatUnit(deltaSeconds,DAY,"day");if(deltaSeconds<YEAR)return formatUnit(deltaSeconds,MONTH,"month");return formatUnit(deltaSeconds,YEAR,"year")}function formatUnit(deltaSeconds,unit,label){const n=Math.floor(deltaSeconds/unit);return`${n} ${label}${n===1?"":"s"} ago`}function buildPackageSummarySuccessPayload(summary){const pkg=summary.package;const payload={registry:lowerRegistry2(pkg.registry),name:pkg.name,version:pkg.latestVersion};assignIfDefined(payload,"versionCount",pkg.versionCount);assignIfDefined(payload,"description",pkg.description);assignIfDefined(payload,"license",pkg.license);assignIfDefined(payload,"homepage",pkg.homepage);assignIfDefined(payload,"repository",pkg.repositoryUrl);assignIfDefined(payload,"registryRepository",pkg.registryRepository);assignIfDefined(payload,"publishedAt",toIsoDate(pkg.latestVersionPublishedAt));const downloads=buildDownloads(pkg.downloadsLastMonth,pkg.downloadsTotal,pkg.downloadsRefreshedAt);if(downloads)payload.downloads=downloads;const github=buildGithub(pkg.githubRepository);if(github)payload.github=github;const vulns=buildVulnerabilities(summary.security);if(vulns)payload.vulnerabilities=vulns;const advisoryHistory=buildAdvisoryHistory(summary.security);if(advisoryHistory)payload.advisoryHistory=advisoryHistory;const recent=buildRecentChanges(summary.latestChangelogs);if(recent)payload.recentChanges=recent;return payload}function lowerRegistry2(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function assignIfDefined(target,key,value){if(value!==undefined&&value!==null){target[key]=value}}function buildDownloads(lastMonth,total,refreshedAt){const result={};if(typeof lastMonth==="number")result.lastMonth=lastMonth;if(typeof total==="number")result.total=total;const normalizedRefresh=toIsoDate(refreshedAt);if(normalizedRefresh)result.refreshedAt=normalizedRefresh;return Object.keys(result).length>0?result:undefined}function buildGithub(github){if(!github)return;const result={};if(typeof github.stargazersCount==="number"){result.stars=github.stargazersCount}if(typeof github.forksCount==="number"){result.forks=github.forksCount}if(typeof github.openIssuesCount==="number"){result.openIssues=github.openIssuesCount}if(typeof github.archived==="boolean"){result.archived=github.archived}if(github.language){result.language=github.language}if(github.topics&&github.topics.length>0){result.topics=github.topics}const lastPushedAt=toIsoDate(github.pushedAt);if(lastPushedAt)result.lastPushedAt=lastPushedAt;return Object.keys(result).length>0?result:undefined}function buildVulnerabilities(security){if(!security)return;if(typeof security.vulnerabilityCount!=="number")return;const total=security.vulnerabilityCount;const result={total,affectsLatest:security.hasCurrentVulnerabilities??false};const recent=security.recentVulnerabilities?.map(buildVulnerability).filter((entry)=>entry!==undefined);if(recent&&recent.length>0){result.recent=recent}return result}function buildAdvisoryHistory(security){if(!security)return;return{total:security.allVulnerabilityCount}}function buildVulnerability(entry){const lean={};if(entry.osvId)lean.id=entry.osvId;if(entry.summary)lean.summary=entry.summary;if(typeof entry.severityScore==="number"&&entry.severityScore>0){lean.severity=entry.severityScore;lean.severityLabel=severityLabel(entry.severityScore)}const publishedAt=toIsoDate(entry.publishedAt);if(publishedAt)lean.publishedAt=publishedAt;return Object.keys(lean).length>0?lean:undefined}function severityLabel(score){if(score>=9)return"critical";if(score>=7)return"high";if(score>=4)return"medium";return"low"}function buildRecentChanges(entries){if(!entries||entries.length===0)return;const filtered=entries.filter((entry)=>!!entry.version).map((entry)=>{const lean={version:entry.version};const date=toIsoDate(entry.publishedAt);if(date)lean.date=date;const summary=pickChangelogSummary(entry);if(summary)lean.summary=summary;return lean});return filtered.length>0?filtered:undefined}function pickChangelogSummary(entry){if(!entry.body)return;const firstLine=entry.body.split(/\r?\n/).map((line)=>stripMarkdownHeading(line.trim())).find((line)=>line.length>0);if(!firstLine)return;return firstLine.length>120?`${firstLine.slice(0,117).trimEnd()}...`:firstLine}function stripMarkdownHeading(line){return line.replace(/^#{1,6}\s+/,"").trim()}function formatPackageSummaryTerminal(summary,options={}){const lean=buildPackageSummarySuccessPayload(summary);const useColors=options.useColors??false;const width=resolveWidth(options.terminalWidth);const now=options.now??new Date;const sections=[];const header=lean.license?`${colorize(lean.name,"bold",useColors)} @ ${lean.version} | ${lean.license}`:`${colorize(lean.name,"bold",useColors)} @ ${lean.version}`;sections.push(header);if(lean.description){sections.push(wrapText(lean.description,width))}const fields=buildFieldList(lean,summary,useColors,now,options.verbose??false,width);if(fields.length>0){sections.push(fields.join(`
152
+ `).trimEnd()}function formatGroupDependencyRow(dep,group,payload,nameWidth){const constraint=dep.constraint??"";if(group.lifecycle!=="runtime"){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const resolvedVersion=payload.runtime?.items.find((item)=>item.name===dep.name)?.version;if(!resolvedVersion){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const versionedName=`${dep.name}@${resolvedVersion}`.padEnd(nameWidth);return`${versionedName} ${constraint}`.trimEnd()}function formatEnvironmentMarker(marker){if(marker.type&&marker.value)return`${marker.type}: ${marker.value}`;if(marker.value)return marker.value;if(marker.type)return marker.type;return marker.raw??"(empty marker)"}function formatGroupHeading(group,registry){if(group.conditionType==="always"){return group.name}const displayCondition=displayConditionType(group.conditionType,registry);const showValue=group.conditionValue!==undefined&&group.conditionValue.toLowerCase()!==group.name.toLowerCase();const tail=showValue?`${displayCondition}: ${group.conditionValue}`:displayCondition;return`${group.name} (${group.lifecycle}, ${tail})`}function displayConditionType(conditionType,registry){if(conditionType==="feature"&&registry==="pypi")return"extra";return conditionType}function formatGroupMeta(group){const rows=[];if(group.selectionMode!=="required"){rows.push(`selectionMode: ${group.selectionMode}`)}if(group.defaultEnabled!==undefined){rows.push(`defaultEnabled: ${group.defaultEnabled}`)}if(group.exclusiveGroup){rows.push(`exclusiveGroup: ${group.exclusiveGroup}`)}if(group.fallbackPriority!==undefined){rows.push(`fallbackPriority: ${group.fallbackPriority}`)}if(group.compatibleWith&&group.compatibleWith.length>0){rows.push(`compatibleWith: ${group.compatibleWith.join(", ")}`)}return rows}function dedupeGroupItems(items){const seen=new Set;const out=[];for(const item of items){const key=`${item.name}\x00${item.constraint??""}`;if(seen.has(key))continue;seen.add(key);out.push(item)}return out}function summariseGroupsByLifecycle(groups){const counts=new Map;for(const g of groups){counts.set(g.lifecycle,(counts.get(g.lifecycle)??0)+1)}const parts=[];for(const lc of["runtime","development","build","peer","optional"]){const n=counts.get(lc);if(n&&n>0)parts.push(`${n} ${lc}`)}return parts.join(", ")||"0"}function sortAlphabetically(items,key){return items.slice().sort((a,b)=>{const ka=key(a);const kb=key(b);return ka<kb?-1:ka>kb?1:0})}var schema5={target:z5.string().describe("Package registry:name[@version], for example npm:express@5.2.1; omit the version for latest. Go accepts versions with or without v; other registries reject v-prefixed git tags except Swift."),lifecycle:z5.union([z5.string(),z5.array(z5.string())]).optional().describe("Lifecycle breadth. Omit for runtime-only. Use `runtime` for explicit runtime-only, a concrete non-runtime lifecycle (`development`, `build`, `peer`, `optional`) for runtime plus matching groups, or `all` for runtime plus all available groups. Accepts a single value, a comma-separated string, or an array; `all` cannot be combined with other values. Uppercase is tolerated."),include_importers:z5.boolean().optional().describe("When true, each entry in `transitive.packages[]` also carries an `importers` array — every upstream package that pulls it in, with that importer's own resolved version and the constraint it declared. Off by default because adding provenance roughly quadruples the envelope size on heavy graphs. If `max_depth` is omitted, this also requests the full transitive block."),include_issues:z5.boolean().optional().describe("When true, computes deprecated, outdated, duplicate, and conflict analysis across the resolved dependency graph. Without `max_depth`, this traverses the full graph; set `max_depth` to bound analysis cost and scope. Off by default; JSON exposes complete issue rows for direct code consumption."),max_depth:z5.number().int().min(1).max(10).optional().describe("Add a `transitive` block and cap traversal at this depth (1-10). Omit for direct output unless `include_importers` is true; `include_issues` can still analyze the full graph."),format:z5.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text. JSON includes complete issue rows.")};var DESCRIPTION5="Inspect what a package depends on, directly or transitively. Lists direct runtime "+"dependencies with resolved versions; non-runtime groups are omitted by default. "+"Opt into transitive footprint, per-package provenance, or issue analysis with "+"the corresponding fields; full-graph analysis is not local application lockfile "+"or reachability evidence. Supports "+`${SUPPORTED_DEPS_REGISTRIES_LIST}.`;function createPackageDependenciesTool(service){return{name:"pkg_deps",description:DESCRIPTION5,schema:schema5,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());const includeIssues=args.include_issues;const includeTransitiveOutput=args.max_depth!==undefined||args.include_importers===true;const wireMaxDepth=includeTransitiveOutput||includeIssues===true?args.max_depth:1;const{params,canonicalLifecycles}=buildPackageDependenciesParams({registry:target.registry,packageName:target.name,version:target.version,includeTransitive:true,maxDepth:wireMaxDepth,lifecycle:args.lifecycle,includeIssues});const showGroups=canonicalLifecycles.length>0&&!canonicalLifecycles.every((item)=>item==="runtime");const textFormat=isTextFormat3(args.format);const report=await service.packageDependencies({...params,includeTransitiveDetails:includeTransitiveOutput,includeGroups:showGroups||textFormat},...serviceRequestArgs(context?.signal));if(textFormat){const textLifecycles=canonicalLifecycles.length>0?canonicalLifecycles:["all"];return textResult(formatPackageDependenciesTerminal(report,{useColors:false,includeImporters:args.include_importers===true,requestedVersion:params.version,canonicalLifecycles:textLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,showGroups,hiddenGroupsHint:'pass lifecycle="all".',includeIssues,issuesDetailHint:'Pass format: "json" for complete issue details.'}).trimEnd())}const payload=buildPackageDependenciesSuccessPayload(report,{requestedVersion:params.version,canonicalLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,includeImporters:args.include_importers??false,includeIssues});return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_deps",args}})}}}}function isTextFormat3(format){return format===undefined||format==="text"}import{z as z6}from"zod";function buildPackageSummaryParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registry=parsePkgseerRegistryArg(input.registry??"");if(!registry){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}return{params:{registry:toPkgseerRegistry2(registry),packageName:trimmedName}}}function toIsoDate(iso){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;return parsed.toISOString().slice(0,10)}var MINUTE=60;var HOUR=60*MINUTE;var DAY=24*HOUR;var MONTH=30*DAY;var YEAR=365*DAY;function toRelativeDate(iso,now=new Date){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;const deltaSeconds=Math.floor((now.getTime()-parsed.getTime())/1000);if(deltaSeconds<0){return toIsoDate(iso)}if(deltaSeconds<MINUTE)return"just now";if(deltaSeconds<HOUR)return formatUnit(deltaSeconds,MINUTE,"minute");if(deltaSeconds<DAY)return formatUnit(deltaSeconds,HOUR,"hour");if(deltaSeconds<MONTH)return formatUnit(deltaSeconds,DAY,"day");if(deltaSeconds<YEAR)return formatUnit(deltaSeconds,MONTH,"month");return formatUnit(deltaSeconds,YEAR,"year")}function formatUnit(deltaSeconds,unit,label){const n=Math.floor(deltaSeconds/unit);return`${n} ${label}${n===1?"":"s"} ago`}function buildPackageSummarySuccessPayload(summary){const pkg=summary.package;const payload={registry:lowerRegistry2(pkg.registry),name:pkg.name,version:pkg.latestVersion};assignIfDefined(payload,"versionCount",pkg.versionCount);assignIfDefined(payload,"description",pkg.description);assignIfDefined(payload,"license",pkg.license);assignIfDefined(payload,"homepage",pkg.homepage);assignIfDefined(payload,"repository",pkg.repositoryUrl);assignIfDefined(payload,"registryRepository",pkg.registryRepository);assignIfDefined(payload,"publishedAt",toIsoDate(pkg.latestVersionPublishedAt));const downloads=buildDownloads(pkg.downloadsLastMonth,pkg.downloadsTotal,pkg.downloadsRefreshedAt);if(downloads)payload.downloads=downloads;const github=buildGithub(pkg.githubRepository);if(github)payload.github=github;const vulns=buildVulnerabilities(summary.security);if(vulns)payload.vulnerabilities=vulns;const advisoryHistory=buildAdvisoryHistory(summary.security);if(advisoryHistory)payload.advisoryHistory=advisoryHistory;const recent=buildRecentChanges(summary.latestChangelogs);if(recent)payload.recentChanges=recent;return payload}function lowerRegistry2(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function assignIfDefined(target,key,value){if(value!==undefined&&value!==null){target[key]=value}}function buildDownloads(lastMonth,total,refreshedAt){const result={};if(typeof lastMonth==="number")result.lastMonth=lastMonth;if(typeof total==="number")result.total=total;const normalizedRefresh=toIsoDate(refreshedAt);if(normalizedRefresh)result.refreshedAt=normalizedRefresh;return Object.keys(result).length>0?result:undefined}function buildGithub(github){if(!github)return;const result={};if(typeof github.stargazersCount==="number"){result.stars=github.stargazersCount}if(typeof github.forksCount==="number"){result.forks=github.forksCount}if(typeof github.openIssuesCount==="number"){result.openIssues=github.openIssuesCount}if(typeof github.archived==="boolean"){result.archived=github.archived}if(github.language){result.language=github.language}if(github.topics&&github.topics.length>0){result.topics=github.topics}const lastPushedAt=toIsoDate(github.pushedAt);if(lastPushedAt)result.lastPushedAt=lastPushedAt;return Object.keys(result).length>0?result:undefined}function buildVulnerabilities(security){if(!security)return;if(typeof security.vulnerabilityCount!=="number")return;const total=security.vulnerabilityCount;const result={total,affectsLatest:security.hasCurrentVulnerabilities??false};const recent=security.recentVulnerabilities?.map(buildVulnerability).filter((entry)=>entry!==undefined);if(recent&&recent.length>0){result.recent=recent}return result}function buildAdvisoryHistory(security){if(!security)return;return{total:security.allVulnerabilityCount}}function buildVulnerability(entry){const lean={};if(entry.osvId)lean.id=entry.osvId;if(entry.summary)lean.summary=entry.summary;if(typeof entry.severityScore==="number"&&entry.severityScore>0){lean.severity=entry.severityScore;lean.severityLabel=severityLabel(entry.severityScore)}const publishedAt=toIsoDate(entry.publishedAt);if(publishedAt)lean.publishedAt=publishedAt;return Object.keys(lean).length>0?lean:undefined}function severityLabel(score){if(score>=9)return"critical";if(score>=7)return"high";if(score>=4)return"medium";return"low"}function buildRecentChanges(entries){if(!entries||entries.length===0)return;const filtered=entries.filter((entry)=>!!entry.version).map((entry)=>{const lean={version:entry.version};const date=toIsoDate(entry.publishedAt);if(date)lean.date=date;const summary=pickChangelogSummary(entry);if(summary)lean.summary=summary;return lean});return filtered.length>0?filtered:undefined}function pickChangelogSummary(entry){if(!entry.body)return;const firstLine=entry.body.split(/\r?\n/).map((line)=>stripMarkdownHeading(line.trim())).find((line)=>line.length>0);if(!firstLine)return;return firstLine.length>120?`${firstLine.slice(0,117).trimEnd()}...`:firstLine}function stripMarkdownHeading(line){return line.replace(/^#{1,6}\s+/,"").trim()}function formatPackageSummaryTerminal(summary,options={}){const lean=buildPackageSummarySuccessPayload(summary);const useColors=options.useColors??false;const width=resolveWidth(options.terminalWidth);const now=options.now??new Date;const sections=[];const header=lean.license?`${colorize(lean.name,"bold",useColors)} @ ${lean.version} | ${lean.license}`:`${colorize(lean.name,"bold",useColors)} @ ${lean.version}`;sections.push(header);if(lean.description){sections.push(wrapText(lean.description,width))}const fields=buildFieldList(lean,summary,useColors,now,options.verbose??false,width);if(fields.length>0){sections.push(fields.join(`
153
153
  `))}if(options.verbose){const verbose=buildVerboseSections(lean,useColors);if(verbose.length>0)sections.push(verbose)}return`${sections.join(`
154
154
 
155
155
  `)}
@@ -171,7 +171,7 @@ ${PKG_INFO_GUARDRAIL}`;function createPackageSummaryTool(service){return{name:"p
171
171
  `).trimEnd()}
172
172
  `}for(const review of reviews){lines.push("");lines.push(highlight(`${review.registry}:${review.name} ${review.currentVersion} -> ${review.targetVersion} (${review.versionDelta})`,useColors));lines.push(...formatMigrationGuides(review,options));appendSection(lines,formatVulnerabilitySection(review,options));const deprecation=formatDeprecationLine(review,options);if(deprecation)appendSection(lines,deprecation);appendSection(lines,formatChangesSection(review.changelog,options));if(review.compatibility){appendSection(lines,formatCompatibilitySection(review.compatibility,options))}if(review.dependencyChanges){appendSection(lines,formatDependencyChangesSection(review.dependencyChanges,options))}if(review.dependencyIssues)appendSection(lines,formatDependencyIssuesSection(review.dependencyIssues,options));if(review.unknownDetails?.length){const unknownLines=[attentionSectionTitle("Unknown evidence",useColors)];const details=review.unknownDetails??[];for(const detail of details){appendWrappedText(unknownLines," - ",safeRiskText(`${detail.section} (${detail.code}): ${detail.message}`),width," ")}appendSection(lines,unknownLines)}}return`${lines.join(`
173
173
  `).trimEnd()}
174
- `}function sectionTitle(text,useColors){return useColors?`${colors.bold}${text}${colors.reset}`:text}function attentionSectionTitle(text,useColors){return useColors?`${colors.bold}${colors.yellow}${text}${colors.reset}`:text}function normaliseTerminalWidth(width){if(width===undefined||!Number.isFinite(width))return 80;return Math.max(20,Math.floor(width))}function appendSection(lines,section){if(section.length===0)return;lines.push("",...section)}function appendWrappedText(lines,prefix,text,width,continuationPrefix=" ".repeat(prefix.length),style){const words=text.trim().split(/\s+/).filter(Boolean);if(words.length===0){lines.push(style?style(prefix.trimEnd()):prefix.trimEnd());return}let current=prefix;for(const word of words){const separator=current===prefix?"":" ";if(current.length+separator.length+word.length<=width||current===prefix&&current.trimEnd().length>=width){current+=`${separator}${word}`;continue}if(current.trim())lines.push(style?style(current.trimEnd()):current.trimEnd());current=`${continuationPrefix}${word}`}lines.push(style?style(current.trimEnd()):current.trimEnd())}function aggregateSummary(response){const reviewsWithTransitive=response.reviews.filter((review)=>review.security.transitive!==undefined).length;const omittedTransitive=response.reviews.length-reviewsWithTransitive;const clauses=[`${response.summary.withUnknowns} with reported unknowns`,`${response.summary.withAddedAdvisories} with added direct vulnerabilities`];const classificationGaps=response.reviews.filter(({changelog})=>{const coverage=changelog.riskCoverage;return coverage.versionsNotAssessed>0||coverage.versionsWithoutNotes>0||coverage.versionsUnparseable>0}).length;if(classificationGaps>0)clauses.splice(1,0,`${classificationGaps} with classification coverage gaps`);if(reviewsWithTransitive===0){clauses.push("transitive security not checked")}else{clauses.push(`${response.summary.withTransitiveVulnerabilityAdditions} with added transitive vulnerabilities`);if(omittedTransitive>0)clauses.push(`${omittedTransitive} without transitive security evidence`)}clauses.push(`${response.summary.withBreakingSignals} with heuristic change signals`,`${response.summary.withDirectDependencyChanges} with direct dependency changes`);return clauses.join(" | ")}function formatDeprecationLine(review,options){const current=review.security.current;const target=review.security.target;const width=normaliseTerminalWidth(options.terminalWidth);const useColors=options.useColors===true;const hasCurrentDeprecation=current?.deprecated===true;const hasTargetDeprecation=target?.deprecated===true;const targetDeprecationUnknown=target===undefined||target.deprecated===undefined;if(!hasCurrentDeprecation&&!hasTargetDeprecation&&!targetDeprecationUnknown)return;const lines=[sectionTitle("Deprecation",useColors)];if(current?.deprecated===true)lines.push(attentionLine(" Current: deprecated",useColors));if(target?.deprecated===true){const reason=target.deprecationReason?`deprecated: ${target.deprecationReason}`:"deprecated";appendWrappedText(lines," Target: ",reason,width," ",(line)=>attentionLine(line,useColors))}if(targetDeprecationUnknown)lines.push(attentionLine(" Target: deprecation unknown",useColors));return lines.length>1?lines:undefined}function formatVulnerabilitySection(review,options){const security=review.security;const current=security.current?.affectedCount??"unknown";const target=security.target?.affectedCount??"unknown";const width=normaliseTerminalWidth(options.terminalWidth);const useColors=options.useColors===true;const lines=[sectionTitle("Security",useColors)];appendWrappedText(lines," Direct: ",`${current} affected -> ${target} affected | ${security.removed.length} fixed | ${security.added.length} added | ${security.notAddressed.length} still present`,width," ",security.added.length>0||security.notAddressed.length>0?(line)=>attentionLine(line,useColors):undefined);for(const[label,summary]of[["Current",security.current],["Target",security.target]]){if(!summary)continue;const unknown=summary.unknownVulnerabilityCount??0;const uncertainty=formatAssessmentUncertainty(summary.assessmentStatus,summary.affectedCount>0);if(unknown===0&&uncertainty===undefined)continue;const target=`${review.registry}:${review.name}@${summary.version}`;const explanation=unknown>0?`${unknown} of ${summary.allCount} ${summary.allCount===1?"advisory":"advisories"} not evaluable`:uncertainty;const action=unknown>0?options.surface==="mcp"?`pkg_vulns target="${target}" advisory_scope="unknown"`:`pkg vulns ${target} --scope unknown`:undefined;appendWrappedText(lines,` ${label}: `,safeRiskText([explanation,unknown>0&&summary.assessmentStatus!=="UNKNOWN"?uncertainty:undefined,action].filter(Boolean).join("; ")),width," ")}lines.push(...formatTransitiveVulnerabilitySummary(security.transitive,options));const limit=options.verbose?Number.POSITIVE_INFINITY:5;appendAdvisoryLines(lines,"Added direct advisories",security.added,limit,width,useColors,true);appendAdvisoryLines(lines,"Fixed direct advisories",security.removed,limit,width,useColors,false);appendAdvisoryLines(lines,"Still present direct advisories",security.notAddressed,limit,width,useColors,true);lines.push(...formatTransitiveVulnerabilityDetails(security.transitive,options));return lines}function appendAdvisoryLines(lines,label,advisories,limit,width,useColors,attention){if(advisories.length===0)return;lines.push(attention?attentionLine(` ${label}`,useColors):` ${label}`);for(const advisory of advisories.slice(0,limit)){const prefix=` - ${formatAdvisoryPrefix(advisory)}`;const prose=formatAdvisoryProse(advisory);if(prose){appendWrappedText(lines,`${prefix}: `,prose,width," ")}else{lines.push(prefix)}}const remaining=advisories.length-limit;if(remaining>0)lines.push(` - ... +${remaining} more with verbose output`)}function formatAdvisoryPrefix(advisory){const id=advisory.id??advisory.aliases?.[0]??"unknown-id";const severity=advisory.severityLabel?` ${advisory.severityLabel}${typeof advisory.severity==="number"?`(${advisory.severity})`:""}`:"";const malicious=advisory.isMalicious?" malicious":"";return`${id}${severity}${malicious}`}function formatAdvisoryProse(advisory){const parts=[];const uncertainty=formatAssessmentUncertainty(advisory.assessmentStatus,true);if(uncertainty!==undefined&&advisory.assessmentStatus!=="NOT_ASSESSED")parts.push(safeRiskText(uncertainty));if(advisory.assessmentReasons?.length)parts.push(safeRiskText(advisory.assessmentReasons.map(formatVulnerabilityAssessmentReason).join("; ")));if(advisory.summary)parts.push(advisory.summary);if(advisory.fixedIn?.length)parts.push(`fixed in ${advisory.fixedIn.join(", ")}`);return parts.join(" | ")}function formatTransitiveVulnerabilitySummary(transitive,options){const useColors=options.useColors===true;if(!transitive)return[attentionLine(" Transitive: not checked",useColors)];const lines=[];const width=normaliseTerminalWidth(options.terminalWidth);appendWrappedText(lines," Transitive: ",`${transitive.currentAffected} affected packages -> ${transitive.targetAffected} | ${transitive.fixedPackageDetailsTotalCount} fixed | ${transitive.introducedPackageDetailsTotalCount} added | ${transitive.stillAffectedPackageDetailsTotalCount} still affected`,width," ",transitive.introducedPackageDetailsTotalCount>0||transitive.stillAffectedPackageDetailsTotalCount>0?(line)=>attentionLine(line,useColors):undefined);return lines}function formatTransitiveVulnerabilityDetails(transitive,options){if(!transitive)return[];const useColors=options.useColors===true;const width=normaliseTerminalWidth(options.terminalWidth);const lines=[];const limit=options.verbose?Number.POSITIVE_INFINITY:5;appendTransitivePackageLines(lines,"Added transitive vulnerable packages",transitive.introducedPackageDetails,transitive.introducedPackageDetailsTotalCount,transitive.introducedPackageDetailsTruncated,limit,width,true,useColors);appendTransitivePackageLines(lines,"Still affected transitive packages",transitive.stillAffectedPackageDetails,transitive.stillAffectedPackageDetailsTotalCount,transitive.stillAffectedPackageDetailsTruncated,limit,width,true,useColors);appendTransitivePackageLines(lines,"Fixed transitive vulnerable packages",transitive.fixedPackageDetails,transitive.fixedPackageDetailsTotalCount,transitive.fixedPackageDetailsTruncated,limit,width,false,useColors);return lines}function appendTransitivePackageLines(lines,label,packages,totalCount,truncated,limit,width,attention,useColors){if(totalCount===0)return;lines.push(attention?attentionLine(` ${label}`,useColors):` ${label}`);const visible=packages.slice(0,limit);for(const pkg of visible)lines.push(...formatTransitivePackageLines(pkg,width));const verboseRemaining=Math.max(0,packages.length-visible.length);if(verboseRemaining>0)lines.push(` - ... +${verboseRemaining} more with verbose output`);const backendRemaining=Math.max(0,totalCount-packages.length);if(truncated||backendRemaining>0)lines.push(` - ... +${backendRemaining} more not returned by backend page`)}function formatTransitivePackageLines(pkg,width){const severity=pkg.maxSeverityLabel?` ${pkg.maxSeverityLabel}${typeof pkg.maxSeverityScore==="number"?`(${pkg.maxSeverityScore})`:""}`:"";const lines=[` - ${pkg.registry}:${pkg.name}@${pkg.versions.join("|")} affected=${pkg.affectedCount}${severity}`];if(pkg.advisoryIds.length>0){const prefix=" Advisories: ";appendWrappedText(lines,prefix,pkg.advisoryIds.join(", "),width," ".repeat(prefix.length))}return lines}function formatChangesSection(changelog,options){const width=normaliseTerminalWidth(options.terminalWidth);const statements=changelog.statements;const coverage=changelog.riskCoverage;const lines=[sectionTitle("Changes (classified by agent)",options.useColors===true)];appendWrappedText(lines," ",`${formatRiskTierCount(changelog,"must_act","require action")} | ${formatRiskTierCount(changelog,"should_know","should know")} | ${coverage.itemsUnclassified} too long to classify`,width," ");appendWrappedText(lines," Classification coverage: ",`${riskCoverageText(changelog)} | ${coverage.unitsNoImpact} statements labeled no impact`,width," ");if(!statements)return lines;appendWrappedText(lines," ",`Selection: ${statements.selection} | ${statements.count} matching statements of ${statements.totalCount} parsed.`,width," ");const pending=statements.coverage.reduce((n,c)=>n+c.statementsNotAssessed,0);if(statements.selection!=="all")appendWrappedText(lines," ",`Filter excludes ${coverage.unitsNoImpact} no-impact and ${pending} not-assessed statements${statements.selection!=="focused"?`, and ${coverage.itemsUnclassified} too-long-to-classify statements`:""}${statements.selection==="actionable"?", and should-know statements":""}.`,width," ");if(coverage.versionsNotAssessed)appendWrappedText(lines," ",PENDING_CLASSIFICATION_MESSAGE,width," ");if(coverage.versionsWithoutNotes||coverage.versionsUnparseable)appendWrappedText(lines," ","Missing or unparseable notes are not evidence of no risk.",width," ");if(changelog.fallback==="package_versions")appendWrappedText(lines," ","Release notes unavailable; using package versions.",width," ");appendWrappedText(lines," ","! requires action | kind tags: should know | plain: no impact identified",width," ");const entries=[...changelog.entries??[],...changelog.sampledEntries??[],...changelog.keywordEntries??[]];const releases=[...statements.coverage];for(const entry of changelog.keywordEntries??[])if(entry.signals?.length&&!releases.some((release)=>release.version===entry.version))releases.push({version:entry.version});for(const release of releases){const items=statements.items.filter((item)=>item.version===release.version);const metadata=entries.find((entry)=>entry.version===release.version);const keywords=[];for(const entry of changelog.keywordEntries??[]){if(entry.version!==release.version)continue;const chunks=changelogExcerptChunks(entry.body??entry.headline??entry.bodyPreview??"");const matches=new Map;for(const signal of entry.signals??[]){const text=chunks.find((chunk)=>matchesSignalTerm(chunk,signal))??"";matches.set(text,[...matches.get(text)??[],signal])}for(const[text,signals]of matches){const plain=releaseNoteText(text,()=>"");if(!plain||!items.some((item)=>item.source===entry.detailSource&&releaseNoteText(item.text,()=>"").includes(plain)))keywords.push({text,signals,url:entry.htmlUrl})}}if(!items.length&&!keywords.length&&(release.statementsTotal??0)>0)continue;lines.push("");lines.push(...wrapTerminalProse(sanitizeTerminalText(` ${release.version??"(unversioned)"}${metadata?.publishedAt?` (${metadata.publishedAt.slice(0,10)})`:""}`),width," ").map((line)=>highlight(line,options.useColors===true)));lines.push(...formatChangelogVersionStatements(items,{useColors:options.useColors===true,terminalWidth:width-2,compactNonAction:!options.verbose}).map((line)=>` ${line}`));const shownUrls=new Set(items.flatMap((item)=>item.url?[safeRiskText(item.url)]:[]));if(!items.length&&metadata?.htmlUrl){const url=safeRiskText(metadata.htmlUrl);appendWrappedText(lines," ",url,width," ");shownUrls.add(url)}if(!items.length&&!keywords.length)appendWrappedText(lines," ",release.status==="without_notes"?"No release notes available.":"Notes contain no parsed statements.",width," ");if(keywords.length){lines.push(" Keyword matches (lexical evidence)");for(const keyword of keywords){const url=keyword.url?safeRiskText(keyword.url):undefined;if(url&&!shownUrls.has(url)){appendWrappedText(lines," ",url,width," ");shownUrls.add(url)}const quote=releaseNoteText(keyword.text,(sourceUrl)=>sourceUrl);const signals=keyword.signals.map(safeRiskText);const characters=Array.from(quote);const excerpted=!options.verbose&&characters.length>240;const text=excerpted?`${characters.slice(0,240).join("").trimEnd()}...`:quote;appendWrappedText(lines," * ",`[${signals.join(", ")}] ${text||"Entry keyword matched; excerpt unavailable."}`,width," ",(line)=>colorizeSignalKeywords(line,signals,options.useColors===true));if(excerpted)appendWrappedText(lines," ","Excerpt; use verbose for the full keyword quote.",width," ")}}}const entrySignals=new Set((changelog.keywordEntries??[]).flatMap((entry)=>entry.signals??[]));const unmatched=changelogKeywordSummary(changelog).filter((signal)=>!entrySignals.has(signal));if(unmatched.length||!changelog.keywordEntries?.length&&changelog.totalKeywordEntries>0)appendWrappedText(lines," Keyword matches without excerpts: ",unmatched.map(safeRiskText).join(", ")||`${changelog.totalKeywordEntries} matching entries`,width," ");return lines}function formatRiskTierCount(changelog,tier,label){const coverage=changelog.riskCoverage;const confident=tier==="must_act"?coverage.itemsMustActConfident:coverage.itemsShouldKnowConfident;const uncertain=tier==="must_act"?coverage.itemsMustActAmbiguous:coverage.itemsShouldKnowAmbiguous;return`${confident} ${label}${uncertain?` (+${uncertain} uncertain)`:""}`}function riskCoverageText(changelog){const c=changelog.riskCoverage;return`${c.versionsClassified} classified | ${c.versionsNotAssessed} not assessed | ${c.versionsWithoutNotes} without notes${c.versionsUnparseable>0?` | ${c.versionsUnparseable} unparseable`:""}`}function formatMigrationGuides(review,options,prefix=" "){const lines=[];for(const guide of review.migrationGuides??[]){const url=safeRiskText(guide.url);const label=safeRiskText(guide.label??"").trim();const informativeLabel=label&&label!==url&&!["migration guide","upgrade guide"].includes(label.toLowerCase());appendWrappedText(lines,prefix,`Migration guide available at ${url}${informativeLabel?` (${label})`:""}`,normaliseTerminalWidth(options.terminalWidth),`${prefix} `)}return lines}function formatBatchTriage(reviews,options){const lines=[sectionTitle("Batch triage - statement totals",options.useColors===true)];for(const review of reviews){const c=review.changelog;const target=review.security.target;const deprecation=target?.deprecated===true?"deprecated":target?.deprecated===false?"not deprecated":"deprecation unknown";const transitive=review.security.transitive;const unknownCurrent=review.security.current?.unknownVulnerabilityCount;const unknownTarget=target?.unknownVulnerabilityCount;const uncertainty=(unknownCurrent??0)>0||(unknownTarget??0)>0?` / ${unknownCurrent??"?"} -> ${unknownTarget??"?"} unknown advisories`:"";const assessments=[["current",review.security.current],["target",target]];const assessmentText=assessments.map(([label,summary])=>{if(!summary||(summary.unknownVulnerabilityCount??0)>0&&summary.assessmentStatus==="UNKNOWN")return;const uncertainty=formatAssessmentUncertainty(summary.assessmentStatus,summary.affectedCount>0);return uncertainty===undefined?undefined:`${label}: ${safeRiskText(uncertainty)}`}).filter(Boolean).join(" / ");const security=`direct vulnerabilities: ${review.security.added.length} added / ${review.security.notAddressed.length} still present${uncertainty}${assessmentText?` / ${assessmentText}`:""}`;const transitiveText=transitive?`transitive: ${transitive.introducedPackageDetailsTotalCount} added / ${transitive.stillAffectedPackageDetailsTotalCount} still affected`:"transitive: not checked";const dependencyCount=review.dependencyChanges?[review.dependencyChanges.direct.added,review.dependencyChanges.direct.removed,review.dependencyChanges.direct.changed].reduce((n,rows)=>n+rows.length,0):undefined;const issues=review.dependencyIssues;const issueCount=issues?issues.introducedDeprecated.length+issues.introducedDuplicates.length+issues.introducedConflicts.length+issues.introducedOutdated.length:undefined;lines.push(` ${safeRiskText(`${review.registry}:${review.name} ${review.currentVersion} -> ${review.targetVersion} (${review.versionDelta})`)} | ${formatRiskTierCount(c,"must_act","act")} | ${formatRiskTierCount(c,"should_know","know")} | ${c.riskCoverage.itemsUnclassified} too long to classify | versions: ${riskCoverageText(c)} | ${c.riskCoverage.unitsNoImpact} labeled no impact | ${deprecation} | ${security} | ${transitiveText} | ${c.totalKeywordEntries} keyword entries | ${review.compatibility?.peerDependencyChanges.length??"not checked"} peer dependency changes | ${review.compatibility?.notes.length??"not checked"} compatibility notes | ${dependencyCount??"not checked"} direct dependency changes | ${issueCount??"not checked"} dependency issues | ${review.unknowns.length} unknowns`);if(!options.verbose)lines.push(...formatMigrationGuides(review,options," "));for(const detail of options.verbose?[]:review.unknownDetails??[]){appendWrappedText(lines," Unknown: ",safeRiskText(`${detail.section} (${detail.code}): ${detail.message}`),normaliseTerminalWidth(options.terminalWidth)," ")}}const width=normaliseTerminalWidth(options.terminalWidth);if(reviews.some((review)=>review.changelog.riskCoverage.versionsNotAssessed>0))appendWrappedText(lines," ",PENDING_CLASSIFICATION_MESSAGE,width," ");appendWrappedText(lines," ","Counts separate backend-confident statements from uncertain ones; ranking uses only confident action totals. Totals cover the whole range independently of the detailed statement filter.",width," ");appendWrappedText(lines," ","Classified by an agent. Missing or unparseable notes are not evidence of no risk. Use verbose for full per-package quotes and evidence.",width," ");return lines}function formatCompatibilitySection(compatibility,options){if(compatibility.peerDependencyChanges.length===0&&compatibility.notes.length===0)return[];const width=normaliseTerminalWidth(options.terminalWidth);const lines=[sectionTitle("Compatibility",options.useColors===true)];if(compatibility.peerDependencyChanges.length>0){lines.push(" Peer dependency changes");const limit=options.verbose?Number.POSITIVE_INFINITY:10;for(const change of compatibility.peerDependencyChanges.slice(0,limit)){appendWrappedText(lines," - ",change,width," ")}const remaining=compatibility.peerDependencyChanges.length-limit;if(remaining>0)lines.push(` - ... +${remaining} more with verbose output`)}for(const note of compatibility.notes){appendWrappedText(lines," Note: ",note,width," ")}return lines}function changelogKeywordSummary(changelog){return[...new Set([...changelog.breakingSignals,...changelog.migrationSignals])]}function colorizeSignalKeywords(line,keywords,useColors){if(!useColors||keywords.length===0)return line;let result=line;for(const keyword of keywords){result=result.replace(keyword,`${colors.yellow}${keyword}${colors.reset}`)}return result}function changelogExcerptChunks(body){return changelogSignalText(body).split(/\r?\n+/).map((line)=>normaliseChangelogLine(line)).filter((line)=>line.length>0&&!isGenericChangelogHeading(line))}function normaliseChangelogLine(line){return line.replace(/^#{1,6}\s+/,"").trim()}function isGenericChangelogHeading(line){return/^(what'?s changed|main changes|changes|commits?|contributors?|breaking changes?)$/i.test(line.trim())}function formatDependencyChangesSection(changes,options){const useColors=options.useColors===true;const lines=[sectionTitle("Dependencies",useColors)];lines.push(` Direct: ${changes.direct.added.length} added | ${changes.direct.removed.length} removed | ${changes.direct.changed.length} changed`);lines.push(...formatDependencyChangeGroup("Direct",changes.direct,options));lines.push(` Transitive: ${changes.transitive.added.length} added | ${changes.transitive.removed.length} removed | ${changes.transitive.changed.length} changed`);if(options.verbose){lines.push(...formatDependencyChangeGroup("Transitive",changes.transitive,options))}else if(hasDependencyChangeGroupItems(changes.transitive)){lines.push(" More transitive dependency details are available with verbose output.")}return lines}function hasDependencyChangeGroupItems(group){return group.added.length>0||group.removed.length>0||group.changed.length>0}function formatDependencyChangeGroup(scope,group,options){const lines=[];const limit=options.verbose?Number.POSITIVE_INFINITY:5;appendChangeLines(lines,`${scope} added`,group.added,limit);appendChangeLines(lines,`${scope} removed`,group.removed,limit);appendChangeLines(lines,`${scope} changed`,group.changed,limit);return lines}function appendChangeLines(lines,label,items,limit){if(items.length===0)return;const sample=items.slice(0,limit).map(formatDependencyChangeItem);const more=items.length>limit?` (+${items.length-limit} more)`:"";lines.push(` ${label}${more?`${more} with verbose output`:""}`);for(const item of sample)lines.push(` - ${item}`)}function formatDependencyIssuesSection(issues,options){const introduced=issues.introducedDeprecated.length+issues.introducedDuplicates.length+issues.introducedConflicts.length+issues.introducedOutdated.length;const useColors=options.useColors===true;const limit=options.verbose?Number.POSITIVE_INFINITY:5;const lines=[sectionTitle("Dependency issues",useColors)];if(introduced===0){lines.push(` none introduced | current total: ${issues.currentTotal} | target total: ${issues.targetTotal}`);return lines}lines.push(attentionLine(` ${introduced} introduced | current total: ${issues.currentTotal} | target total: ${issues.targetTotal}`,useColors));appendStringList(lines,"Introduced deprecated",issues.introducedDeprecated,limit,useColors);appendStringList(lines,"Introduced duplicates",issues.introducedDuplicates,limit,useColors);appendStringList(lines,"Introduced conflicts",issues.introducedConflicts,limit,useColors);appendStringList(lines,"Introduced outdated",issues.introducedOutdated,limit,useColors);return lines}function appendStringList(lines,label,items,limit,useColors){if(items.length===0)return;lines.push(attentionLine(` ${label}`,useColors));for(const item of items.slice(0,limit))lines.push(` - ${item}`);const remaining=items.length-limit;if(remaining>0)lines.push(` - ... +${remaining} more with verbose output`)}function attentionLine(text,useColors){return colorize(text,"yellow",useColors)}function formatDependencyChangeItem(item){const name=item.registry?`${item.registry}:${item.name}`:item.name;const from=item.fromVersions?.join("|")??"";const to=item.toVersions?.join("|")??"";if(from&&to&&from!==to)return`${name} ${from} -> ${to}`;if(to)return`${name}@${to}`;if(from)return`${name}@${from}`;return name}var packageSchema=z7.object({registry:z7.string().describe(`Package registry. Supported: ${PKGSEER_REGISTRY_LIST2}.`),package_name:z7.string().describe("Package name, scoped names ok."),current_version:z7.string().describe("Currently used package version. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift."),target_version:z7.string().describe("Target package version. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift.")});var schema7={registry:z7.string().optional().describe(`Package registry for single-package mode. Supported: ${PKGSEER_REGISTRY_LIST2}.`),package_name:z7.string().optional().describe("Package name for single-package mode."),current_version:z7.string().optional().describe("Currently used version for single-package mode. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift."),target_version:z7.string().optional().describe("Target version for single-package mode. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift."),packages:z7.array(packageSchema).optional().describe(`Batch mode with at most ${PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES} upgrades after blank rows are removed. Mutually exclusive with single-package fields.`),skip_transitive_security:z7.boolean().optional().describe("When true, skip current-vs-target transitive vulnerability summary diffs. Defaults false, so transitive security evidence is included unless explicitly skipped."),include_dependency_issues:z7.boolean().optional().describe("When true, diff current vs target transitive deprecated/outdated/duplicate/conflict summaries. Defaults false."),min_severity:z7.string().optional().describe("Minimum direct-advisory severity: low, medium, high, or critical."),changes:z7.string().optional().describe("Filter detailed statement quotes only: actionable (MUST_ACT), important (MUST_ACT + SHOULD_KNOW), or all parsed units, including no-impact and unassessed. Omit or pass blank to use focused (MUST_ACT + SHOULD_KNOW + too-long-to-classify (oversize) statements). Whole-range counters and batch ranking do not change."),verbose:z7.boolean().optional().describe("Text output only. Batches default to triage rows; verbose adds full per-package reports, expands statement quotes up to backend bounds, and expands dependency change examples."),format:z7.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text.")};var DESCRIPTION7="Review a package upgrade: vulnerabilities, releases, peers, dependency changes. "+"Compares current and target versions using direct vulnerability checks, changelog ranges, target deprecation metadata, peer dependency changes, and optional transitive evidence diffs. "+"The tool reports facts only, including agent-classified release-note statements in backend source order, with nearby authoritative URLs and assessment coverage. JSON includes complete selected statement pages, source positions and context, and classifier provenance. It does not assign package-level risk or decide whether to accept an upgrade. Batches default to triage rows; use verbose for full per-package evidence. "+"Use this instead of inferring acceptability from semver, including patch bumps. "+"Use signals as a starting point to evaluate the impact of changes on the codebase. "+"You can use pkg_changelog and code_diff to obtain full release-note and source-change details. "+"Accepts either one package via registry/package_name/current_version/"+`target_version or batch \`packages[]\` with at most ${PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES} upgrades.`+`
174
+ `}function sectionTitle(text,useColors){return useColors?`${colors.bold}${text}${colors.reset}`:text}function attentionSectionTitle(text,useColors){return useColors?`${colors.bold}${colors.yellow}${text}${colors.reset}`:text}function normaliseTerminalWidth(width){if(width===undefined||!Number.isFinite(width))return 80;return Math.max(20,Math.floor(width))}function appendSection(lines,section){if(section.length===0)return;lines.push("",...section)}function appendWrappedText(lines,prefix,text,width,continuationPrefix=" ".repeat(prefix.length),style){const words=text.trim().split(/\s+/).filter(Boolean);if(words.length===0){lines.push(style?style(prefix.trimEnd()):prefix.trimEnd());return}let current=prefix;for(const word of words){const separator=current===prefix?"":" ";if(current.length+separator.length+word.length<=width||current===prefix&&current.trimEnd().length>=width){current+=`${separator}${word}`;continue}if(current.trim())lines.push(style?style(current.trimEnd()):current.trimEnd());current=`${continuationPrefix}${word}`}lines.push(style?style(current.trimEnd()):current.trimEnd())}function aggregateSummary(response){const reviewsWithTransitive=response.reviews.filter((review)=>review.security.transitive!==undefined).length;const omittedTransitive=response.reviews.length-reviewsWithTransitive;const clauses=[`${response.summary.withUnknowns} with reported unknowns`,`${response.summary.withAddedAdvisories} with added direct vulnerabilities`];const classificationGaps=response.reviews.filter(({changelog})=>{const coverage=changelog.riskCoverage;return coverage.versionsNotAssessed>0||coverage.versionsWithoutNotes>0||coverage.versionsUnparseable>0}).length;if(classificationGaps>0)clauses.splice(1,0,`${classificationGaps} with classification coverage gaps`);if(reviewsWithTransitive===0){clauses.push("transitive security not checked")}else{clauses.push(`${response.summary.withTransitiveVulnerabilityAdditions} with added transitive vulnerabilities`);if(omittedTransitive>0)clauses.push(`${omittedTransitive} without transitive security evidence`)}clauses.push(`${response.summary.withBreakingSignals} with heuristic change signals`,`${response.summary.withDirectDependencyChanges} with direct dependency changes`);return clauses.join(" | ")}function formatDeprecationLine(review,options){const current=review.security.current;const target=review.security.target;const width=normaliseTerminalWidth(options.terminalWidth);const useColors=options.useColors===true;const hasCurrentDeprecation=current?.deprecated===true;const hasTargetDeprecation=target?.deprecated===true;const targetDeprecationUnknown=target===undefined||target.deprecated===undefined;if(!hasCurrentDeprecation&&!hasTargetDeprecation&&!targetDeprecationUnknown)return;const lines=[sectionTitle("Deprecation",useColors)];if(current?.deprecated===true)lines.push(attentionLine(" Current: deprecated",useColors));if(target?.deprecated===true){const reason=target.deprecationReason?`deprecated: ${target.deprecationReason}`:"deprecated";appendWrappedText(lines," Target: ",reason,width," ",(line)=>attentionLine(line,useColors))}if(targetDeprecationUnknown)lines.push(attentionLine(" Target: deprecation unknown",useColors));return lines.length>1?lines:undefined}function formatVulnerabilitySection(review,options){const security=review.security;const current=security.current?.affectedCount??"unknown";const target=security.target?.affectedCount??"unknown";const width=normaliseTerminalWidth(options.terminalWidth);const useColors=options.useColors===true;const lines=[sectionTitle("Security",useColors)];appendWrappedText(lines," Direct: ",`${current} affected -> ${target} affected | ${security.removed.length} fixed | ${security.added.length} added | ${security.notAddressed.length} still present`,width," ",security.added.length>0||security.notAddressed.length>0?(line)=>attentionLine(line,useColors):undefined);for(const[label,summary]of[["Current",security.current],["Target",security.target]]){if(!summary)continue;const unknown=summary.unknownVulnerabilityCount??0;const uncertainty=formatAssessmentUncertainty(summary.assessmentStatus,summary.affectedCount>0);if(unknown===0&&uncertainty===undefined)continue;const target=`${review.registry}:${review.name}@${summary.version}`;const explanation=unknown>0?`${unknown} of ${summary.allCount} ${summary.allCount===1?"advisory":"advisories"} not evaluable`:uncertainty;const action=unknown>0?options.surface==="mcp"?`pkg_vulns target="${target}" advisory_scope="unknown"`:`pkg vulns ${target} --scope unknown`:undefined;appendWrappedText(lines,` ${label}: `,safeRiskText([explanation,unknown>0&&summary.assessmentStatus!=="UNKNOWN"?uncertainty:undefined,action].filter(Boolean).join("; ")),width," ")}lines.push(...formatTransitiveVulnerabilitySummary(security.transitive,options));const limit=options.verbose?Number.POSITIVE_INFINITY:5;appendAdvisoryLines(lines,"Added direct advisories",security.added,limit,width,useColors,true);appendAdvisoryLines(lines,"Fixed direct advisories",security.removed,limit,width,useColors,false);appendAdvisoryLines(lines,"Still present direct advisories",security.notAddressed,limit,width,useColors,true);lines.push(...formatTransitiveVulnerabilityDetails(security.transitive,options));return lines}function appendAdvisoryLines(lines,label,advisories,limit,width,useColors,attention){if(advisories.length===0)return;lines.push(attention?attentionLine(` ${label}`,useColors):` ${label}`);for(const advisory of advisories.slice(0,limit)){const prefix=` - ${formatAdvisoryPrefix(advisory)}`;const prose=formatAdvisoryProse(advisory);if(prose){appendWrappedText(lines,`${prefix}: `,prose,width," ")}else{lines.push(prefix)}}const remaining=advisories.length-limit;if(remaining>0)lines.push(` - ... +${remaining} more with verbose output`)}function formatAdvisoryPrefix(advisory){const id=advisory.id??advisory.aliases?.[0]??"unknown-id";const severity=advisory.severityLabel?` ${advisory.severityLabel}${typeof advisory.severity==="number"?`(${advisory.severity})`:""}`:"";const malicious=advisory.isMalicious?" malicious":"";return`${id}${severity}${malicious}`}function formatAdvisoryProse(advisory){const parts=[];const uncertainty=formatAssessmentUncertainty(advisory.assessmentStatus,true);if(uncertainty!==undefined&&advisory.assessmentStatus!=="NOT_ASSESSED")parts.push(safeRiskText(uncertainty));if(advisory.assessmentReasons?.length)parts.push(safeRiskText(advisory.assessmentReasons.map(formatVulnerabilityAssessmentReason).join("; ")));if(advisory.summary)parts.push(advisory.summary);if(advisory.fixedIn?.length)parts.push(`fixed in ${advisory.fixedIn.join(", ")}`);return parts.join(" | ")}function formatTransitiveVulnerabilitySummary(transitive,options){const useColors=options.useColors===true;if(!transitive)return[attentionLine(" Transitive: not checked",useColors)];const lines=[];const width=normaliseTerminalWidth(options.terminalWidth);appendWrappedText(lines," Transitive: ",`${transitive.currentAffected} affected packages -> ${transitive.targetAffected} | ${transitive.fixedPackageDetailsTotalCount} fixed | ${transitive.introducedPackageDetailsTotalCount} added | ${transitive.stillAffectedPackageDetailsTotalCount} still affected`,width," ",transitive.introducedPackageDetailsTotalCount>0||transitive.stillAffectedPackageDetailsTotalCount>0?(line)=>attentionLine(line,useColors):undefined);return lines}function formatTransitiveVulnerabilityDetails(transitive,options){if(!transitive)return[];const useColors=options.useColors===true;const width=normaliseTerminalWidth(options.terminalWidth);const lines=[];const limit=options.verbose?Number.POSITIVE_INFINITY:5;appendTransitivePackageLines(lines,"Added transitive vulnerable packages",transitive.introducedPackageDetails,transitive.introducedPackageDetailsTotalCount,transitive.introducedPackageDetailsTruncated,limit,width,true,useColors);appendTransitivePackageLines(lines,"Still affected transitive packages",transitive.stillAffectedPackageDetails,transitive.stillAffectedPackageDetailsTotalCount,transitive.stillAffectedPackageDetailsTruncated,limit,width,true,useColors);appendTransitivePackageLines(lines,"Fixed transitive vulnerable packages",transitive.fixedPackageDetails,transitive.fixedPackageDetailsTotalCount,transitive.fixedPackageDetailsTruncated,limit,width,false,useColors);return lines}function appendTransitivePackageLines(lines,label,packages,totalCount,truncated,limit,width,attention,useColors){if(totalCount===0)return;lines.push(attention?attentionLine(` ${label}`,useColors):` ${label}`);const visible=packages.slice(0,limit);for(const pkg of visible)lines.push(...formatTransitivePackageLines(pkg,width));const verboseRemaining=Math.max(0,packages.length-visible.length);if(verboseRemaining>0)lines.push(` - ... +${verboseRemaining} more with verbose output`);const backendRemaining=Math.max(0,totalCount-packages.length);if(truncated||backendRemaining>0)lines.push(` - ... +${backendRemaining} more not returned by backend page`)}function formatTransitivePackageLines(pkg,width){const severity=pkg.maxSeverityLabel?` ${pkg.maxSeverityLabel}${typeof pkg.maxSeverityScore==="number"?`(${pkg.maxSeverityScore})`:""}`:"";const lines=[` - ${pkg.registry}:${pkg.name}@${pkg.versions.join("|")} affected=${pkg.affectedCount}${severity}`];if(pkg.advisoryIds.length>0){const prefix=" Advisories: ";appendWrappedText(lines,prefix,pkg.advisoryIds.join(", "),width," ".repeat(prefix.length))}return lines}function formatChangesSection(changelog,options){const width=normaliseTerminalWidth(options.terminalWidth);const statements=changelog.statements;const coverage=changelog.riskCoverage;const lines=[sectionTitle("Changes (classified by agent)",options.useColors===true)];appendWrappedText(lines," ",`${formatRiskTierCount(changelog,"must_act","require action")} | ${formatRiskTierCount(changelog,"should_know","should know")} | ${coverage.itemsUnclassified} too long to classify`,width," ");appendWrappedText(lines," Classification coverage: ",`${riskCoverageText(changelog)} | ${coverage.unitsNoImpact} statements labeled no impact`,width," ");if(!statements)return lines;appendWrappedText(lines," ",`Selection: ${statements.selection} | ${statements.count} matching statements of ${statements.totalCount} parsed.`,width," ");const pending=statements.coverage.reduce((n,c)=>n+c.statementsNotAssessed,0);if(statements.selection!=="all")appendWrappedText(lines," ",`Filter excludes ${coverage.unitsNoImpact} no-impact and ${pending} not-assessed statements${statements.selection!=="focused"?`, and ${coverage.itemsUnclassified} too-long-to-classify statements`:""}${statements.selection==="actionable"?", and should-know statements":""}.`,width," ");if(coverage.versionsNotAssessed)appendWrappedText(lines," ",PENDING_CLASSIFICATION_MESSAGE,width," ");if(coverage.versionsWithoutNotes||coverage.versionsUnparseable)appendWrappedText(lines," ","Missing or unparseable notes are not evidence of no risk.",width," ");if(changelog.fallback==="package_versions")appendWrappedText(lines," ","Release notes unavailable; using package versions.",width," ");appendWrappedText(lines," ","! requires action | kind tags: should know | plain: no impact identified",width," ");const entries=[...changelog.entries??[],...changelog.sampledEntries??[],...changelog.keywordEntries??[]];const releases=[...statements.coverage];for(const entry of changelog.keywordEntries??[])if(entry.signals?.length&&!releases.some((release)=>release.version===entry.version))releases.push({version:entry.version});for(const release of releases){const items=statements.items.filter((item)=>item.version===release.version);const metadata=entries.find((entry)=>entry.version===release.version);const keywords=[];for(const entry of changelog.keywordEntries??[]){if(entry.version!==release.version)continue;const chunks=changelogExcerptChunks(entry.body??entry.headline??entry.bodyPreview??"");const matches=new Map;for(const signal of entry.signals??[]){const text=chunks.find((chunk)=>matchesSignalTerm(chunk,signal))??"";matches.set(text,[...matches.get(text)??[],signal])}for(const[text,signals]of matches){const plain=releaseNoteText(text,()=>"");if(!plain||!items.some((item)=>item.source===entry.detailSource&&releaseNoteText(item.text,()=>"").includes(plain)))keywords.push({text,signals,url:entry.htmlUrl})}}if(!items.length&&!keywords.length&&(release.statementsTotal??0)>0&&!release.generation)continue;lines.push("");lines.push(...wrapTerminalProse(sanitizeTerminalText(` ${release.version??"(unversioned)"}${metadata?.publishedAt?` (${metadata.publishedAt.slice(0,10)})`:""}`),width," ").map((line)=>highlight(line,options.useColors===true)));lines.push(...formatChangelogGeneration({...release,statementsTotal:release.statementsTotal??0},{useColors:options.useColors===true,terminalWidth:width-2}).map((line)=>` ${line}`),...formatChangelogVersionStatements(items,{useColors:options.useColors===true,terminalWidth:width-2,compactNonAction:!options.verbose}).map((line)=>` ${line}`));const shownUrls=new Set(items.flatMap((item)=>item.url?[safeRiskText(item.url)]:[]));if(!items.length&&metadata?.htmlUrl){const url=safeRiskText(metadata.htmlUrl);appendWrappedText(lines," ",url,width," ");shownUrls.add(url)}if(!items.length&&!keywords.length&&!(release.generation?.status==="generated"&&release.statementsTotal===0))appendWrappedText(lines," ",release.generation&&(release.statementsTotal??0)>0?"No statements match this filter.":release.status==="without_notes"?"No release notes available.":"Notes contain no parsed statements.",width," ");if(keywords.length){lines.push(" Keyword matches (lexical evidence)");for(const keyword of keywords){const url=keyword.url?safeRiskText(keyword.url):undefined;if(url&&!shownUrls.has(url)){appendWrappedText(lines," ",url,width," ");shownUrls.add(url)}const quote=releaseNoteText(keyword.text,(sourceUrl)=>sourceUrl);const signals=keyword.signals.map(safeRiskText);const characters=Array.from(quote);const excerpted=!options.verbose&&characters.length>240;const text=excerpted?`${characters.slice(0,240).join("").trimEnd()}...`:quote;appendWrappedText(lines," * ",`[${signals.join(", ")}] ${text||"Entry keyword matched; excerpt unavailable."}`,width," ",(line)=>colorizeSignalKeywords(line,signals,options.useColors===true));if(excerpted)appendWrappedText(lines," ","Excerpt; use verbose for the full keyword quote.",width," ")}}}const entrySignals=new Set((changelog.keywordEntries??[]).flatMap((entry)=>entry.signals??[]));const unmatched=changelogKeywordSummary(changelog).filter((signal)=>!entrySignals.has(signal));if(unmatched.length||!changelog.keywordEntries?.length&&changelog.totalKeywordEntries>0)appendWrappedText(lines," Keyword matches without excerpts: ",unmatched.map(safeRiskText).join(", ")||`${changelog.totalKeywordEntries} matching entries`,width," ");return lines}function formatRiskTierCount(changelog,tier,label){const coverage=changelog.riskCoverage;const confident=tier==="must_act"?coverage.itemsMustActConfident:coverage.itemsShouldKnowConfident;const uncertain=tier==="must_act"?coverage.itemsMustActAmbiguous:coverage.itemsShouldKnowAmbiguous;return`${confident} ${label}${uncertain?` (+${uncertain} uncertain)`:""}`}function riskCoverageText(changelog){const c=changelog.riskCoverage;return`${c.versionsClassified} classified | ${c.versionsNotAssessed} not assessed | ${c.versionsWithoutNotes} without notes${c.versionsUnparseable>0?` | ${c.versionsUnparseable} unparseable`:""}`}function formatMigrationGuides(review,options,prefix=" "){const lines=[];for(const guide of review.migrationGuides??[]){const url=safeRiskText(guide.url);const label=safeRiskText(guide.label??"").trim();const informativeLabel=label&&label!==url&&!["migration guide","upgrade guide"].includes(label.toLowerCase());appendWrappedText(lines,prefix,`Migration guide available at ${url}${informativeLabel?` (${label})`:""}`,normaliseTerminalWidth(options.terminalWidth),`${prefix} `)}return lines}function formatBatchTriage(reviews,options){const lines=[sectionTitle("Batch triage - statement totals",options.useColors===true)];for(const review of reviews){const c=review.changelog;const target=review.security.target;const deprecation=target?.deprecated===true?"deprecated":target?.deprecated===false?"not deprecated":"deprecation unknown";const transitive=review.security.transitive;const unknownCurrent=review.security.current?.unknownVulnerabilityCount;const unknownTarget=target?.unknownVulnerabilityCount;const uncertainty=(unknownCurrent??0)>0||(unknownTarget??0)>0?` / ${unknownCurrent??"?"} -> ${unknownTarget??"?"} unknown advisories`:"";const assessments=[["current",review.security.current],["target",target]];const assessmentText=assessments.map(([label,summary])=>{if(!summary||(summary.unknownVulnerabilityCount??0)>0&&summary.assessmentStatus==="UNKNOWN")return;const uncertainty=formatAssessmentUncertainty(summary.assessmentStatus,summary.affectedCount>0);return uncertainty===undefined?undefined:`${label}: ${safeRiskText(uncertainty)}`}).filter(Boolean).join(" / ");const security=`direct vulnerabilities: ${review.security.added.length} added / ${review.security.notAddressed.length} still present${uncertainty}${assessmentText?` / ${assessmentText}`:""}`;const transitiveText=transitive?`transitive: ${transitive.introducedPackageDetailsTotalCount} added / ${transitive.stillAffectedPackageDetailsTotalCount} still affected`:"transitive: not checked";const dependencyCount=review.dependencyChanges?[review.dependencyChanges.direct.added,review.dependencyChanges.direct.removed,review.dependencyChanges.direct.changed].reduce((n,rows)=>n+rows.length,0):undefined;const issues=review.dependencyIssues;const issueCount=issues?issues.introducedDeprecated.length+issues.introducedDuplicates.length+issues.introducedConflicts.length+issues.introducedOutdated.length:undefined;lines.push(` ${safeRiskText(`${review.registry}:${review.name} ${review.currentVersion} -> ${review.targetVersion} (${review.versionDelta})`)} | ${formatRiskTierCount(c,"must_act","act")} | ${formatRiskTierCount(c,"should_know","know")} | ${c.riskCoverage.itemsUnclassified} too long to classify | versions: ${riskCoverageText(c)} | ${c.riskCoverage.unitsNoImpact} labeled no impact | ${deprecation} | ${security} | ${transitiveText} | ${c.totalKeywordEntries} keyword entries | ${review.compatibility?.peerDependencyChanges.length??"not checked"} peer dependency changes | ${review.compatibility?.notes.length??"not checked"} compatibility notes | ${dependencyCount??"not checked"} direct dependency changes | ${issueCount??"not checked"} dependency issues | ${review.unknowns.length} unknowns`);if(!options.verbose)lines.push(...formatMigrationGuides(review,options," "));for(const detail of options.verbose?[]:review.unknownDetails??[]){appendWrappedText(lines," Unknown: ",safeRiskText(`${detail.section} (${detail.code}): ${detail.message}`),normaliseTerminalWidth(options.terminalWidth)," ")}}const width=normaliseTerminalWidth(options.terminalWidth);if(reviews.some((review)=>review.changelog.riskCoverage.versionsNotAssessed>0))appendWrappedText(lines," ",PENDING_CLASSIFICATION_MESSAGE,width," ");appendWrappedText(lines," ","Counts separate backend-confident statements from uncertain ones; ranking uses only confident action totals. Totals cover the whole range independently of the detailed statement filter.",width," ");appendWrappedText(lines," ","Classified by an agent. Missing or unparseable notes are not evidence of no risk. Use verbose for full per-package quotes and evidence.",width," ");return lines}function formatCompatibilitySection(compatibility,options){if(compatibility.peerDependencyChanges.length===0&&compatibility.notes.length===0)return[];const width=normaliseTerminalWidth(options.terminalWidth);const lines=[sectionTitle("Compatibility",options.useColors===true)];if(compatibility.peerDependencyChanges.length>0){lines.push(" Peer dependency changes");const limit=options.verbose?Number.POSITIVE_INFINITY:10;for(const change of compatibility.peerDependencyChanges.slice(0,limit)){appendWrappedText(lines," - ",change,width," ")}const remaining=compatibility.peerDependencyChanges.length-limit;if(remaining>0)lines.push(` - ... +${remaining} more with verbose output`)}for(const note of compatibility.notes){appendWrappedText(lines," Note: ",note,width," ")}return lines}function changelogKeywordSummary(changelog){return[...new Set([...changelog.breakingSignals,...changelog.migrationSignals])]}function colorizeSignalKeywords(line,keywords,useColors){if(!useColors||keywords.length===0)return line;let result=line;for(const keyword of keywords){result=result.replace(keyword,`${colors.yellow}${keyword}${colors.reset}`)}return result}function changelogExcerptChunks(body){return changelogSignalText(body).split(/\r?\n+/).map((line)=>normaliseChangelogLine(line)).filter((line)=>line.length>0&&!isGenericChangelogHeading(line))}function normaliseChangelogLine(line){return line.replace(/^#{1,6}\s+/,"").trim()}function isGenericChangelogHeading(line){return/^(what'?s changed|main changes|changes|commits?|contributors?|breaking changes?)$/i.test(line.trim())}function formatDependencyChangesSection(changes,options){const useColors=options.useColors===true;const lines=[sectionTitle("Dependencies",useColors)];lines.push(` Direct: ${changes.direct.added.length} added | ${changes.direct.removed.length} removed | ${changes.direct.changed.length} changed`);lines.push(...formatDependencyChangeGroup("Direct",changes.direct,options));lines.push(` Transitive: ${changes.transitive.added.length} added | ${changes.transitive.removed.length} removed | ${changes.transitive.changed.length} changed`);if(options.verbose){lines.push(...formatDependencyChangeGroup("Transitive",changes.transitive,options))}else if(hasDependencyChangeGroupItems(changes.transitive)){lines.push(" More transitive dependency details are available with verbose output.")}return lines}function hasDependencyChangeGroupItems(group){return group.added.length>0||group.removed.length>0||group.changed.length>0}function formatDependencyChangeGroup(scope,group,options){const lines=[];const limit=options.verbose?Number.POSITIVE_INFINITY:5;appendChangeLines(lines,`${scope} added`,group.added,limit);appendChangeLines(lines,`${scope} removed`,group.removed,limit);appendChangeLines(lines,`${scope} changed`,group.changed,limit);return lines}function appendChangeLines(lines,label,items,limit){if(items.length===0)return;const sample=items.slice(0,limit).map(formatDependencyChangeItem);const more=items.length>limit?` (+${items.length-limit} more)`:"";lines.push(` ${label}${more?`${more} with verbose output`:""}`);for(const item of sample)lines.push(` - ${item}`)}function formatDependencyIssuesSection(issues,options){const introduced=issues.introducedDeprecated.length+issues.introducedDuplicates.length+issues.introducedConflicts.length+issues.introducedOutdated.length;const useColors=options.useColors===true;const limit=options.verbose?Number.POSITIVE_INFINITY:5;const lines=[sectionTitle("Dependency issues",useColors)];if(introduced===0){lines.push(` none introduced | current total: ${issues.currentTotal} | target total: ${issues.targetTotal}`);return lines}lines.push(attentionLine(` ${introduced} introduced | current total: ${issues.currentTotal} | target total: ${issues.targetTotal}`,useColors));appendStringList(lines,"Introduced deprecated",issues.introducedDeprecated,limit,useColors);appendStringList(lines,"Introduced duplicates",issues.introducedDuplicates,limit,useColors);appendStringList(lines,"Introduced conflicts",issues.introducedConflicts,limit,useColors);appendStringList(lines,"Introduced outdated",issues.introducedOutdated,limit,useColors);return lines}function appendStringList(lines,label,items,limit,useColors){if(items.length===0)return;lines.push(attentionLine(` ${label}`,useColors));for(const item of items.slice(0,limit))lines.push(` - ${item}`);const remaining=items.length-limit;if(remaining>0)lines.push(` - ... +${remaining} more with verbose output`)}function attentionLine(text,useColors){return colorize(text,"yellow",useColors)}function formatDependencyChangeItem(item){const name=item.registry?`${item.registry}:${item.name}`:item.name;const from=item.fromVersions?.join("|")??"";const to=item.toVersions?.join("|")??"";if(from&&to&&from!==to)return`${name} ${from} -> ${to}`;if(to)return`${name}@${to}`;if(from)return`${name}@${from}`;return name}var packageSchema=z7.object({registry:z7.string().describe(`Package registry. Supported: ${PKGSEER_REGISTRY_LIST2}.`),package_name:z7.string().describe("Package name, scoped names ok."),current_version:z7.string().describe("Currently used package version. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift."),target_version:z7.string().describe("Target package version. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift.")});var schema7={registry:z7.string().optional().describe(`Package registry for single-package mode. Supported: ${PKGSEER_REGISTRY_LIST2}.`),package_name:z7.string().optional().describe("Package name for single-package mode."),current_version:z7.string().optional().describe("Currently used version for single-package mode. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift."),target_version:z7.string().optional().describe("Target version for single-package mode. Go accepts versions with or without its canonical v prefix; tag-style v prefixes are rejected for other registries except Swift."),packages:z7.array(packageSchema).optional().describe(`Batch mode with at most ${PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES} upgrades after blank rows are removed. Mutually exclusive with single-package fields.`),skip_transitive_security:z7.boolean().optional().describe("When true, skip current-vs-target transitive vulnerability summary diffs. Defaults false, so transitive security evidence is included unless explicitly skipped."),include_dependency_issues:z7.boolean().optional().describe("When true, diff current vs target transitive deprecated/outdated/duplicate/conflict summaries. Defaults false."),min_severity:z7.string().optional().describe("Minimum direct-advisory severity: low, medium, high, or critical."),changes:z7.string().optional().describe("Filter detailed statement quotes only: actionable (MUST_ACT), important (MUST_ACT + SHOULD_KNOW), or all parsed units, including no-impact and unassessed. Omit or pass blank to use focused (MUST_ACT + SHOULD_KNOW + too-long-to-classify (oversize) statements). Whole-range counters and batch ranking do not change."),verbose:z7.boolean().optional().describe("Text output only. Batches default to triage rows; verbose adds full per-package reports, expands statement quotes up to backend bounds, and expands dependency change examples."),format:z7.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text.")};var DESCRIPTION7="Review a package upgrade: vulnerabilities, releases, peers, dependency changes. "+"Compares current and target versions using direct vulnerability checks, changelog ranges, target deprecation metadata, peer dependency changes, and optional transitive evidence diffs. "+"The tool reports facts only, including agent-classified release-note statements in backend source order, with nearby authoritative URLs and assessment coverage. JSON includes complete selected statement pages, source positions and context, and classifier provenance. It does not assign package-level risk or decide whether to accept an upgrade. Batches default to triage rows; use verbose for full per-package evidence. "+"Use this instead of inferring acceptability from semver, including patch bumps. "+"Use signals as a starting point to evaluate the impact of changes on the codebase. "+"You can use pkg_changelog and code_diff to obtain full release-note and source-change details. "+"Accepts either one package via registry/package_name/current_version/"+`target_version or batch \`packages[]\` with at most ${PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES} upgrades.`+`
175
175
 
176
176
  ${PKG_UPGRADE_REVIEW_GUARDRAIL}`;function createPackageUpgradeReviewTool(service){return{name:"pkg_upgrade_review",description:DESCRIPTION7,schema:schema7,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const request=buildPackageUpgradeReviewRequest({registry:args.registry,packageName:args.package_name,currentVersion:args.current_version,targetVersion:args.target_version,packages:args.packages?.map((pkg)=>({registry:pkg.registry,packageName:pkg.package_name,currentVersion:pkg.current_version,targetVersion:pkg.target_version})),includeTransitiveSecurity:args.skip_transitive_security!==true,includeDependencyIssues:args.include_dependency_issues,minSeverity:args.min_severity,changes:args.changes,format:args.format,verbose:args.verbose===true});const response=await buildPackageUpgradeReview(service,request.packages,request.options,context?.signal);if(args.format==="json")return textResult(JSON.stringify(response));return textResult(formatPackageUpgradeReviewTerminal(response,{surface:"mcp",verbose:args.verbose===true}).trimEnd())}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_upgrade_review",args}})}}}}import{z as z8}from"zod";var DEFAULT_ADVISORY_CAP=5;function buildPackageVulnerabilitiesSuccessPayload(report,options={}){const pkg=report.package;const security=report.security;const dedupedAdvisories=dedupAdvisoriesByAlias(security?.vulnerabilities??[]);const total=security?.affectedVulnerabilityCount??dedupedAdvisories.length;const payload={registry:lowerRegistry3(pkg.registry),name:pkg.name,version:pkg.version,summary:buildSummary(total,security,dedupedAdvisories)};if(pkg.registryRepository)payload.registryRepository=pkg.registryRepository;const requestedEcho=deriveRequestedVersion2(options.requestedVersion,pkg.version);if(requestedEcho!==undefined){payload.requestedVersion=requestedEcho}if(options.filter!==undefined){payload.filter=options.filter}const sortedAdvisories=sortAdvisories(dedupedAdvisories.map(buildAdvisory));if(sortedAdvisories.length>0){payload.advisories=sortedAdvisories}const upgradePaths=security?.upgradePaths;if(upgradePaths&&upgradePaths.length>0){const unique=Array.from(new Set(upgradePaths));unique.sort(compareVersionsAscending);payload.upgradePaths=unique}if(report.transitive!==undefined){payload.transitive=buildTransitiveAudit(report.transitive)}return payload}function compareVersionsAscending(a,b){const pa=parseVersionForSort(a);const pb=parseVersionForSort(b);const len=Math.max(pa.main.length,pb.main.length);for(let i=0;i<len;i++){const diff=(pa.main[i]??0)-(pb.main[i]??0);if(diff!==0)return diff}if(pa.pre===undefined&&pb.pre===undefined)return 0;if(pa.pre===undefined)return 1;if(pb.pre===undefined)return-1;return pa.pre<pb.pre?-1:pa.pre>pb.pre?1:0}function parseVersionForSort(v){const[rawMainStr,...preParts]=v.split("-");const pre=preParts.length>0?preParts.join("-"):undefined;const mainStr=rawMainStr?.replace(/^v(?=\d)/i,"");const main=(mainStr??"").split(".").map((segment)=>{const n=Number.parseInt(segment,10);return Number.isFinite(n)?n:0});return{main,pre}}function buildSummary(total,security,dedupedAdvisories){const summary={total};if(security){summary.affectedVulnerabilityCount=security.affectedVulnerabilityCount;summary.nonAffectingVulnerabilityCount=security.nonAffectingVulnerabilityCount;summary.allVulnerabilityCount=security.allVulnerabilityCount;summary.unknownVulnerabilityCount=security.unknownVulnerabilityCount;summary.assessmentStatus=security.assessmentStatus}if(typeof security?.currentVersionAffected==="boolean"){summary.affected=security.currentVersionAffected}if(dedupedAdvisories.length===0)return summary;const bySeverity=computeBySeverity(dedupedAdvisories);const anyCounted=Object.values(bySeverity).some((n)=>n>0);if(anyCounted){const trimmed={};for(const key of BUCKET_ORDER){const n=bySeverity[key];if(n>0)trimmed[key]=n}summary.bySeverity=trimmed}return summary}function buildTransitiveAudit(audit){const packages=audit.packages.map((pkg)=>({registry:lowerRegistry3(pkg.registry),name:pkg.name,occurrenceCount:pkg.occurrenceCount,...audit.advisoryScope!=="ALL"&&audit.advisoryScope!=="AFFECTED"&&pkg.affectedCount>0?{affectedCount:pkg.affectedCount}:{},...audit.advisoryScope!=="ALL"&&audit.advisoryScope!=="NON_AFFECTING"&&pkg.nonAffectingCount>0?{nonAffectingCount:pkg.nonAffectingCount}:{},...audit.advisoryScope!=="ALL"&&audit.advisoryScope!=="UNKNOWN"&&pkg.unknownCount>0?{unknownCount:pkg.unknownCount}:{},occurrences:pkg.occurrences.map(buildTransitiveOccurrence).sort(compareTransitiveOccurrences)})).sort(compareTransitivePackages);const occurrences=packages.flatMap((pkg)=>pkg.occurrences);const bySeverity=computeTransitiveBySeverity(occurrences);const hasCountedSeverity=Object.values(bySeverity).some((count)=>count>0);return{scope:"resolved_dependencies",advisoryScope:toAdvisoryScopeLabel(audit.advisoryScope),withdrawnAdvisoriesIncluded:false,summary:{totalPackagesAnalyzed:audit.totalPackagesAnalyzed,packageCount:audit.packageCount,occurrenceCount:audit.occurrenceCount,affectedCount:audit.affectedCount,nonAffectingCount:audit.nonAffectingCount,unknownCount:audit.unknownCount,totalCount:audit.totalCount,...hasCountedSeverity?{bySeverity:trimSeverityBuckets(bySeverity)}:{}},...audit.calculatedAt!==undefined?{calculatedAt:audit.calculatedAt}:{},packages}}function buildTransitiveOccurrence(occurrence){const advisory=occurrence.advisory;const publishedAt=toIsoDate(advisory.publishedAt);const modifiedAt=toIsoDate(advisory.modifiedAt);const lean={resolvedVersion:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges.slice(),fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved.slice()};if(!isAssessmentStatusImplied(occurrence.assessmentStatus,occurrence.affectsResolvedVersion))lean.assessmentStatus=occurrence.assessmentStatus;if(occurrence.assessmentReasons?.length)lean.assessmentReasons=occurrence.assessmentReasons.slice();if(advisory.osvId)lean.id=advisory.osvId;if(advisory.aliases&&advisory.aliases.length>0){lean.aliases=advisory.aliases.slice()}if(advisory.summary&&!isPlaceholderSummary(advisory.summary)){lean.summary=advisory.summary}if(typeof advisory.severityScore==="number"&&advisory.severityScore>0){lean.severity=advisory.severityScore;const severityLabel=vulnSeverityLabel(advisory.severityScore);if(severityLabel!==undefined)lean.severityLabel=severityLabel}if(advisory.affectedVersionRanges&&advisory.affectedVersionRanges.length>0){lean.affectedRanges=advisory.affectedVersionRanges.slice()}if(advisory.fixedInVersions&&advisory.fixedInVersions.length>0){lean.fixedIn=advisory.fixedInVersions.slice()}if(occurrence.nearestFixedVersion){lean.nearestFixedVersion=occurrence.nearestFixedVersion}if(publishedAt)lean.publishedAt=publishedAt;if(modifiedAt&&modifiedAt!==publishedAt)lean.modifiedAt=modifiedAt;if(advisory.isMalicious===true)lean.isMalicious=true;return lean}function toAdvisoryScopeLabel(scope){if(scope==="NON_AFFECTING")return"non_affecting";if(scope==="UNKNOWN")return"unknown";return scope==="ALL"?"all":"affected"}function computeTransitiveBySeverity(occurrences){const histogram={malware:0,critical:0,high:0,medium:0,low:0,unrated:0};for(const occurrence of occurrences){if(occurrence.isMalicious===true){histogram.malware+=1;continue}if(occurrence.severityLabel!==undefined){histogram[occurrence.severityLabel]+=1}else{histogram.unrated+=1}}return histogram}function trimSeverityBuckets(histogram){const trimmed={};for(const key of BUCKET_ORDER){if(histogram[key]>0)trimmed[key]=histogram[key]}return trimmed}function compareTransitivePackages(a,b){const registry=compareStrings(a.registry,b.registry);return registry!==0?registry:compareStrings(a.name,b.name)}function compareTransitiveOccurrences(a,b){const risk=transitiveRiskRank(b)-transitiveRiskRank(a);if(risk!==0)return risk;const version=compareStrings(a.resolvedVersion,b.resolvedVersion);if(version!==0)return version;const identity=compareStrings(transitiveAdvisoryIdentity(a),transitiveAdvisoryIdentity(b));if(identity!==0)return identity;const aliases=compareStrings((a.aliases??[]).join("\x00"),(b.aliases??[]).join("\x00"));if(aliases!==0)return aliases;return compareStrings(JSON.stringify(a),JSON.stringify(b))}function transitiveAdvisoryIdentity(occurrence){return occurrence.id??occurrence.aliases?.[0]??occurrence.summary??""}function transitiveRiskRank(occurrence){const severityRank=occurrence.severityLabel?SEVERITY_RANK[occurrence.severityLabel]:0;return(occurrence.isMalicious===true?100:0)+severityRank}function compareStrings(a,b){return a<b?-1:a>b?1:0}function computeBySeverity(advisories){const histogram={malware:0,critical:0,high:0,medium:0,low:0,unrated:0};for(const advisory of advisories){if(advisory.isMalicious===true){histogram.malware+=1;continue}const label=vulnSeverityLabel(advisory.severityScore);if(label!==undefined){histogram[label]+=1}else{histogram.unrated+=1}}return histogram}var BUCKET_ORDER=["malware","critical","high","medium","low","unrated"];function vulnSeverityLabel(score){if(typeof score!=="number"||score<=0)return;if(score>=9)return"critical";if(score>=7)return"high";if(score>=4)return"medium";return"low"}function dedupAdvisoriesByAlias(advisories){if(advisories.length===0)return[];const parent=new Map;const find=(id)=>{let root=id;let next=parent.get(root);while(next!==undefined&&next!==root){root=next;next=parent.get(root)}let cursor=id;while(cursor!==root){const parentOfCursor=parent.get(cursor);if(parentOfCursor===undefined)break;parent.set(cursor,root);cursor=parentOfCursor}return root};const union=(a,b)=>{const ra=find(a);const rb=find(b);if(ra!==rb)parent.set(ra,rb)};const ensure=(id)=>{if(!parent.has(id))parent.set(id,id)};const advisoryKeys=[];for(let i=0;i<advisories.length;i++){const advisory=advisories[i];if(!advisory){advisoryKeys.push(`__synthetic_${i}`);continue}const ids=[];if(advisory.osvId)ids.push(advisory.osvId);for(const alias of advisory.aliases??[]){if(alias)ids.push(alias)}if(ids.length===0){const synthetic=`__synthetic_${i}`;ensure(synthetic);advisoryKeys.push(synthetic);continue}for(const id of ids)ensure(id);for(let j=1;j<ids.length;j++){const a=ids[j-1];const b=ids[j];if(a!==undefined&&b!==undefined)union(a,b)}advisoryKeys.push(ids[0])}const clusters=new Map;for(let i=0;i<advisories.length;i++){const advisory=advisories[i];if(!advisory)continue;const key=advisoryKeys[i];if(key===undefined)continue;const root=find(key);const bucket=clusters.get(root);if(bucket)bucket.push(advisory);else clusters.set(root,[advisory])}const merged=[];for(const cluster of clusters.values()){merged.push(mergeAdvisoryCluster(cluster))}return merged}function mergeAdvisoryCluster(cluster){if(cluster.length===1){const only=cluster[0];if(!only)throw new Error("empty advisory cluster");return only}const canonical=pickCanonical(cluster);const aliasSet=new Set;for(const member of cluster){if(member.osvId)aliasSet.add(member.osvId);for(const alias of member.aliases??[]){if(alias)aliasSet.add(alias)}}if(canonical.osvId)aliasSet.delete(canonical.osvId);const aliases=Array.from(aliasSet).sort();const affectedRangesSet=new Set;const matchedAffectedRangesSet=new Set;const fixedInSet=new Set;const duplicateIdsSet=new Set;const assessmentReasons=new Set;let isMalicious=false;let affectsInspectedVersion=false;const assessmentPrecedence={AFFECTED:3,UNKNOWN:2,NON_AFFECTING:1};let assessmentStatus=canonical.assessmentStatus;let affectedVersionRangesTruncated=false;let affectedVersionRangesCount=0;let latestModifiedAt=canonical.modifiedAt;let withdrawnAt;let allWithdrawn=true;let maxSeverityScore=typeof canonical.severityScore==="number"?canonical.severityScore:0;for(const member of cluster){if(member.assessmentStatus!==undefined&&(assessmentStatus===undefined||(assessmentPrecedence[member.assessmentStatus]??2)>(assessmentPrecedence[assessmentStatus]??2)))assessmentStatus=member.assessmentStatus;for(const reason of member.assessmentReasons??[])assessmentReasons.add(reason);for(const range of member.affectedVersionRanges??[]){affectedRangesSet.add(range)}for(const range of member.matchedAffectedVersionRanges??[]){matchedAffectedRangesSet.add(range)}for(const fix of member.fixedInVersions??[]){fixedInSet.add(fix)}for(const duplicateId of member.duplicateIds??[]){duplicateIdsSet.add(duplicateId)}if(member.isMalicious===true)isMalicious=true;if(member.affectsInspectedVersion===true)affectsInspectedVersion=true;if(member.affectedVersionRangesTruncated===true){affectedVersionRangesTruncated=true}if(typeof member.affectedVersionRangesCount==="number"){affectedVersionRangesCount=Math.max(affectedVersionRangesCount,member.affectedVersionRangesCount)}if(member.modifiedAt){if(!latestModifiedAt||member.modifiedAt>latestModifiedAt){latestModifiedAt=member.modifiedAt}}if(member.withdrawnAt){if(!withdrawnAt||member.withdrawnAt>withdrawnAt){withdrawnAt=member.withdrawnAt}}else{allWithdrawn=false}if(!member.withdrawnAt&&typeof member.severityScore==="number"&&member.severityScore>maxSeverityScore){maxSeverityScore=member.severityScore}}const merged={...canonical,aliases};if(maxSeverityScore>0){merged.severityScore=maxSeverityScore}if(affectedRangesSet.size>0){merged.affectedVersionRanges=Array.from(affectedRangesSet)}const exactOrLowerBoundCount=Math.max(affectedVersionRangesCount,affectedRangesSet.size);if(exactOrLowerBoundCount>0){merged.affectedVersionRangesCount=exactOrLowerBoundCount}if(affectedVersionRangesTruncated){merged.affectedVersionRangesTruncated=true}if(matchedAffectedRangesSet.size>0){merged.matchedAffectedVersionRanges=Array.from(matchedAffectedRangesSet)}if(affectsInspectedVersion)merged.affectsInspectedVersion=true;if(assessmentStatus!==undefined)merged.assessmentStatus=assessmentStatus;if(assessmentReasons.size>0)merged.assessmentReasons=[...assessmentReasons];if(duplicateIdsSet.size>0){merged.duplicateIds=Array.from(duplicateIdsSet).sort()}if(fixedInSet.size>0){merged.fixedInVersions=Array.from(fixedInSet)}if(isMalicious)merged.isMalicious=true;if(latestModifiedAt){merged.modifiedAt=latestModifiedAt}else{delete merged.modifiedAt}if(allWithdrawn&&withdrawnAt){merged.withdrawnAt=withdrawnAt}else{delete merged.withdrawnAt}return merged}function pickCanonical(cluster){const ranked=cluster.slice().sort((a,b)=>{const aHasScore=typeof a.severityScore==="number"&&a.severityScore>0?1:0;const bHasScore=typeof b.severityScore==="number"&&b.severityScore>0?1:0;if(aHasScore!==bHasScore)return bHasScore-aHasScore;const aRank=idPrefixRank(a.osvId);const bRank=idPrefixRank(b.osvId);if(aRank!==bRank)return aRank-bRank;const aId=a.osvId??"";const bId=b.osvId??"";if(aId!==bId)return aId<bId?-1:1;return 0});const winner=ranked[0];if(!winner)throw new Error("empty cluster passed to pickCanonical");return winner}function idPrefixRank(id){if(!id)return 99;if(id.startsWith("GHSA-"))return 0;if(id.startsWith("RUSTSEC-"))return 2;return 1}function buildAdvisory(advisory){const lean={};if(advisory.osvId)lean.id=advisory.osvId;if(advisory.aliases&&advisory.aliases.length>0){lean.aliases=advisory.aliases.slice()}if(advisory.summary&&!isPlaceholderSummary(advisory.summary)){lean.summary=advisory.summary}if(typeof advisory.severityScore==="number"&&advisory.severityScore>0){lean.severity=advisory.severityScore;const label=vulnSeverityLabel(advisory.severityScore);if(label!==undefined)lean.severityLabel=label}if(advisory.affectedVersionRanges&&advisory.affectedVersionRanges.length>0){lean.affectedRanges=advisory.affectedVersionRanges.slice()}if(typeof advisory.affectedVersionRangesCount==="number"){lean.affectedVersionRangesCount=advisory.affectedVersionRangesCount}if(advisory.affectedVersionRangesTruncated===true){lean.affectedVersionRangesTruncated=true}if(!isAssessmentStatusImplied(advisory.assessmentStatus,advisory.affectsInspectedVersion))lean.assessmentStatus=advisory.assessmentStatus;if(advisory.assessmentReasons?.length)lean.assessmentReasons=advisory.assessmentReasons.slice();if(typeof advisory.affectsInspectedVersion==="boolean"){lean.affectsInspectedVersion=advisory.affectsInspectedVersion}if(advisory.matchedAffectedVersionRanges&&advisory.matchedAffectedVersionRanges.length>0){lean.matchedAffectedVersionRanges=advisory.matchedAffectedVersionRanges.slice()}if(advisory.duplicateIds&&advisory.duplicateIds.length>0){lean.duplicateIds=advisory.duplicateIds.slice()}if(advisory.fixedInVersions&&advisory.fixedInVersions.length>0){lean.fixedIn=advisory.fixedInVersions.slice()}const publishedAt=toIsoDate(advisory.publishedAt);if(publishedAt)lean.publishedAt=publishedAt;const modifiedAt=toIsoDate(advisory.modifiedAt);if(modifiedAt&&modifiedAt!==publishedAt){lean.modifiedAt=modifiedAt}const withdrawnAt=toIsoDate(advisory.withdrawnAt);if(withdrawnAt)lean.withdrawnAt=withdrawnAt;if(advisory.isMalicious===true){lean.isMalicious=true}return lean}var SEVERITY_RANK={critical:4,high:3,medium:2,low:1};function sortAdvisories(advisories){return advisories.slice().sort(compareAdvisories)}function compareAdvisories(a,b){const aWithdrawn=a.withdrawnAt!==undefined;const bWithdrawn=b.withdrawnAt!==undefined;if(aWithdrawn!==bWithdrawn)return aWithdrawn?1:-1;const aMalware=a.isMalicious===true;const bMalware=b.isMalicious===true;if(aMalware!==bMalware)return aMalware?-1:1;const aRank=a.severityLabel?SEVERITY_RANK[a.severityLabel]:0;const bRank=b.severityLabel?SEVERITY_RANK[b.severityLabel]:0;if(aRank!==bRank)return bRank-aRank;const aDate=a.publishedAt??"";const bDate=b.publishedAt??"";if(aDate!==bDate)return aDate<bDate?1:-1;const aId=a.id??"";const bId=b.id??"";if(aId!==bId)return aId<bId?-1:1;return 0}function deriveRequestedVersion2(requested,resolved){if(requested===undefined)return;const trimmed=requested.trim();if(trimmed.length===0)return;if(trimmed===resolved)return;return trimmed}function lowerRegistry3(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function formatPackageVulnerabilitiesTerminal(report,options={}){const payload=buildPackageVulnerabilitiesSuccessPayload(report,{requestedVersion:options.requestedVersion,filter:options.filter});const useColors=options.useColors??false;const verbose=options.verbose??false;const surface=options.surface??"cli";const headerLine=formatHeader(payload,useColors);const requestedLine=payload.requestedVersion?dim(`(requested ${sanitizeIdentity(payload.requestedVersion)})`,useColors):undefined;const filterLines=formatFilterLines(payload.filter);const transitiveBlock=payload.transitive&&report.transitive?formatTransitiveAuditTerminal(payload.transitive,report.transitive,{verbose,useColors,surface,terminalWidth:options.terminalWidth,includeWithdrawn:payload.filter?.includeWithdrawn===true}):undefined;if(payload.summary.total===0){const lines=[headerLine];if(requestedLine)lines.push(requestedLine);lines.push(...filterLines);lines.push(formatNoAffectedVulnerabilitiesLine(payload));lines.push(...formatAssessmentLines(payload,surface,options.terminalWidth));if(payload.advisories&&payload.advisories.length>0){const rangeLimit=resolveAffectedRangesLimit(options.terminalWidth);lines.push("",formatAdvisoryList(payload.advisories,verbose,useColors,rangeLimit,surface,options.terminalWidth))}if(transitiveBlock)lines.push("",transitiveBlock);return`${lines.join(`
177
177
  `)}
@@ -182,7 +182,7 @@ ${PKG_UPGRADE_REVIEW_GUARDRAIL}`;function createPackageUpgradeReviewTool(service
182
182
  `}function formatHeader(payload,useColors){const name=colorize(sanitizeIdentity(payload.name),"bold",useColors);return`${name} @ ${sanitizeIdentity(payload.version)} | ${sanitizeIdentity(payload.registry)}`}function formatFilterLines(filter){if(!filter)return[];const lines=[];if(filter.advisoryScope){lines.push(`Scope ${sanitizeIdentity(formatAdvisoryScope(filter.advisoryScope))}`)}if(filter.minSeverity){lines.push(`Filter severity >= ${sanitizeIdentity(filter.minSeverity)}`)}if(filter.includeWithdrawn===true){lines.push("Filter include withdrawn")}return lines}function formatAdvisoryScope(scope){if(scope==="non_affecting")return"non-affecting advisories only";if(scope==="all")return"all package advisories";return scope}function formatSummaryLine(payload,useColors){const n=payload.summary.total;const noun=n===1?"vulnerability":"vulnerabilities";const verb=n===1?"affects":"affect";const base=`${n} ${noun} ${verb} this version`;if(payload.summary.affected===true){return colorize(base,"yellow",useColors)}if(payload.summary.affected===false){return base}return base}function formatAssessmentLines(payload,surface,terminalWidth){const summary=payload.summary;return formatAssessmentHintLines({affectedCount:summary.total,nonAffectingCount:summary.nonAffectingVulnerabilityCount,unknownCount:summary.unknownVulnerabilityCount,totalCount:summary.allVulnerabilityCount,assessmentStatus:summary.assessmentStatus},payload.filter?.advisoryScope??"affected",surface,normaliseTerminalWidth2(terminalWidth))}function formatAssessmentHintLines(counts,scope,surface,width){const unknown=counts.unknownCount??0;const uncertainty=formatAssessmentUncertainty(counts.assessmentStatus,counts.affectedCount>0);if(unknown===0&&uncertainty===undefined)return[];const parts=[];if(counts.nonAffectingCount!==undefined)parts.push(`${counts.nonAffectingCount} non-affecting`);if(counts.unknownCount!==undefined)parts.push(`${counts.unknownCount} unknown`);if(counts.totalCount!==undefined)parts.push(`${counts.totalCount} all`);const explanations=[];if(unknown>0){const action=surface==="mcp"?'advisory_scope="unknown"':"--scope unknown";explanations.push(scope==="unknown"?"unknown = not evaluable; reasons below":`unknown = not evaluable, list with ${action}`)}if(uncertainty!==undefined&&!(unknown>0&&counts.assessmentStatus==="UNKNOWN"))explanations.push(sanitizeProse(uncertainty));return wrapFreeText([parts.join(" | "),...explanations].filter(Boolean).join("; "),width)}function formatNoAffectedVulnerabilitiesLine(payload){const selectedAdvisoryCount=payload.advisories?.length??0;if((payload.summary.unknownVulnerabilityCount??0)>0||!isAssessmentStatusImplied(payload.summary.assessmentStatus,false)){return"No confirmed vulnerabilities affect this version."}if(payload.filter?.advisoryScope==="non_affecting"){if(selectedAdvisoryCount>0){return"No active vulnerabilities affect this version; non-affecting advisories are listed below."}return"No active vulnerabilities affect this version; no non-affecting advisories match the current filter."}if(payload.filter?.advisoryScope==="all"){if(selectedAdvisoryCount>0){return"No active vulnerabilities affect this version; package advisories are listed below."}return"No active vulnerabilities affect this version; no package advisories match the current filter."}if(payload.filter!==undefined){return"No vulnerabilities matching the filter affect this version."}const nonAffecting=payload.summary.nonAffectingVulnerabilityCount??0;if(nonAffecting>0){const noun=nonAffecting===1?"advisory":"advisories";const verb=nonAffecting===1?"does":"do";return`No active vulnerabilities affect this version (${nonAffecting} ${noun} ${verb} not apply).`}return"No active vulnerabilities affect this version."}function formatSelectedAdvisoryCountLine(count,scope){if(scope===undefined)return;const noun=count===1?"advisory":"advisories";if(scope==="non_affecting"){return` showing ${count} non-affecting ${noun}`}if(scope==="all"){return` showing ${count} package ${noun} across affected, non-affecting and unknown scopes`}return}function formatBreakdownLine(summary,useColors,terminalWidth){if(summary.total<=1)return;const bucket=summary.bySeverity;if(!bucket)return;const labels={malware:"MALWARE",critical:"crit",high:"high",medium:"medium",low:"low",unrated:"unrated"};const parts=[];for(const key of BUCKET_ORDER){const count=bucket[key];if(typeof count==="number"&&count>0){const segment=`${count} ${labels[key]}`;parts.push({text:segment,color:key==="malware"?"red":undefined})}}if(parts.length===0)return;return formatBreakdownParts(parts,useColors,terminalWidth)}function formatBreakdownParts(parts,useColors,terminalWidth2){const width=normaliseTerminalWidth2(terminalWidth2);const lines=[];let current=[];for(const part of parts){const candidate=[...current,part].map(({text})=>text).join(" | ");if(current.length===0||terminalWidth(` ${candidate}`)<=width){current.push(part)}else{lines.push(current);current=[part]}}if(current.length>0)lines.push(current);return lines.map((line)=>` ${line.map(({text,color})=>color?colorize(text,color,useColors):text).join(" | ")}`).join(`
183
183
  `)}function formatAdvisoryList(advisories,verbose,useColors,rangeLimit,surface,terminalWidth){const renderedAdvisories=verbose||surface==="cli"?advisories:advisories.slice(0,DEFAULT_ADVISORY_CAP);const labelWidth=Math.max(...renderedAdvisories.map((a)=>severityColumnLabel(a).length));const lines=[];for(const advisory of renderedAdvisories){lines.push(...formatAdvisoryLines(advisory,labelWidth,verbose,useColors,rangeLimit,surface));lines.push("")}const hidden=advisories.length-renderedAdvisories.length;if(hidden>0){lines.push(...wrapFreeText(formatAdvisoryCapHint(hidden,surface),normaliseTerminalWidth2(terminalWidth)).map((line)=>dim(line,useColors)))}return lines.join(`
184
184
  `).trimEnd()}function formatAdvisoryCapHint(hidden,surface){const hint=surface==="mcp"?"use verbose=true or format=json":"use -v";return`... (+${hidden} more; ${hint})`}function severityColumnLabel(advisory){if(advisory.isMalicious===true){if(advisory.severityLabel)return`MALWARE | ${advisory.severityLabel}`;return"MALWARE"}return advisory.severityLabel??"unrated"}function isPlaceholderSummary(summary){return/^\s*no summary available\s*$/i.test(summary)}function severityColumnColor(advisory,useColors,padded){if(!useColors)return padded;if(advisory.withdrawnAt!==undefined)return dim(padded,useColors);if(advisory.isMalicious===true){return`${colorize(padded,"red",useColors)}`}switch(advisory.severityLabel){case"critical":return colorize(padded,"red",useColors);case"high":return colorize(padded,"yellow",useColors);case"medium":return colorize(padded,"yellow",useColors);case"low":return dim(padded,useColors);default:return dim(padded,useColors)}}function formatAdvisoryLines(advisory,labelWidth,verbose,useColors,rangeLimit,surface){const rawLabel=severityColumnLabel(advisory);const padded=rawLabel.padEnd(labelWidth);const colouredLabel=severityColumnColor(advisory,useColors,padded);const parts=[colouredLabel];if(advisory.id)parts.push(sanitizeIdentity(advisory.id));const assessment=formatAdvisoryAssessment(advisory.assessmentStatus,advisory.affectsInspectedVersion);if(assessment!==undefined)parts.push(`[${sanitizeIdentity(assessment)}]`);if(advisory.publishedAt)parts.push(sanitizeIdentity(advisory.publishedAt));if(advisory.summary)parts.push(sanitizeProse(advisory.summary));const lines=[` ${parts.join(" ")}`];const detailWidth=verbose?12:8;const pushRow=(label,value)=>{lines.push(` ${label.padEnd(detailWidth)} ${value}`)};if(advisory.assessmentReasons?.length&&formatAdvisoryAssessment(advisory.assessmentStatus,advisory.affectsInspectedVersion)!=="affects this version"){pushRow("reason",advisory.assessmentReasons.map(formatVulnerabilityAssessmentReason).map(sanitizeProse).join("; "))}if(advisory.affectedRanges&&advisory.affectedRanges.length>0){pushRow("affected",formatRangeList(advisory.affectedRanges.map((range)=>range.startsWith("osv-invalid:")?"(unevaluable source range)":range),verbose,useColors,rangeLimit,surface,advisory.affectedVersionRangesCount,advisory.affectedVersionRangesTruncated))}if(advisory.fixedIn&&advisory.fixedIn.length>0){pushRow("fixed in",advisory.fixedIn.map(sanitizeIdentity).join(", "))}if(verbose){if(advisory.aliases&&advisory.aliases.length>0){pushRow("aliases",advisory.aliases.map(sanitizeIdentity).join(", "))}if(typeof advisory.severity==="number"){pushRow("severity",`${advisory.severity} (CVSS)`)}if(advisory.publishedAt){pushRow("published",sanitizeIdentity(advisory.publishedAt))}if(advisory.modifiedAt){pushRow("modified",sanitizeIdentity(advisory.modifiedAt))}if(advisory.withdrawnAt){pushRow("withdrawn",sanitizeIdentity(advisory.withdrawnAt))}if(advisory.isMalicious===true){pushRow("malicious","yes")}}return lines}function formatRangeList(ranges,verbose,useColors,limit,surface,totalCount,backendTruncated){const safeRanges=ranges.map(sanitizeIdentity);const actualTotal=Math.max(totalCount??safeRanges.length,safeRanges.length);const backendHidden=backendTruncated===true?actualTotal-safeRanges.length:0;const appendBackendHint=(shown)=>{if(backendHidden>0){const hint=dim(`... (+${backendHidden} ranges omitted by service)`,useColors);return shown.length>0?`${shown}, ${hint}`:hint}return shown};if(verbose||safeRanges.length<=limit){return appendBackendHint(safeRanges.join(", "))}const shown=safeRanges.slice(0,limit).join(", ");const localHidden=safeRanges.length-limit;const localHint=surface==="mcp"?"use verbose=true":"use -v";const hintText=backendHidden>0?`... (+${localHidden} more with ${localHint}; +${backendHidden} omitted by service)`:`... (+${localHidden} more; ${localHint})`;const hint=dim(hintText,useColors);return`${shown}, ${hint}`}function sanitizeIdentity(value){return sanitizeTerminalText(value)}function sanitizeProse(value){return sanitizeTerminalText(value.replace(/\s+/g," ")).replace(/\s+/g," ").trim()}function formatTransitiveAuditTerminal(audit,fullAudit,options){const width=normaliseTerminalWidth2(options.terminalWidth);const lines=["Resolved dependencies"];lines.push(...wrapFreeText(formatTransitiveSummaryLine(audit),width));const breakdown=formatTransitiveBreakdown(audit.summary,options.useColors,width);if(breakdown)lines.push(breakdown);if(audit.advisoryScope!=="all")lines.push(...formatAssessmentHintLines(audit.summary,audit.advisoryScope,options.surface,width));if(audit.advisoryScope==="affected"||audit.advisoryScope==="non_affecting"){const mixedRegistries=new Set(fullAudit.packages.map((pkg)=>lowerRegistry3(pkg.registry))).size>1;for(const pkg of[...fullAudit.packages].sort(compareTransitivePackages)){if(pkg.unknownCount>0){const identity=mixedRegistries?`${lowerRegistry3(pkg.registry)}:${pkg.name}`:pkg.name;lines.push(...wrapFreeText(`${sanitizeIdentity(identity)}: ${formatTransitiveCounts(pkg)}`,width-2," ").map((line)=>` ${line}`))}}}if(options.includeWithdrawn){lines.push(...wrapFreeText("Dependency analysis excludes withdrawn advisories.",width," "))}const rows=flattenTransitiveRows(audit);if(rows.length>0){lines.push("",...formatTransitiveRows(rows,options))}return lines.join(`
185
- `)}function formatTransitiveSummaryLine(audit){const summary=audit.summary;const scopeLabel=audit.advisoryScope==="unknown"?"unknown":audit.advisoryScope==="affected"?"affected":"non-affecting";const occurrenceNoun=`${scopeLabel} advisory ${summary.occurrenceCount===1?"occurrence":"occurrences"}`;const packageNoun=summary.packageCount===1?"dependency package":"dependency packages";const versionNoun=summary.totalPackagesAnalyzed===1?"resolved package version":"resolved package versions";if(summary.occurrenceCount===0){if(audit.advisoryScope==="all")return`No advisory occurrences found. ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`;return`No ${scopeLabel} advisory occurrences found; ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`}if(audit.advisoryScope==="all"){const unknownText=summary.unknownCount>0?`, ${summary.unknownCount} unknown`:"";const noun=summary.occurrenceCount===1?"occurrence":"occurrences";return`${summary.occurrenceCount} advisory ${noun} (${summary.affectedCount} affected, ${summary.nonAffectingCount} non-affecting${unknownText}) in ${summary.packageCount} ${packageNoun}; ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`}return`${summary.occurrenceCount} ${occurrenceNoun} in ${summary.packageCount} ${packageNoun}; ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`}function formatTransitiveCounts(counts){return`${counts.affectedCount} affected | ${counts.nonAffectingCount} non-affecting | ${counts.unknownCount} unknown | ${counts.totalCount} all`}var TRANSITIVE_ROW_MARGIN=" ";var TRANSITIVE_COLUMN_SEPARATOR=" ";var TRANSITIVE_SEVERITY_LABEL_WIDTH="critical".length;var TRANSITIVE_COORDINATE_INDENT=TRANSITIVE_ROW_MARGIN.length+TRANSITIVE_SEVERITY_LABEL_WIDTH+TRANSITIVE_COLUMN_SEPARATOR.length;var TRANSITIVE_DETAIL_LABEL_WIDTH="advisory ranges".length;var TRANSITIVE_COORDINATE_PREFIX=" ".repeat(TRANSITIVE_COORDINATE_INDENT);function formatTransitiveBreakdown(summary,useColors,terminalWidth){if(!summary.bySeverity)return;const labels={malware:"MALWARE",critical:"critical",high:"high",medium:"medium",low:"low",unrated:"unrated"};const parts=[];for(const key of BUCKET_ORDER){const count=summary.bySeverity[key];if(typeof count==="number"&&count>0){const part=`${count} ${labels[key]}`;parts.push({text:part,color:key==="malware"?"red":undefined})}}return parts.length>0?formatBreakdownParts(parts,useColors,terminalWidth):undefined}function flattenTransitiveRows(audit){return audit.packages.flatMap((pkg)=>pkg.occurrences.map((occurrence)=>({registry:pkg.registry,name:pkg.name,occurrence}))).sort(compareTransitiveTextRows)}function compareTransitiveTextRows(a,b){const risk=transitiveRiskRank(b.occurrence)-transitiveRiskRank(a.occurrence);if(risk!==0)return risk;const registry=compareStrings(a.registry,b.registry);if(registry!==0)return registry;const name=compareStrings(a.name,b.name);if(name!==0)return name;const version=compareStrings(a.occurrence.resolvedVersion,b.occurrence.resolvedVersion);if(version!==0)return version;const identity=compareStrings(transitiveAdvisoryIdentity(a.occurrence),transitiveAdvisoryIdentity(b.occurrence));if(identity!==0)return identity;return compareStrings(JSON.stringify(a.occurrence),JSON.stringify(b.occurrence))}function formatTransitiveRows(rows,options){const shownRows=options.verbose||options.surface==="cli"?rows:rows.slice(0,DEFAULT_ADVISORY_CAP);const lines=[];for(const row of shownRows){lines.push(...formatTransitiveOccurrence(row,options))}const hidden=rows.length-shownRows.length;if(hidden>0){const hint=options.surface==="mcp"?"use verbose=true or format=json":"use -v";lines.push(...wrapFreeText(`... (+${hidden} more; ${hint})`,normaliseTerminalWidth2(options.terminalWidth)).map((line)=>dim(line,options.useColors)))}return lines}function formatTransitiveOccurrence(row,options){const occurrence=row.occurrence;const label=transitiveSeverityColumnLabel(occurrence);const paddedLabel=label.padEnd(TRANSITIVE_SEVERITY_LABEL_WIDTH);const coordinate=`${sanitizeIdentity(row.name)}@${sanitizeIdentity(occurrence.resolvedVersion)}`;const identity=occurrence.id?sanitizeIdentity(occurrence.id):undefined;const headlineParts=[paddedLabel,coordinate];const assessment=formatAdvisoryAssessment(occurrence.assessmentStatus,occurrence.affectsResolvedVersion);if(assessment!==undefined&&assessment!=="affects this version")headlineParts.push(`[${sanitizeIdentity(assessment)}]`);if(identity)headlineParts.push(identity);const headline=`${TRANSITIVE_ROW_MARGIN}${headlineParts.join(TRANSITIVE_COLUMN_SEPARATOR)}`;const lines=formatTransitiveHeadline(headline,occurrence.summary,options.terminalWidth);const coloredLabel=colorize(label,transitiveLabelColor(label),options.useColors);const labelStart=lines[0]?.indexOf(paddedLabel)??0;lines[0]=`${lines[0]?.slice(0,labelStart)??""}${coloredLabel}${" ".repeat(paddedLabel.length-label.length)}${lines[0]?.slice(labelStart+paddedLabel.length)??""}`;if(!occurrence.affectsResolvedVersion&&occurrence.assessmentReasons?.length){for(const reason of occurrence.assessmentReasons)lines.push(...formatFreeDetail("reason",formatVulnerabilityAssessmentReason(reason),options.terminalWidth))}if(occurrence.affectsResolvedVersion){lines.push(...formatAtomicDetail("matched",occurrence.matchedAffectedVersionRanges,options.terminalWidth));const nearest=occurrence.nearestFixedVersion?sanitizeIdentity(occurrence.nearestFixedVersion):"no higher fixed version known";lines.push(...formatFreeDetail("nearest fix",nearest,options.terminalWidth));const higherFixesRepeatNearest=occurrence.fixVersionsAboveResolved.length===1&&occurrence.nearestFixedVersion!==undefined&&occurrence.fixVersionsAboveResolved[0]===occurrence.nearestFixedVersion;if(options.verbose&&occurrence.fixVersionsAboveResolved.length>0&&!higherFixesRepeatNearest){lines.push(...formatAtomicDetail("higher fixes",occurrence.fixVersionsAboveResolved,options.terminalWidth))}if(options.verbose&&occurrence.aliases&&occurrence.aliases.length>0){lines.push(...formatAtomicDetail("aliases",occurrence.aliases,options.terminalWidth))}}else if(options.verbose){if(occurrence.affectedRanges&&occurrence.affectedRanges.length>0){lines.push(...formatAtomicDetail("advisory ranges",occurrence.affectedRanges,options.terminalWidth))}if(occurrence.fixedIn&&occurrence.fixedIn.length>0){lines.push(...formatAtomicDetail("advisory fixes",occurrence.fixedIn,options.terminalWidth))}if(occurrence.aliases&&occurrence.aliases.length>0){lines.push(...formatAtomicDetail("aliases",occurrence.aliases,options.terminalWidth))}}return lines}function formatTransitiveHeadline(headline,summary,terminalWidth2){const cleanSummary=summary?sanitizeProse(summary):"";if(!cleanSummary)return[headline];const words=cleanSummary.split(" ").filter(Boolean);const width=normaliseTerminalWidth2(terminalWidth2);const lines=[];let current=headline;for(const word of words){const separator=current===headline?" ":" ";const candidate=`${current}${separator}${word}`;if(terminalWidth(candidate)<=width){current=candidate;continue}lines.push(current.trimEnd());current=`${TRANSITIVE_COORDINATE_PREFIX}${word}`}lines.push(current.trimEnd());return lines}function formatAtomicDetail(label,values,terminalWidth2){const width=normaliseTerminalWidth2(terminalWidth2);const prefix=`${TRANSITIVE_COORDINATE_PREFIX}${label.padEnd(TRANSITIVE_DETAIL_LABEL_WIDTH)} `;const continuation=" ".repeat(prefix.length);const lines=[];let current=prefix;for(const[index,rawValue]of values.entries()){const value=sanitizeIdentity(rawValue);const addition=index===0?value:`, ${value}`;if(index===0||terminalWidth(`${current}${addition}`)<=width){current+=addition;continue}lines.push(current.trimEnd());current=`${continuation}${value}`}if(current!==prefix)lines.push(current.trimEnd());return lines}function formatFreeDetail(label,value,terminalWidth2){const prefix=`${TRANSITIVE_COORDINATE_PREFIX}${label.padEnd(TRANSITIVE_DETAIL_LABEL_WIDTH)} `;const width=normaliseTerminalWidth2(terminalWidth2);const words=sanitizeProse(value).split(" ").filter(Boolean);if(words.length===0)return[prefix.trimEnd()];const continuation=" ".repeat(prefix.length);const lines=[];let current=prefix;for(const word of words){if(current===prefix||terminalWidth(`${current}${current===prefix?"":" "}${word}`)<=width){current+=`${current===prefix?"":" "}${word}`;continue}lines.push(current.trimEnd());current=`${continuation}${word}`}lines.push(current.trimEnd());return lines}function wrapFreeText(value,width,continuationPrefix=" "){const words=value.match(/--scope unknown|\S+/g)??[];if(words.length===0)return[];const lines=[];let current=words[0]??"";for(const word of words.slice(1)){const candidate=`${current} ${word}`;if(terminalWidth(candidate)<=width){current=candidate}else{lines.push(current);current=`${continuationPrefix}${word}`}}lines.push(current);return lines}function transitiveSeverityColumnLabel(occurrence){if(occurrence.isMalicious===true)return"MALWARE";return occurrence.severityLabel??"unrated"}function transitiveLabelColor(label){if(label==="MALWARE"||label==="critical")return"red";if(label==="high"||label==="medium")return"yellow";return"dim"}function normaliseTerminalWidth2(width){if(width===undefined||!Number.isFinite(width))return 80;return Math.max(20,Math.floor(width))}function resolveAffectedRangesLimit(terminalWidth){const cols=typeof terminalWidth==="number"?terminalWidth:80;if(cols>=160)return 8;if(cols>=120)return 6;return 4}function formatUpgradeFooter(paths){if(!paths||paths.length===0)return;const safePaths=paths.map(sanitizeIdentity);if(safePaths.length===1)return`Fix version: ${safePaths[0]}.`;return`Fix versions: ${safePaths.join(", ")}.`}var schema8={target:z8.string().describe("Package registry:name[@version], for example npm:lodash@4.17.20; omit the version for latest. Go accepts versions with or without v; other registries reject v-prefixed git tags except Swift."),min_severity:z8.string().optional().describe("Only return advisories at or above this severity (`low`, `medium`, `high`, `critical`; uppercase tolerated). Omit to see all, including null-severity advisories."),include_withdrawn:z8.boolean().optional().describe("Include retracted advisories (default: false)."),include_transitive:z8.boolean().optional().describe("Opt in to dependency vulnerability evidence for the resolved graph. Adds graph-analysis cost; min_severity and advisory_scope apply to direct and transitive rows, while include_withdrawn affects direct rows only. Transitive withdrawn advisories remain excluded."),advisory_scope:z8.string().optional().describe("Advisory rows to return: `affected` (default), `non_affecting` for non-affecting advisories that do not affect the inspected version, `unknown` for advisories that could not be evaluated, or `all` for every outcome. Counts always include affected/non-affecting/unknown/all totals."),verbose:z8.boolean().optional().describe("Text output only. Show every advisory and full detail rows; format=json always returns the complete structured envelope."),format:z8.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text.")};var DESCRIPTION_BASE3="Check current package advisories. Do not trust your memory for vulnerabilities. "+"Advisories can be published or revised after training; a cutoff disclaimer is not current evidence. "+"Covers pinned releases, latest-version risk, and package security history. "+'For package-wide history, use an unpinned target and `advisory_scope:"all"`: `{"target":"npm:next","advisory_scope":"all"}`. '+"Supports npm, PyPI, Hex, Crates, NuGet, Maven, Packagist, RubyGems, Go, and Swift; vcpkg and Zig unsupported. "+"Returns counts/details: identifiers and aliases, including CVEs when available, severity, affected ranges, and fixes; malicious advisories are separate. "+"Default text is capped; `verbose:true` shows all selected rows and identifier aliases (including CVEs). "+"Transitive evidence is opt-in and adds graph-analysis cost; see `include_transitive` for scope and filter limits.";var DESCRIPTION8=`${DESCRIPTION_BASE3}
185
+ `)}function formatTransitiveSummaryLine(audit){const summary=audit.summary;const scopeLabel=audit.advisoryScope==="unknown"?"unknown":audit.advisoryScope==="affected"?"affected":"non-affecting";const occurrenceNoun=`${scopeLabel} advisory ${summary.occurrenceCount===1?"occurrence":"occurrences"}`;const packageNoun=summary.packageCount===1?"dependency package":"dependency packages";const versionNoun=summary.totalPackagesAnalyzed===1?"resolved package version":"resolved package versions";if(summary.occurrenceCount===0){if(audit.advisoryScope==="all")return`No advisory occurrences found. ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`;return`No ${scopeLabel} advisory occurrences found; ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`}if(audit.advisoryScope==="all"){const unknownText=summary.unknownCount>0?`, ${summary.unknownCount} unknown`:"";const noun=summary.occurrenceCount===1?"occurrence":"occurrences";return`${summary.occurrenceCount} advisory ${noun} (${summary.affectedCount} affected, ${summary.nonAffectingCount} non-affecting${unknownText}) in ${summary.packageCount} ${packageNoun}; ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`}return`${summary.occurrenceCount} ${occurrenceNoun} in ${summary.packageCount} ${packageNoun}; ${summary.totalPackagesAnalyzed} ${versionNoun} checked.`}function formatTransitiveCounts(counts){return`${counts.affectedCount} affected | ${counts.nonAffectingCount} non-affecting | ${counts.unknownCount} unknown | ${counts.totalCount} all`}var TRANSITIVE_ROW_MARGIN=" ";var TRANSITIVE_COLUMN_SEPARATOR=" ";var TRANSITIVE_SEVERITY_LABEL_WIDTH="critical".length;var TRANSITIVE_COORDINATE_INDENT=TRANSITIVE_ROW_MARGIN.length+TRANSITIVE_SEVERITY_LABEL_WIDTH+TRANSITIVE_COLUMN_SEPARATOR.length;var TRANSITIVE_DETAIL_LABEL_WIDTH="advisory ranges".length;var TRANSITIVE_COORDINATE_PREFIX=" ".repeat(TRANSITIVE_COORDINATE_INDENT);function formatTransitiveBreakdown(summary,useColors,terminalWidth){if(!summary.bySeverity)return;const labels={malware:"MALWARE",critical:"critical",high:"high",medium:"medium",low:"low",unrated:"unrated"};const parts=[];for(const key of BUCKET_ORDER){const count=summary.bySeverity[key];if(typeof count==="number"&&count>0){const part=`${count} ${labels[key]}`;parts.push({text:part,color:key==="malware"?"red":undefined})}}return parts.length>0?formatBreakdownParts(parts,useColors,terminalWidth):undefined}function flattenTransitiveRows(audit){return audit.packages.flatMap((pkg)=>pkg.occurrences.map((occurrence)=>({registry:pkg.registry,name:pkg.name,occurrence}))).sort(compareTransitiveTextRows)}function compareTransitiveTextRows(a,b){const risk=transitiveRiskRank(b.occurrence)-transitiveRiskRank(a.occurrence);if(risk!==0)return risk;const registry=compareStrings(a.registry,b.registry);if(registry!==0)return registry;const name=compareStrings(a.name,b.name);if(name!==0)return name;const version=compareStrings(a.occurrence.resolvedVersion,b.occurrence.resolvedVersion);if(version!==0)return version;const identity=compareStrings(transitiveAdvisoryIdentity(a.occurrence),transitiveAdvisoryIdentity(b.occurrence));if(identity!==0)return identity;return compareStrings(JSON.stringify(a.occurrence),JSON.stringify(b.occurrence))}function formatTransitiveRows(rows,options){const shownRows=options.verbose||options.surface==="cli"?rows:rows.slice(0,DEFAULT_ADVISORY_CAP);const lines=[];for(const row of shownRows){lines.push(...formatTransitiveOccurrence(row,options))}const hidden=rows.length-shownRows.length;if(hidden>0){const hint=options.surface==="mcp"?"use verbose=true or format=json":"use -v";lines.push(...wrapFreeText(`... (+${hidden} more; ${hint})`,normaliseTerminalWidth2(options.terminalWidth)).map((line)=>dim(line,options.useColors)))}return lines}function formatTransitiveOccurrence(row,options){const occurrence=row.occurrence;const label=transitiveSeverityColumnLabel(occurrence);const paddedLabel=label.padEnd(TRANSITIVE_SEVERITY_LABEL_WIDTH);const coordinate=`${sanitizeIdentity(row.name)}@${sanitizeIdentity(occurrence.resolvedVersion)}`;const identity=occurrence.id?sanitizeIdentity(occurrence.id):undefined;const headlineParts=[paddedLabel,coordinate];const assessment=formatAdvisoryAssessment(occurrence.assessmentStatus,occurrence.affectsResolvedVersion);if(assessment!==undefined&&assessment!=="affects this version")headlineParts.push(`[${sanitizeIdentity(assessment)}]`);if(identity)headlineParts.push(identity);const headline=`${TRANSITIVE_ROW_MARGIN}${headlineParts.join(TRANSITIVE_COLUMN_SEPARATOR)}`;const lines=formatTransitiveHeadline(headline,occurrence.summary,options.terminalWidth);const coloredLabel=colorize(label,transitiveLabelColor(label),options.useColors);const labelStart=lines[0]?.indexOf(paddedLabel)??0;lines[0]=`${lines[0]?.slice(0,labelStart)??""}${coloredLabel}${" ".repeat(paddedLabel.length-label.length)}${lines[0]?.slice(labelStart+paddedLabel.length)??""}`;if(!occurrence.affectsResolvedVersion&&occurrence.assessmentReasons?.length){for(const reason of occurrence.assessmentReasons)lines.push(...formatFreeDetail("reason",formatVulnerabilityAssessmentReason(reason),options.terminalWidth))}if(occurrence.affectsResolvedVersion){lines.push(...formatAtomicDetail("matched",occurrence.matchedAffectedVersionRanges,options.terminalWidth));const nearest=occurrence.nearestFixedVersion?sanitizeIdentity(occurrence.nearestFixedVersion):"no higher fixed version known";lines.push(...formatFreeDetail("nearest fix",nearest,options.terminalWidth));const higherFixesRepeatNearest=occurrence.fixVersionsAboveResolved.length===1&&occurrence.nearestFixedVersion!==undefined&&occurrence.fixVersionsAboveResolved[0]===occurrence.nearestFixedVersion;if(options.verbose&&occurrence.fixVersionsAboveResolved.length>0&&!higherFixesRepeatNearest){lines.push(...formatAtomicDetail("higher fixes",occurrence.fixVersionsAboveResolved,options.terminalWidth))}if(options.verbose&&occurrence.aliases&&occurrence.aliases.length>0){lines.push(...formatAtomicDetail("aliases",occurrence.aliases,options.terminalWidth))}}else if(options.verbose){if(occurrence.affectedRanges&&occurrence.affectedRanges.length>0){lines.push(...formatAtomicDetail("advisory ranges",occurrence.affectedRanges,options.terminalWidth))}if(occurrence.fixedIn&&occurrence.fixedIn.length>0){lines.push(...formatAtomicDetail("advisory fixes",occurrence.fixedIn,options.terminalWidth))}if(occurrence.aliases&&occurrence.aliases.length>0){lines.push(...formatAtomicDetail("aliases",occurrence.aliases,options.terminalWidth))}}return lines}function formatTransitiveHeadline(headline,summary,terminalWidth2){const cleanSummary=summary?sanitizeProse(summary):"";if(!cleanSummary)return[headline];const words=cleanSummary.split(" ").filter(Boolean);const width=normaliseTerminalWidth2(terminalWidth2);const lines=[];let current=headline;for(const word of words){const separator=current===headline?" ":" ";const candidate=`${current}${separator}${word}`;if(terminalWidth(candidate)<=width){current=candidate;continue}lines.push(current.trimEnd());current=`${TRANSITIVE_COORDINATE_PREFIX}${word}`}lines.push(current.trimEnd());return lines}function formatAtomicDetail(label,values,terminalWidth2){const width=normaliseTerminalWidth2(terminalWidth2);const prefix=`${TRANSITIVE_COORDINATE_PREFIX}${label.padEnd(TRANSITIVE_DETAIL_LABEL_WIDTH)} `;const continuation=" ".repeat(prefix.length);const lines=[];let current=prefix;for(const[index,rawValue]of values.entries()){const value=sanitizeIdentity(rawValue);const addition=index===0?value:`, ${value}`;if(index===0||terminalWidth(`${current}${addition}`)<=width){current+=addition;continue}lines.push(current.trimEnd());current=`${continuation}${value}`}if(current!==prefix)lines.push(current.trimEnd());return lines}function formatFreeDetail(label,value,terminalWidth2){const prefix=`${TRANSITIVE_COORDINATE_PREFIX}${label.padEnd(TRANSITIVE_DETAIL_LABEL_WIDTH)} `;const width=normaliseTerminalWidth2(terminalWidth2);const words=sanitizeProse(value).split(" ").filter(Boolean);if(words.length===0)return[prefix.trimEnd()];const continuation=" ".repeat(prefix.length);const lines=[];let current=prefix;for(const word of words){if(current===prefix||terminalWidth(`${current}${current===prefix?"":" "}${word}`)<=width){current+=`${current===prefix?"":" "}${word}`;continue}lines.push(current.trimEnd());current=`${continuation}${word}`}lines.push(current.trimEnd());return lines}function wrapFreeText(value,width,continuationPrefix=" "){const words=value.match(/--scope unknown|\S+/g)??[];if(words.length===0)return[];const lines=[];let current=words[0]??"";for(const word of words.slice(1)){const candidate=`${current} ${word}`;if(terminalWidth(candidate)<=width){current=candidate}else{lines.push(current);current=`${continuationPrefix}${word}`}}lines.push(current);return lines}function transitiveSeverityColumnLabel(occurrence){if(occurrence.isMalicious===true)return"MALWARE";return occurrence.severityLabel??"unrated"}function transitiveLabelColor(label){if(label==="MALWARE"||label==="critical")return"red";if(label==="high"||label==="medium")return"yellow";return"dim"}function normaliseTerminalWidth2(width){if(width===undefined||!Number.isFinite(width))return 80;return Math.max(20,Math.floor(width))}function resolveAffectedRangesLimit(terminalWidth){const cols=typeof terminalWidth==="number"?terminalWidth:80;if(cols>=160)return 8;if(cols>=120)return 6;return 4}function formatUpgradeFooter(paths){if(!paths||paths.length===0)return;const safePaths=paths.map(sanitizeIdentity);if(safePaths.length===1)return`Fix version: ${safePaths[0]}.`;return`Fix versions: ${safePaths.join(", ")}.`}var schema8={target:z8.string().describe("Package registry:name[@version], for example npm:lodash@4.17.20; omit the version for latest. Go accepts versions with or without v; other registries reject v-prefixed git tags except Swift."),min_severity:z8.string().optional().describe("Only return advisories at or above this severity (`low`, `medium`, `high`, `critical`; uppercase tolerated). Omit to see all, including null-severity advisories."),include_withdrawn:z8.boolean().optional().describe("Include retracted advisories (default: false)."),include_transitive:z8.boolean().optional().describe("Opt in to dependency vulnerability evidence for the resolved graph. Adds graph-analysis cost; min_severity and advisory_scope apply to direct and transitive rows, while include_withdrawn affects direct rows only. Transitive withdrawn advisories remain excluded."),advisory_scope:z8.string().optional().describe("Advisory rows to return: `affected` (default), `non_affecting` for non-affecting advisories that do not affect the inspected version, `unknown` for advisories that could not be evaluated, or `all` for every outcome. Counts always include affected/non-affecting/unknown/all totals."),verbose:z8.boolean().optional().describe("Text output only. Show every advisory and full detail rows; format=json always returns the complete structured envelope."),format:z8.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text.")};var DESCRIPTION_BASE3="Check current package advisories. Do not trust your memory for vulnerabilities. "+"Advisories can be published or revised after training; a cutoff disclaimer is not current evidence. "+"Covers pinned releases, latest-version risk, and package security history. "+'For package-wide history, use an unpinned target and `advisory_scope:"all"`: `{"target":"npm:next","advisory_scope":"all"}`. '+"Supports npm, PyPI, Hex, Crates, NuGet, Maven, Packagist, RubyGems, Go, Swift, and Pub; vcpkg and Zig unsupported. "+"Returns counts/details: identifiers and aliases, including CVEs when available, severity, affected ranges, and fixes; malicious advisories are separate. "+"Default text is capped; `verbose:true` shows all selected rows and identifier aliases (including CVEs). "+"Transitive evidence is opt-in and adds graph-analysis cost; see `include_transitive` for scope and filter limits.";var DESCRIPTION8=`${DESCRIPTION_BASE3}
186
186
 
187
187
  ${PKG_VULNS_GUARDRAIL}`;function createPackageVulnerabilitiesTool(service){return{name:"pkg_vulns",description:DESCRIPTION8,schema:schema8,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());const{params:builtParams,filter}=buildPackageVulnerabilitiesParams({surface:"mcp",registry:target.registry,packageName:target.name,version:target.version,minSeverity:args.min_severity,includeWithdrawn:args.include_withdrawn,includeTransitive:args.include_transitive,advisoryScope:args.advisory_scope});const params={...builtParams,includeTransitiveAdvisoryDetails:args.format==="json"||args.verbose===true&&(builtParams.advisoryScope??"AFFECTED")!=="AFFECTED"};const report=await service.packageVulnerabilities(params,...serviceRequestArgs(context?.signal));const payload=buildPackageVulnerabilitiesSuccessPayload(report,{requestedVersion:params.version,filter});if(isTextFormat5(args.format)){return textResult(formatPackageVulnerabilitiesTerminal(report,{useColors:false,requestedVersion:params.version,filter,verbose:args.verbose,surface:"mcp"}).trimEnd())}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_vulns",args}})}}}}function isTextFormat5(format){return format===undefined||format==="text"}var schema9={};var DESCRIPTION9="Call quick_start first to choose tools and load untrusted-content rules. Call once per session before discovering evidence tools, unless the loaded githits-mcp skill already contains this guide. Covers tool choice, workflow, target conventions, result conventions, and upgrade checks.";var QUICK_START_PREREQUISITE="Before using this tool, call `quick_start` once per session unless the `githits-mcp` skill is loaded.";function createQuickStartTool(guide){return{name:"quick_start",description:DESCRIPTION9,schema:schema9,annotations:READ_ONLY_TOOL_ANNOTATIONS,handler:async()=>textResult(guide)}}import{z as z10}from"zod";function isSiteReadTarget(target){return target.trim().startsWith("site:")}function resolveReadLocator(target,path){if(typeof target!=="string"||!target.trim()){throw new InvalidPackageSpecError("A nonempty string target is required.")}if(path!==undefined&&typeof path!=="string"){throw new InvalidPackageSpecError("path must be an exact file path string.")}const filePath=path?.trim();return filePath?{target,path:filePath}:{target}}function validateReadRange(startLine,endLine){for(const[name,value]of[["start_line",startLine],["end_line",endLine]]){if(value!==undefined&&(!Number.isInteger(value)||value<1)){throw new InvalidPackageSpecError(`\`${name}\` must be a positive integer (lines are 1-indexed). Got ${value}.`)}}if(startLine!==undefined&&endLine!==undefined&&startLine>endLine){throw new InvalidPackageSpecError(`Line range is reversed: start_line (${startLine}) must be ≤ end_line (${endLine}).`)}}function normalizeReadWaitTimeoutMs(value){if(value===undefined)return DEFAULT_WAIT_TIMEOUT_MS;if(!Number.isInteger(value)||value<0||value>MAX_WAIT_TIMEOUT_MS){throw new InvalidPackageSpecError(`\`wait_timeout_ms\` must be an integer between 0 and ${MAX_WAIT_TIMEOUT_MS}. Got ${value}.`)}return value}function buildReadFileSuccessPayload(result,options){const envelope={path:result.filePath??options.requestedFilePath,...result.indexingEstimates!==undefined?{indexingEstimates:projectIndexingEstimates(result.indexingEstimates)}:{}};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);return verbose?formatVerboseSentinel(envelope,options,sentinel):`${sentinel}
188
188
  `}function formatNoContent(envelope,options,verbose){const sentinel=dim("(no content returned)",options.useColors);return verbose?formatVerboseSentinel(envelope,options,sentinel):`${sentinel}