@githits/mcp 0.32.0 → 0.33.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/client.d.ts +9 -1
- package/dist/client.js +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.js +21 -16
- package/dist/shared/{chunk-j6q0y6f2.js → chunk-0ch431yh.js} +12 -3
- package/dist/shared/{chunk-a1w4dxpc.js → chunk-0sd6v5ad.js} +1 -1
- package/dist/shared/chunk-nawnggb2.js +31 -0
- package/dist/tools.js +1 -1
- package/package.json +1 -1
- package/dist/shared/chunk-9qbcj09a.js +0 -31
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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,terminalWidth,sanitizeTerminalText,wrapTerminalProse,toCodeNavigationRegistry,KNOWN_REGISTRIES,UnsupportedRegistryError,InvalidPackageSpecError,InvalidArgumentError,parsePackageSpec,isKnownRegistry,LegacyRepositoryRefError,isRepositoryTargetSpec,parseRepositoryTargetSpec,formatRepositoryTarget,formatRepositoryTargetLabel,buildInvalidTargetSpecError,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,projectTargetResolution,buildTargetResolutionNotes,buildRetryCandidateLine,buildSuggestedRefsLine,buildResolutionFromRetryCandidates,formatTargetResolutionIdentity,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-
|
|
1
|
+
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,terminalWidth,sanitizeTerminalText,wrapTerminalProse,toCodeNavigationRegistry,KNOWN_REGISTRIES,UnsupportedRegistryError,InvalidPackageSpecError,InvalidArgumentError,parsePackageSpec,isKnownRegistry,LegacyRepositoryRefError,isRepositoryTargetSpec,parseRepositoryTargetSpec,isCanonicalRepositoryUrl,formatRepositoryTarget,formatRepositoryTargetLabel,buildInvalidTargetSpecError,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,projectTargetResolution,buildTargetResolutionNotes,buildRetryCandidateLine,buildSuggestedRefsLine,buildResolutionFromRetryCandidates,formatTargetResolutionIdentity,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-nawnggb2.js";import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-0ch431yh.js";import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2}from"./shared/chunk-0sd6v5ad.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,
|
|
@@ -62,9 +62,14 @@ unverified paths.
|
|
|
62
62
|
\`pypi:requests@2.32.3\` (never the literal \`registry:\`); Swift
|
|
63
63
|
\`swift:github.com/<owner>/<repo>\`, Zig \`zig:gh/<owner>/<repo>\`. A package target covers its package subpath,
|
|
64
64
|
including in monorepos.
|
|
65
|
-
- Repositories: \`github:owner/repo@ref\`, \`codeberg:\`, \`gitlab:\`, or a
|
|
65
|
+
- Repositories: \`github:owner/repo@ref\`, \`codeberg:\`, \`gitlab:\`, \`launchpad:\`, or a
|
|
66
66
|
supported full URL, for whole repositories or sibling packages. Never infer
|
|
67
|
-
a provider.
|
|
67
|
+
a provider. Launchpad accepts \`lp:project\`, \`lp:distro/+source/source\`,
|
|
68
|
+
\`lp:~owner/project\`, \`lp:~owner/distro/+source/source\`, and complete
|
|
69
|
+
\`launchpad:~owner/[project/]+git/repo\` or
|
|
70
|
+
\`launchpad:~owner/distro/+source/source/+git/repo\` paths. Case-insensitive
|
|
71
|
+
\`lp:\` aliases \`launchpad:\`. HTTPS \`code.launchpad.net\`/\`git.launchpad.net\`
|
|
72
|
+
URLs accept the same paths; follow returned owner-qualified targets for replay.
|
|
68
73
|
- Docs sites: \`site:host[/path]\`. Research takes the project's package or
|
|
69
74
|
repository instead; it covers code and docs.
|
|
70
75
|
- Omit the suffix for the latest package version or default branch. A ref may
|
|
@@ -104,18 +109,18 @@ sources.`;function buildMcpQuickStart(options={}){const includeExternalContentPo
|
|
|
104
109
|
|
|
105
110
|
${EXTERNAL_CONTENT_POSTURE}`:GUIDE}function buildMcpInstructions(options={}){return buildMcpQuickStart(options)}import{McpServer}from"@modelcontextprotocol/sdk/server/mcp.js";import{z}from"zod";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)}`];appendWarnings(lines,envelope);const displayTruncatedPreviews=appendFiles(lines,envelope);lines.push(nextAction(envelope,displayTruncatedPreviews));return`${lines.join(`
|
|
106
111
|
`)}
|
|
107
|
-
`}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\`, or \`gitlab:group/subgroup/project\`).`)}}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)}function quoteGitPath(path){let quoted=false;let output="";for(const character of path){const codePoint=character.codePointAt(0);if(character==='"'||character==="\\"){quoted=true;output+=`\\${character}`;continue}if(codePoint!==undefined&&(codePoint<=31||codePoint>=127&&codePoint<=159||codePoint===8232||codePoint===8233)){quoted=true;for(const byte of new TextEncoder().encode(character)){output+=`\\${byte.toString(8).padStart(3,"0")}`}continue}output+=character}return quoted?`"${output}"`:output}function buildCodeDiffSuccessPayload(result,options){const envelope={target:buildTarget(result,options.target),view:options.view,from:projectResolution(result.fromResolution),to:projectResolution(result.toResolution),summary:projectSummary(result.raw.summary),scope:projectScope(result.raw.scope),contentCoverage:lower(result.raw.contentCoverage),files:result.raw.files.map((file)=>projectFile(file,options.view)),hasMoreFiles:result.raw.hasMoreFiles};if(result.raw.contentFailure!=null){envelope.contentFailure=projectContentFailure(result.raw.contentFailure)}return envelope}function buildTarget(result,target){if("registry"in target){const packageInfo=result.package;return{kind:"package",registry:lower(packageInfo?.registry??target.registry),name:packageInfo?.name??target.packageName,...packageInfo?.repoUrl!=null?{repoUrl:packageInfo.repoUrl}:{}}}return{kind:"repository",repoUrl:target.repoUrl}}function projectResolution(resolution){const projected={requested:resolution.requested,ref:resolution.ref,commitSha:resolution.commitSha,refKind:lower(resolution.refKind)};if(resolution.resolvedVersion!=null){projected.resolvedVersion=resolution.resolvedVersion}if(resolution.versionSource!=null){projected.versionSource=lower(resolution.versionSource)}return projected}function projectSummary(summary){return{filesChanged:summary.filesChanged,added:summary.added,deleted:summary.deleted,modified:summary.modified,modeChanged:summary.modeChanged,typeChanged:summary.typeChanged,inventoryComplete:summary.inventoryComplete,unprojectableFiles:summary.unprojectableFiles}}function projectScope(scope){const projected={status:lower(scope.status)};if(scope.fromSubpath!=null)projected.fromSubpath=scope.fromSubpath;if(scope.toSubpath!=null)projected.toSubpath=scope.toSubpath;if(scope.pathPrefix!=null)projected.pathPrefix=scope.pathPrefix;if(scope.pathGlob!=null)projected.pathGlob=scope.pathGlob;return projected}function projectContentFailure(failure){const projected={code:failure.code,retryable:failure.retryable};if(failure.retryAfterMs!=null){projected.retryAfterMs=failure.retryAfterMs}if(failure.stage!=null)projected.stage=failure.stage;if(failure.limitKind!=null)projected.limitKind=failure.limitKind;return projected}function projectFile(file,view){const base={path:file.path,pathEncoding:lower(file.pathEncoding)};if(view==="name-only")return base;const nameStatus={...base,status:lower(file.status)};if(view==="name-status")return nameStatus;const stat={...nameStatus,modeChanged:file.modeChanged,typeChanged:file.typeChanged,contentStatus:lower(file.contentStatus)};if(file.additions!=null)stat.additions=file.additions;if(file.deletions!=null)stat.deletions=file.deletions;if(view==="stat")return stat;const patch={...stat,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications.map(lower)}};if(file.patch!=null){patch.patch=bindPatchHeaders(file.patch,file.path,patch.status)}if(file.contentOmissionReason!=null){patch.contentOmissionReason=file.contentOmissionReason}return patch}function bindPatchHeaders(patch,path,status){const firstEnd=patch.indexOf(`
|
|
112
|
+
`}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)}function quoteGitPath(path){let quoted=false;let output="";for(const character of path){const codePoint=character.codePointAt(0);if(character==='"'||character==="\\"){quoted=true;output+=`\\${character}`;continue}if(codePoint!==undefined&&(codePoint<=31||codePoint>=127&&codePoint<=159||codePoint===8232||codePoint===8233)){quoted=true;for(const byte of new TextEncoder().encode(character)){output+=`\\${byte.toString(8).padStart(3,"0")}`}continue}output+=character}return quoted?`"${output}"`:output}function buildCodeDiffSuccessPayload(result,options){const envelope={target:buildTarget(result,options.target),view:options.view,from:projectResolution(result.fromResolution),to:projectResolution(result.toResolution),summary:projectSummary(result.raw.summary),scope:projectScope(result.raw.scope),contentCoverage:lower(result.raw.contentCoverage),files:result.raw.files.map((file)=>projectFile(file,options.view)),hasMoreFiles:result.raw.hasMoreFiles};if(result.raw.contentFailure!=null){envelope.contentFailure=projectContentFailure(result.raw.contentFailure)}return envelope}function buildTarget(result,target){if("registry"in target){const packageInfo=result.package;return{kind:"package",registry:lower(packageInfo?.registry??target.registry),name:packageInfo?.name??target.packageName,...packageInfo?.repoUrl!=null?{repoUrl:packageInfo.repoUrl}:{}}}return{kind:"repository",repoUrl:target.repoUrl}}function projectResolution(resolution){const projected={requested:resolution.requested,ref:resolution.ref,commitSha:resolution.commitSha,refKind:lower(resolution.refKind)};if(resolution.resolvedVersion!=null){projected.resolvedVersion=resolution.resolvedVersion}if(resolution.versionSource!=null){projected.versionSource=lower(resolution.versionSource)}return projected}function projectSummary(summary){return{filesChanged:summary.filesChanged,added:summary.added,deleted:summary.deleted,modified:summary.modified,modeChanged:summary.modeChanged,typeChanged:summary.typeChanged,inventoryComplete:summary.inventoryComplete,unprojectableFiles:summary.unprojectableFiles}}function projectScope(scope){const projected={status:lower(scope.status)};if(scope.fromSubpath!=null)projected.fromSubpath=scope.fromSubpath;if(scope.toSubpath!=null)projected.toSubpath=scope.toSubpath;if(scope.pathPrefix!=null)projected.pathPrefix=scope.pathPrefix;if(scope.pathGlob!=null)projected.pathGlob=scope.pathGlob;return projected}function projectContentFailure(failure){const projected={code:failure.code,retryable:failure.retryable};if(failure.retryAfterMs!=null){projected.retryAfterMs=failure.retryAfterMs}if(failure.stage!=null)projected.stage=failure.stage;if(failure.limitKind!=null)projected.limitKind=failure.limitKind;return projected}function projectFile(file,view){const base={path:file.path,pathEncoding:lower(file.pathEncoding)};if(view==="name-only")return base;const nameStatus={...base,status:lower(file.status)};if(view==="name-status")return nameStatus;const stat={...nameStatus,modeChanged:file.modeChanged,typeChanged:file.typeChanged,contentStatus:lower(file.contentStatus)};if(file.additions!=null)stat.additions=file.additions;if(file.deletions!=null)stat.deletions=file.deletions;if(view==="stat")return stat;const patch={...stat,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications.map(lower)}};if(file.patch!=null){patch.patch=bindPatchHeaders(file.patch,file.path,patch.status)}if(file.contentOmissionReason!=null){patch.contentOmissionReason=file.contentOmissionReason}return patch}function bindPatchHeaders(patch,path,status){const firstEnd=patch.indexOf(`
|
|
108
113
|
`);if(firstEnd<0)return patch;const secondStart=firstEnd+1;const secondEnd=patch.indexOf(`
|
|
109
114
|
`,secondStart);if(secondEnd<0)return patch;const originalFrom=patch.slice(0,firstEnd);const originalTo=patch.slice(secondStart,secondEnd);if(originalFrom!=="--- a/file"&&originalTo!=="+++ b/file"){return patch}const fromPath=status==="added"?"/dev/null":quoteGitPath(`a/${path}`);const toPath=status==="deleted"?"/dev/null":quoteGitPath(`b/${path}`);const from=originalFrom==="--- a/file"?`--- ${fromPath}`:originalFrom;const to=originalTo==="+++ b/file"?`+++ ${toPath}`:originalTo;return`${from}
|
|
110
115
|
${to}
|
|
111
|
-
${patch.slice(secondEnd+1)}`}function lower(value){return value.toLowerCase()}var schema={target:z.string().describe("One unversioned compact target string such as `npm:express` or `github:expressjs/express`. 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 still 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";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"?"INDEXING":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))));details.hint=details.targetIssues.map((issue)=>{const target=typeof issue.target==="string"?issue.target:typeof issue.input_index==="number"?`Input ${issue.input_index}`:undefined;const reason=typeof issue.reason==="string"?grepPreparationReason(issue.reason):"target is unavailable";return`${target?`${target}: `:""}${reason}${typeof issue.file_path==="string"?`; path ${issue.file_path}`:""}`}).join(`
|
|
112
|
-
`)}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}}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 projectGrepResult(result){const projected=parseGrepResult({...result,indexingEstimates:result.indexingEstimates??[]});if(result.indexingEstimates===undefined)delete projected.indexingEstimates;return projected}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 omissionsOnly=result.unavailableTargets.length>0&&result.targets.every((scope)=>!hasPageCoverageGap(scope))&&!["FAILED","CURSOR_EXPIRED"].includes(result.traversal);const retryableOmissionsOnly=omissionsOnly&&result.unavailableTargets.every((target)=>target.retryable);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?retryableOmissionsOnly?"No matches available yet on this page.":"No matches on this page.":retryableOmissionsOnly?"No matches available yet.":"No matches found.");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 isPreparing=(reason)=>["repository_indexing","documentation_publishing"].includes(reason);const pending=result.unavailableTargets.filter((entry)=>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(` Suggested site: ${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(` Suggested site: ${target}`)}const otherOmissions=result.unavailableTargets.filter((entry)=>!isPreparing(entry.reason));if(otherOmissions.length)lines.push("Omitted:");for(const omitted of otherOmissions){prose(` - ${omitted.target} (${grepPreparationReason(omitted.reason)})`);for(const target of omitted.suggestedSiteTargets??[])prose(` Suggested site: ${target}`)}for(const scope of result.targets)renderCoverage(scope,prose);if(result.traversal==="CURSOR_EXPIRED")prose("Cursor expired. Restart explicitly without the cursor; retained matches and omissions are included.");else if(result.traversal!=="COMPLETE"&&(!result.nextCursor||result.traversal!=="RESUMABLE_LIMIT")&&!omissionsOnly)prose(result.nextCursor?"Some requested content could not be searched.":"Traversal is incomplete and has no continuation cursor.");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)}`));if(result.unavailableTargets.some((target)=>target.retryable)){const wait=indexingWaitMs(result.indexingEstimates);followUp.push(...proseLines(`To retry omitted targets, rerun the original query with ${options.syntax==="mcp"?`wait_timeout_ms=${wait}`:`--wait ${wait}`}.`))}appendSearchGrepFooter(lines,{read,more,followUp},options.useColors===true);return lines.join(`
|
|
113
|
-
`)}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(scope.errorCode)notes.push(scope.errorCode);if(scope.publicMessage)notes.push(scope.publicMessage);const details=[];if(notes.length){if(scope.retryable)notes.push("retryable");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} files.`)}if(scope.binaryFilesSkipped)details.push(`Skipped ${scope.binaryFilesSkipped} binary file(s).`);if(scope.filesTooLargeSkipped)details.push(`Skipped ${scope.filesTooLargeSkipped} oversized file(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&&!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness);if(unsearched)qualifiers.push("not searched");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?.includes("not searched")?[exhaustive?"no results":"no results on this page"]:[],...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 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. "+"Replaces code_grep. 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."+`
|
|
116
|
+
${patch.slice(secondEnd+1)}`}function lower(value){return value.toLowerCase()}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 still 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";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"?"INDEXING":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))));details.hint=details.targetIssues.map((issue)=>{const target=typeof issue.target==="string"?issue.target:typeof issue.input_index==="number"?`Input ${issue.input_index}`:undefined;const reason=typeof issue.reason==="string"?grepPreparationReason(issue.reason):"target is unavailable";return`${target?`${target}: `:""}${reason}${typeof issue.file_path==="string"?`; path ${issue.file_path}`:""}`}).join(`
|
|
117
|
+
`)}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}}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 projectGrepResult(result){const projected=parseGrepResult({...result,indexingEstimates:result.indexingEstimates??[]});if(result.indexingEstimates===undefined)delete projected.indexingEstimates;return projected}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 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.");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(`
|
|
118
|
+
`)}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. "+"Replaces code_grep. 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."+`
|
|
114
119
|
|
|
115
|
-
${CODE_GREP_GUARDRAIL}`;function createGrepTool(service){return{name:"grep",description:DESCRIPTION2,schema:schema2,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const params=buildGrepParams({targets:args.targets.map((entry)=>({target:entry.target,corpus:entry.corpus,pathSelectors:entry.path_selectors})),pattern:args.pattern,patternType:args.pattern_type,ignoreCase:args.ignore_case,contextLinesBefore:args.context_lines_before,contextLinesAfter:args.context_lines_after,maxMatches:args.max_matches,cursor:args.cursor,waitTimeoutMs:args.wait_timeout_ms,includeDetailedFields:args.format==="json"});const projected=projectGrepResult(await service.grep(params,...serviceRequestArgs(context?.signal)));return textResult(args.format==="json"?JSON.stringify(projected):formatGrepText(projected,{syntax:"mcp",useColors:false}))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapGrepError(error);if(mapped.code==="INDEXING"&&mapped.retryable){mapped.details={...mapped.details,action:"Retry grep with the same targets, pattern, and other controls; set wait_timeout_ms (up to 300000) to wait for target preparation."}}return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"grep",args}})}}}}import{z as z3}from"zod";function mapListError(error,context){if(error instanceof ListGraphQLError2&&error.recovery)return mapVersionRefRecovery(error.message,error.recovery);const sessionError=mapSessionIdError(error);if(sessionError)return sessionError;const termsError=mapTermsAcceptanceError(error);if(termsError)return termsError;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 ListAccessError2){return{code:"ACCESS_DENIED",message:error.message,retryable:false}}if(error instanceof ListNetworkError2){return{code:"NETWORK",message:error.message,retryable:true}}if(error instanceof MalformedListResponseError2){return{code:"PROTOCOL_ERROR",message:error.message,retryable:false}}if(error instanceof ListBackendError2){return mapBackendError(error)}if(error instanceof ListGraphQLError2){return mapGraphQLError(error,context)}if(isInvalidArgumentError(error)){return{code:"INVALID_ARGUMENT",message:error.message,retryable:false}}if(error instanceof Error){return{code:"UNKNOWN",message:error.message,retryable:false}}return{code:"UNKNOWN",message:"Unknown error",retryable:false}}function mapBackendError(error){const details={};if(typeof error.status==="number")details.status=error.status;if(isNonempty(error.graphqlCode))details.graphqlCode=error.graphqlCode;const build=(code,defaultRetryable)=>({code,message:error.message,retryable:error.retryable??defaultRetryable,details:Object.keys(details).length>0?details:undefined});switch(error.graphqlCode){case"TIMEOUT":return build("TIMEOUT",true);case"RATE_LIMITED":return build("RATE_LIMITED",true);default:return build("BACKEND_ERROR",false)}}function mapGraphQLError(error,context){const details=graphQLErrorDetails(error);const build=(code,defaultRetryable,message=error.message,extraDetails)=>{const allDetails={...details,...extraDetails};return{code,message,retryable:error.retryable??defaultRetryable,details:Object.keys(allDetails).length>0?allDetails:undefined}};switch(error.code){case"NOT_FOUND":return build("NOT_FOUND",false);case"INDEXING":case"PACKAGE_INDEXING":return build("INDEXING",true);case"VALIDATION_ERROR":return build("INVALID_ARGUMENT",false,context?.hasAfter?`${error.message} Retry once without \`after\`; if validation still fails, correct the request.`:`${error.message} Correct the request and try again.`);case"SOURCE_INVENTORY_SCOPE_UNAVAILABLE":return mapScopeUnavailableError(error,build);case"LIST_UNSUPPORTED_API":return build("LIST_UNSUPPORTED_API",false);case"LIST_PAGE_TOO_LARGE":return build("LIST_PAGE_TOO_LARGE",false);case"TIMEOUT":return build("TIMEOUT",true);case"RATE_LIMITED":return build("RATE_LIMITED",true);default:return build("BACKEND_ERROR",false)}}function mapScopeUnavailableError(error,build){const extraDetails={};const repoUrl=nonemptyValue(error.repoUrl);const commitSha=nonemptyValue(error.commitSha);if(repoUrl!==undefined)extraDetails.repoUrl=repoUrl;if(commitSha!==undefined)extraDetails.commitSha=commitSha;if(repoUrl===undefined||commitSha===undefined){return build("SOURCE_INVENTORY_SCOPE_UNAVAILABLE",false,error.message,extraDetails)}const action=`${repoUrl}@${commitSha}`;extraDetails.action=action;return build("SOURCE_INVENTORY_SCOPE_UNAVAILABLE",false,`${error.message} The repository-wide alternative ${action} broadens scope; use it only if those broader results are acceptable.`,extraDetails)}function graphQLErrorDetails(error){const details={};if(isNonempty(error.code))details.graphqlCode=error.code;if(isNonempty(error.indexingRef))details.indexingRef=error.indexingRef;if(isNonempty(error.hint))details.hint=error.hint;if(isNonempty(error.repoUrl))details.repoUrl=error.repoUrl;if(isNonempty(error.commitSha))details.commitSha=error.commitSha;if(error.indexingMetadata?.indexingEstimate)details.indexingEstimate=error.indexingMetadata.indexingEstimate;if(error.indexingMetadata?.availableVersions)details.availableVersions=error.indexingMetadata.availableVersions;if(error.indexingMetadata?.package)details.package=error.indexingMetadata.package;return details}function nonemptyValue(value){return isNonempty(value)?value:undefined}function isNonempty(value){return value!==undefined&&value.trim().length>0}function isInvalidArgumentError(error){if(!(error instanceof Error))return false;return error.name.startsWith("Invalid")||error.name.startsWith("Unsupported")}var MAX_PATHS=1000;var MAX_PATH_BYTES=2048;var MAX_SOURCE_FILTER_VALUES=64;var MIN_LIMIT=1;var MAX_LIMIT=500;var MIN_WAIT_TIMEOUT_MS=0;var MAX_WAIT_TIMEOUT_MS2=300000;var LIST_FILE_INTENTS=["PRODUCTION","TEST","BENCHMARK","EXAMPLE","GENERATED","FIXTURE","BUILD","VENDOR"];class InvalidListRequestError extends InvalidArgumentError{field;constructor(field,message){super(message);this.field=field;this.name="InvalidListRequestError"}}function buildListParams(input){if(typeof input.target!=="string"||input.target.trim().length===0){throw invalid3("target","`target` is required.")}if(hasLoneSurrogate2(input.target)){throw invalid3("target","`target` must contain valid Unicode.")}if(typeof input.includeDetailedFields!=="boolean"){throw invalid3("includeDetailedFields","`includeDetailedFields` must be a boolean.")}const isSiteTarget=input.target.trim().startsWith("site:");const paths=normalizePaths(input.paths,isSiteTarget);const fileTypes=normalizeStringList(input.fileTypes,"fileTypes");const languages=normalizeStringList(input.languages,"languages");const intents=normalizeIntents(input.intents);const limit=normalizeInteger2(input.limit,"limit",MIN_LIMIT,MAX_LIMIT);const waitTimeoutMs=normalizeInteger2(input.waitTimeoutMs,"waitTimeoutMs",MIN_WAIT_TIMEOUT_MS,MAX_WAIT_TIMEOUT_MS2);const after=normalizeAfter(input.after);if(isSiteTarget&&(fileTypes.length>0||languages.length>0||intents.length>0)){const field=fileTypes.length>0?"fileTypes":languages.length>0?"languages":"intents";throw invalid3(field,`${field} cannot be used with a site target.`)}return{target:input.target,...paths.length>0?{paths}:{},...input.recursive!==undefined?{recursive:input.recursive}:{},...fileTypes.length>0?{fileTypes}:{},...languages.length>0?{languages}:{},...intents.length>0?{intents}:{},...limit!==undefined?{limit}:{},...after!==undefined?{after}:{},waitTimeoutMs:waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS,includeDetailedFields:input.includeDetailedFields,...input.includeTargetProvenance!==undefined?{includeTargetProvenance:input.includeTargetProvenance}:{},includeReadActions:input.includeDetailedFields||isSiteTarget}}function normalizePaths(paths,isSiteTarget){if(paths===undefined||paths.length===0)return[];if(paths.length>MAX_PATHS){throw invalid3("paths",`paths may contain at most ${MAX_PATHS} entries.`)}const normalized=[];for(const path of paths){if(path.trim().length===0){throw invalid3("paths","`paths` entries cannot be blank.")}if(hasLoneSurrogate2(path)){throw invalid3("paths","`paths` entries must contain valid Unicode.")}if(Buffer.byteLength(path,"utf8")>MAX_PATH_BYTES){throw invalid3("paths",`paths entries must be at most ${MAX_PATH_BYTES} UTF-8 bytes.`)}normalized.push(isSiteTarget&&path.startsWith("/")?path.slice(1):path)}if(isSiteTarget&&normalized.includes("")){if(normalized.length>1){throw invalid3("paths","`/` cannot be combined with other site paths.")}return[]}return normalized}function normalizeStringList(values,field){if(values===undefined||values.length===0)return[];if(values.length>MAX_SOURCE_FILTER_VALUES){throw invalid3(field,`${field} may contain at most ${MAX_SOURCE_FILTER_VALUES} entries.`)}return values.map((value)=>{if(hasLoneSurrogate2(value)){throw invalid3(field,`${field} entries must contain valid Unicode.`)}const trimmed=value.trim();if(trimmed.length===0){throw invalid3(field,`${field} entries cannot be blank.`)}return trimmed.toLowerCase()})}function normalizeIntents(values){if(values===undefined||values.length===0)return[];if(values.length>MAX_SOURCE_FILTER_VALUES){throw invalid3("intents",`intents may contain at most ${MAX_SOURCE_FILTER_VALUES} entries.`)}return values.map((value)=>{if(hasLoneSurrogate2(value)){throw invalid3("intents","`intents` entries must contain valid Unicode.")}const trimmed=value.trim();const intent=uppercaseAscii(trimmed);if(!LIST_FILE_INTENTS.some((known)=>known===intent)){throw invalid3("intents","`intents` entries must be PRODUCTION, TEST, BENCHMARK, EXAMPLE, GENERATED, FIXTURE, BUILD, or VENDOR.")}return intent})}function normalizeAfter(after){if(after===undefined||after.trim().length===0)return;if(hasLoneSurrogate2(after)){throw invalid3("after","`after` must contain valid Unicode.")}return after}function normalizeInteger2(value,field,minimum,maximum){if(value===undefined)return;if(!Number.isInteger(value)||value<minimum||value>maximum){throw invalid3(field,`${field} must be an integer from ${minimum} to ${maximum}.`)}return value}function uppercaseAscii(value){return value.replace(/[a-z]/g,(letter)=>String.fromCharCode(letter.charCodeAt(0)-32))}function hasLoneSurrogate2(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 invalid3(field,message){return new InvalidListRequestError(field,message)}function projectIndexingEstimates(entries){return entries.map((entry)=>({kind:entry.kind,targets:[...entry.targets],repositoryUrl:entry.repositoryUrl,commitSha:entry.commitSha,unavailableReason:entry.unavailableReason,estimate:entry.estimate?{lowerSeconds:entry.estimate.lowerSeconds,upperSeconds:entry.estimate.upperSeconds,elapsedSeconds:entry.estimate.elapsedSeconds,sampleCount:entry.estimate.sampleCount,source:entry.estimate.source}:undefined}))}function projectListResult(result){const projected={inventoryKind:result.inventoryKind,...result.indexingEstimates!==undefined?{indexingEstimates:projectIndexingEstimates(result.indexingEstimates)}:{},requestedTarget:result.requestedTarget,canonicalTarget:result.canonicalTarget,entries:result.entries.map((entry)=>({kind:entry.kind,path:entry.path,...entry.title!==undefined?{title:entry.title}:{},...entry.read!==undefined?{read:entry.read===null?null:projectReadAction(entry.read)}:{},...entry.browse!==undefined?{browse:entry.browse===null?null:projectBrowseAction(entry.browse)}:{},...entry.language!==undefined?{language:entry.language}:{},...entry.fileType!==undefined?{fileType:entry.fileType}:{},...entry.intent!==undefined?{intent:entry.intent}:{},...entry.byteSize!==undefined?{byteSize:entry.byteSize}:{},...entry.lineCount!==undefined?{lineCount:entry.lineCount}:{},...entry.contentHash!==undefined?{contentHash:entry.contentHash}:{}})),hasMore:result.hasMore,nextCursor:result.nextCursor,indexedVersion:result.indexedVersion,codeIndexState:result.codeIndexState,indexingStatus:result.indexingStatus,indexingRef:result.indexingRef,inventoryState:result.inventoryState,crawlStatus:result.crawlStatus,coverageState:result.coverageState,coverageReason:result.coverageReason,preparation:result.preparation===null?null:projectPreparation(result.preparation)};if(result.resolution!==undefined){projected.resolution=result.resolution===null?null:projectResolution2(result.resolution)}if(result.targetResolution!==undefined){projected.targetResolution=result.targetResolution===null?null:projectTargetResolution2(result.targetResolution)}if(result.availableVersions!==undefined){projected.availableVersions=result.availableVersions===null?null:result.availableVersions.map(projectAvailableVersion)}if(result.indexingEstimate!==undefined){projected.indexingEstimate=result.indexingEstimate===null?null:projectIndexingEstimate(result.indexingEstimate)}return projected}function projectReadAction(action){return{target:action.target,path:action.path}}function projectBrowseAction(action){return{target:action.target,paths:action.paths===null?null:[...action.paths]}}function projectAvailableVersion(version){return{version:version.version,ref:version.ref}}function projectResolution2(resolution){return{requestedVersion:resolution.requestedVersion,requestedRef:resolution.requestedRef,resolvedRef:resolution.resolvedRef,commitSha:resolution.commitSha}}function projectTargetIdentity(identity){return{...identity.kind!==undefined?{kind:identity.kind}:{},...identity.registry!==undefined?{registry:identity.registry}:{},...identity.packageName!==undefined?{packageName:identity.packageName}:{},...identity.version!==undefined?{version:identity.version}:{},...identity.repoUrl!==undefined?{repoUrl:identity.repoUrl}:{},gitRef:identity.gitRef,...identity.commitSha!==undefined?{commitSha:identity.commitSha}:{},...identity.committedAt!==undefined?{committedAt:identity.committedAt}:{}}}function projectTargetResolution2(resolution){return{requested:resolution.requested===null?null:projectTargetIdentity(resolution.requested),resolvedRequested:resolution.resolvedRequested===null?null:projectTargetIdentity(resolution.resolvedRequested),served:resolution.served===null?null:projectTargetIdentity(resolution.served),freshness:resolution.freshness,freshnessReason:resolution.freshnessReason,...resolution.indexingRef!==undefined?{indexingRef:resolution.indexingRef}:{},...resolution.availableVersions!==undefined?{availableVersions:resolution.availableVersions===null?null:resolution.availableVersions.map(projectAvailableVersion)}:{},...resolution.availableRefs!==undefined?{availableRefs:resolution.availableRefs===null?null:resolution.availableRefs.map(projectAvailableVersion)}:{},...resolution.suggestedRefs!==undefined?{suggestedRefs:resolution.suggestedRefs===null?null:resolution.suggestedRefs.map(projectAvailableVersion)}:{}}}function projectIndexingEstimate(estimate){return{lowerSeconds:estimate.lowerSeconds,upperSeconds:estimate.upperSeconds,elapsedSeconds:estimate.elapsedSeconds,sampleCount:estimate.sampleCount,source:estimate.source}}function projectPreparation(preparation){return{selected:preparation.selected,enqueued:preparation.enqueued,activeJobs:preparation.activeJobs.map((job)=>({mode:job.mode,state:job.state})),awaited:preparation.awaited.map((wait)=>({mode:wait.mode,outcome:wait.outcome}))}}function formatListText(result,options={}){const siteReadTarget=findSharedSiteReadTarget(result);const paths=result.entries.map((entry)=>formatPath(entry,result.inventoryKind));if(options.includeHeader===false)return paths.join(`
|
|
120
|
+
${CODE_GREP_GUARDRAIL}`;function createGrepTool(service){return{name:"grep",description:DESCRIPTION2,schema:schema2,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const params=buildGrepParams({targets:args.targets.map((entry)=>({target:entry.target,corpus:entry.corpus,pathSelectors:entry.path_selectors})),pattern:args.pattern,patternType:args.pattern_type,ignoreCase:args.ignore_case,contextLinesBefore:args.context_lines_before,contextLinesAfter:args.context_lines_after,maxMatches:args.max_matches,cursor:args.cursor,waitTimeoutMs:args.wait_timeout_ms,includeDetailedFields:args.format==="json"});const projected=projectGrepResult(await service.grep(params,...serviceRequestArgs(context?.signal)));return textResult(args.format==="json"?JSON.stringify(projected):formatGrepText(projected,{syntax:"mcp",useColors:false,requestedTargets:params.targets.map((target)=>target.target)}))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapGrepError(error);if(mapped.code==="INDEXING"&&mapped.retryable){mapped.details={...mapped.details,action:"Retry grep with the same targets, pattern, and other controls; set wait_timeout_ms (up to 300000) to wait for target preparation."}}return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"grep",args}})}}}}import{z as z3}from"zod";function mapListError(error,context){if(error instanceof ListGraphQLError2&&error.recovery)return mapVersionRefRecovery(error.message,error.recovery);const sessionError=mapSessionIdError(error);if(sessionError)return sessionError;const termsError=mapTermsAcceptanceError(error);if(termsError)return termsError;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 ListAccessError2){return{code:"ACCESS_DENIED",message:error.message,retryable:false}}if(error instanceof ListNetworkError2){return{code:"NETWORK",message:error.message,retryable:true}}if(error instanceof MalformedListResponseError2){return{code:"PROTOCOL_ERROR",message:error.message,retryable:false}}if(error instanceof ListBackendError2){return mapBackendError(error)}if(error instanceof ListGraphQLError2){return mapGraphQLError(error,context)}if(isInvalidArgumentError(error)){return{code:"INVALID_ARGUMENT",message:error.message,retryable:false}}if(error instanceof Error){return{code:"UNKNOWN",message:error.message,retryable:false}}return{code:"UNKNOWN",message:"Unknown error",retryable:false}}function mapBackendError(error){const details={};if(typeof error.status==="number")details.status=error.status;if(isNonempty(error.graphqlCode))details.graphqlCode=error.graphqlCode;const build=(code,defaultRetryable)=>({code,message:error.message,retryable:error.retryable??defaultRetryable,details:Object.keys(details).length>0?details:undefined});switch(error.graphqlCode){case"TIMEOUT":return build("TIMEOUT",true);case"RATE_LIMITED":return build("RATE_LIMITED",true);default:return build("BACKEND_ERROR",false)}}function mapGraphQLError(error,context){const details=graphQLErrorDetails(error);const build=(code,defaultRetryable,message=error.message,extraDetails)=>{const allDetails={...details,...extraDetails};return{code,message,retryable:error.retryable??defaultRetryable,details:Object.keys(allDetails).length>0?allDetails:undefined}};switch(error.code){case"NOT_FOUND":return build("NOT_FOUND",false);case"INDEXING":case"PACKAGE_INDEXING":return build("INDEXING",true);case"VALIDATION_ERROR":{return build("INVALID_ARGUMENT",false,context?.hasAfter?`${error.message} Retry once without \`after\`; if validation still fails, correct the request.`:`${error.message} Correct the request and try again.`)}case"SOURCE_INVENTORY_SCOPE_UNAVAILABLE":return mapScopeUnavailableError(error,build);case"LIST_UNSUPPORTED_API":return build("LIST_UNSUPPORTED_API",false);case"LIST_PAGE_TOO_LARGE":return build("LIST_PAGE_TOO_LARGE",false);case"TIMEOUT":return build("TIMEOUT",true);case"RATE_LIMITED":return build("RATE_LIMITED",true);default:return build("BACKEND_ERROR",false)}}function mapScopeUnavailableError(error,build){const extraDetails={};const repoUrl=nonemptyValue(error.repoUrl);const commitSha=nonemptyValue(error.commitSha);if(repoUrl!==undefined)extraDetails.repoUrl=repoUrl;if(commitSha!==undefined)extraDetails.commitSha=commitSha;if(repoUrl===undefined||commitSha===undefined){return build("SOURCE_INVENTORY_SCOPE_UNAVAILABLE",false,error.message,extraDetails)}const action=`${repoUrl}@${commitSha}`;extraDetails.action=action;return build("SOURCE_INVENTORY_SCOPE_UNAVAILABLE",false,`${error.message} The repository-wide alternative ${action} broadens scope; use it only if those broader results are acceptable.`,extraDetails)}function graphQLErrorDetails(error){const details={};if(isNonempty(error.code))details.graphqlCode=error.code;if(isNonempty(error.indexingRef))details.indexingRef=error.indexingRef;if(isNonempty(error.hint))details.hint=error.hint;if(isNonempty(error.repoUrl))details.repoUrl=error.repoUrl;if(isNonempty(error.commitSha))details.commitSha=error.commitSha;if(error.indexingMetadata?.indexingEstimate)details.indexingEstimate=error.indexingMetadata.indexingEstimate;if(error.indexingMetadata?.availableVersions)details.availableVersions=error.indexingMetadata.availableVersions;if(error.indexingMetadata?.package)details.package=error.indexingMetadata.package;return details}function nonemptyValue(value){return isNonempty(value)?value:undefined}function isNonempty(value){return value!==undefined&&value.trim().length>0}function isInvalidArgumentError(error){if(!(error instanceof Error))return false;return error.name.startsWith("Invalid")||error.name.startsWith("Unsupported")}var MAX_PATHS=1000;var MAX_PATH_BYTES=2048;var MAX_SOURCE_FILTER_VALUES=64;var MIN_LIMIT=1;var MAX_LIMIT=500;var MIN_WAIT_TIMEOUT_MS=0;var MAX_WAIT_TIMEOUT_MS2=300000;var LIST_FILE_INTENTS=["PRODUCTION","TEST","BENCHMARK","EXAMPLE","GENERATED","FIXTURE","BUILD","VENDOR"];class InvalidListRequestError extends InvalidArgumentError{field;constructor(field,message){super(message);this.field=field;this.name="InvalidListRequestError"}}function buildListParams(input){if(typeof input.target!=="string"||input.target.trim().length===0){throw invalid3("target","`target` is required.")}if(hasLoneSurrogate2(input.target)){throw invalid3("target","`target` must contain valid Unicode.")}if(typeof input.includeDetailedFields!=="boolean"){throw invalid3("includeDetailedFields","`includeDetailedFields` must be a boolean.")}const isSiteTarget=input.target.trim().startsWith("site:");const paths=normalizePaths(input.paths,isSiteTarget);const fileTypes=normalizeStringList(input.fileTypes,"fileTypes");const languages=normalizeStringList(input.languages,"languages");const intents=normalizeIntents(input.intents);const limit=normalizeInteger2(input.limit,"limit",MIN_LIMIT,MAX_LIMIT);const waitTimeoutMs=normalizeInteger2(input.waitTimeoutMs,"waitTimeoutMs",MIN_WAIT_TIMEOUT_MS,MAX_WAIT_TIMEOUT_MS2);const after=normalizeAfter(input.after);if(isSiteTarget&&(fileTypes.length>0||languages.length>0||intents.length>0)){const field=fileTypes.length>0?"fileTypes":languages.length>0?"languages":"intents";throw invalid3(field,`${field} cannot be used with a site target.`)}return{target:input.target,...paths.length>0?{paths}:{},...input.recursive!==undefined?{recursive:input.recursive}:{},...fileTypes.length>0?{fileTypes}:{},...languages.length>0?{languages}:{},...intents.length>0?{intents}:{},...limit!==undefined?{limit}:{},...after!==undefined?{after}:{},waitTimeoutMs:waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS,includeDetailedFields:input.includeDetailedFields,...input.includeTargetProvenance!==undefined?{includeTargetProvenance:input.includeTargetProvenance}:{},includeReadActions:input.includeDetailedFields||isSiteTarget}}function normalizePaths(paths,isSiteTarget){if(paths===undefined||paths.length===0)return[];if(paths.length>MAX_PATHS){throw invalid3("paths",`paths may contain at most ${MAX_PATHS} entries.`)}const normalized=[];for(const path of paths){if(path.trim().length===0){throw invalid3("paths","`paths` entries cannot be blank.")}if(hasLoneSurrogate2(path)){throw invalid3("paths","`paths` entries must contain valid Unicode.")}if(Buffer.byteLength(path,"utf8")>MAX_PATH_BYTES){throw invalid3("paths",`paths entries must be at most ${MAX_PATH_BYTES} UTF-8 bytes.`)}normalized.push(isSiteTarget&&path.startsWith("/")?path.slice(1):path)}if(isSiteTarget&&normalized.includes("")){if(normalized.length>1){throw invalid3("paths","`/` cannot be combined with other site paths.")}return[]}return normalized}function normalizeStringList(values,field){if(values===undefined||values.length===0)return[];if(values.length>MAX_SOURCE_FILTER_VALUES){throw invalid3(field,`${field} may contain at most ${MAX_SOURCE_FILTER_VALUES} entries.`)}return values.map((value)=>{if(hasLoneSurrogate2(value)){throw invalid3(field,`${field} entries must contain valid Unicode.`)}const trimmed=value.trim();if(trimmed.length===0){throw invalid3(field,`${field} entries cannot be blank.`)}return trimmed.toLowerCase()})}function normalizeIntents(values){if(values===undefined||values.length===0)return[];if(values.length>MAX_SOURCE_FILTER_VALUES){throw invalid3("intents",`intents may contain at most ${MAX_SOURCE_FILTER_VALUES} entries.`)}return values.map((value)=>{if(hasLoneSurrogate2(value)){throw invalid3("intents","`intents` entries must contain valid Unicode.")}const trimmed=value.trim();const intent=uppercaseAscii(trimmed);if(!LIST_FILE_INTENTS.some((known)=>known===intent)){throw invalid3("intents","`intents` entries must be PRODUCTION, TEST, BENCHMARK, EXAMPLE, GENERATED, FIXTURE, BUILD, or VENDOR.")}return intent})}function normalizeAfter(after){if(after===undefined||after.trim().length===0)return;if(hasLoneSurrogate2(after)){throw invalid3("after","`after` must contain valid Unicode.")}return after}function normalizeInteger2(value,field,minimum,maximum){if(value===undefined)return;if(!Number.isInteger(value)||value<minimum||value>maximum){throw invalid3(field,`${field} must be an integer from ${minimum} to ${maximum}.`)}return value}function uppercaseAscii(value){return value.replace(/[a-z]/g,(letter)=>String.fromCharCode(letter.charCodeAt(0)-32))}function hasLoneSurrogate2(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 invalid3(field,message){return new InvalidListRequestError(field,message)}function projectIndexingEstimates(entries){return entries.map((entry)=>({kind:entry.kind,targets:[...entry.targets],repositoryUrl:entry.repositoryUrl,commitSha:entry.commitSha,unavailableReason:entry.unavailableReason,estimate:entry.estimate?{lowerSeconds:entry.estimate.lowerSeconds,upperSeconds:entry.estimate.upperSeconds,elapsedSeconds:entry.estimate.elapsedSeconds,sampleCount:entry.estimate.sampleCount,source:entry.estimate.source}:undefined}))}function projectListResult(result){const projected={inventoryKind:result.inventoryKind,...result.indexingEstimates!==undefined?{indexingEstimates:projectIndexingEstimates(result.indexingEstimates)}:{},requestedTarget:result.requestedTarget,canonicalTarget:result.canonicalTarget,entries:result.entries.map((entry)=>({kind:entry.kind,path:entry.path,...entry.title!==undefined?{title:entry.title}:{},...entry.read!==undefined?{read:entry.read===null?null:projectReadAction(entry.read)}:{},...entry.browse!==undefined?{browse:entry.browse===null?null:projectBrowseAction(entry.browse)}:{},...entry.language!==undefined?{language:entry.language}:{},...entry.fileType!==undefined?{fileType:entry.fileType}:{},...entry.intent!==undefined?{intent:entry.intent}:{},...entry.byteSize!==undefined?{byteSize:entry.byteSize}:{},...entry.lineCount!==undefined?{lineCount:entry.lineCount}:{},...entry.contentHash!==undefined?{contentHash:entry.contentHash}:{}})),hasMore:result.hasMore,nextCursor:result.nextCursor,indexedVersion:result.indexedVersion,codeIndexState:result.codeIndexState,indexingStatus:result.indexingStatus,indexingRef:result.indexingRef,inventoryState:result.inventoryState,crawlStatus:result.crawlStatus,coverageState:result.coverageState,coverageReason:result.coverageReason,preparation:result.preparation===null?null:projectPreparation(result.preparation)};if(result.resolution!==undefined){projected.resolution=result.resolution===null?null:projectResolution2(result.resolution)}if(result.targetResolution!==undefined){projected.targetResolution=result.targetResolution===null?null:projectTargetResolution2(result.targetResolution)}if(result.availableVersions!==undefined){projected.availableVersions=result.availableVersions===null?null:result.availableVersions.map(projectAvailableVersion)}if(result.indexingEstimate!==undefined){projected.indexingEstimate=result.indexingEstimate===null?null:projectIndexingEstimate(result.indexingEstimate)}return projected}function projectReadAction(action){return{target:action.target,path:action.path}}function projectBrowseAction(action){return{target:action.target,paths:action.paths===null?null:[...action.paths]}}function projectAvailableVersion(version){return{version:version.version,ref:version.ref}}function projectResolution2(resolution){return{requestedVersion:resolution.requestedVersion,requestedRef:resolution.requestedRef,resolvedRef:resolution.resolvedRef,commitSha:resolution.commitSha}}function projectTargetIdentity(identity){return{...identity.kind!==undefined?{kind:identity.kind}:{},...identity.registry!==undefined?{registry:identity.registry}:{},...identity.packageName!==undefined?{packageName:identity.packageName}:{},...identity.version!==undefined?{version:identity.version}:{},...identity.repoUrl!==undefined?{repoUrl:identity.repoUrl}:{},gitRef:identity.gitRef,...identity.commitSha!==undefined?{commitSha:identity.commitSha}:{},...identity.committedAt!==undefined?{committedAt:identity.committedAt}:{}}}function projectTargetResolution2(resolution){return{requested:resolution.requested===null?null:projectTargetIdentity(resolution.requested),resolvedRequested:resolution.resolvedRequested===null?null:projectTargetIdentity(resolution.resolvedRequested),served:resolution.served===null?null:projectTargetIdentity(resolution.served),freshness:resolution.freshness,freshnessReason:resolution.freshnessReason,...resolution.indexingRef!==undefined?{indexingRef:resolution.indexingRef}:{},...resolution.availableVersions!==undefined?{availableVersions:resolution.availableVersions===null?null:resolution.availableVersions.map(projectAvailableVersion)}:{},...resolution.availableRefs!==undefined?{availableRefs:resolution.availableRefs===null?null:resolution.availableRefs.map(projectAvailableVersion)}:{},...resolution.suggestedRefs!==undefined?{suggestedRefs:resolution.suggestedRefs===null?null:resolution.suggestedRefs.map(projectAvailableVersion)}:{}}}function projectIndexingEstimate(estimate){return{lowerSeconds:estimate.lowerSeconds,upperSeconds:estimate.upperSeconds,elapsedSeconds:estimate.elapsedSeconds,sampleCount:estimate.sampleCount,source:estimate.source}}function projectPreparation(preparation){return{selected:preparation.selected,enqueued:preparation.enqueued,activeJobs:preparation.activeJobs.map((job)=>({mode:job.mode,state:job.state})),awaited:preparation.awaited.map((wait)=>({mode:wait.mode,outcome:wait.outcome}))}}function formatListText(result,options={}){const siteReadTarget=findSharedSiteReadTarget(result);const paths=result.entries.map((entry)=>formatPath(entry,result.inventoryKind));if(options.includeHeader===false)return paths.join(`
|
|
116
121
|
`);const pending=Boolean(result.indexingEstimates?.length||result.codeIndexState==="INDEXING");const isSource=result.inventoryKind==="SOURCE";const resolution=result.targetResolution;const sourceBase=result.canonicalTarget??result.requestedTarget;const sourceRows=isSource?resolutionSourceFacts(resolution):[];if(isSource&&!sourceRows.length&&(!resolution&&(!pending||paths.length>0)||resolution?.freshness==="current")){sourceRows.push({target:sourceBase})}const lines=isSource?[...paths.length?[]:[pending?"No files available yet.":"No files."],...renderSourceSection(sourceRows,{width:options.width}),...paths.length?[`Read files: ${formatSourceReadAction(sourceBase,options.syntax)}`]:[],...paths]:[...paths.length?[]:[pending?"No pages available yet.":"No pages."],...paths.length||!pending?renderSourceSection([{target:siteReadTarget??result.requestedTarget,qualifiers:["hosted documentation"]}],{width:options.width}):[],...siteReadTarget?[formatSiteReadGuidance(siteReadTarget,options.syntax)]:[],...paths];if(pending){lines.push(...result.indexingEstimates?.length?renderPreparationSection(result.indexingEstimates,isSource?{resolutions:resolution?[resolution]:[],width:options.width}:{width:options.width}):["","Preparing:",...wrapTerminalProse(` - ${escapeLineValue(result.requestedTarget)} (indexing, no estimate available)`,options.width)])}if(isSource){const details=renderResolutionDetails(resolution,result.indexingEstimates,{width:options.width});if(details.length)lines.push("",...details)}if(result.nextCursor){const continuation=[result.indexingEstimates?.length?"More results available now: repeat this list, adding:":"More results: repeat this list, adding:",options.syntax==="mcp"?` after=${JSON.stringify(result.nextCursor)}`:` --after ${shellQuoteExact(result.nextCursor)}`];lines.push("",...continuation.map((line)=>dim(line,options.useColors===true)))}if(pending){lines.push("",formatPreparationRetry({operation:"list",syntax:options.syntax??"cli",waitMs:indexingWaitMs(result.indexingEstimates),hasAfter:options.hasAfter}))}return lines.join(`
|
|
117
122
|
`)}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"],[`
|
|
118
|
-
`,"\\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
|
|
123
|
+
`,"\\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.
|
|
119
124
|
|
|
120
125
|
`+"Replaces code_files and docs_list. 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&®istry!=="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(`
|
|
121
126
|
`)}
|
|
@@ -123,7 +128,7 @@ ${CODE_GREP_GUARDRAIL}`;function createGrepTool(service){return{name:"grep",desc
|
|
|
123
128
|
`);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(`
|
|
124
129
|
`);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 instead; `verbose` is its deprecated alias and `body_lines` requests a legacy original-note preview. `omit_bodies:true` shows only the timeline. Original-note and timeline views skip classification and ignore `changes`.";var DESCRIPTION4=`${DESCRIPTION_BASE}
|
|
125
130
|
|
|
126
|
-
${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};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(`
|
|
131
|
+
${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(`
|
|
127
132
|
|
|
128
133
|
`)}
|
|
129
134
|
`}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(`
|
|
@@ -142,12 +147,12 @@ ${bullets}`}));return lines.join(`
|
|
|
142
147
|
`)}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(`
|
|
143
148
|
`)}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(`
|
|
144
149
|
`)}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(`
|
|
145
|
-
`).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"&®istry==="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,"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(`
|
|
150
|
+
`).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"&®istry==="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(`
|
|
146
151
|
`))}if(options.verbose){const verbose=buildVerboseSections(lean,useColors);if(verbose.length>0)sections.push(verbose)}return`${sections.join(`
|
|
147
152
|
|
|
148
153
|
`)}
|
|
149
154
|
`}function resolveWidth(explicit){if(typeof explicit==="number"&&explicit>0){return Math.min(explicit,80)}const columns=process.stdout?.columns;if(typeof columns==="number"&&columns>0){return Math.min(columns,80)}return 80}function wrapText(text,width){const safeWidth=Math.max(1,width);const words=text.split(/\s+/);const lines=[];let current="";for(const word of words){if(word.length>safeWidth){if(current.length>0){lines.push(current);current=""}for(let offset=0;offset<word.length;offset+=safeWidth){const chunk=word.slice(offset,offset+safeWidth);if(chunk.length===safeWidth||offset+safeWidth<word.length){lines.push(chunk)}else{current=chunk}}continue}if(current.length===0){current=word;continue}if(current.length+1+word.length>safeWidth){lines.push(current);current=word}else{current+=` ${word}`}}if(current.length>0)lines.push(current);return lines.join(`
|
|
150
|
-
`)}function buildFieldList(lean,summary,useColors,now,verbose,width){const fields=[];if(lean.repository){const repositoryParts=[colorize(lean.repository,"cyan",useColors)];const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity)repositoryParts.push(`(${githubPopularity})`);fields.push({label:"Repository",value:repositoryParts.join(" ")})}else{const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity){fields.push({label:"GitHub",value:githubPopularity})}}if(lean.homepage){fields.push({label:"Homepage",value:colorize(lean.homepage,"cyan",useColors)})}const publishedRelative=toRelativeDate(summary.package.latestVersionPublishedAt,now);if(publishedRelative){fields.push({label:"Published",value:publishedRelative})}if(verbose&&lean.versionCount!==undefined){fields.push({label:"Versions",value:`${formatCompactNumber(lean.versionCount)} published`})}if(lean.downloads?.lastMonth!==undefined){const refreshed=verbose&&lean.downloads.refreshedAt?`; refreshed ${lean.downloads.refreshedAt}`:"";fields.push({label:"Downloads",value:`${formatCompactNumber(lean.downloads.lastMonth)} / month${refreshed}`})}else if(lean.downloads?.total!==undefined){const refreshed=verbose&&lean.downloads.refreshedAt?`; refreshed ${lean.downloads.refreshedAt}`:"";fields.push({label:"Downloads",value:`${formatCompactNumber(lean.downloads.total)} total${refreshed}`})}if(lean.advisoryHistory){fields.push({label:"Vulnerabilities",value:formatVulnerabilityStatus(lean.vulnerabilities,lean.advisoryHistory)})}const labelWidth=Math.max(10,...fields.map((field)=>field.label.length));const valueIndent=" ".repeat(labelWidth+2);const valueWidth=Math.max(1,width-valueIndent.length);const lines=fields.flatMap((field)=>{const valueLines=field.label==="Vulnerabilities"?field.value.split(`
|
|
155
|
+
`)}function buildFieldList(lean,summary,useColors,now,verbose,width){const fields=[];if(lean.repository){const repositoryParts=[colorize(lean.repository,"cyan",useColors)];const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity)repositoryParts.push(`(${githubPopularity})`);fields.push({label:"Repository",value:repositoryParts.join(" ")})}else{const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity){fields.push({label:"GitHub",value:githubPopularity})}}if(lean.registryRepository){fields.push({label:"Package registry",value:`${lean.registryRepository.name} (${colorize(lean.registryRepository.url,"cyan",useColors)})`})}if(lean.homepage){fields.push({label:"Homepage",value:colorize(lean.homepage,"cyan",useColors)})}const publishedRelative=toRelativeDate(summary.package.latestVersionPublishedAt,now);if(publishedRelative){fields.push({label:"Published",value:publishedRelative})}if(verbose&&lean.versionCount!==undefined){fields.push({label:"Versions",value:`${formatCompactNumber(lean.versionCount)} published`})}if(lean.downloads?.lastMonth!==undefined){const refreshed=verbose&&lean.downloads.refreshedAt?`; refreshed ${lean.downloads.refreshedAt}`:"";fields.push({label:"Downloads",value:`${formatCompactNumber(lean.downloads.lastMonth)} / month${refreshed}`})}else if(lean.downloads?.total!==undefined){const refreshed=verbose&&lean.downloads.refreshedAt?`; refreshed ${lean.downloads.refreshedAt}`:"";fields.push({label:"Downloads",value:`${formatCompactNumber(lean.downloads.total)} total${refreshed}`})}if(lean.advisoryHistory){fields.push({label:"Vulnerabilities",value:formatVulnerabilityStatus(lean.vulnerabilities,lean.advisoryHistory)})}const labelWidth=Math.max(10,...fields.map((field)=>field.label.length));const valueIndent=" ".repeat(labelWidth+2);const valueWidth=Math.max(1,width-valueIndent.length);const lines=fields.flatMap((field)=>{const valueLines=field.label==="Vulnerabilities"?field.value.split(`
|
|
151
156
|
`).flatMap((value)=>wrapText(value,valueWidth).split(`
|
|
152
157
|
`)):[field.value];return valueLines.map((value,index)=>index===0?`${field.label.padEnd(labelWidth)} ${value}`:`${valueIndent}${value}`)});return lines}function formatGithubPopularity(github){if(!github)return;const parts=[];if(github.archived){parts.push("[ARCHIVED]")}if(github.stars!==undefined){parts.push(`${formatCompactNumber(github.stars)} stars`)}if(github.forks!==undefined){parts.push(`${formatCompactNumber(github.forks)} forks`)}if(github.openIssues!==undefined){parts.push(`${formatCompactNumber(github.openIssues)} issues`)}return parts.length>0?parts.join(", "):undefined}function formatVulnerabilityStatus(vulns,history){let latest;if(!vulns){latest="Latest: unavailable"}else if(vulns.total===0){latest="Latest: none affected"}else{latest=`Latest: ${vulns.total} affected`}const historyNoun=history.total===1?"advisory":"advisories";const inconsistent=vulns!==undefined&&history.total<vulns.total;const historySuffix=inconsistent?" (inconsistent backend evidence)":"";const historyText=history.total===0?`History: none known across all versions${historySuffix}`:`History: ${history.total} known ${historyNoun} across all versions${historySuffix}`;return`${latest}
|
|
153
158
|
${historyText}`}function buildVerboseSections(lean,useColors){const blocks=[];if(lean.github){const github=formatVerboseGithub(lean.github,useColors);if(github)blocks.push(github)}if(lean.vulnerabilities?.recent&&lean.vulnerabilities.recent.length>0){blocks.push(formatVerboseAdvisories(lean.vulnerabilities.recent,useColors))}if(lean.recentChanges&&lean.recentChanges.length>0){blocks.push(formatVerboseChanges(lean.recentChanges,useColors))}return blocks.join(`
|
|
@@ -166,7 +171,7 @@ ${PKG_INFO_GUARDRAIL}`;function createPackageSummaryTool(service){return{name:"p
|
|
|
166
171
|
`).trimEnd()}
|
|
167
172
|
`}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&¤t.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 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`);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.`+`
|
|
168
173
|
|
|
169
|
-
${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)};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(`
|
|
174
|
+
${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(`
|
|
170
175
|
`)}
|
|
171
176
|
`}const blocks=[];const headerBlock=[headerLine];if(requestedLine)headerBlock.push(requestedLine);headerBlock.push(...filterLines);headerBlock.push(formatSummaryLine(payload,useColors));const selectedAdvisoryCount=payload.advisories?.length??0;const scope=payload.filter?.advisoryScope;const selectedCountLine=formatSelectedAdvisoryCountLine(selectedAdvisoryCount,scope);if(selectedCountLine)headerBlock.push(selectedCountLine);const breakdown=scope===undefined?formatBreakdownLine(payload.summary,useColors,options.terminalWidth):undefined;if(breakdown)headerBlock.push(breakdown);headerBlock.push(...formatAssessmentLines(payload,surface,options.terminalWidth));blocks.push(headerBlock.join(`
|
|
172
177
|
`));if(payload.advisories&&payload.advisories.length>0){const rangeLimit=resolveAffectedRangesLimit(options.terminalWidth);blocks.push(formatAdvisoryList(payload.advisories,verbose,useColors,rangeLimit,surface,options.terminalWidth))}const upgradeFooter=formatUpgradeFooter(payload.upgradePaths);if(upgradeFooter)blocks.push(upgradeFooter);if(transitiveBlock)blocks.push(transitiveBlock);return`${blocks.join(`
|
|
@@ -191,14 +196,14 @@ ${PKG_VULNS_GUARDRAIL}`;function createPackageVulnerabilitiesTool(service){retur
|
|
|
191
196
|
`)}function buildHeader4(envelope){const parts=[`read${SEP2}${envelope.docsReadTarget}`];if(envelope.title)parts.push(envelope.title);const range=buildRange2(envelope);if(range)parts.push(range);return parts.join(SEP2)}function buildRange2(envelope){if(envelope.startLine!==undefined&&envelope.endLine!==undefined){return envelope.totalLines!==undefined?`lines ${envelope.startLine}-${envelope.endLine}/${envelope.totalLines}`:`lines ${envelope.startLine}-${envelope.endLine}`}if(envelope.totalLines!==undefined)return`${envelope.totalLines} lines`;return}function renderReadTarget(action,syntax="mcp"){return syntax==="cli"?renderCliReadTarget(action):renderMcpReadTarget(action)}function renderMcpReadTarget(action){const parts=[`read target=${JSON.stringify(action.target)}`];if(action.path!==undefined){parts.push(`path=${JSON.stringify(action.path)}`)}if(action.selector!==undefined){parts.push(`selector=${JSON.stringify(action.selector)}`)}if(action.startLine!==undefined){parts.push(`start_line=${action.startLine}`)}if(action.endLine!==undefined){parts.push(`end_line=${action.endLine}`)}return parts.join(" ")}function renderCliReadTarget(action){const parts=[`githits read ${shellQuote(action.target)}`];const pathNeedsTerminator=action.path?.startsWith("-")===true;if(action.path!==undefined&&!pathNeedsTerminator){parts.push(shellQuote(action.path))}if(action.selector!==undefined){parts.push("--selector",shellQuote(action.selector))}if(action.startLine!==undefined||action.endLine!==undefined){parts.push("--lines",`${action.startLine??""}-${action.endLine??""}`)}if(action.path!==undefined&&pathNeedsTerminator){parts.push("--",shellQuote(action.path))}return parts.join(" ")}function capSearchReadTarget(action,evidence){if(action.path===undefined||action.startLine===undefined||action.endLine===undefined||action.endLine-action.startLine+1<=MCP_READ_MAX_SPAN)return action;return{...action,...boundLargeReadRange({startLine:action.startLine,endLine:action.endLine},evidence)}}function buildReadContinuationHint(action,nextStartLine,returnedEndLine){if(!action)return"Continuation unavailable: missing read target.";const continuation={target:action.target,...action.path!==undefined?{path:action.path}:{},startLine:nextStartLine,endLine:returnedEndLine};return`Continue with ${renderReadTarget(continuation)}.`}function boundLargeReadRange(bounds,evidence){const latestStart=bounds.endLine-MCP_READ_MAX_SPAN+1;const evidenceSpan=evidence?evidence.endLine-evidence.startLine+1:undefined;if(evidence&&typeof evidenceSpan==="number"&&evidenceSpan<=MCP_READ_MAX_SPAN){const leadingContext=Math.floor((MCP_READ_MAX_SPAN-evidenceSpan)/2);const startLine=Math.min(Math.max(bounds.startLine,evidence.startLine-leadingContext),latestStart);return{startLine,endLine:startLine+MCP_READ_MAX_SPAN-1}}const focusedLine=evidence?.matchLine??evidence?.startLine;const leadingContext=Math.floor((MCP_READ_MAX_SPAN-1)/2);const startLine=Math.min(Math.max(bounds.startLine,focusedLine===undefined?bounds.startLine:focusedLine-leadingContext),latestStart);return{startLine,endLine:startLine+MCP_READ_MAX_SPAN-1}}function formatReadResult(response,request,format){const hash=request.target.indexOf("#");const codeFragment=response.source!=="docs"&&request.selector===undefined&&hash>=0?request.target.slice(hash+1):undefined;const followUpTarget=codeFragment===undefined?request.target:request.target.slice(0,hash);if(response.source==="symbol_resolution"){const result=response.result;const selector=request.selector??codeFragment??"";const cli=format==="cli-text"||format==="cli-json";const searchAction=cli?`githits search ${JSON.stringify(selector)} --in ${JSON.stringify(followUpTarget)} --source symbol`:`search({"query":${JSON.stringify(selector)},"target":${JSON.stringify(followUpTarget)},"source":"symbol"})`;const action=result.status==="SNAPSHOT_UNSUPPORTED"?cli?`Use ${searchAction}, then githits read <target> <path> --start N --end M with the returned file and range.`:`Use ${searchAction}, then read the returned exact path with start_line and end_line.`:result.status==="NOT_FOUND"&&result.suggestions.length===0?`Search related names with ${searchAction} or inspect the indexed files.`:undefined;const payload={status:result.status,candidates:result.candidates,suggestions:result.suggestions,hasMore:result.hasMore,repoUrl:result.repoUrl,gitRef:result.gitRef,codeIndexState:result.codeIndexState,...result.message?{message:result.message}:{},target:request.target,selector,...action?{action}:{}};if(format==="mcp-json"||format==="cli-json")return JSON.stringify(payload);const lines=[`${result.status}: ${selector}`,`Repository: ${result.repoUrl}@${result.gitRef}`];if(result.message)lines.push(result.message);for(const candidate of result.candidates){lines.push(`Candidate: ${candidate.qualifiedPath??candidate.name??selector} | ${candidate.filePath??"?"}:${candidate.startLine??"?"}-${candidate.endLine??"?"}`)}for(const suggestion of result.suggestions){lines.push(`Suggestion: ${suggestion.qualifiedPath??suggestion.name} | ${suggestion.filePath??"?"}${suggestion.reason?` | ${suggestion.reason}`:""}`)}if(result.hasMore)lines.push(codeFragment===undefined?"More matches exist; narrow with an exact path or qualified selector.":"More matches exist; narrow with an exact path.");if(action)lines.push(action);return`${lines.join(`
|
|
192
197
|
`)}
|
|
193
198
|
`}if(response.source==="code"){const requested=response.result.targetResolution?.requested;const payload=buildReadFileSuccessPayload(response.result,{registry:requested?.registry?.toLowerCase(),name:requested?.packageName,repoUrl:requested?.repoUrl,gitRef:requested?.gitRef,requestedFilePath:request.path??""});if((format==="mcp-text"||format==="mcp-json")&&!payload.isBinary&&payload.content&&payload.startLine!==undefined){const maxLines=request.endLine===undefined?MCP_READ_DEFAULT_SPAN:MCP_READ_MAX_SPAN;const lines=splitReadFileContentLines(payload);if(lines.length>maxLines){const returnedEndLine=response.result.endLine??payload.startLine+lines.length-1;payload.content=lines.slice(0,maxLines).join(`
|
|
194
|
-
`);payload.endLine=payload.startLine+maxLines-1;payload.hint=buildReadContinuationHint(response.result.readTarget,payload.endLine+1,returnedEndLine)}}if(format==="mcp-json"||format==="cli-json")return JSON.stringify(payload);return format==="cli-text"?formatReadFileTerminal(payload,{useColors:request.useColors??false,verbose:request.verbose,width:request.width}):renderReadFileText(payload)}const maxOutputLines=format==="mcp-text"?request.endLine===undefined?MCP_READ_DEFAULT_SPAN:MCP_READ_MAX_SPAN:undefined;const payload=buildReadPackageDocSuccessPayload(response.result,request.target,maxOutputLines);if(maxOutputLines!==undefined&&payload.endLine!==undefined&&response.result.contentRange.endLine!==undefined&&payload.endLine<response.result.contentRange.endLine){payload.hint=buildReadContinuationHint(response.result.readTarget,payload.endLine+1,response.result.contentRange.endLine)}if(format==="mcp-json"||format==="cli-json")return JSON.stringify(payload);return format==="cli-text"?formatReadPackageDocTerminal(payload,{useColors:request.useColors??false,verbose:request.verbose}):renderReadPackageDocText(payload)}function createReadFileServiceAdapter(readService,target,signal){return{readFile:async(params)=>{const response=await readService.read({target,path:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs},...serviceRequestArgs(signal));if(response.source!=="code"){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return response.result}}}function isExactPathAuthorityError(mapped){return mapped.code==="FILE_PATH_EXCLUDED"||mapped.code==="SOURCE_FILE_INVENTORY_UNKNOWN"}function withExactPathAuthorityRecovery(mapped){if(!isExactPathAuthorityError(mapped)||mapped.details?.filePath===undefined){return mapped}const prefix=buildContainingPathPrefix(mapped.details.filePath);const listing=prefix===""?"Use `list` without `paths`":`Use \`list\` with \`paths: ${JSON.stringify([prefix])}\``;const reason=mapped.code==="FILE_PATH_EXCLUDED"?"This path is excluded from the indexed source.":"The source inventory cannot verify this path.";return{...mapped,details:{...mapped.details,action:`${reason} ${listing} to list indexed paths available to \`read\`.`}}}function buildContainingPathPrefix(filePath){const trimmed=filePath.trim();const slash=trimmed.lastIndexOf("/");return slash===-1?"":trimmed.slice(0,slash+1)}function buildPathPrefixSuggestion(requestedPath){const trimmed=requestedPath.trim();if(trimmed==="")return"";if(trimmed.endsWith("/"))return trimmed;const slash=trimmed.lastIndexOf("/");const basename=slash===-1?trimmed:trimmed.slice(slash+1);if(!basename.includes("."))return`${trimmed}/`;return slash===-1?"":trimmed.slice(0,slash+1)}function looksLikeMissingFileMessage(message){const lower=message.toLowerCase();return lower.includes("file not found")||lower.includes("path not found")||lower.includes("path doesn't resolve")||lower.includes("path does not resolve")}function withReadFileRecovery(mapped,requestedPath){if(isExactPathAuthorityError(mapped)){return withExactPathAuthorityRecovery(mapped)}if(mapped.code!=="FILE_NOT_FOUND"&&(mapped.code!=="NOT_FOUND"||!looksLikeMissingFileMessage(mapped.message))){return mapped}const recoveryPath=mapped.details?.filePath??requestedPath;return{...mapped,details:{...mapped.details,action:buildReadFileNotFoundAction(recoveryPath,mapped.code==="FILE_NOT_FOUND")}}}function buildReadFileNotFoundAction(requestedPath,exactFilePath){const prefix=exactFilePath?buildContainingPathPrefix(requestedPath):buildPathPrefixSuggestion(requestedPath);const preamble=exactFilePath?"`read` requires an indexed exact file path. ":"With path, `read` reads files only, not directories. ";const listing=prefix===""?"Use `list` without `paths`":`Use \`list\` with \`paths: ${JSON.stringify([prefix])}\``;return`${preamble}${listing} to list valid indexed paths, then `+"pass an emitted `path` back to `read`."}function buildReadFileParams(input){const filePath=input.filePath?.trim()??"";if(!filePath){throw new InvalidPackageSpecError("`file_path` is required — pass the path to the file within the package or repo.")}if(filePath.endsWith("/")){throw new InvalidPackageSpecError(`\`file_path\` must be an exact file path, not a directory prefix. Use \`list\` with \`paths: ${JSON.stringify([filePath])}\` to list files, then pass an emitted \`path\` to \`read\`.`)}validateReadRange(input.startLine,input.endLine);const{startLine,endLine}=input;const waitTimeoutMs=normalizeReadWaitTimeoutMs(input.waitTimeoutMs);return{params:{target:input.target,filePath,startLine,endLine,waitTimeoutMs}}}import{z as z9}from"zod";var codeTargetSchema=z9.string().min(1).describe("Compact target: `npm:react@version` or `github:facebook/react@ref`. Omit the suffix for the latest package version or repository default branch; a ref may be a branch, tag, or commit. `#` is for semantic fragments. Package targets scope to the package subpath; repository targets cover the full repository.");function resolveCodeTarget(target,context,format){try{return parseCodeNavigationTargetSpec(target)}catch(error){return mcpMappedErrorResult(mapCodeNavigationError(error),context,format)}}function deriveBoundedRange(startLine,endLine){const start=startLine??1;if(endLine===undefined){return{startLine:start,endLine:start+MCP_READ_DEFAULT_SPAN-1,capped:true,spanLimit:MCP_READ_DEFAULT_SPAN}}const span=endLine-start+1;if(span>MCP_READ_MAX_SPAN){return{startLine:start,endLine:start+MCP_READ_MAX_SPAN-1,capped:true,spanLimit:MCP_READ_MAX_SPAN}}return{startLine:start,endLine,capped:false,spanLimit:MCP_READ_MAX_SPAN}}async function readSourceFile(args,service,context){const target=resolveCodeTarget(args.target,context,args.format);if("content"in target)return target;try{const bounded=deriveBoundedRange(args.start_line,args.end_line);const build=buildReadFileParams({target,filePath:args.path,startLine:bounded.startLine,endLine:bounded.endLine,waitTimeoutMs:args.wait_timeout_ms});const result=await service.readFile(build.params);const payload=buildReadFileSuccessPayload(result,{registry:target.registry?toPkgseerRegistryLowercase2(target.registry):undefined,name:target.packageName,repoUrl:target.repoUrl,gitRef:target.gitRef,requestedFilePath:build.params.filePath});if(shouldEmitCappedHint(bounded,payload)){payload.hint=buildCappedHint(payload,args.start_line,args.end_line,bounded.spanLimit)}if(isTextFormat6(args.format)){return textResult(renderReadFileText(payload))}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=withReadFileRecovery(mapCodeNavigationError(error),args.path);return mcpMappedErrorResult(withIndexingRetryAction(mapped,"read","mcp",{maxWaitMs:MAX_WAIT_TIMEOUT_MS}),context,args.format,{recovery:{syntax:"mcp",tool:"read",args},indexingTarget:args.target,indexingOutcome:"This content is not available yet."})}}function isTextFormat6(format){return format===undefined||format==="text"}function shouldEmitCappedHint(bounded,payload){if(!bounded.capped)return false;if(payload.isBinary)return false;if(payload.endLine===undefined)return false;if(payload.totalLines===undefined)return false;return payload.endLine<payload.totalLines}function buildCappedHint(payload,originalStart,originalEnd,spanLimit){const requested=describeRequest(originalStart,originalEnd);const endArgument=originalEnd===undefined?"":` end_line=${Math.min(originalEnd,payload.totalLines)}`;const continuation=` To continue, retry with start_line=${payload.endLine+1}${endArgument}.`;return`Returned lines ${payload.startLine}-${payload.endLine}/${payload.totalLines} `+`(${originalEnd===undefined?"default span":"explicit-range ceiling"}: ${spanLimit} lines; you requested ${requested}).`+`${continuation} `+`Use start_line/end_line to read only the lines needed around a search/grep match. `+`Each retry also costs context, so aim for one well-sized read.`}function describeRequest(originalStart,originalEnd){if(originalStart===undefined&&originalEnd===undefined){return"no range"}if(originalEnd===undefined){return`start_line=${originalStart}, no end_line`}if(originalStart===undefined){return`end_line=${originalEnd}, no start_line`}return`lines ${originalStart}-${originalEnd}`}var readSchema={target:z10.string().describe("Pass a returned HTTP(S) page URL unchanged to read it directly. A site: target requires a separate exact page path, including / for its root. With path: use a compact package/repo target for a file; target#symbol narrows a symbol read to that file. Without path: use a docs target/page ID or compact target#symbol unchanged. Preserve emitted targets unchanged."),path:z10.string().optional().describe("Page path relative to the supplied site: target; do not repeat its scope. For code, use an exact package/repo-relative file path from search, list, or grep. Preserve emitted paths unchanged. Omit for other documentation targets; empty means omitted."),selector:z10.string().optional().describe("Logical docs heading ID or indexed code symbol. With a site path it selects a hosted heading; with a code path it searches exactly that file. Omit path to search a code target. Do not combine with a docs URL fragment or compact target#symbol."),start_line:z10.number().optional().describe("Positive 1-indexed start. Either bound overrides a docs URL fragment with a page-relative range."),end_line:z10.number().optional().describe(`Inclusive end, at least start_line. Text: ${MCP_READ_DEFAULT_SPAN} lines without an end, up to ${MCP_READ_MAX_SPAN} with one. Code JSON is also bounded; docs JSON keeps the backend selection.`),wait_timeout_ms:z10.number().optional().describe(`Indexing wait in ms (0-${MAX_WAIT_TIMEOUT_MS}, default ${DEFAULT_WAIT_TIMEOUT_MS}); the backend applies it when relevant.`),format:z10.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result. Use json when code consumes the raw response instead of the model or required metadata is absent from text.")};var DESCRIPTION_BASE4="Read an indexed source file, code symbol, or documentation section. "+"Pass target and path for a file or site page; use compact target#symbol or selector for a code symbol, and selector for a docs heading. "+"Preserve emitted documentation targets; the resolved result determines code or docs. "+"Replaces code_read and docs_read. "+"Hosted/crawled HTTP(S) docs targets read mutable current content; repository-doc targets address snapshots. "+"A docs URL fragment needs no bounds and returns its heading with the full subtree through the next equal-or-higher heading; either bound replaces it with a page-relative range. "+"Use emitted locators to preserve exact revisions. It does not list directories: use list. "+"Read focused windows from search/grep; follow returned continuation and error actions. "+"On INDEXING retry the same target/path with wait_timeout_ms; no content is available yet.";var DESCRIPTION10=`${DESCRIPTION_BASE4}
|
|
199
|
+
`);payload.endLine=payload.startLine+maxLines-1;payload.hint=buildReadContinuationHint(response.result.readTarget,payload.endLine+1,returnedEndLine)}}if(format==="mcp-json"||format==="cli-json")return JSON.stringify(payload);return format==="cli-text"?formatReadFileTerminal(payload,{useColors:request.useColors??false,verbose:request.verbose,width:request.width}):renderReadFileText(payload)}const maxOutputLines=format==="mcp-text"?request.endLine===undefined?MCP_READ_DEFAULT_SPAN:MCP_READ_MAX_SPAN:undefined;const payload=buildReadPackageDocSuccessPayload(response.result,request.target,maxOutputLines);if(maxOutputLines!==undefined&&payload.endLine!==undefined&&response.result.contentRange.endLine!==undefined&&payload.endLine<response.result.contentRange.endLine){payload.hint=buildReadContinuationHint(response.result.readTarget,payload.endLine+1,response.result.contentRange.endLine)}if(format==="mcp-json"||format==="cli-json")return JSON.stringify(payload);return format==="cli-text"?formatReadPackageDocTerminal(payload,{useColors:request.useColors??false,verbose:request.verbose}):renderReadPackageDocText(payload)}function createReadFileServiceAdapter(readService,target,signal){return{readFile:async(params)=>{const response=await readService.read({target,path:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs},...serviceRequestArgs(signal));if(response.source!=="code"){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return response.result}}}function isExactPathAuthorityError(mapped){return mapped.code==="FILE_PATH_EXCLUDED"||mapped.code==="SOURCE_FILE_INVENTORY_UNKNOWN"}function withExactPathAuthorityRecovery(mapped){if(!isExactPathAuthorityError(mapped)||mapped.details?.filePath===undefined){return mapped}const prefix=buildContainingPathPrefix(mapped.details.filePath);const listing=prefix===""?"Use `list` without `paths`":`Use \`list\` with \`paths: ${JSON.stringify([prefix])}\``;const reason=mapped.code==="FILE_PATH_EXCLUDED"?"This path is excluded from the indexed source.":"The source inventory cannot verify this path.";return{...mapped,details:{...mapped.details,action:`${reason} ${listing} to list indexed paths available to \`read\`.`}}}function buildContainingPathPrefix(filePath){const trimmed=filePath.trim();const slash=trimmed.lastIndexOf("/");return slash===-1?"":trimmed.slice(0,slash+1)}function buildPathPrefixSuggestion(requestedPath){const trimmed=requestedPath.trim();if(trimmed==="")return"";if(trimmed.endsWith("/"))return trimmed;const slash=trimmed.lastIndexOf("/");const basename=slash===-1?trimmed:trimmed.slice(slash+1);if(!basename.includes("."))return`${trimmed}/`;return slash===-1?"":trimmed.slice(0,slash+1)}function looksLikeMissingFileMessage(message){const lower=message.toLowerCase();return lower.includes("file not found")||lower.includes("path not found")||lower.includes("path doesn't resolve")||lower.includes("path does not resolve")}function withReadFileRecovery(mapped,requestedPath){if(isExactPathAuthorityError(mapped)){return withExactPathAuthorityRecovery(mapped)}if(mapped.code!=="FILE_NOT_FOUND"&&(mapped.code!=="NOT_FOUND"||!looksLikeMissingFileMessage(mapped.message))){return mapped}const recoveryPath=mapped.details?.filePath??requestedPath;return{...mapped,details:{...mapped.details,action:buildReadFileNotFoundAction(recoveryPath,mapped.code==="FILE_NOT_FOUND")}}}function buildReadFileNotFoundAction(requestedPath,exactFilePath){const prefix=exactFilePath?buildContainingPathPrefix(requestedPath):buildPathPrefixSuggestion(requestedPath);const preamble=exactFilePath?"`read` requires an indexed exact file path. ":"With path, `read` reads files only, not directories. ";const listing=prefix===""?"Use `list` without `paths`":`Use \`list\` with \`paths: ${JSON.stringify([prefix])}\``;return`${preamble}${listing} to list valid indexed paths, then `+"pass an emitted `path` back to `read`."}function buildReadFileParams(input){const filePath=input.filePath?.trim()??"";if(!filePath){throw new InvalidPackageSpecError("`file_path` is required — pass the path to the file within the package or repo.")}if(filePath.endsWith("/")){throw new InvalidPackageSpecError(`\`file_path\` must be an exact file path, not a directory prefix. Use \`list\` with \`paths: ${JSON.stringify([filePath])}\` to list files, then pass an emitted \`path\` to \`read\`.`)}validateReadRange(input.startLine,input.endLine);const{startLine,endLine}=input;const waitTimeoutMs=normalizeReadWaitTimeoutMs(input.waitTimeoutMs);return{params:{target:input.target,filePath,startLine,endLine,waitTimeoutMs}}}import{z as z9}from"zod";var codeTargetSchema=z9.string().min(1).describe("Compact target: `npm:react@version`, `github:facebook/react@ref`, or `launchpad:~owner/+git/repo@ref` (`lp:PROJECT` also accepted). Omit the suffix for the latest package version or repository default branch; a ref may be a branch, tag, or commit. `#` is for semantic fragments. Package targets scope to the package subpath; repository targets cover the full repository.");function resolveCodeTarget(target,context,format){try{return parseCodeNavigationTargetSpec(target)}catch(error){return mcpMappedErrorResult(mapCodeNavigationError(error),context,format)}}function deriveBoundedRange(startLine,endLine){const start=startLine??1;if(endLine===undefined){return{startLine:start,endLine:start+MCP_READ_DEFAULT_SPAN-1,capped:true,spanLimit:MCP_READ_DEFAULT_SPAN}}const span=endLine-start+1;if(span>MCP_READ_MAX_SPAN){return{startLine:start,endLine:start+MCP_READ_MAX_SPAN-1,capped:true,spanLimit:MCP_READ_MAX_SPAN}}return{startLine:start,endLine,capped:false,spanLimit:MCP_READ_MAX_SPAN}}async function readSourceFile(args,service,context){const target=resolveCodeTarget(args.target,context,args.format);if("content"in target)return target;try{const bounded=deriveBoundedRange(args.start_line,args.end_line);const build=buildReadFileParams({target,filePath:args.path,startLine:bounded.startLine,endLine:bounded.endLine,waitTimeoutMs:args.wait_timeout_ms});const result=await service.readFile(build.params);const payload=buildReadFileSuccessPayload(result,{registry:target.registry?toPkgseerRegistryLowercase2(target.registry):undefined,name:target.packageName,repoUrl:target.repoUrl,gitRef:target.gitRef,requestedFilePath:build.params.filePath});if(shouldEmitCappedHint(bounded,payload)){payload.hint=buildCappedHint(payload,args.start_line,args.end_line,bounded.spanLimit)}if(isTextFormat6(args.format)){return textResult(renderReadFileText(payload))}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=withReadFileRecovery(mapCodeNavigationError(error),args.path);return mcpMappedErrorResult(withIndexingRetryAction(mapped,"read","mcp",{maxWaitMs:MAX_WAIT_TIMEOUT_MS}),context,args.format,{recovery:{syntax:"mcp",tool:"read",args},indexingTarget:args.target,indexingOutcome:"This content is not available yet."})}}function isTextFormat6(format){return format===undefined||format==="text"}function shouldEmitCappedHint(bounded,payload){if(!bounded.capped)return false;if(payload.isBinary)return false;if(payload.endLine===undefined)return false;if(payload.totalLines===undefined)return false;return payload.endLine<payload.totalLines}function buildCappedHint(payload,originalStart,originalEnd,spanLimit){const requested=describeRequest(originalStart,originalEnd);const endArgument=originalEnd===undefined?"":` end_line=${Math.min(originalEnd,payload.totalLines)}`;const continuation=` To continue, retry with start_line=${payload.endLine+1}${endArgument}.`;return`Returned lines ${payload.startLine}-${payload.endLine}/${payload.totalLines} `+`(${originalEnd===undefined?"default span":"explicit-range ceiling"}: ${spanLimit} lines; you requested ${requested}).`+`${continuation} `+`Use start_line/end_line to read only the lines needed around a search/grep match. `+`Each retry also costs context, so aim for one well-sized read.`}function describeRequest(originalStart,originalEnd){if(originalStart===undefined&&originalEnd===undefined){return"no range"}if(originalEnd===undefined){return`start_line=${originalStart}, no end_line`}if(originalStart===undefined){return`end_line=${originalEnd}, no start_line`}return`lines ${originalStart}-${originalEnd}`}var readSchema={target:z10.string().describe("Pass a returned HTTP(S) page URL unchanged to read it directly. A site: target requires a separate exact page path, including / for its root. With path: use a compact package/repo target for a file; target#symbol narrows a symbol read to that file. Without path: use a docs target/page ID or compact target#symbol unchanged. Preserve emitted targets unchanged."),path:z10.string().optional().describe("Page path relative to the supplied site: target; do not repeat its scope. For code, use an exact package/repo-relative file path from search, list, or grep. Preserve emitted paths unchanged. Omit for other documentation targets; empty means omitted."),selector:z10.string().optional().describe("Logical docs heading ID or indexed code symbol. With a site path it selects a hosted heading; with a code path it searches exactly that file. Omit path to search a code target. Do not combine with a docs URL fragment or compact target#symbol."),start_line:z10.number().optional().describe("Positive 1-indexed start. Either bound overrides a docs URL fragment with a page-relative range."),end_line:z10.number().optional().describe(`Inclusive end, at least start_line. Text: ${MCP_READ_DEFAULT_SPAN} lines without an end, up to ${MCP_READ_MAX_SPAN} with one. Code JSON is also bounded; docs JSON keeps the backend selection.`),wait_timeout_ms:z10.number().optional().describe(`Indexing wait in ms (0-${MAX_WAIT_TIMEOUT_MS}, default ${DEFAULT_WAIT_TIMEOUT_MS}); the backend applies it when relevant.`),format:z10.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result. Use json when code consumes the raw response instead of the model or required metadata is absent from text.")};var DESCRIPTION_BASE4="Read an indexed source file, code symbol, or documentation section. "+"Pass target and path for a file or site page; use compact target#symbol or selector for a code symbol, and selector for a docs heading. "+"Preserve emitted documentation targets; the resolved result determines code or docs. "+"Replaces code_read and docs_read. "+"Hosted/crawled HTTP(S) docs targets read mutable current content; repository-doc targets address snapshots. "+"A docs URL fragment needs no bounds and returns its heading with the full subtree through the next equal-or-higher heading; either bound replaces it with a page-relative range. "+"Use emitted locators to preserve exact revisions. It does not list directories: use list. "+"Read focused windows from search/grep; follow returned continuation and error actions. "+"On INDEXING retry the same target/path with wait_timeout_ms; no content is available yet.";var DESCRIPTION10=`${DESCRIPTION_BASE4}
|
|
195
200
|
|
|
196
|
-
${CODE_READ_GUARDRAIL}`;function createReadTool(services){return{name:"read",description:DESCRIPTION10,schema:readSchema,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{let locator;let wait;try{locator=resolveReadLocator(args.target,args.path);if(args.selector!==undefined&&(typeof args.selector!=="string"||!args.selector.trim())){throw new InvalidPackageSpecError("selector must be a nonblank string.")}validateReadRange(args.start_line,args.end_line);wait=normalizeReadWaitTimeoutMs(args.wait_timeout_ms);if(args.format!==undefined&&args.format!=="text"&&args.format!=="json"){throw new InvalidPackageSpecError("format must be text or json.")}}catch(error){return mcpMappedErrorResult(mapCodeNavigationError(error),context,args.format)}if(args.selector!==undefined||locator.path===undefined||locator.target.includes("#")||isSiteReadTarget(locator.target)){try{const response=await services.readService.read({target:locator.target,...locator.path?{path:locator.path}:{},...args.selector!==undefined?{selector:args.selector}:{},...args.start_line!==undefined?{startLine:args.start_line}:{},...args.end_line!==undefined?{endLine:args.end_line}:{},waitTimeoutMs:wait},...serviceRequestArgs(context?.signal));return textResult(formatReadResult(response,{target:locator.target,selector:args.selector,path:locator.path,endLine:args.end_line},args.format==="json"?"mcp-json":"mcp-text"))}catch(error){throwIfCallerCancellation(error,context?.signal);const docsError=mapPackageIntelligenceError(error);return mcpMappedErrorResult(withIndexingRetryAction(docsError.code!=="UNKNOWN"?docsError:mapCodeNavigationError(error),"read","mcp",{maxWaitMs:MAX_WAIT_TIMEOUT_MS}),context,args.format,{recovery:{syntax:"mcp",tool:"read",args},indexingTarget:args.target,indexingOutcome:"This content is not available yet."})}}return readSourceFile({...args,target:locator.target,path:locator.path,wait_timeout_ms:wait},createReadFileServiceAdapter(services.readService,locator.target,context?.signal),context)}}}import{z as z11}from"zod";var DEFAULT_UNIFIED_SEARCH_LIMIT=10;function buildUnifiedSearchParams(input){const targets=resolveTargets(input.target,input.targets);const rawQuery=normaliseRequiredQuery(input.query);const selectsAuto=!input.sources?.length||input.sources.includes("AUTO");const selectsCode=input.sources?.includes("CODE")||selectsAuto&&targets.some((target)=>!target.site);if(input.pathPrefix&&!selectsCode){throw new InvalidArgumentError("Path prefixes require a code search source. Remove the path prefix for documentation or symbol searches.")}const limit=input.limit??DEFAULT_UNIFIED_SEARCH_LIMIT;const offset=input.offset??0;const waitTimeoutMs=input.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS;const qualifierClauses=buildQualifierClauses({name:input.name,language:input.language});const compiledQuery=compileQuery(rawQuery,qualifierClauses);const stripCodeAndSymbolFilters=isDocsOnlySource(input.sources);const filters=buildFilters({kind:stripCodeAndSymbolFilters?undefined:input.kind,category:stripCodeAndSymbolFilters?undefined:input.category,pathPrefix:input.pathPrefix,fileIntent:stripCodeAndSymbolFilters?undefined:input.fileIntent,publicOnly:stripCodeAndSymbolFilters?undefined:input.publicOnly});return{params:{targets,query:compiledQuery,sources:input.sources,filters,allowPartialResults:input.allowPartialResults??true,limit,offset,waitTimeoutMs},rawQuery,compiledQuery}}function isDocsOnlySource(sources){return sources?.length===1&&sources[0]==="DOCS"}function resolveTargets(target,targets){const nonEmptyTargets=targets?.length?targets:undefined;if(target&&nonEmptyTargets){throw new InvalidArgumentError("Provide either `target` for one search target or `targets` for multiple, not both.")}const resolved=target?[target]:nonEmptyTargets??[];if(resolved.length===0){throw new InvalidArgumentError("Provide either `target` for one search target or `targets` for multiple; neither was set.")}const deduped=[];const seen=new Set;for(const entry of resolved){const key=JSON.stringify(entry);if(seen.has(key))continue;seen.add(key);deduped.push(entry)}return deduped}function normaliseRequiredQuery(query){const trimmed=query.trim();if(trimmed.length===0){throw new InvalidArgumentError("Query cannot be empty.")}return trimmed}function buildQualifierClauses(input){const clauses=[];if(input.name){clauses.push(`name:${quoteQualifierValue(input.name)}`)}if(input.language){clauses.push(`lang:${quoteQualifierValue(input.language)}`)}return clauses}function quoteQualifierValue(value){const trimmed=value.trim();if(trimmed.length===0){throw new InvalidArgumentError("Structured qualifier values cannot be empty.")}if(!needsQuoting(trimmed)){return trimmed}return`"${trimmed.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function needsQuoting(value){return/\s|[():"]|\bAND\b|\bOR\b|-/.test(value)}function compileQuery(rawQuery,qualifierClauses){if(qualifierClauses.length===0){return rawQuery}return`(${rawQuery}) AND (${qualifierClauses.join(" AND ")})`}function buildFilters(input){const filters={};if(input.kind)filters.kind=input.kind;if(input.category)filters.category=input.category;if(input.pathPrefix)filters.pathPrefix=input.pathPrefix;if(input.fileIntent)filters.fileIntent=input.fileIntent;if(input.publicOnly===true){filters.publicOnly=input.publicOnly}return Object.keys(filters).length>0?filters:undefined}function buildSearchHitFollowUpCommand(hit,syntax="mcp"){const action=hit.readTarget;if(action){const matched=hit.repositoryEvidence?.matchedSource;const evidence=hit.repositoryEvidence?.semanticContext?matched?{startLine:matched.startLine,endLine:matched.endLine,matchLine:matched.matchLine??undefined}:undefined:hit.locator.evidenceRange;return renderReadTarget(syntax==="mcp"?capSearchReadTarget(action,evidence):action,syntax)}const loc=hit.locator;const code=hit.type==="repository_code"||hit.type==="repository_symbol";if(code&&loc.repoUrl&&!loc.commitSha&&!isPackageTarget(hit))return"follow-up unavailable: missing exact revision";if(code&&!loc.filePath&&!loc.repositoryFilePath)return"follow-up unavailable: missing filePath";return"follow-up unavailable: missing read target"}function isPackageTarget(hit){const registry=hit.locator.registry;const packageName=hit.locator.packageName;return Boolean(registry&&packageName&&hit.target.startsWith(`${registry}:${packageName}`))}function isHealthySearchLifecycleState(state){return state==="INDEXED"||state==="CURRENT"}var DEFAULT_LIMIT=DEFAULT_UNIFIED_SEARCH_LIMIT;var DEFAULT_OFFSET=0;function isActiveUnifiedSearchSessionStatus(status){return status==="PENDING"||status==="INDEXING"||status==="SEARCHING"}function projectHitPayload(hit){return{type:hit.type,target:hit.target,locator:hit.locator,...hit.requestedTarget!==undefined?{requestedTarget:hit.requestedTarget}:{},...hit.freshTarget!==undefined?{freshTarget:hit.freshTarget}:{},...hit.servedTarget!==undefined?{servedTarget:hit.servedTarget}:{},...hit.freshness!==undefined?{freshness:hit.freshness}:{},...hit.title!==undefined?{title:hit.title}:{},...hit.highlights!==undefined?{highlights:hit.highlights}:{},...hit.repositoryEvidence!==undefined?{repositoryEvidence:hit.repositoryEvidence}:{},...hit.documentationPreview!==undefined?{documentationPreview:hit.documentationPreview}:{},...hit.followUp!==undefined?{followUp:hit.followUp}:{}}}function projectUnifiedSearchSuccessPayload(payload){const projected={...payload};delete projected.sourceStatusForText;return{...projected,results:payload.results.map(projectHitPayload)}}function projectStatusResultPayload(payload){const projected={...payload};delete projected.sourceStatusForText;return{...projected,results:payload.results.map(projectHitPayload)}}function projectUnifiedSearchStatusPayload(payload){return payload.completed?{...payload,result:projectStatusResultPayload(payload.result)}:{...payload,...payload.result!==undefined?{result:projectStatusResultPayload(payload.result)}:{}}}function buildUnifiedSearchSuccessPayload(params,rawQuery,compiledQuery,outcome){const warnings=outcome.state==="completed"?outcome.result.queryWarnings:outcome.result?.queryWarnings??outcome.progress?.queryWarnings??[];const progress=compactProgress(outcome.progress);const query=buildQueryEcho(params,rawQuery,compiledQuery,warnings);if(outcome.state==="incomplete"){const result=outcome.result;const payload={query,completed:false,hasMore:result?.page.hasMore??false,results:result?.results.map(buildHitPayload)??[],searchRef:outcome.searchRef};if(result)payload.partialResults=result.partialResults;if(result?.page.hasMore===true){payload.nextOffset=result.page.offset+result.page.returned}if(progress)payload.progress=progress;const sourceStatus=compactSourceStatus(result?.sourceStatus,{completed:false});if(sourceStatus)payload.sourceStatus=sourceStatus;const textSourceStatus=compactSourceStatus(result?.sourceStatus,{completed:false,includeHealthy:true});if(textSourceStatus)payload.sourceStatusForText=textSourceStatus;if(result?.evidenceNotice){payload.evidenceNotice=result.evidenceNotice}const combinedWarnings=combineWarnings(warnings,sourceStatus,payload.results,progress,false);if(combinedWarnings.length>0)payload.warnings=combinedWarnings;return payload}const completed={query,completed:true,partialResults:outcome.result.partialResults,hasMore:outcome.result.page.hasMore,results:outcome.result.results.map(buildHitPayload)};if(outcome.result.page.hasMore){completed.nextOffset=outcome.result.page.offset+outcome.result.page.returned}if(outcome.searchRef)completed.searchRef=outcome.searchRef;const sourceStatus=compactSourceStatus(outcome.result.sourceStatus,{completed:true,includeEmptyResultContext:completed.results.length===0});if(sourceStatus)completed.sourceStatus=sourceStatus;const textSourceStatus=compactSourceStatus(outcome.result.sourceStatus,{completed:true,includeEmptyResultContext:completed.results.length===0,includeHealthy:true});if(textSourceStatus)completed.sourceStatusForText=textSourceStatus;if(outcome.result.evidenceNotice){completed.evidenceNotice=outcome.result.evidenceNotice}const combinedWarnings=combineWarnings(warnings,sourceStatus,completed.results,undefined,true);if(combinedWarnings.length>0)completed.warnings=combinedWarnings;return completed}function combineWarnings(parserWarnings,sourceStatus,hits=[],progress,completed=false){const out=[];if(parserWarnings.length>0)out.push(...parserWarnings);out.push(...buildHitFreshnessWarnings(hits));out.push(...buildProgressFreshnessWarnings(progress));out.push(...buildSourceStatusWarnings(sourceStatus,{completed}));return Array.from(new Set(out))}function buildUnifiedSearchErrorPayload(error){const mapped=mapCodeNavigationError(error);const payload={error:mapped.message,code:mapped.code};if(typeof mapped.retryable==="boolean"){payload.retryable=mapped.retryable}if(mapped.details&&Object.keys(mapped.details).length>0){payload.details=mapped.details}return payload}function buildUnifiedSearchStatusPayload(outcome){if(outcome.state==="incomplete"){const payload={completed:false,searchRef:outcome.searchRef};const progress=compactProgress(outcome.progress);if(progress)payload.progress=progress;const progressWarnings=buildProgressFreshnessWarnings(progress);if(progressWarnings.length>0)payload.warnings=progressWarnings;if(outcome.result){payload.result=buildUnifiedSearchStatusResultPayload(outcome.result,{completed:false})}return payload}const payload={completed:true,result:buildUnifiedSearchStatusResultPayload(outcome.result,{completed:true})};if(outcome.searchRef)payload.searchRef=outcome.searchRef;return payload}function buildUnifiedSearchStatusResultPayload(result,options){const payload={query:buildStatusQueryEcho(result),partialResults:result.partialResults,hasMore:result.page.hasMore,results:result.results.map(buildHitPayload)};if(result.page.hasMore){payload.nextOffset=result.page.offset+result.page.returned}if(result.sources.length>0){payload.sources=result.sources.map((entry)=>entry.toLowerCase())}const sourceStatus=compactSourceStatus(result.sourceStatus,{...options,includeEmptyResultContext:options.completed&&result.results.length===0});if(sourceStatus)payload.sourceStatus=sourceStatus;const textSourceStatus=compactSourceStatus(result.sourceStatus,{...options,includeEmptyResultContext:options.completed&&result.results.length===0,includeHealthy:true});if(textSourceStatus)payload.sourceStatusForText=textSourceStatus;if(result.evidenceNotice)payload.evidenceNotice=result.evidenceNotice;const combinedWarnings=combineWarnings(result.queryWarnings,sourceStatus,[],undefined,options.completed);if(combinedWarnings.length>0){payload.warnings=combinedWarnings}return payload}function buildStatusQueryEcho(result){const query={raw:result.query};if(result.queryWarnings.length>0){query.warnings=result.queryWarnings}if(result.sources.length>0){query.sources=result.sources.map((entry)=>entry.toLowerCase())}return query}function buildQueryEcho(params,rawQuery,compiledQuery,warnings){const echo={raw:rawQuery};if(compiledQuery!==rawQuery){echo.compiled=compiledQuery}if(warnings.length>0){echo.warnings=warnings}if(params.sources&¶ms.sources.length>0){echo.sources=params.sources.map((entry)=>entry.toLowerCase())}if(params.filters){const filters={};if(params.filters.kind)filters.kind=params.filters.kind.toLowerCase();if(params.filters.category)filters.category=params.filters.category.toLowerCase();if(params.filters.pathPrefix)filters.pathPrefix=params.filters.pathPrefix;if(params.filters.fileIntent)filters.fileIntent=params.filters.fileIntent.toLowerCase();if(typeof params.filters.publicOnly==="boolean")filters.publicOnly=params.filters.publicOnly;if(Object.keys(filters).length>0)echo.filters=filters}if(params.allowPartialResults===false){echo.allowPartialResults=false}if(params.limit!==undefined&¶ms.limit!==DEFAULT_LIMIT){echo.limit=params.limit}if(params.offset!==undefined&¶ms.offset!==DEFAULT_OFFSET){echo.offset=params.offset}if(params.waitTimeoutMs!==undefined&¶ms.waitTimeoutMs!==DEFAULT_WAIT_TIMEOUT_MS){echo.waitTimeoutMs=params.waitTimeoutMs}return echo}function buildHitPayload(hit){assertSearchFollowUpInvariant(hit);const payload={type:hit.resultType.toLowerCase(),target:formatTargetLabel(hit.targetLabel,hit.locator.repoUrl),locator:buildLocatorPayload(hit)};if(hit.readTarget!==undefined)payload.readTarget=hit.readTarget;appendFreshness(payload,{requestedTargetLabel:hit.requestedTargetLabel,freshTargetLabel:hit.freshTargetLabel,servedTargetLabel:hit.servedTargetLabel,freshness:hit.freshness},hit.locator.repoUrl);if(hit.title)payload.title=hit.title;const highlights=buildHighlights(hit.highlights);if(highlights)payload.highlights=highlights;if(hit.repositoryEvidence!==undefined){if(hit.repositoryEvidence===null){payload.repositoryEvidence=null}else{const{focusedSource:_legacySource,...evidence}=hit.repositoryEvidence;payload.repositoryEvidence=evidence}}if(hit.documentationPreview!==undefined){payload.documentationPreview=hit.documentationPreview}const followUp=buildSearchHitFollowUpCommand(payload);if(followUp)payload.followUp=followUp;return payload}function formatTargetLabel(label,repoUrl){return formatRepositoryTargetLabel(label,repoUrl)??label}function buildLocatorPayload(hit){const locator={};const src=hit.locator;if(src.registry)locator.registry=src.registry;if(src.packageName)locator.packageName=src.packageName;if(src.version)locator.version=src.version;if(src.pageId)locator.pageId=src.pageId;if(src.docsReadTarget)locator.docsReadTarget=src.docsReadTarget;if(src.sourceKind)locator.sourceKind=src.sourceKind;if(src.sourceUrl)locator.sourceUrl=src.sourceUrl;if(src.repoUrl)locator.repoUrl=src.repoUrl;if(src.gitRef)locator.gitRef=src.gitRef;if(src.commitSha)locator.commitSha=src.commitSha;if(src.requestedRef)locator.requestedRef=src.requestedRef;if(src.filePath)locator.filePath=src.filePath;if(src.repositoryFilePath){locator.repositoryFilePath=src.repositoryFilePath}if(typeof src.startLine==="number")locator.startLine=src.startLine;if(typeof src.endLine==="number")locator.endLine=src.endLine;if(src.evidenceRange)locator.evidenceRange={...src.evidenceRange};if(src.indexedRange)locator.indexedRange={...src.indexedRange};if(src.symbolContext){if(src.symbolContext.relation==="encloses_match"){locator.symbolContext={name:src.symbolContext.name,relation:src.symbolContext.relation,definitionRange:{...src.symbolContext.definitionRange},...src.symbolContext.qualifiedPath?{qualifiedPath:src.symbolContext.qualifiedPath}:{},...src.symbolContext.kind?{kind:src.symbolContext.kind}:{}}}else{locator.symbolContext={name:src.symbolContext.name,relation:src.symbolContext.relation,...src.symbolContext.qualifiedPath?{qualifiedPath:src.symbolContext.qualifiedPath}:{},...src.symbolContext.kind?{kind:src.symbolContext.kind}:{},...src.symbolContext.definitionRange?{definitionRange:{...src.symbolContext.definitionRange}}:{}}}}if(src.qualifiedPath&&src.qualifiedPath!==hit.title){locator.qualifiedPath=src.qualifiedPath}if(src.kind)locator.kind=src.kind;if(src.category)locator.category=src.category;if(src.language)locator.language=src.language;return locator}function buildHighlights(highlights){if(!highlights)return;const compact={};if(highlights.title&&highlights.title.length>0){compact.title=highlights.title}return Object.keys(compact).length>0?compact:undefined}function compactProgress(progress){if(!progress)return;const payload={status:progress.status,targetsReady:progress.targetsReady,targetsTotal:progress.targetsTotal,elapsedMs:progress.elapsedMs};if(progress.query)payload.query=progress.query;if(progress.requestedSources?.length){payload.requestedSources=progress.requestedSources.map((entry)=>entry.toLowerCase())}if(progress.targetMode)payload.targetMode=progress.targetMode;if(progress.requestedTargets?.length){payload.requestedTargets=progress.requestedTargets}if(progress.filters)payload.filters=buildFilterEcho2(progress.filters);if(typeof progress.limit==="number")payload.limit=progress.limit;if(typeof progress.offset==="number")payload.offset=progress.offset;const targets=progress.targets?.map(compactProgressTarget).filter(Boolean);if(targets?.length){payload.targets=targets}if(progress.indexingEstimates!==undefined){payload.indexingEstimates=progress.indexingEstimates.map(compactIndexingEstimate)}if(progress.expiresAt)payload.expiresAt=progress.expiresAt;payload.next=isActiveUnifiedSearchSessionStatus(progress.status)?`search_status search_ref=${JSON.stringify(progress.searchRef)} wait_timeout_ms=${indexingWaitMs(progress.indexingEstimates)}`:"rerun search";return payload}function compactIndexingEstimate(estimate){return{...estimate,targets:estimate.kind==="REPOSITORY"?estimate.targets.map((target)=>formatRepositoryTargetLabel(target,estimate.repositoryUrl)??target):[...estimate.targets]}}function appendFreshness(payload,source,repoUrl){if(!isTrustRelevantFreshness(source.freshness)||!labelsDiverge({requestedTarget:source.requestedTargetLabel,freshTarget:source.freshTargetLabel,servedTarget:source.servedTargetLabel})){return}if(source.requestedTargetLabel)payload.requestedTarget=formatTargetLabel(source.requestedTargetLabel,repoUrl);if(source.freshTargetLabel)payload.freshTarget=formatTargetLabel(source.freshTargetLabel,repoUrl);if(source.servedTargetLabel)payload.servedTarget=formatTargetLabel(source.servedTargetLabel,repoUrl);if(source.freshness)payload.freshness=source.freshness}function compactProgressTarget(target){const payload={};if(target.requested)payload.requested=formatTargetLabel(target.requested,target.targetResolution?.requested?.repoUrl);if(target.resolvedRequested)payload.resolvedRequested=formatTargetLabel(target.resolvedRequested,target.targetResolution?.resolvedRequested?.repoUrl);if(target.served)payload.served=formatTargetLabel(target.served,target.targetResolution?.served?.repoUrl);if(target.freshness)payload.freshness=target.freshness;if(target.indexingRef)payload.indexingRef=target.indexingRef;if(target.requestedRefKind)payload.requestedRefKind=target.requestedRefKind;const targetResolution=projectTargetResolution(target.targetResolution);if(targetResolution)payload.targetResolution=targetResolution;if(target.availableVersions?.length){payload.availableVersions=target.availableVersions}if(target.availableRefs?.length){payload.availableRefs=target.availableRefs}if(target.suggestedRefs?.length){payload.suggestedRefs=target.suggestedRefs}const coverage=projectDocCoverage(target.coverage);if(coverage)payload.coverage=coverage;return Object.keys(payload).length>0?payload:undefined}function buildFilterEcho2(filters){const echo={};if(filters.kind)echo.kind=filters.kind.toLowerCase();if(filters.category)echo.category=filters.category.toLowerCase();if(filters.pathPrefix)echo.pathPrefix=filters.pathPrefix;if(filters.fileIntent)echo.fileIntent=filters.fileIntent.toLowerCase();if(typeof filters.publicOnly==="boolean"){echo.publicOnly=filters.publicOnly}return Object.keys(echo).length>0?echo:undefined}function buildSourceStatusWarnings(sourceStatus,options={}){if(!sourceStatus||sourceStatus.length===0)return[];const warnings=[];for(const entry of sourceStatus){const message=warningForEntry(entry,options);if(message!==undefined)warnings.push(message)}return warnings}function buildHitFreshnessWarnings(hits){return hits.map((hit)=>freshnessWarning({freshness:hit.freshness,requestedTarget:hit.requestedTarget,freshTarget:hit.freshTarget,servedTarget:hit.servedTarget})).filter((entry)=>Boolean(entry))}function buildProgressFreshnessWarnings(progress){return(progress?.targets??[]).map((target)=>freshnessWarning({freshness:target.freshness,requestedTarget:target.requested,freshTarget:target.resolvedRequested,servedTarget:target.served})).concat((progress?.targets??[]).map((target)=>progressTargetResolutionWarning(target)).filter((entry)=>Boolean(entry))).filter((entry)=>Boolean(entry))}function progressTargetResolutionWarning(target){const notes=buildTargetResolutionNotes(target.targetResolution??buildResolutionFromRetryCandidates(target));const coverage=docCoverageWarningReason(target.coverage);if(coverage)notes.push(coverage);return notes.length>0?notes.join(" "):undefined}function freshnessWarning(input){if(!isTrustRelevantFreshness(input.freshness))return;if(!labelsDiverge(input))return;const requested=input.requestedTarget??"requested target";const served=input.servedTarget??"served target";const fresh=input.freshTarget;return fresh?`requested ${requested}; served older snapshot ${served} while ${fresh} indexes.`:`requested ${requested}; served older snapshot ${served}.`}function isTrustRelevantFreshness(value){return value==="STALE"||value==="INDEXING"}function labelsDiverge(input){const served=input.servedTarget;if(!served)return false;return Boolean(input.freshTarget&&canonicalTargetLabel(input.freshTarget)!==canonicalTargetLabel(served))}function canonicalTargetLabel(label){const parsed=parsePackageVersionLabel(label);if(!parsed)return formatTargetLabel(label);const version=parsed.version.replace(/^v(?=\d)/i,"");return`${parsed.registry.toLowerCase()}:${parsed.packageName}@${version}`}function parsePackageVersionLabel(label){const registryEnd=label.indexOf(":");if(registryEnd<=0)return;const versionStart=label.lastIndexOf("@");if(versionStart<=registryEnd+1)return;const version=label.slice(versionStart+1);if(!version)return;return{registry:label.slice(0,registryEnd),packageName:label.slice(registryEnd+1,versionStart),version}}function docCoverageWarningReason(coverage){if(!coverage)return;const scale=docCoverageScale(coverage);if(coverage.note&&coverage.coverageState!=="PARTIAL"){return`${coverage.note}${scale}`}if(coverage.coverageState==="PARTIAL"){return`published docs coverage is partial; evidence may be incomplete${scale}`}if(coverage.coverageState==="CAPPED"){const reason=coverage.coverageReason?` (${coverage.coverageReason})`:"";return`published docs coverage is capped${reason}; evidence may be incomplete${scale}`}return}function docCoverageScale(coverage){const parts=[];if(typeof coverage.pagesCrawled==="number"){parts.push(`${coverage.pagesCrawled} published pages`)}if(typeof coverage.frontierRemaining==="number"){parts.push(`${coverage.frontierRemaining} discovered pages outside this snapshot`)}else if(typeof coverage.estimatedTotalPages==="number"){parts.push(`~${coverage.estimatedTotalPages} pages estimated`)}return parts.length>0?` [${parts.join(", ")}]`:""}function warningForEntry(entry,options){const reasons=[];const freshness=freshnessWarning({freshness:entry.codeIndexState,requestedTarget:entry.requestedTarget,freshTarget:entry.freshTarget,servedTarget:entry.servedTarget});if(freshness)return freshness;const terminalLifecycleReason=terminalLifecycleWarningReason(entry);if(terminalLifecycleReason){reasons.push(terminalLifecycleReason)}else{const targetResolutionWarning=targetResolutionWarningForEntry(entry,options);if(targetResolutionWarning)reasons.push(targetResolutionWarning)}const coverageReason=docCoverageWarningReason(entry.coverage);if(coverageReason)reasons.push(coverageReason);if(entry.incompatibleQueryFeatures?.length){reasons.push(`incompatible query features [${entry.incompatibleQueryFeatures.join(", ")}]`)}if(entry.ignoredQueryFeatures?.length){reasons.push(`ignored query features [${entry.ignoredQueryFeatures.join(", ")}]`)}if(entry.incompatibleFilters?.length){reasons.push(`incompatible filters [${entry.incompatibleFilters.join(", ")}]`)}if(entry.ignoredFilters?.length){reasons.push(`ignored filters [${entry.ignoredFilters.join(", ")}]`)}if(!terminalLifecycleReason&&reasons.length===0&&entry.indexingStatus&&!isHealthySearchLifecycleState(entry.indexingStatus)&&entry.indexingStatus!=="STALE"&&!(entry.indexingStatus==="INDEXING"&&options.completed)){reasons.push(`indexing status ${entry.indexingStatus}`)}if(!terminalLifecycleReason&&reasons.length===0&&entry.codeIndexState){if(!isHealthySearchLifecycleState(entry.codeIndexState)&&entry.codeIndexState!=="STALE"&&!(entry.codeIndexState==="INDEXING"&&options.completed)){reasons.push(entry.codeIndexState==="PROVISIONAL"?"code index state provisional (still indexing)":`code index state ${entry.codeIndexState}`)}}const prefix=`Source '${entry.source}' for ${formatSourceStatusTarget(entry)}`;if(reasons.length>0){return`${prefix}: ${reasons.join("; ")}`}if(entry.note){return`${prefix}: ${entry.note}`}return}function formatSourceStatusTarget(entry){return formatTargetResolutionIdentity(entry.targetResolution?.requested)??formatRepositoryTargetLabel(entry.targetLabel)??entry.targetLabel}function terminalLifecycleWarningReason(entry){const states=Array.from(new Set([entry.indexingStatus,entry.codeIndexState].filter(Boolean)));const terminalStates=states.filter((state)=>!isHealthySearchLifecycleState(state)&&state!=="INDEXING"&&state!=="STALE"&&state!=="PROVISIONAL");if(terminalStates.length===0)return;const status=terminalStates.join("/");return entry.note?`${entry.note} (${status})`:`status ${status}`}function targetResolutionWarningForEntry(entry,options){if(entry.targetResolution?.freshness==="indexing"&&options.completed){return}const notes=buildTargetResolutionNotes(entry.targetResolution);if(options.completed===true&&entry.targetResolution?.freshness==="indexing"&¬es.length>0){return`Search completed; fresh target may still be indexing. ${notes.join(" ")}`}return notes.length>0?notes.join(" "):undefined}function projectDocCoverage(coverage){if(!coverage)return;if(coverage.coverageState!=="PARTIAL"&&coverage.coverageState!=="CAPPED"){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function compactSourceStatus(sourceStatus,options={}){if(!sourceStatus||sourceStatus.length===0)return;const compact=[];for(const entry of sourceStatus){const slim=compactSourceStatusEntry(entry,options);if(slim)compact.push(slim)}return compact.length>0?compact:undefined}function compactSourceStatusEntry(entry,options){const payload={source:entry.source.toLowerCase(),targetLabel:formatTargetLabel(entry.targetLabel,entry.targetResolution?.requested?.repoUrl)};let interesting=false;const contributors=projectDocumentationContributors(entry.contributors);if(contributors){payload.contributors=contributors;interesting=true}if(options.includeEmptyResultContext){const servedTarget=entry.servedTargetLabel?formatTargetLabel(entry.servedTargetLabel,entry.targetResolution?.served?.repoUrl??entry.targetResolution?.requested?.repoUrl):undefined;const comparisonTarget=servedTarget??payload.targetLabel;const requestedTarget=entry.requestedTargetLabel?formatTargetLabel(entry.requestedTargetLabel,entry.targetResolution?.requested?.repoUrl):undefined;const freshTarget=entry.freshTargetLabel?formatTargetLabel(entry.freshTargetLabel,entry.targetResolution?.resolvedRequested?.repoUrl??entry.targetResolution?.requested?.repoUrl):undefined;if(requestedTarget&&canonicalTargetLabel(requestedTarget)!==canonicalTargetLabel(comparisonTarget)){payload.requestedTarget=requestedTarget}if(freshTarget&&canonicalTargetLabel(freshTarget)!==canonicalTargetLabel(comparisonTarget)){payload.freshTarget=freshTarget}const contributorIdentityDiverges=Boolean(contributors&&servedTarget&&(canonicalTargetLabel(servedTarget)!==canonicalTargetLabel(payload.targetLabel)||payload.requestedTarget||payload.freshTarget));if(servedTarget&&(!contributors||contributorIdentityDiverges)){payload.servedTarget=servedTarget}if(!contributors){if(entry.indexingStatus)payload.indexingStatus=entry.indexingStatus;if(entry.codeIndexState)payload.codeIndexState=entry.codeIndexState;if(typeof entry.resultCount==="number"){payload.resultCount=entry.resultCount}}interesting=true}const staleDiverges=entry.codeIndexState==="STALE"&&labelsDiverge({requestedTarget:entry.requestedTargetLabel,freshTarget:entry.freshTargetLabel,servedTarget:entry.servedTargetLabel});if(staleDiverges){if(entry.requestedTargetLabel)payload.requestedTarget=formatTargetLabel(entry.requestedTargetLabel,entry.targetResolution?.requested?.repoUrl);if(entry.freshTargetLabel)payload.freshTarget=formatTargetLabel(entry.freshTargetLabel,entry.targetResolution?.resolvedRequested?.repoUrl??entry.targetResolution?.requested?.repoUrl);if(entry.servedTargetLabel)payload.servedTarget=formatTargetLabel(entry.servedTargetLabel,entry.targetResolution?.served?.repoUrl??entry.targetResolution?.requested?.repoUrl);payload.codeIndexState=entry.codeIndexState;interesting=true}const targetResolution=projectTargetResolution(entry.targetResolution);if(targetResolution){const targetResolutionCarriesNotes=buildTargetResolutionNotes(targetResolution).length>0;const hasRetryCandidates=Boolean(buildRetryCandidateLine(targetResolution)??buildSuggestedRefsLine(targetResolution));const targetResolutionIsInteresting=targetResolutionCarriesNotes&&!(targetResolution.freshness==="indexing"&&options.completed)||targetResolution.freshness==="current"&&hasRetryCandidates;if(options.includeHealthy||!contributors||targetResolutionCarriesNotes||targetResolutionIsInteresting){payload.targetResolution=targetResolution}if(targetResolutionIsInteresting){interesting=true}}if(entry.indexingStatus&&entry.indexingStatus!=="INDEXED"&&!(entry.indexingStatus==="INDEXING"&&options.completed)){payload.indexingStatus=entry.indexingStatus;interesting=true}if(entry.codeIndexState&&entry.codeIndexState!=="CURRENT"&&(entry.codeIndexState!=="STALE"||staleDiverges)&&!(entry.codeIndexState==="INDEXING"&&options.completed)){payload.codeIndexState=entry.codeIndexState;interesting=true}if(!contributors){const coverage=projectDocCoverage(entry.coverage);if(coverage){payload.coverage=coverage;interesting=true}}if(!contributors&&!options.includeEmptyResultContext&&typeof entry.resultCount==="number"&&(entry.resultCount>0||options.includeHealthy)){payload.resultCount=entry.resultCount}if(entry.ignoredFilters.length>0){payload.ignoredFilters=entry.ignoredFilters;interesting=true}if(entry.incompatibleFilters.length>0){payload.incompatibleFilters=entry.incompatibleFilters;interesting=true}if(entry.ignoredQueryFeatures.length>0){payload.ignoredQueryFeatures=entry.ignoredQueryFeatures;interesting=true}if(entry.incompatibleQueryFeatures.length>0){payload.incompatibleQueryFeatures=entry.incompatibleQueryFeatures;interesting=true}if(entry.suggestedSiteTargets.length>0||entry.suggestedSiteTargetsTruncated){payload.suggestedSiteTargets=entry.suggestedSiteTargets;payload.suggestedSiteTargetsTruncated=entry.suggestedSiteTargetsTruncated;interesting=true}const redundantContributorNote=contributors&&entry.source==="DOCS"&&entry.note==="Documentation indexing in progress";if(entry.note&&!redundantContributorNote){payload.note=entry.note;interesting=true}return interesting||options.includeHealthy?payload:undefined}function projectDocumentationContributors(contributors){if(!contributors||contributors.length===0)return;return contributors.map((contributor)=>{const payload={kind:contributor.kind,state:contributor.state,resultCount:contributor.resultCount};if(contributor.freshness)payload.freshness=contributor.freshness;if(contributor.kind==="REPOSITORY_DOCS"){if(contributor.repositoryUrl){payload.repositoryUrl=contributor.repositoryUrl}if(contributor.commitSha)payload.commitSha=contributor.commitSha}else{if(contributor.siteKey)payload.siteKey=contributor.siteKey;if(contributor.siteUrl)payload.siteUrl=contributor.siteUrl;const coverage=projectDocumentationContributorCoverage(contributor.coverage);if(coverage)payload.coverage=coverage}return payload})}function projectDocumentationContributorCoverage(coverage){if(!coverage)return;const payload={coverageState:coverage.coverageState};if(coverage.coverageReason){payload.coverageReason=coverage.coverageReason}if(typeof coverage.pagesCrawled==="number"){payload.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){payload.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){payload.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){payload.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)payload.note=coverage.note;return payload}function assertSearchFollowUpInvariant(hit){if((hit.resultType==="DOCUMENTATION_PAGE"||hit.resultType==="REPOSITORY_DOC")&&!hit.locator.pageId){throw new MalformedCodeNavigationResponseError(`${hit.resultType} search hit missing required pageId.`)}if(hit.resultType==="REPOSITORY_DOC"&&(!hit.locator.repoUrl||!hit.locator.filePath)){throw new MalformedCodeNavigationResponseError("REPOSITORY_DOC search hit missing repo locator fields.")}}var MAX_ALTERNATIVES=3;function projectUnifiedSearchPresentation(payload){const snapshot=extractSnapshot(payload);const progress="progress"in payload?payload.progress:undefined;const lifecycle=projectLifecycle(payload,progress);const availability=projectAvailability(snapshot,lifecycle);const sourceStatus=snapshot?.sourceStatus;const sources=projectSources(sourceStatus);const siteSuggestions=projectSiteSuggestions(sourceStatus);const trustLimits=projectTrustLimits(snapshot,sources,sourceStatus);const query=snapshot?.query??("query"in payload?payload.query:undefined);const alternatives=projectAlternatives(progress,sourceStatus);const searchRef="searchRef"in payload?payload.searchRef:undefined;const targets=projectTargets(progress);const targetGroups=projectTargetGroups({targets,sources,alternatives,siteSuggestions,trustLimits,lifecycle,availability,snapshot});const warnings=projectWarnings(query,sourceStatus,targetGroups);return{provenance:projectProvenance(snapshot,progress),availability,lifecycle,query,progress:projectProgress(progress),indexingEstimates:progress?.indexingEstimates,targetGroups,hasMore:snapshot?.hasMore??false,warnings,action:projectAction({indexingEstimates:progress?.indexingEstimates,searchRef,snapshot,lifecycle,availability,targetGroups})}}function extractSnapshot(payload){if("result"in payload){const result=payload.result;return result?{...result,sourceStatus:result.sourceStatusForText??result.sourceStatus}:undefined}if(!("partialResults"in payload)||payload.partialResults===undefined){return}return{query:"query"in payload?payload.query:undefined,partialResults:payload.partialResults,hasMore:payload.hasMore,results:payload.results,sourceStatus:payload.sourceStatusForText??payload.sourceStatus,evidenceNotice:payload.evidenceNotice}}function projectProgress(progress){if(!progress)return;return{targetsReady:progress.targetsReady,targetsTotal:progress.targetsTotal,elapsedMs:progress.elapsedMs,...progress.requestedSources?.length?{requestedSources:progress.requestedSources.map((source)=>source.toLowerCase())}:{}}}function projectTargets(progress){return(progress?.targets??[]).map((target)=>({...target.requested?{requested:target.requested}:{},...target.resolvedRequested?{fresh:target.resolvedRequested}:{},...target.served?{served:target.served}:{},...target.freshness?{freshness:target.freshness}:{}}))}function projectLifecycle(payload,progress){if(payload.completed)return{kind:"completed",status:"COMPLETED"};const status=progress?.status;switch(status){case"PENDING":case"INDEXING":case"SEARCHING":return{kind:"active",status};case"DEFERRED":case"TIMEOUT":case"FAILED":return{kind:"terminal",status};default:return{kind:"unknown",status}}}function projectAvailability(snapshot,lifecycle){if(!snapshot){return{kind:"no_snapshot",hasSnapshot:false,resultCount:0,partialResults:false}}const resultCount=snapshot.results.length;const kind=resultCount===0?"empty":snapshot.partialResults?"partial":lifecycle.kind==="active"?"interim":"final";return{kind,hasSnapshot:true,resultCount,partialResults:snapshot.partialResults}}function projectSources(sourceStatus){if(!sourceStatus)return[];const groups=[];for(const entry of sourceStatus){if(entry.contributors&&entry.contributors.length>0){for(const contributor of entry.contributors){const kind=contributor.kind==="DOCPACK"?"site_docs":"repository_docs";const identity=contributorIdentity(entry,contributor);appendSourceEntry(groups,kind,{state:contributorState(contributor.state),...identity,resultCount:contributor.resultCount})}continue}const kind=sourceKind(entry);const terminalReason=sourceTerminalReason(entry);appendSourceEntry(groups,kind,{state:sourceState(entry),...sourceIdentity(entry,kind),resultCount:entry.resultCount,...terminalReason?{terminalReason}:{}})}return groups}function projectSiteSuggestions(sourceStatus){return(sourceStatus??[]).filter((entry)=>Boolean(entry.suggestedSiteTargets?.length)||entry.suggestedSiteTargetsTruncated===true).map((entry)=>({target:sourceTarget(entry),suggestions:[...entry.suggestedSiteTargets??[]],truncated:entry.suggestedSiteTargetsTruncated===true}))}function appendSourceEntry(groups,kind,entry){const group=groups.find((candidate)=>candidate.kind===kind);if(group)group.entries.push(entry);else groups.push({kind,entries:[entry]})}function sourceKind(entry){const source=entry.source.toLowerCase();if(source==="code")return"code";if(source==="symbol")return"symbols";if(isSiteTarget(entry.targetLabel,entry))return"site_docs";return entry.targetResolution?.served?.repoUrl?"repository_docs":"docs"}function contributorIdentity(entry,contributor){const searchTarget=sourceTarget(entry);const target=contributor.kind==="REPOSITORY_DOCS"?contributor.repositoryUrl??searchTarget:contributor.siteUrl??contributor.siteKey??searchTarget;return{target,searchTarget,...sourceTargetAliases(entry),...contributor.repositoryUrl?{repositoryUrl:contributor.repositoryUrl}:{},...contributor.commitSha?{commitSha:contributor.commitSha}:{},...contributor.siteKey?{siteKey:contributor.siteKey}:{},...contributor.siteUrl?{siteUrl:contributor.siteUrl}:{}}}function sourceIdentity(entry,kind){const target=sourceTarget(entry);const served=entry.targetResolution?.served;const identity=kind==="repository_docs"?{...served?.repoUrl?{repositoryUrl:served.repoUrl}:{},...served?.commitSha?{commitSha:served.commitSha}:{}}:kind==="site_docs"&&served?.site?{siteKey:served.site}:{};return{target,searchTarget:target,...sourceTargetAliases(entry),...identity}}function sourceTargetAliases(entry){const aliases=uniqueAliases([entry.targetLabel,entry.requestedTarget,entry.freshTarget,entry.servedTarget]);return{...aliases.length>1?{targetAliases:aliases}:{},...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{},...entry.freshTarget?{freshTarget:entry.freshTarget}:{},...entry.servedTarget?{servedTarget:entry.servedTarget}:{}}}function sourceTarget(entry){return entry.servedTarget??entry.targetLabel}function sourceState(entry){const states=[entry.indexingStatus,entry.codeIndexState].filter((state)=>Boolean(state));if(states.length===0)return"searched";if(states.some((state)=>["INDEXING","PENDING"].includes(state))){return"waiting"}return states.every((state)=>["CURRENT","INDEXED","PROVISIONAL","STALE"].includes(state))?"searched":"unavailable"}function sourceTerminalReason(entry){const kind=[entry.indexingStatus,entry.codeIndexState].find((state)=>state==="NOT_FOUND"||state==="UNRESOLVABLE");if(!kind)return;const family=classifyTargetFamily(entry);const requestedTarget=entry.requestedTarget??entry.targetLabel;const specificity=terminalSpecificity(family,requestedTarget);return{kind:kind.toLowerCase(),family,...specificity?{specificity}:{}}}function terminalSpecificity(family,target){try{if(family==="package"&&parsePackageSpec(target).version){return"version"}if(family==="repository"&&parseRepositoryTargetSpec(target).gitRef){return"ref"}}catch{return}return}function contributorState(state){const readiness={SEARCHED:"searched",READY:"available_not_searched",PENDING:"waiting",UNAVAILABLE:"unavailable"};return readiness[state]}function repositoryHitsForSource(snapshot,entry){const targets=entry.requestedTarget?[entry.requestedTarget]:[entry.targetLabel,entry.servedTarget];return(snapshot?.results??[]).filter((hit)=>hit.type===(entry.source.toLowerCase()==="symbol"?"repository_symbol":entry.source.toLowerCase()==="code"?"repository_code":"repository_doc")&&targets.includes(hit.requestedTarget??hit.target))}function hasRepositoryEvidence(snapshot,entry){const served=entry.targetResolution?.served;return Boolean(served?.repoUrl&&served.commitSha&&entry.resultCount!==0&&repositoryHitsForSource(snapshot,entry).some((hit)=>hit.locator.repoUrl===served.repoUrl&&hit.locator.commitSha===served.commitSha))}function projectProvenance(snapshot,progress){const records=[];for(const entry of snapshot?.sourceStatus??[]){const resolution=entry.targetResolution;const target=entry.requestedTarget??entry.targetLabel;const sources=[];const alias=isKnownPackageTarget(target)||explicitRepositoryRef(target)?[`requested: ${target}`]:[];if(entry.contributors?.length){for(const contributor of entry.contributors){if(contributor.state!=="SEARCHED")continue;const identity=contributor.kind==="REPOSITORY_DOCS"?{site:undefined,repoUrl:contributor.repositoryUrl,commitSha:contributor.commitSha,...sameRepositoryCommit({repoUrl:contributor.repositoryUrl,commitSha:contributor.commitSha},resolution?.served)?{gitRef:resolution?.served?.gitRef,committedAt:resolution?.served?.committedAt}:{}}:{repoUrl:undefined,commitSha:undefined,site:contributor.siteUrl?`site:${contributor.siteUrl.replace(/^https?:\/\//i,"").replace(/\/$/,"")}`:contributor.siteKey?`site:${contributor.siteKey}`:undefined};sources.push({target,identity,qualifiers:[contributor.kind==="DOCPACK"?"hosted documentation":"repository docs",...identity.repoUrl||identity.site&&identity.site!==target?alias:[],...contributor.freshness==="PROVISIONAL"?["provisional"]:contributor.freshness==="STALE"?["older snapshot"]:[],...contributor.coverage?.coverageState&&["PARTIAL","CAPPED"].includes(contributor.coverage.coverageState)?[`${contributor.coverage.pagesCrawled===undefined?"":`${contributor.coverage.pagesCrawled} pages, `}${contributor.coverage.coverageState.toLowerCase()}`]:[],...contributor.resultCount===0?[snapshot?.hasMore?"no results on this page":"no results"]:[]]})}}else if(resolution?.served?.repoUrl&&resolution.served.commitSha?hasRepositoryEvidence(snapshot,entry)||sourceState(entry)==="searched"&&entry.resultCount===0:sourceState(entry)==="searched"){const identities=resolution?.served?[resolution.served]:[...new Map(repositoryHitsForSource(snapshot,entry).filter((hit)=>hit.locator.repoUrl&&hit.locator.commitSha).map((hit)=>[JSON.stringify([hit.locator.repoUrl,hit.locator.commitSha]),{repoUrl:hit.locator.repoUrl,commitSha:hit.locator.commitSha}])).values()];for(const identity of identities.length?identities:[undefined])sources.push({target:entry.servedTarget??target,identity:isSiteTarget(entry.targetLabel,entry)?{site:target}:identity,qualifiers:[...!["code","symbol"].includes(entry.source.toLowerCase())?[isSiteTarget(entry.targetLabel,entry)?"hosted documentation":identity?.repoUrl?"repository docs":"docs"]:[],...(new Set((snapshot?.sourceStatus??[]).map((source)=>source.source)).size>1||!resolution?.served?.repoUrl)&&["code","symbol"].includes(entry.source.toLowerCase())?[entry.source.toLowerCase()==="symbol"?"symbols":"code"]:[],...identity?.repoUrl||entry.servedTarget&&entry.servedTarget!==target?alias:[],...resolution?.freshness==="fallback_recent"||entry.codeIndexState==="STALE"?["older snapshot"]:[],...resolution?.freshness==="provisional"||entry.codeIndexState==="PROVISIONAL"?["provisional"]:[],...entry.coverage&&["PARTIAL","CAPPED"].includes(entry.coverage.coverageState)?[`${entry.coverage.pagesCrawled===undefined?"":`${entry.coverage.pagesCrawled} pages, `}${entry.coverage.coverageState.toLowerCase()}`]:[],...entry.resultCount===0?[snapshot?.hasMore?"no results on this page":"no results"]:[]]})}records.push({target,sources,...resolution?{resolution:projectProvenanceResolution(resolution)}:{}})}for(const target of progress?.targets??[]){if(target.targetResolution&&!records.some((record)=>record.target===target.requested&&record.resolution))records.push({target:target.requested??target.served??"target",sources:[],resolution:projectProvenanceResolution(target.targetResolution)})}return records}function projectProvenanceResolution(resolution){return{requested:resolution.requested,resolvedRequested:resolution.resolvedRequested,served:resolution.served,freshness:resolution.freshness,...["requested_ref_indexing","no_current_fallback"].includes(resolution.freshnessReason??"")?{freshnessReason:resolution.freshnessReason}:{}}}function explicitRepositoryRef(target){try{const ref=parseRepositoryTargetSpec(target).gitRef;return Boolean(ref&&ref!=="HEAD")}catch{return false}}function isKnownPackageTarget(target){try{return isKnownRegistry(parsePackageSpec(target).registry)}catch{return false}}function projectTrustLimits(snapshot,sources,sourceStatus){const limits=new Map;const add=(limit)=>{const key=limit.kind==="stale"?`stale:${limit.requestedTarget??""}:${limit.servedTarget??limit.target??""}`:JSON.stringify(limit);const existing=limits.get(key);if(existing===undefined||limit.kind==="stale"&&existing.kind==="stale"&&staleSpecificity(limit)>staleSpecificity(existing)){limits.set(key,limit)}};for(const group of sources){for(const entry of group.entries){if(entry.state!=="searched"){add({kind:"source",source:group.kind,state:entry.state,target:entry.target,...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{}})}}}for(const hit of snapshot?.results??[]){if(hit.freshness==="STALE"||hit.freshness==="INDEXING"){add({kind:"stale",target:hit.servedTarget??hit.target,requestedTarget:hit.requestedTarget,freshTarget:hit.freshTarget,servedTarget:hit.servedTarget})}}for(const entry of sourceStatus??[]){const target=sourceTarget(entry);const resolution=entry.targetResolution;const freshness=resolution?.freshness;const served=resolution?.served;const requestedSha=resolution?.resolvedRequested?.commitSha;const servedSha=served?.commitSha;const hasRepositoryHits=hasRepositoryEvidence(snapshot,entry);const searchedRepositorySnapshot=hasRepositoryHits||entry.resultCount===0&&sourceState(entry)==="searched";if(searchedRepositorySnapshot&&servedSha&&served?.repoUrl&&(freshness!=="current"||["INDEXING","STALE","PROVISIONAL"].includes(entry.codeIndexState??""))){const headIntent=["repo_default_branch","repo_head"].includes(resolution?.requested?.kind??"");const requestedRef=headIntent?"HEAD":resolution?.requested?.gitRef??resolution?.resolvedRequested?.gitRef;const requestedCommitDiffers=Boolean(requestedSha&&requestedSha!==servedSha);add({kind:"repository_snapshot",target,requestedTarget:entry.requestedTarget,commitTarget:formatRepositoryTarget(served.repoUrl,servedSha.slice(0,8)),...served.committedAt?{servedCommitDate:served.committedAt.slice(0,10)}:{},...requestedCommitDiffers&&resolution?.resolvedRequested?.committedAt?{requestedCommitDate:resolution.resolvedRequested.committedAt.slice(0,10)}:{},...served.gitRef&&!/^[0-9a-f]{7,40}$/i.test(served.gitRef)?{indexedRef:served.gitRef}:{},requestedRef,requestedCommitDiffers,priorHead:hasRepositoryHits&&headIntent&&freshness==="fallback_recent"&&requestedCommitDiffers,...resolution?.freshnessReason==="requested_ref_indexing"&&requestedRef?{indexingRequestedRef:requestedRef}:{}})}const repositoryResolution=Boolean(served?.repoUrl||resolution?.requested?.kind?.startsWith("repo_"));if((entry.codeIndexState==="STALE"||freshness==="fallback_recent")&&!(servedSha&&requestedSha===servedSha)&&(!repositoryResolution||hasRepositoryHits)){add({kind:"stale",target,requestedTarget:entry.requestedTarget,freshTarget:entry.freshTarget,servedTarget:entry.servedTarget})}if(entry.codeIndexState==="PROVISIONAL"||freshness==="provisional"||entry.contributors?.some((contributor)=>contributor.freshness==="PROVISIONAL")){add({kind:"provisional",target,...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{}})}const kind=sourceKind(entry);addCoverage(add,kind,target,entry.requestedTarget,entry.coverage);for(const contributor of entry.contributors??[]){const contributorTargetValue=contributorIdentity(entry,contributor);if(contributor.freshness==="STALE"){add({kind:"stale",target:contributorTargetValue.target,...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{}})}addCoverage(add,contributor.kind==="DOCPACK"?"site_docs":"repository_docs",contributorTargetValue.target,entry.requestedTarget,contributor.coverage)}addConstraints(add,entry)}if(snapshot?.evidenceNotice!==undefined){add({kind:"mutable_evidence"})}return[...limits.values()]}function staleSpecificity(limit){return[limit.requestedTarget,limit.freshTarget,limit.servedTarget].filter(Boolean).length}function addCoverage(add,source,target,requestedTarget,coverage){if(!coverage||!["PARTIAL","CAPPED"].includes(coverage.coverageState)){return}add({kind:"coverage",source,state:coverage.coverageState.toLowerCase(),target,...requestedTarget?{requestedTarget}:{},pagesCrawled:coverage.pagesCrawled,frontierRemaining:typeof coverage.frontierRemaining==="number"?coverage.frontierRemaining:undefined,estimatedTotalPages:coverage.estimatedTotalPages})}function addConstraints(add,entry){const target=entry.targetLabel;for(const[constraint,values]of sourceConstraints(entry)){if(values?.length)add({kind:"constraint",constraint,source:normalizeSourceLane(entry.source),target:target||undefined,values})}}function sourceConstraints(entry){return[["ignored_filter",entry.ignoredFilters],["incompatible_filter",entry.incompatibleFilters],["ignored_query_feature",entry.ignoredQueryFeatures],["incompatible_query_feature",entry.incompatibleQueryFeatures]]}function projectWarnings(query,sourceStatus,targetGroups){const warnings=[];for(const message of query?.warnings??[]){warnings.push({kind:"query",message})}for(const entry of sourceStatus??[]){const source=normalizeSourceLane(entry.source);const target=entry.targetLabel||undefined;const aliases=uniqueAliases([entry.targetLabel,entry.requestedTarget,entry.freshTarget,entry.servedTarget]);const hasTargetOwner=findMatchingTargetGroup(targetGroups,aliases,entry.requestedTarget)!==undefined||targetGroups.length===1&&target===undefined;for(const[kind,values]of sourceConstraints(entry)){if(values?.length&&!hasTargetOwner){warnings.push({kind,source,target,values})}}}return warnings}function normalizeSourceLane(source){const normalized=source?.trim().toLowerCase();return normalized||undefined}function projectAlternatives(progress,sourceStatus){const candidates=[...(progress?.targets??[]).map((target)=>({target:target.requested??target.resolvedRequested??target.served,requestedTarget:target.requested,aliases:uniqueAliases([target.requested,target.resolvedRequested,target.served]),versions:target.targetResolution?.availableVersions??target.availableVersions??[],refs:target.targetResolution?.availableRefs??target.availableRefs??[],suggestedRefs:target.targetResolution?.suggestedRefs??target.suggestedRefs??[]})),...(sourceStatus??[]).flatMap((entry)=>{const resolution=entry.targetResolution;return resolution?[{target:entry.requestedTarget??sourceTarget(entry),requestedTarget:entry.requestedTarget,aliases:uniqueAliases([sourceTarget(entry),entry.targetLabel,entry.requestedTarget,entry.freshTarget,entry.servedTarget]),versions:resolution.availableVersions,refs:resolution.availableRefs,suggestedRefs:resolution.suggestedRefs??[]}]:[]})];return mergeAlternativeCandidates(candidates).filter((candidate)=>candidate.versions.length>0||candidate.refs.length>0||candidate.suggestedRefs.length>0).map((candidate)=>({target:candidate.target,...boundedAlternatives(candidate.versions,candidate.refs,candidate.suggestedRefs)}))}function projectTargetGroups(input){const groups=[];for(const identity of input.targets){const existing=groups.find((group)=>targetIdentitiesMatch(group.identity,identity));if(existing){existing.identity.requested??=identity.requested;existing.identity.fresh??=identity.fresh;existing.identity.served??=identity.served;existing.identity.freshness??=identity.freshness;existing.freshnessKind??=classifyTargetFreshness(identity.freshness);continue}groups.push({identity:{...identity},freshnessKind:classifyTargetFreshness(identity.freshness),sources:[],siteSuggestions:[],trustLimits:[]})}const findOrCreate=(target)=>{return findOrCreateForAliases(target?[target]:[],target)};const findOrCreateForAliases=(aliases,target,requestedTarget)=>{const existing=findMatchingTargetGroup(groups,aliases,requestedTarget);if(existing)return existing;const created={identity:requestedTarget||target?{requested:requestedTarget??target}:{},sources:[],siteSuggestions:[],trustLimits:[]};groups.push(created);return created};for(const limit of input.trustLimits){if(limit.kind!=="stale"||!limit.requestedTarget&&!limit.freshTarget&&!limit.servedTarget){continue}const aliases=uniqueAliases([limit.requestedTarget,limit.freshTarget,limit.servedTarget,limit.target]);const group=findMatchingTargetGroup(groups,aliases,limit.requestedTarget)??findOrCreateForAliases(aliases,aliases[0],limit.requestedTarget);if(limit.requestedTarget)group.identity.requested=limit.requestedTarget;if(limit.freshTarget)group.identity.fresh=limit.freshTarget;if(limit.servedTarget)group.identity.served=limit.servedTarget}for(const sourceGroup of input.sources){for(const entry of sourceGroup.entries){const aliases=entry.targetAliases??[entry.searchTarget];const group=findMatchingTargetGroup(groups,aliases,entry.requestedTarget)??findOrCreateForAliases(aliases,entry.searchTarget,entry.requestedTarget);if(entry.requestedTarget){group.identity.requested??=entry.requestedTarget}if(entry.freshTarget)group.identity.fresh??=entry.freshTarget;if(entry.servedTarget)group.identity.served??=entry.servedTarget;const existingSource=group.sources.find((candidate)=>candidate.kind===sourceGroup.kind);if(existingSource)existingSource.entries.push(entry);else group.sources.push({kind:sourceGroup.kind,entries:[entry]})}}for(const alternatives of input.alternatives){const aliases=uniqueAliases([alternatives.target]);const group=findMatchingTargetGroup(groups,aliases,alternatives.target)??findOrCreateForAliases(aliases,alternatives.target);group.alternatives=alternatives}for(const suggestion of input.siteSuggestions){findOrCreate(suggestion.target).siteSuggestions.push(suggestion)}for(const limit of input.trustLimits){if(limit.kind==="mutable_evidence"){continue}const target="target"in limit?limit.target:undefined;const requestedTarget="requestedTarget"in limit?limit.requestedTarget:undefined;const aliases=limit.kind==="stale"?uniqueAliases([limit.requestedTarget,limit.freshTarget,limit.servedTarget,limit.target]):uniqueAliases([requestedTarget,target]);const sourceGroup=findMatchingTargetGroup(groups,aliases,requestedTarget);const group=sourceGroup??(groups.length===1?groups[0]:undefined)??findOrCreateForAliases(aliases,target,requestedTarget);if(limit.kind==="stale"){if(limit.requestedTarget)group.identity.requested=limit.requestedTarget;if(limit.freshTarget)group.identity.fresh=limit.freshTarget;if(limit.servedTarget)group.identity.served=limit.servedTarget}group.trustLimits.push(limit)}for(const group of groups){const recovery=projectTargetRecovery(group,input.lifecycle,input.availability,input.snapshot);if(recovery)group.recovery=recovery}return groups.filter((group)=>targetIdentityValues(group.identity).length>0||group.sources.length>0||group.alternatives!==undefined||group.siteSuggestions.length>0||group.trustLimits.length>0||group.recovery!==undefined)}function targetIdentityValues(identity){return[identity.requested,identity.fresh,identity.served].filter((value)=>Boolean(value))}function targetGroupMatchesAliases(group,aliases){return targetIdentityValues(group.identity).some((value)=>aliases.includes(value))||group.sources.some((source)=>source.entries.some((entry)=>[...entry.targetAliases??[],entry.target,entry.searchTarget].some((value)=>value!==undefined&&aliases.includes(value))))}function findMatchingTargetGroup(groups,aliases,requestedTarget){if(requestedTarget){const requestedMatch=groups.find((group)=>group.identity.requested===requestedTarget);if(requestedMatch)return requestedMatch}const directRequestedMatches=groups.filter((group)=>group.identity.requested!==undefined&&aliases.includes(group.identity.requested));if(directRequestedMatches.length===1)return directRequestedMatches[0];const matches=groups.filter((group)=>targetGroupMatchesAliases(group,aliases));return matches.length===1?matches[0]:undefined}function targetIdentitiesMatch(left,right){if(left.requested!==undefined&&right.requested!==undefined&&left.requested!==right.requested){return false}return targetIdentityValues(left).some((target)=>targetIdentityValues(right).includes(target))}function uniqueAliases(values){return[...new Set(values.filter((value)=>Boolean(value)))]}function targetDisplayFamilyKey(target){if(!target)return"";const normalized=target.trim().replace(/\s+latest$/,"").replace(/#[^#]+$/,"");return normalized.startsWith("npm:")?normalized.replace(/@[^/@]+$/,""):normalized.replace(/@[^#]+$/,"")}function classifyTargetFreshness(freshness){switch(freshness?.toLowerCase()){case"current":case"indexed":return"current";case"stale":case"fallback_recent":return"stale";case"indexing":return"indexing";case"pending":return"pending";case"provisional":return"provisional";default:return}}function mergeAlternativeCandidates(candidates){const merged=[];for(const candidate of candidates){const existing=merged.find((value)=>!(candidate.requestedTarget&&value.requestedTarget&&candidate.requestedTarget!==value.requestedTarget)&&candidate.aliases.some((alias)=>value.aliases.includes(alias)));if(existing){existing.aliases=uniqueAliases([...existing.aliases,...candidate.aliases]);existing.versions.push(...candidate.versions);existing.refs.push(...candidate.refs);existing.suggestedRefs.push(...candidate.suggestedRefs);existing.requestedTarget??=candidate.requestedTarget}else{merged.push({target:candidate.target,requestedTarget:candidate.requestedTarget,aliases:[...candidate.aliases],versions:[...candidate.versions],refs:[...candidate.refs],suggestedRefs:[...candidate.suggestedRefs]})}}return merged}function boundedAlternatives(versions,refs,suggestedRefs){const bounded=(values)=>{const seen=new Set;const display=[];let remaining=0;for(const value of values){const key=`${value.version??""}\x00${value.ref}`;if(seen.has(key))continue;seen.add(key);if(display.length<MAX_ALTERNATIVES)display.push(value);else remaining++}return{values:display,remaining}};const versionFacts=bounded(versions.filter((alternative)=>alternative.version!==undefined));const refFacts=bounded([...refs,...versions.filter((alternative)=>alternative.version===undefined)]);const suggestedRefFacts=bounded(suggestedRefs);return{versions:versionFacts.values,versionsRemaining:versionFacts.remaining,refs:refFacts.values,refsRemaining:refFacts.remaining,suggestedRefs:suggestedRefFacts.values,suggestedRefsRemaining:suggestedRefFacts.remaining}}function projectAction(input){if(input.lifecycle.kind==="active"){return input.searchRef?{kind:"poll",searchRef:input.searchRef,waitTimeoutMs:indexingWaitMs(input.indexingEstimates),...input.availability.resultCount>0?{useResults:true}:{}}:{kind:"none"}}if(input.lifecycle.kind==="completed"&&input.snapshot?.evidenceNotice!==undefined){return{kind:"new_search",...input.availability.resultCount>0?{useResults:true}:{}}}const hasLocalRecovery=input.targetGroups.some((group)=>group.recovery!==undefined);const hasBareTerminalReason=input.targetGroups.some(hasBareTerminalReasonForGroup);if((input.lifecycle.kind==="terminal"||input.lifecycle.kind==="unknown")&&hasLocalRecovery){return{kind:"none"}}if(input.lifecycle.kind==="terminal"||input.lifecycle.kind==="unknown"){return{kind:"new_search",...input.availability.resultCount>0?{useResults:true}:{}}}if(!input.snapshot||input.availability.kind!=="empty"){return{kind:"none"}}if(hasLocalRecovery)return{kind:"none"};const hasIndexing=input.targetGroups.some((group)=>groupHasIndexing(group));if(hasIndexing)return{kind:"new_search"};if(hasBareTerminalReason){return projectQueryRewrite(input.snapshot.query)}if(input.targetGroups.some((group)=>group.trustLimits.some((limit)=>limit.kind==="source"||limit.kind==="coverage"||limit.kind==="mutable_evidence"||limit.kind==="stale"))){return{kind:"new_search"}}if(input.snapshot.sourceStatus?.length&&input.snapshot.sourceStatus.every((entry)=>isSiteTarget(entry.targetLabel,entry))){return{kind:"query_rewrite",rewrites:["site_shorter_or_broader"]}}return projectQueryRewrite(input.snapshot.query)}function projectQueryRewrite(query){const rewrites=["shorter_or_broader"];if(hasRestrictiveFilters(query))rewrites.push("remove_filters");const symbolSource=query?.sources?.some((source)=>source.toLowerCase()==="symbol");if(!symbolSource)rewrites.push("symbol");rewrites.push("code_grep");return{kind:"query_rewrite",rewrites}}function projectTargetRecovery(group,lifecycle,availability,snapshot){const hasTerminalReason=groupHasTerminalReason(group);const hasBareTerminalReason=hasBareTerminalReasonForGroup(group);const alternative=projectAlternativeRecovery(group);const site=projectSiteRecovery(group);const candidate=site??alternative;if(lifecycle.kind==="active"){return hasTerminalReason&&!hasBareTerminalReason?candidate??fixRecovery(group):undefined}if(lifecycle.kind==="terminal"||lifecycle.kind==="unknown"){if(hasBareTerminalReason)return;if(candidate)return candidate;return hasTerminalReason?fixRecovery(group):undefined}if(lifecycle.kind==="completed"&&hasTerminalReason){return hasBareTerminalReason?undefined:candidate??fixRecovery(group)}if(availability.kind!=="empty"||!snapshot)return;if(site)return site;return groupHasIndexing(group)?alternative:undefined}function projectAlternativeRecovery(group){const alternatives=group.alternatives;if(!alternatives)return;const identity=primaryTargetIdentity(group);if(!identity)return;const family=groupTerminalFamily(group)??familyForTarget(identity);if(family==="package"){const versions=alternatives.versions.map((alternative)=>composePackageTarget(identity,alternative.version)).filter((target)=>target!==undefined);const target=versions[0];if(!target)return;return{kind:"try",category:"version",target,additionalTargets:versions.slice(1),truncated:alternatives.versionsRemaining>0}}if(family==="repository"){const refs=[...alternatives.refs,...alternatives.suggestedRefs].map((alternative)=>composeRepositoryTarget(identity,alternative.ref)).filter((target)=>target!==undefined);const unique=[...new Set(refs)];const target=unique[0];if(!target)return;return{kind:"try",category:"ref",target,additionalTargets:unique.slice(1),truncated:alternatives.refsRemaining>0||alternatives.suggestedRefsRemaining>0}}return}function projectSiteRecovery(group){const suggestions=[...new Set(group.siteSuggestions.flatMap((suggestion)=>suggestion.suggestions))];const target=suggestions[0];if(!target)return;return{kind:"try",category:"site",target,additionalTargets:suggestions.slice(1),truncated:group.siteSuggestions.some((suggestion)=>suggestion.truncated)}}function fixRecovery(group){return{kind:"fix",family:groupTerminalFamily(group)??familyForTarget(primaryTargetIdentity(group))}}function primaryTargetIdentity(group){return group.identity.requested??group.identity.fresh??group.identity.served??group.alternatives?.target}function groupTerminalReason(group){for(const source of group.sources){for(const entry of source.entries){if(entry.terminalReason)return entry.terminalReason}}return}function groupTerminalFamily(group){return groupTerminalReason(group)?.family}function groupHasTerminalReason(group){return groupTerminalReason(group)!==undefined}function groupHasIndexing(group){return group.freshnessKind==="indexing"||group.freshnessKind==="pending"||group.sources.some((source)=>source.entries.some((entry)=>entry.state==="waiting"))}function hasBareTerminalReasonForGroup(group){return groupHasTerminalReason(group)&&group.sources.some((source)=>source.entries.some((entry)=>entry.state==="searched"||entry.state==="waiting"))}function familyForTarget(target){if(!target)return"unknown";if(isSiteTarget(target,{targetLabel:target,source:"docs"})){return"site"}const packageSeparator=target.indexOf(":");if(packageSeparator>0&&parsePkgseerRegistryArg(target.slice(0,packageSeparator))){return"package"}try{parseRepositoryTargetSpec(target);return"repository"}catch{return"unknown"}}function composePackageTarget(identity,version){if(!version)return;try{const parsed=parsePackageSpec(identity.trim().replace(/\s+latest$/,""));return`${parsed.registry}:${parsed.name}@${version}`}catch{return}}function composeRepositoryTarget(identity,ref){try{const parsed=parseRepositoryTargetSpec(identity);if(!parsed.repoUrl)return;return formatRepositoryTarget(parsed.repoUrl,ref)}catch{return}}function classifyTargetFamily(entry){if(isSiteTarget(entry.targetLabel,entry))return"site";const target=entry.targetLabel.trim().toLowerCase();const separator=target.indexOf(":");if(separator>0&&parsePkgseerRegistryArg(target.slice(0,separator))){return"package"}if(familyForTarget(target)==="repository"||entry.targetResolution?.requested?.repoUrl||entry.targetResolution?.resolvedRequested?.repoUrl||entry.targetResolution?.served?.repoUrl){return"repository"}return"unknown"}function hasRestrictiveFilters(query){const filters=query?.filters;return Boolean(filters?.kind||filters?.category||filters?.pathPrefix||filters?.fileIntent||filters?.publicOnly===true||query?.raw&&/(?:^|\s)(?:kind|category|path|lang|name|intent):/i.test(query.raw))}function isSiteTarget(target,entry){return Boolean(target.startsWith("site:")||entry.targetResolution?.requested?.site||entry.targetResolution?.resolvedRequested?.site||entry.targetResolution?.served?.site)}var DEFAULT_TEXT_WIDTH=80;function renderUnifiedSearchSuccess(payload,options={}){return renderUnifiedSearchPresentationText(projectUnifiedSearchPresentation(payload),payload,options)}function renderUnifiedSearchPresentationText(presentation,result,options={}){const settings=normalizeTextOptions(options);const lines=wrapTerminalProse(formatPresentationOutcome(presentation,result.results),settings.width).map((line)=>styleOutcome(line,presentation,settings.useColors));const notice=formatPresentationNotice(presentation);if(notice)lines.push(...wrapTerminalProse(notice,settings.width));appendPresentationContext(lines,presentation,settings);if(result.results.length>0){lines.push("");appendUnifiedSearchHits(lines,result.results,identifierQueryFragments(presentation.query?.raw),settings)}appendPresentationAction(lines,presentation,result,settings);return lines.join(`
|
|
201
|
+
${CODE_READ_GUARDRAIL}`;function createReadTool(services){return{name:"read",description:DESCRIPTION10,schema:readSchema,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{let locator;let wait;try{locator=resolveReadLocator(args.target,args.path);if(args.selector!==undefined&&(typeof args.selector!=="string"||!args.selector.trim())){throw new InvalidPackageSpecError("selector must be a nonblank string.")}validateReadRange(args.start_line,args.end_line);wait=normalizeReadWaitTimeoutMs(args.wait_timeout_ms);if(args.format!==undefined&&args.format!=="text"&&args.format!=="json"){throw new InvalidPackageSpecError("format must be text or json.")}}catch(error){return mcpMappedErrorResult(mapCodeNavigationError(error),context,args.format)}if(args.selector!==undefined||locator.path===undefined||locator.target.includes("#")||isSiteReadTarget(locator.target)){try{const response=await services.readService.read({target:locator.target,...locator.path?{path:locator.path}:{},...args.selector!==undefined?{selector:args.selector}:{},...args.start_line!==undefined?{startLine:args.start_line}:{},...args.end_line!==undefined?{endLine:args.end_line}:{},waitTimeoutMs:wait},...serviceRequestArgs(context?.signal));return textResult(formatReadResult(response,{target:locator.target,selector:args.selector,path:locator.path,endLine:args.end_line},args.format==="json"?"mcp-json":"mcp-text"))}catch(error){throwIfCallerCancellation(error,context?.signal);const docsError=mapPackageIntelligenceError(error);return mcpMappedErrorResult(withIndexingRetryAction(docsError.code!=="UNKNOWN"?docsError:mapCodeNavigationError(error),"read","mcp",{maxWaitMs:MAX_WAIT_TIMEOUT_MS}),context,args.format,{recovery:{syntax:"mcp",tool:"read",args},indexingTarget:args.target,indexingOutcome:"This content is not available yet."})}}return readSourceFile({...args,target:locator.target,path:locator.path,wait_timeout_ms:wait},createReadFileServiceAdapter(services.readService,locator.target,context?.signal),context)}}}import{z as z11}from"zod";var DEFAULT_UNIFIED_SEARCH_LIMIT=10;function buildUnifiedSearchParams(input){const targets=resolveTargets(input.target,input.targets);const rawQuery=normaliseRequiredQuery(input.query);const selectsAuto=!input.sources?.length||input.sources.includes("AUTO");const selectsCode=input.sources?.includes("CODE")||selectsAuto&&targets.some((target)=>!target.site);if(input.pathPrefix&&!selectsCode){throw new InvalidArgumentError("Path prefixes require a code search source. Remove the path prefix for documentation or symbol searches.")}const limit=input.limit??DEFAULT_UNIFIED_SEARCH_LIMIT;const offset=input.offset??0;const waitTimeoutMs=input.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS;const qualifierClauses=buildQualifierClauses({name:input.name,language:input.language});const compiledQuery=compileQuery(rawQuery,qualifierClauses);const stripCodeAndSymbolFilters=isDocsOnlySource(input.sources);const filters=buildFilters({kind:stripCodeAndSymbolFilters?undefined:input.kind,category:stripCodeAndSymbolFilters?undefined:input.category,pathPrefix:input.pathPrefix,fileIntent:stripCodeAndSymbolFilters?undefined:input.fileIntent,publicOnly:stripCodeAndSymbolFilters?undefined:input.publicOnly});return{params:{targets,query:compiledQuery,sources:input.sources,filters,allowPartialResults:input.allowPartialResults??true,limit,offset,waitTimeoutMs},rawQuery,compiledQuery}}function isDocsOnlySource(sources){return sources?.length===1&&sources[0]==="DOCS"}function resolveTargets(target,targets){const nonEmptyTargets=targets?.length?targets:undefined;if(target&&nonEmptyTargets){throw new InvalidArgumentError("Provide either `target` for one search target or `targets` for multiple, not both.")}const resolved=target?[target]:nonEmptyTargets??[];if(resolved.length===0){throw new InvalidArgumentError("Provide either `target` for one search target or `targets` for multiple; neither was set.")}const deduped=[];const seen=new Set;for(const entry of resolved){const key=JSON.stringify(entry);if(seen.has(key))continue;seen.add(key);deduped.push(entry)}return deduped}function normaliseRequiredQuery(query){const trimmed=query.trim();if(trimmed.length===0){throw new InvalidArgumentError("Query cannot be empty.")}return trimmed}function buildQualifierClauses(input){const clauses=[];if(input.name){clauses.push(`name:${quoteQualifierValue(input.name)}`)}if(input.language){clauses.push(`lang:${quoteQualifierValue(input.language)}`)}return clauses}function quoteQualifierValue(value){const trimmed=value.trim();if(trimmed.length===0){throw new InvalidArgumentError("Structured qualifier values cannot be empty.")}if(!needsQuoting(trimmed)){return trimmed}return`"${trimmed.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function needsQuoting(value){return/\s|[():"]|\bAND\b|\bOR\b|-/.test(value)}function compileQuery(rawQuery,qualifierClauses){if(qualifierClauses.length===0){return rawQuery}return`(${rawQuery}) AND (${qualifierClauses.join(" AND ")})`}function buildFilters(input){const filters={};if(input.kind)filters.kind=input.kind;if(input.category)filters.category=input.category;if(input.pathPrefix)filters.pathPrefix=input.pathPrefix;if(input.fileIntent)filters.fileIntent=input.fileIntent;if(input.publicOnly===true){filters.publicOnly=input.publicOnly}return Object.keys(filters).length>0?filters:undefined}function buildSearchHitFollowUpCommand(hit,syntax="mcp"){const action=hit.readTarget;if(action){const matched=hit.repositoryEvidence?.matchedSource;const evidence=hit.repositoryEvidence?.semanticContext?matched?{startLine:matched.startLine,endLine:matched.endLine,matchLine:matched.matchLine??undefined}:undefined:hit.locator.evidenceRange;return renderReadTarget(syntax==="mcp"?capSearchReadTarget(action,evidence):action,syntax)}const loc=hit.locator;const code=hit.type==="repository_code"||hit.type==="repository_symbol";if(code&&loc.repoUrl&&!loc.commitSha&&!isPackageTarget(hit))return"follow-up unavailable: missing exact revision";if(code&&!loc.filePath&&!loc.repositoryFilePath)return"follow-up unavailable: missing filePath";return"follow-up unavailable: missing read target"}function isPackageTarget(hit){const registry=hit.locator.registry;const packageName=hit.locator.packageName;return Boolean(registry&&packageName&&hit.target.startsWith(`${registry}:${packageName}`))}function isHealthySearchLifecycleState(state){return state==="INDEXED"||state==="CURRENT"}var DEFAULT_LIMIT=DEFAULT_UNIFIED_SEARCH_LIMIT;var DEFAULT_OFFSET=0;function isActiveUnifiedSearchSessionStatus(status){return status==="PENDING"||status==="INDEXING"||status==="SEARCHING"}function projectHitPayload(hit){return{type:hit.type,target:hit.target,locator:hit.locator,...hit.requestedTarget!==undefined?{requestedTarget:hit.requestedTarget}:{},...hit.freshTarget!==undefined?{freshTarget:hit.freshTarget}:{},...hit.servedTarget!==undefined?{servedTarget:hit.servedTarget}:{},...hit.freshness!==undefined?{freshness:hit.freshness}:{},...hit.title!==undefined?{title:hit.title}:{},...hit.highlights!==undefined?{highlights:hit.highlights}:{},...hit.repositoryEvidence!==undefined?{repositoryEvidence:hit.repositoryEvidence}:{},...hit.documentationPreview!==undefined?{documentationPreview:hit.documentationPreview}:{},...hit.followUp!==undefined?{followUp:hit.followUp}:{}}}function projectUnifiedSearchSuccessPayload(payload){const projected={...payload};delete projected.sourceStatusForText;return{...projected,results:payload.results.map(projectHitPayload)}}function projectStatusResultPayload(payload){const projected={...payload};delete projected.sourceStatusForText;return{...projected,results:payload.results.map(projectHitPayload)}}function projectUnifiedSearchStatusPayload(payload){return payload.completed?{...payload,result:projectStatusResultPayload(payload.result)}:{...payload,...payload.result!==undefined?{result:projectStatusResultPayload(payload.result)}:{}}}function buildUnifiedSearchSuccessPayload(params,rawQuery,compiledQuery,outcome){const warnings=outcome.state==="completed"?outcome.result.queryWarnings:outcome.result?.queryWarnings??outcome.progress?.queryWarnings??[];const progress=compactProgress(outcome.progress);const query=buildQueryEcho(params,rawQuery,compiledQuery,warnings);if(outcome.state==="incomplete"){const result=outcome.result;const payload={query,completed:false,hasMore:result?.page.hasMore??false,results:result?.results.map(buildHitPayload)??[],searchRef:outcome.searchRef};if(result)payload.partialResults=result.partialResults;if(result?.page.hasMore===true){payload.nextOffset=result.page.offset+result.page.returned}if(progress)payload.progress=progress;const sourceStatus=compactSourceStatus(result?.sourceStatus,{completed:false});if(sourceStatus)payload.sourceStatus=sourceStatus;const textSourceStatus=compactSourceStatus(result?.sourceStatus,{completed:false,includeHealthy:true});if(textSourceStatus)payload.sourceStatusForText=textSourceStatus;if(result?.evidenceNotice){payload.evidenceNotice=result.evidenceNotice}const combinedWarnings=combineWarnings(warnings,sourceStatus,payload.results,progress,false);if(combinedWarnings.length>0)payload.warnings=combinedWarnings;return payload}const completed={query,completed:true,partialResults:outcome.result.partialResults,hasMore:outcome.result.page.hasMore,results:outcome.result.results.map(buildHitPayload)};if(outcome.result.page.hasMore){completed.nextOffset=outcome.result.page.offset+outcome.result.page.returned}if(outcome.searchRef)completed.searchRef=outcome.searchRef;const sourceStatus=compactSourceStatus(outcome.result.sourceStatus,{completed:true,includeEmptyResultContext:completed.results.length===0});if(sourceStatus)completed.sourceStatus=sourceStatus;const textSourceStatus=compactSourceStatus(outcome.result.sourceStatus,{completed:true,includeEmptyResultContext:completed.results.length===0,includeHealthy:true});if(textSourceStatus)completed.sourceStatusForText=textSourceStatus;if(outcome.result.evidenceNotice){completed.evidenceNotice=outcome.result.evidenceNotice}const combinedWarnings=combineWarnings(warnings,sourceStatus,completed.results,undefined,true);if(combinedWarnings.length>0)completed.warnings=combinedWarnings;return completed}function combineWarnings(parserWarnings,sourceStatus,hits=[],progress,completed=false){const out=[];if(parserWarnings.length>0)out.push(...parserWarnings);out.push(...buildHitFreshnessWarnings(hits));out.push(...buildProgressFreshnessWarnings(progress));out.push(...buildSourceStatusWarnings(sourceStatus,{completed}));return Array.from(new Set(out))}function buildUnifiedSearchErrorPayload(error){const mapped=mapCodeNavigationError(error);const payload={error:mapped.message,code:mapped.code};if(typeof mapped.retryable==="boolean"){payload.retryable=mapped.retryable}if(mapped.details&&Object.keys(mapped.details).length>0){payload.details=mapped.details}return payload}function buildUnifiedSearchStatusPayload(outcome){if(outcome.state==="incomplete"){const payload={completed:false,searchRef:outcome.searchRef};const progress=compactProgress(outcome.progress);if(progress)payload.progress=progress;const progressWarnings=buildProgressFreshnessWarnings(progress);if(progressWarnings.length>0)payload.warnings=progressWarnings;if(outcome.result){payload.result=buildUnifiedSearchStatusResultPayload(outcome.result,{completed:false})}return payload}const payload={completed:true,result:buildUnifiedSearchStatusResultPayload(outcome.result,{completed:true})};if(outcome.searchRef)payload.searchRef=outcome.searchRef;return payload}function buildUnifiedSearchStatusResultPayload(result,options){const payload={query:buildStatusQueryEcho(result),partialResults:result.partialResults,hasMore:result.page.hasMore,results:result.results.map(buildHitPayload)};if(result.page.hasMore){payload.nextOffset=result.page.offset+result.page.returned}if(result.sources.length>0){payload.sources=result.sources.map((entry)=>entry.toLowerCase())}const sourceStatus=compactSourceStatus(result.sourceStatus,{...options,includeEmptyResultContext:options.completed&&result.results.length===0});if(sourceStatus)payload.sourceStatus=sourceStatus;const textSourceStatus=compactSourceStatus(result.sourceStatus,{...options,includeEmptyResultContext:options.completed&&result.results.length===0,includeHealthy:true});if(textSourceStatus)payload.sourceStatusForText=textSourceStatus;if(result.evidenceNotice)payload.evidenceNotice=result.evidenceNotice;const combinedWarnings=combineWarnings(result.queryWarnings,sourceStatus,[],undefined,options.completed);if(combinedWarnings.length>0){payload.warnings=combinedWarnings}return payload}function buildStatusQueryEcho(result){const query={raw:result.query};if(result.queryWarnings.length>0){query.warnings=result.queryWarnings}if(result.sources.length>0){query.sources=result.sources.map((entry)=>entry.toLowerCase())}return query}function buildQueryEcho(params,rawQuery,compiledQuery,warnings){const echo={raw:rawQuery};if(compiledQuery!==rawQuery){echo.compiled=compiledQuery}if(warnings.length>0){echo.warnings=warnings}if(params.sources&¶ms.sources.length>0){echo.sources=params.sources.map((entry)=>entry.toLowerCase())}if(params.filters){const filters={};if(params.filters.kind)filters.kind=params.filters.kind.toLowerCase();if(params.filters.category)filters.category=params.filters.category.toLowerCase();if(params.filters.pathPrefix)filters.pathPrefix=params.filters.pathPrefix;if(params.filters.fileIntent)filters.fileIntent=params.filters.fileIntent.toLowerCase();if(typeof params.filters.publicOnly==="boolean")filters.publicOnly=params.filters.publicOnly;if(Object.keys(filters).length>0)echo.filters=filters}if(params.allowPartialResults===false){echo.allowPartialResults=false}if(params.limit!==undefined&¶ms.limit!==DEFAULT_LIMIT){echo.limit=params.limit}if(params.offset!==undefined&¶ms.offset!==DEFAULT_OFFSET){echo.offset=params.offset}if(params.waitTimeoutMs!==undefined&¶ms.waitTimeoutMs!==DEFAULT_WAIT_TIMEOUT_MS){echo.waitTimeoutMs=params.waitTimeoutMs}return echo}function buildHitPayload(hit){assertSearchFollowUpInvariant(hit);const payload={type:hit.resultType.toLowerCase(),target:formatTargetLabel(hit.targetLabel,hit.locator.repoUrl),locator:buildLocatorPayload(hit)};if(hit.readTarget!==undefined)payload.readTarget=hit.readTarget;appendFreshness(payload,{requestedTargetLabel:hit.requestedTargetLabel,freshTargetLabel:hit.freshTargetLabel,servedTargetLabel:hit.servedTargetLabel,freshness:hit.freshness},hit.locator.repoUrl);if(hit.title)payload.title=hit.title;const highlights=buildHighlights(hit.highlights);if(highlights)payload.highlights=highlights;if(hit.repositoryEvidence!==undefined){if(hit.repositoryEvidence===null){payload.repositoryEvidence=null}else{const{focusedSource:_legacySource,...evidence}=hit.repositoryEvidence;payload.repositoryEvidence=evidence}}if(hit.documentationPreview!==undefined){payload.documentationPreview=hit.documentationPreview}const followUp=buildSearchHitFollowUpCommand(payload);if(followUp)payload.followUp=followUp;return payload}function formatTargetLabel(label,repoUrl){return formatRepositoryTargetLabel(label,repoUrl)??label}function buildLocatorPayload(hit){const locator={};const src=hit.locator;if(src.registry)locator.registry=src.registry;if(src.packageName)locator.packageName=src.packageName;if(src.version)locator.version=src.version;if(src.pageId)locator.pageId=src.pageId;if(src.docsReadTarget)locator.docsReadTarget=src.docsReadTarget;if(src.sourceKind)locator.sourceKind=src.sourceKind;if(src.sourceUrl)locator.sourceUrl=src.sourceUrl;if(src.repoUrl)locator.repoUrl=src.repoUrl;if(src.gitRef)locator.gitRef=src.gitRef;if(src.commitSha)locator.commitSha=src.commitSha;if(src.requestedRef)locator.requestedRef=src.requestedRef;if(src.filePath)locator.filePath=src.filePath;if(src.repositoryFilePath){locator.repositoryFilePath=src.repositoryFilePath}if(typeof src.startLine==="number")locator.startLine=src.startLine;if(typeof src.endLine==="number")locator.endLine=src.endLine;if(src.evidenceRange)locator.evidenceRange={...src.evidenceRange};if(src.indexedRange)locator.indexedRange={...src.indexedRange};if(src.symbolContext){if(src.symbolContext.relation==="encloses_match"){locator.symbolContext={name:src.symbolContext.name,relation:src.symbolContext.relation,definitionRange:{...src.symbolContext.definitionRange},...src.symbolContext.qualifiedPath?{qualifiedPath:src.symbolContext.qualifiedPath}:{},...src.symbolContext.kind?{kind:src.symbolContext.kind}:{}}}else{locator.symbolContext={name:src.symbolContext.name,relation:src.symbolContext.relation,...src.symbolContext.qualifiedPath?{qualifiedPath:src.symbolContext.qualifiedPath}:{},...src.symbolContext.kind?{kind:src.symbolContext.kind}:{},...src.symbolContext.definitionRange?{definitionRange:{...src.symbolContext.definitionRange}}:{}}}}if(src.qualifiedPath&&src.qualifiedPath!==hit.title){locator.qualifiedPath=src.qualifiedPath}if(src.kind)locator.kind=src.kind;if(src.category)locator.category=src.category;if(src.language)locator.language=src.language;return locator}function buildHighlights(highlights){if(!highlights)return;const compact={};if(highlights.title&&highlights.title.length>0){compact.title=highlights.title}return Object.keys(compact).length>0?compact:undefined}function compactProgress(progress){if(!progress)return;const payload={status:progress.status,targetsReady:progress.targetsReady,targetsTotal:progress.targetsTotal,elapsedMs:progress.elapsedMs};if(progress.query)payload.query=progress.query;if(progress.requestedSources?.length){payload.requestedSources=progress.requestedSources.map((entry)=>entry.toLowerCase())}if(progress.targetMode)payload.targetMode=progress.targetMode;if(progress.requestedTargets?.length){payload.requestedTargets=progress.requestedTargets}if(progress.filters)payload.filters=buildFilterEcho2(progress.filters);if(typeof progress.limit==="number")payload.limit=progress.limit;if(typeof progress.offset==="number")payload.offset=progress.offset;const targets=progress.targets?.map(compactProgressTarget).filter(Boolean);if(targets?.length){payload.targets=targets}if(progress.indexingEstimates!==undefined){payload.indexingEstimates=progress.indexingEstimates.map(compactIndexingEstimate)}if(progress.expiresAt)payload.expiresAt=progress.expiresAt;payload.next=isActiveUnifiedSearchSessionStatus(progress.status)?`search_status search_ref=${JSON.stringify(progress.searchRef)} wait_timeout_ms=${indexingWaitMs(progress.indexingEstimates)}`:"rerun search";return payload}function compactIndexingEstimate(estimate){return{...estimate,targets:estimate.kind==="REPOSITORY"?estimate.targets.map((target)=>formatRepositoryTargetLabel(target,estimate.repositoryUrl)??target):[...estimate.targets]}}function appendFreshness(payload,source,repoUrl){if(!isTrustRelevantFreshness(source.freshness)||!labelsDiverge({requestedTarget:source.requestedTargetLabel,freshTarget:source.freshTargetLabel,servedTarget:source.servedTargetLabel})){return}if(source.requestedTargetLabel)payload.requestedTarget=formatTargetLabel(source.requestedTargetLabel,repoUrl);if(source.freshTargetLabel)payload.freshTarget=formatTargetLabel(source.freshTargetLabel,repoUrl);if(source.servedTargetLabel)payload.servedTarget=formatTargetLabel(source.servedTargetLabel,repoUrl);if(source.freshness)payload.freshness=source.freshness}function compactProgressTarget(target){const payload={};if(target.requested)payload.requested=formatTargetLabel(target.requested,target.targetResolution?.requested?.repoUrl);if(target.resolvedRequested)payload.resolvedRequested=formatTargetLabel(target.resolvedRequested,target.targetResolution?.resolvedRequested?.repoUrl);if(target.served)payload.served=formatTargetLabel(target.served,target.targetResolution?.served?.repoUrl);if(target.freshness)payload.freshness=target.freshness;if(target.indexingRef)payload.indexingRef=target.indexingRef;if(target.requestedRefKind)payload.requestedRefKind=target.requestedRefKind;const targetResolution=projectTargetResolution(target.targetResolution);if(targetResolution)payload.targetResolution=targetResolution;if(target.availableVersions?.length){payload.availableVersions=target.availableVersions}if(target.availableRefs?.length){payload.availableRefs=target.availableRefs}if(target.suggestedRefs?.length){payload.suggestedRefs=target.suggestedRefs}const coverage=projectDocCoverage(target.coverage);if(coverage)payload.coverage=coverage;return Object.keys(payload).length>0?payload:undefined}function buildFilterEcho2(filters){const echo={};if(filters.kind)echo.kind=filters.kind.toLowerCase();if(filters.category)echo.category=filters.category.toLowerCase();if(filters.pathPrefix)echo.pathPrefix=filters.pathPrefix;if(filters.fileIntent)echo.fileIntent=filters.fileIntent.toLowerCase();if(typeof filters.publicOnly==="boolean"){echo.publicOnly=filters.publicOnly}return Object.keys(echo).length>0?echo:undefined}function buildSourceStatusWarnings(sourceStatus,options={}){if(!sourceStatus||sourceStatus.length===0)return[];const warnings=[];for(const entry of sourceStatus){const message=warningForEntry(entry,options);if(message!==undefined)warnings.push(message)}return warnings}function buildHitFreshnessWarnings(hits){return hits.map((hit)=>freshnessWarning({freshness:hit.freshness,requestedTarget:hit.requestedTarget,freshTarget:hit.freshTarget,servedTarget:hit.servedTarget})).filter((entry)=>Boolean(entry))}function buildProgressFreshnessWarnings(progress){return(progress?.targets??[]).map((target)=>freshnessWarning({freshness:target.freshness,requestedTarget:target.requested,freshTarget:target.resolvedRequested,servedTarget:target.served})).concat((progress?.targets??[]).map((target)=>progressTargetResolutionWarning(target)).filter((entry)=>Boolean(entry))).filter((entry)=>Boolean(entry))}function progressTargetResolutionWarning(target){const notes=buildTargetResolutionNotes(target.targetResolution??buildResolutionFromRetryCandidates(target));const coverage=docCoverageWarningReason(target.coverage);if(coverage)notes.push(coverage);return notes.length>0?notes.join(" "):undefined}function freshnessWarning(input){if(!isTrustRelevantFreshness(input.freshness))return;if(!labelsDiverge(input))return;const requested=input.requestedTarget??"requested target";const served=input.servedTarget??"served target";const fresh=input.freshTarget;return fresh?`requested ${requested}; served older snapshot ${served} while ${fresh} indexes.`:`requested ${requested}; served older snapshot ${served}.`}function isTrustRelevantFreshness(value){return value==="STALE"||value==="INDEXING"}function labelsDiverge(input){const served=input.servedTarget;if(!served)return false;return Boolean(input.freshTarget&&canonicalTargetLabel(input.freshTarget)!==canonicalTargetLabel(served))}function canonicalTargetLabel(label){const parsed=parsePackageVersionLabel(label);if(!parsed)return formatTargetLabel(label);const version=parsed.version.replace(/^v(?=\d)/i,"");return`${parsed.registry.toLowerCase()}:${parsed.packageName}@${version}`}function parsePackageVersionLabel(label){const registryEnd=label.indexOf(":");if(registryEnd<=0)return;const versionStart=label.lastIndexOf("@");if(versionStart<=registryEnd+1)return;const version=label.slice(versionStart+1);if(!version)return;return{registry:label.slice(0,registryEnd),packageName:label.slice(registryEnd+1,versionStart),version}}function docCoverageWarningReason(coverage){if(!coverage)return;const scale=docCoverageScale(coverage);if(coverage.note&&coverage.coverageState!=="PARTIAL"){return`${coverage.note}${scale}`}if(coverage.coverageState==="PARTIAL"){return`published docs coverage is partial; evidence may be incomplete${scale}`}if(coverage.coverageState==="CAPPED"){const reason=coverage.coverageReason?` (${coverage.coverageReason})`:"";return`published docs coverage is capped${reason}; evidence may be incomplete${scale}`}return}function docCoverageScale(coverage){const parts=[];if(typeof coverage.pagesCrawled==="number"){parts.push(`${coverage.pagesCrawled} published pages`)}if(typeof coverage.frontierRemaining==="number"){parts.push(`${coverage.frontierRemaining} discovered pages outside this snapshot`)}else if(typeof coverage.estimatedTotalPages==="number"){parts.push(`~${coverage.estimatedTotalPages} pages estimated`)}return parts.length>0?` [${parts.join(", ")}]`:""}function warningForEntry(entry,options){const reasons=[];const freshness=freshnessWarning({freshness:entry.codeIndexState,requestedTarget:entry.requestedTarget,freshTarget:entry.freshTarget,servedTarget:entry.servedTarget});if(freshness)return freshness;const terminalLifecycleReason=terminalLifecycleWarningReason(entry);if(terminalLifecycleReason){reasons.push(terminalLifecycleReason)}else{const targetResolutionWarning=targetResolutionWarningForEntry(entry,options);if(targetResolutionWarning)reasons.push(targetResolutionWarning)}const coverageReason=docCoverageWarningReason(entry.coverage);if(coverageReason)reasons.push(coverageReason);if(entry.incompatibleQueryFeatures?.length){reasons.push(`incompatible query features [${entry.incompatibleQueryFeatures.join(", ")}]`)}if(entry.ignoredQueryFeatures?.length){reasons.push(`ignored query features [${entry.ignoredQueryFeatures.join(", ")}]`)}if(entry.incompatibleFilters?.length){reasons.push(`incompatible filters [${entry.incompatibleFilters.join(", ")}]`)}if(entry.ignoredFilters?.length){reasons.push(`ignored filters [${entry.ignoredFilters.join(", ")}]`)}if(!terminalLifecycleReason&&reasons.length===0&&entry.indexingStatus&&!isHealthySearchLifecycleState(entry.indexingStatus)&&entry.indexingStatus!=="STALE"&&!(entry.indexingStatus==="INDEXING"&&options.completed)){reasons.push(`indexing status ${entry.indexingStatus}`)}if(!terminalLifecycleReason&&reasons.length===0&&entry.codeIndexState){if(!isHealthySearchLifecycleState(entry.codeIndexState)&&entry.codeIndexState!=="STALE"&&!(entry.codeIndexState==="INDEXING"&&options.completed)){reasons.push(entry.codeIndexState==="PROVISIONAL"?"code index state provisional (still indexing)":`code index state ${entry.codeIndexState}`)}}const prefix=`Source '${entry.source}' for ${formatSourceStatusTarget(entry)}`;if(reasons.length>0){return`${prefix}: ${reasons.join("; ")}`}if(entry.note){return`${prefix}: ${entry.note}`}return}function formatSourceStatusTarget(entry){return formatTargetResolutionIdentity(entry.targetResolution?.requested)??formatRepositoryTargetLabel(entry.targetLabel)??entry.targetLabel}function terminalLifecycleWarningReason(entry){const states=Array.from(new Set([entry.indexingStatus,entry.codeIndexState].filter(Boolean)));const terminalStates=states.filter((state)=>!isHealthySearchLifecycleState(state)&&state!=="INDEXING"&&state!=="STALE"&&state!=="PROVISIONAL");if(terminalStates.length===0)return;const status=terminalStates.join("/");return entry.note?`${entry.note} (${status})`:`status ${status}`}function targetResolutionWarningForEntry(entry,options){if(entry.targetResolution?.freshness==="indexing"&&options.completed){return}const notes=buildTargetResolutionNotes(entry.targetResolution);if(options.completed===true&&entry.targetResolution?.freshness==="indexing"&¬es.length>0){return`Search completed; fresh target may still be indexing. ${notes.join(" ")}`}return notes.length>0?notes.join(" "):undefined}function projectDocCoverage(coverage){if(!coverage)return;if(coverage.coverageState!=="PARTIAL"&&coverage.coverageState!=="CAPPED"){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function compactSourceStatus(sourceStatus,options={}){if(!sourceStatus||sourceStatus.length===0)return;const compact=[];for(const entry of sourceStatus){const slim=compactSourceStatusEntry(entry,options);if(slim)compact.push(slim)}return compact.length>0?compact:undefined}function compactSourceStatusEntry(entry,options){const payload={source:entry.source.toLowerCase(),targetLabel:formatTargetLabel(entry.targetLabel,entry.targetResolution?.requested?.repoUrl)};let interesting=false;const contributors=projectDocumentationContributors(entry.contributors);if(contributors){payload.contributors=contributors;interesting=true}if(options.includeEmptyResultContext){const servedTarget=entry.servedTargetLabel?formatTargetLabel(entry.servedTargetLabel,entry.targetResolution?.served?.repoUrl??entry.targetResolution?.requested?.repoUrl):undefined;const comparisonTarget=servedTarget??payload.targetLabel;const requestedTarget=entry.requestedTargetLabel?formatTargetLabel(entry.requestedTargetLabel,entry.targetResolution?.requested?.repoUrl):undefined;const freshTarget=entry.freshTargetLabel?formatTargetLabel(entry.freshTargetLabel,entry.targetResolution?.resolvedRequested?.repoUrl??entry.targetResolution?.requested?.repoUrl):undefined;if(requestedTarget&&canonicalTargetLabel(requestedTarget)!==canonicalTargetLabel(comparisonTarget)){payload.requestedTarget=requestedTarget}if(freshTarget&&canonicalTargetLabel(freshTarget)!==canonicalTargetLabel(comparisonTarget)){payload.freshTarget=freshTarget}const contributorIdentityDiverges=Boolean(contributors&&servedTarget&&(canonicalTargetLabel(servedTarget)!==canonicalTargetLabel(payload.targetLabel)||payload.requestedTarget||payload.freshTarget));if(servedTarget&&(!contributors||contributorIdentityDiverges)){payload.servedTarget=servedTarget}if(!contributors){if(entry.indexingStatus)payload.indexingStatus=entry.indexingStatus;if(entry.codeIndexState)payload.codeIndexState=entry.codeIndexState;if(typeof entry.resultCount==="number"){payload.resultCount=entry.resultCount}}interesting=true}const staleDiverges=entry.codeIndexState==="STALE"&&labelsDiverge({requestedTarget:entry.requestedTargetLabel,freshTarget:entry.freshTargetLabel,servedTarget:entry.servedTargetLabel});if(staleDiverges){if(entry.requestedTargetLabel)payload.requestedTarget=formatTargetLabel(entry.requestedTargetLabel,entry.targetResolution?.requested?.repoUrl);if(entry.freshTargetLabel)payload.freshTarget=formatTargetLabel(entry.freshTargetLabel,entry.targetResolution?.resolvedRequested?.repoUrl??entry.targetResolution?.requested?.repoUrl);if(entry.servedTargetLabel)payload.servedTarget=formatTargetLabel(entry.servedTargetLabel,entry.targetResolution?.served?.repoUrl??entry.targetResolution?.requested?.repoUrl);payload.codeIndexState=entry.codeIndexState;interesting=true}const targetResolution=projectTargetResolution(entry.targetResolution);if(targetResolution){const targetResolutionCarriesNotes=buildTargetResolutionNotes(targetResolution).length>0;const hasRetryCandidates=Boolean(buildRetryCandidateLine(targetResolution)??buildSuggestedRefsLine(targetResolution));const targetResolutionIsInteresting=targetResolutionCarriesNotes&&!(targetResolution.freshness==="indexing"&&options.completed)||targetResolution.freshness==="current"&&hasRetryCandidates;if(options.includeHealthy||!contributors||targetResolutionCarriesNotes||targetResolutionIsInteresting){payload.targetResolution=targetResolution}if(targetResolutionIsInteresting){interesting=true}}if(entry.indexingStatus&&entry.indexingStatus!=="INDEXED"&&!(entry.indexingStatus==="INDEXING"&&options.completed)){payload.indexingStatus=entry.indexingStatus;interesting=true}if(entry.codeIndexState&&entry.codeIndexState!=="CURRENT"&&(entry.codeIndexState!=="STALE"||staleDiverges)&&!(entry.codeIndexState==="INDEXING"&&options.completed)){payload.codeIndexState=entry.codeIndexState;interesting=true}if(!contributors){const coverage=projectDocCoverage(entry.coverage);if(coverage){payload.coverage=coverage;interesting=true}}if(!contributors&&!options.includeEmptyResultContext&&typeof entry.resultCount==="number"&&(entry.resultCount>0||options.includeHealthy)){payload.resultCount=entry.resultCount}if(entry.ignoredFilters.length>0){payload.ignoredFilters=entry.ignoredFilters;interesting=true}if(entry.incompatibleFilters.length>0){payload.incompatibleFilters=entry.incompatibleFilters;interesting=true}if(entry.ignoredQueryFeatures.length>0){payload.ignoredQueryFeatures=entry.ignoredQueryFeatures;interesting=true}if(entry.incompatibleQueryFeatures.length>0){payload.incompatibleQueryFeatures=entry.incompatibleQueryFeatures;interesting=true}if(entry.suggestedSiteTargets.length>0||entry.suggestedSiteTargetsTruncated){payload.suggestedSiteTargets=entry.suggestedSiteTargets;payload.suggestedSiteTargetsTruncated=entry.suggestedSiteTargetsTruncated;interesting=true}const redundantContributorNote=contributors&&entry.source==="DOCS"&&entry.note==="Documentation indexing in progress";if(entry.note&&!redundantContributorNote){payload.note=entry.note;interesting=true}return interesting||options.includeHealthy?payload:undefined}function projectDocumentationContributors(contributors){if(!contributors||contributors.length===0)return;return contributors.map((contributor)=>{const payload={kind:contributor.kind,state:contributor.state,resultCount:contributor.resultCount};if(contributor.freshness)payload.freshness=contributor.freshness;if(contributor.kind==="REPOSITORY_DOCS"){if(contributor.repositoryUrl){payload.repositoryUrl=contributor.repositoryUrl}if(contributor.commitSha)payload.commitSha=contributor.commitSha}else{if(contributor.siteKey)payload.siteKey=contributor.siteKey;if(contributor.siteUrl)payload.siteUrl=contributor.siteUrl;const coverage=projectDocumentationContributorCoverage(contributor.coverage);if(coverage)payload.coverage=coverage}return payload})}function projectDocumentationContributorCoverage(coverage){if(!coverage)return;const payload={coverageState:coverage.coverageState};if(coverage.coverageReason){payload.coverageReason=coverage.coverageReason}if(typeof coverage.pagesCrawled==="number"){payload.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){payload.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){payload.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){payload.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)payload.note=coverage.note;return payload}function assertSearchFollowUpInvariant(hit){if((hit.resultType==="DOCUMENTATION_PAGE"||hit.resultType==="REPOSITORY_DOC")&&!hit.locator.pageId){throw new MalformedCodeNavigationResponseError(`${hit.resultType} search hit missing required pageId.`)}if(hit.resultType==="REPOSITORY_DOC"&&(!hit.locator.repoUrl||!hit.locator.filePath)){throw new MalformedCodeNavigationResponseError("REPOSITORY_DOC search hit missing repo locator fields.")}}var MAX_ALTERNATIVES=3;function projectUnifiedSearchPresentation(payload){const snapshot=extractSnapshot(payload);const progress="progress"in payload?payload.progress:undefined;const lifecycle=projectLifecycle(payload,progress);const availability=projectAvailability(snapshot,lifecycle);const sourceStatus=snapshot?.sourceStatus;const sources=projectSources(sourceStatus);const siteSuggestions=projectSiteSuggestions(sourceStatus);const trustLimits=projectTrustLimits(snapshot,sources,sourceStatus);const query=snapshot?.query??("query"in payload?payload.query:undefined);const alternatives=projectAlternatives(progress,sourceStatus);const searchRef="searchRef"in payload?payload.searchRef:undefined;const targets=projectTargets(progress);const targetGroups=projectTargetGroups({targets,sources,alternatives,siteSuggestions,trustLimits,lifecycle,availability,snapshot});const warnings=projectWarnings(query,sourceStatus,targetGroups);return{provenance:projectProvenance(snapshot,progress),availability,lifecycle,query,progress:projectProgress(progress),indexingEstimates:progress?.indexingEstimates,targetGroups,hasMore:snapshot?.hasMore??false,warnings,action:projectAction({indexingEstimates:progress?.indexingEstimates,searchRef,snapshot,lifecycle,availability,targetGroups})}}function extractSnapshot(payload){if("result"in payload){const result=payload.result;return result?{...result,sourceStatus:result.sourceStatusForText??result.sourceStatus}:undefined}if(!("partialResults"in payload)||payload.partialResults===undefined){return}return{query:"query"in payload?payload.query:undefined,partialResults:payload.partialResults,hasMore:payload.hasMore,results:payload.results,sourceStatus:payload.sourceStatusForText??payload.sourceStatus,evidenceNotice:payload.evidenceNotice}}function projectProgress(progress){if(!progress)return;return{targetsReady:progress.targetsReady,targetsTotal:progress.targetsTotal,elapsedMs:progress.elapsedMs,...progress.requestedSources?.length?{requestedSources:progress.requestedSources.map((source)=>source.toLowerCase())}:{}}}function projectTargets(progress){return(progress?.targets??[]).map((target)=>({...target.requested?{requested:target.requested}:{},...target.resolvedRequested?{fresh:target.resolvedRequested}:{},...target.served?{served:target.served}:{},...target.freshness?{freshness:target.freshness}:{}}))}function projectLifecycle(payload,progress){if(payload.completed)return{kind:"completed",status:"COMPLETED"};const status=progress?.status;switch(status){case"PENDING":case"INDEXING":case"SEARCHING":return{kind:"active",status};case"DEFERRED":case"TIMEOUT":case"FAILED":return{kind:"terminal",status};default:return{kind:"unknown",status}}}function projectAvailability(snapshot,lifecycle){if(!snapshot){return{kind:"no_snapshot",hasSnapshot:false,resultCount:0,partialResults:false}}const resultCount=snapshot.results.length;const kind=resultCount===0?"empty":snapshot.partialResults?"partial":lifecycle.kind==="active"?"interim":"final";return{kind,hasSnapshot:true,resultCount,partialResults:snapshot.partialResults}}function projectSources(sourceStatus){if(!sourceStatus)return[];const groups=[];for(const entry of sourceStatus){if(entry.contributors&&entry.contributors.length>0){for(const contributor of entry.contributors){const kind=contributor.kind==="DOCPACK"?"site_docs":"repository_docs";const identity=contributorIdentity(entry,contributor);appendSourceEntry(groups,kind,{state:contributorState(contributor.state),...identity,resultCount:contributor.resultCount})}continue}const kind=sourceKind(entry);const terminalReason=sourceTerminalReason(entry);appendSourceEntry(groups,kind,{state:sourceState(entry),...sourceIdentity(entry,kind),resultCount:entry.resultCount,...terminalReason?{terminalReason}:{}})}return groups}function projectSiteSuggestions(sourceStatus){return(sourceStatus??[]).filter((entry)=>Boolean(entry.suggestedSiteTargets?.length)||entry.suggestedSiteTargetsTruncated===true).map((entry)=>({target:sourceTarget(entry),suggestions:[...entry.suggestedSiteTargets??[]],truncated:entry.suggestedSiteTargetsTruncated===true}))}function appendSourceEntry(groups,kind,entry){const group=groups.find((candidate)=>candidate.kind===kind);if(group)group.entries.push(entry);else groups.push({kind,entries:[entry]})}function sourceKind(entry){const source=entry.source.toLowerCase();if(source==="code")return"code";if(source==="symbol")return"symbols";if(isSiteTarget(entry.targetLabel,entry))return"site_docs";return entry.targetResolution?.served?.repoUrl?"repository_docs":"docs"}function contributorIdentity(entry,contributor){const searchTarget=sourceTarget(entry);const target=contributor.kind==="REPOSITORY_DOCS"?contributor.repositoryUrl??searchTarget:contributor.siteUrl??contributor.siteKey??searchTarget;return{target,searchTarget,...sourceTargetAliases(entry),...contributor.repositoryUrl?{repositoryUrl:contributor.repositoryUrl}:{},...contributor.commitSha?{commitSha:contributor.commitSha}:{},...contributor.siteKey?{siteKey:contributor.siteKey}:{},...contributor.siteUrl?{siteUrl:contributor.siteUrl}:{}}}function sourceIdentity(entry,kind){const target=sourceTarget(entry);const served=entry.targetResolution?.served;const identity=kind==="repository_docs"?{...served?.repoUrl?{repositoryUrl:served.repoUrl}:{},...served?.commitSha?{commitSha:served.commitSha}:{}}:kind==="site_docs"&&served?.site?{siteKey:served.site}:{};return{target,searchTarget:target,...sourceTargetAliases(entry),...identity}}function sourceTargetAliases(entry){const aliases=uniqueAliases([entry.targetLabel,entry.requestedTarget,entry.freshTarget,entry.servedTarget]);return{...aliases.length>1?{targetAliases:aliases}:{},...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{},...entry.freshTarget?{freshTarget:entry.freshTarget}:{},...entry.servedTarget?{servedTarget:entry.servedTarget}:{}}}function sourceTarget(entry){return entry.servedTarget??entry.targetLabel}function sourceState(entry){const states=[entry.indexingStatus,entry.codeIndexState].filter((state)=>Boolean(state));if(states.length===0)return"searched";if(states.some((state)=>["INDEXING","PENDING"].includes(state))){return"waiting"}return states.every((state)=>["CURRENT","INDEXED","PROVISIONAL","STALE"].includes(state))?"searched":"unavailable"}function sourceTerminalReason(entry){const kind=[entry.indexingStatus,entry.codeIndexState].find((state)=>state==="NOT_FOUND"||state==="UNRESOLVABLE");if(!kind)return;const family=classifyTargetFamily(entry);const requestedTarget=entry.requestedTarget??entry.targetLabel;const specificity=terminalSpecificity(family,requestedTarget);return{kind:kind.toLowerCase(),family,...specificity?{specificity}:{}}}function terminalSpecificity(family,target){try{if(family==="package"&&parsePackageSpec(target).version){return"version"}if(family==="repository"&&parseRepositoryTargetSpec(target).gitRef){return"ref"}}catch{return}return}function contributorState(state){const readiness={SEARCHED:"searched",READY:"available_not_searched",PENDING:"waiting",UNAVAILABLE:"unavailable"};return readiness[state]}function repositoryHitsForSource(snapshot,entry){const targets=entry.requestedTarget?[entry.requestedTarget]:[entry.targetLabel,entry.servedTarget];return(snapshot?.results??[]).filter((hit)=>hit.type===(entry.source.toLowerCase()==="symbol"?"repository_symbol":entry.source.toLowerCase()==="code"?"repository_code":"repository_doc")&&targets.includes(hit.requestedTarget??hit.target))}function hasRepositoryEvidence(snapshot,entry){const served=entry.targetResolution?.served;return Boolean(served?.repoUrl&&served.commitSha&&entry.resultCount!==0&&repositoryHitsForSource(snapshot,entry).some((hit)=>hit.locator.repoUrl===served.repoUrl&&hit.locator.commitSha===served.commitSha))}function projectProvenance(snapshot,progress){const records=[];for(const entry of snapshot?.sourceStatus??[]){const resolution=entry.targetResolution;const target=entry.requestedTarget??entry.targetLabel;const sources=[];const alias=isKnownPackageTarget(target)||explicitRepositoryRef(target)?[`requested: ${target}`]:[];if(entry.contributors?.length){for(const contributor of entry.contributors){if(contributor.state!=="SEARCHED")continue;const identity=contributor.kind==="REPOSITORY_DOCS"?{site:undefined,repoUrl:contributor.repositoryUrl,commitSha:contributor.commitSha,...sameRepositoryCommit({repoUrl:contributor.repositoryUrl,commitSha:contributor.commitSha},resolution?.served)?{gitRef:resolution?.served?.gitRef,committedAt:resolution?.served?.committedAt}:{}}:{repoUrl:undefined,commitSha:undefined,site:contributor.siteUrl?`site:${contributor.siteUrl.replace(/^https?:\/\//i,"").replace(/\/$/,"")}`:contributor.siteKey?`site:${contributor.siteKey}`:undefined};sources.push({target,identity,qualifiers:[contributor.kind==="DOCPACK"?"hosted documentation":"repository docs",...identity.repoUrl||identity.site&&identity.site!==target?alias:[],...contributor.freshness==="PROVISIONAL"?["provisional"]:contributor.freshness==="STALE"?["older snapshot"]:[],...contributor.coverage?.coverageState&&["PARTIAL","CAPPED"].includes(contributor.coverage.coverageState)?[`${contributor.coverage.pagesCrawled===undefined?"":`${contributor.coverage.pagesCrawled} pages, `}${contributor.coverage.coverageState.toLowerCase()}`]:[],...contributor.resultCount===0?[snapshot?.hasMore?"no results on this page":"no results"]:[]]})}}else if(resolution?.served?.repoUrl&&resolution.served.commitSha?hasRepositoryEvidence(snapshot,entry)||sourceState(entry)==="searched"&&entry.resultCount===0:sourceState(entry)==="searched"){const identities=resolution?.served?[resolution.served]:[...new Map(repositoryHitsForSource(snapshot,entry).filter((hit)=>hit.locator.repoUrl&&hit.locator.commitSha).map((hit)=>[JSON.stringify([hit.locator.repoUrl,hit.locator.commitSha]),{repoUrl:hit.locator.repoUrl,commitSha:hit.locator.commitSha}])).values()];for(const identity of identities.length?identities:[undefined])sources.push({target:entry.servedTarget??target,identity:isSiteTarget(entry.targetLabel,entry)?{site:target}:identity,qualifiers:[...!["code","symbol"].includes(entry.source.toLowerCase())?[isSiteTarget(entry.targetLabel,entry)?"hosted documentation":identity?.repoUrl?"repository docs":"docs"]:[],...(new Set((snapshot?.sourceStatus??[]).map((source)=>source.source)).size>1||!resolution?.served?.repoUrl)&&["code","symbol"].includes(entry.source.toLowerCase())?[entry.source.toLowerCase()==="symbol"?"symbols":"code"]:[],...identity?.repoUrl||entry.servedTarget&&entry.servedTarget!==target?alias:[],...resolution?.freshness==="fallback_recent"||entry.codeIndexState==="STALE"?["older snapshot"]:[],...resolution?.freshness==="provisional"||entry.codeIndexState==="PROVISIONAL"?["provisional"]:[],...entry.coverage&&["PARTIAL","CAPPED"].includes(entry.coverage.coverageState)?[`${entry.coverage.pagesCrawled===undefined?"":`${entry.coverage.pagesCrawled} pages, `}${entry.coverage.coverageState.toLowerCase()}`]:[],...entry.resultCount===0?[snapshot?.hasMore?"no results on this page":"no results"]:[]]})}records.push({target,sources,...resolution?{resolution:projectProvenanceResolution(resolution)}:{}})}for(const target of progress?.targets??[]){if(target.targetResolution&&!records.some((record)=>record.target===target.requested&&record.resolution))records.push({target:target.requested??target.served??"target",sources:[],resolution:projectProvenanceResolution(target.targetResolution)})}return records}function projectProvenanceResolution(resolution){return{requested:resolution.requested,resolvedRequested:resolution.resolvedRequested,served:resolution.served,freshness:resolution.freshness,...["requested_ref_indexing","no_current_fallback"].includes(resolution.freshnessReason??"")?{freshnessReason:resolution.freshnessReason}:{}}}function explicitRepositoryRef(target){try{const ref=parseRepositoryTargetSpec(target).gitRef;return Boolean(ref&&ref!=="HEAD")}catch{return false}}function isKnownPackageTarget(target){try{return isKnownRegistry(parsePackageSpec(target).registry)}catch{return false}}function projectTrustLimits(snapshot,sources,sourceStatus){const limits=new Map;const add=(limit)=>{const key=limit.kind==="stale"?`stale:${limit.requestedTarget??""}:${limit.servedTarget??limit.target??""}`:JSON.stringify(limit);const existing=limits.get(key);if(existing===undefined||limit.kind==="stale"&&existing.kind==="stale"&&staleSpecificity(limit)>staleSpecificity(existing)){limits.set(key,limit)}};for(const group of sources){for(const entry of group.entries){if(entry.state!=="searched"){add({kind:"source",source:group.kind,state:entry.state,target:entry.target,...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{}})}}}for(const hit of snapshot?.results??[]){if(hit.freshness==="STALE"||hit.freshness==="INDEXING"){add({kind:"stale",target:hit.servedTarget??hit.target,requestedTarget:hit.requestedTarget,freshTarget:hit.freshTarget,servedTarget:hit.servedTarget})}}for(const entry of sourceStatus??[]){const target=sourceTarget(entry);const resolution=entry.targetResolution;const freshness=resolution?.freshness;const served=resolution?.served;const requestedSha=resolution?.resolvedRequested?.commitSha;const servedSha=served?.commitSha;const hasRepositoryHits=hasRepositoryEvidence(snapshot,entry);const searchedRepositorySnapshot=hasRepositoryHits||entry.resultCount===0&&sourceState(entry)==="searched";if(searchedRepositorySnapshot&&servedSha&&served?.repoUrl&&(freshness!=="current"||["INDEXING","STALE","PROVISIONAL"].includes(entry.codeIndexState??""))){const headIntent=["repo_default_branch","repo_head"].includes(resolution?.requested?.kind??"");const requestedRef=headIntent?"HEAD":resolution?.requested?.gitRef??resolution?.resolvedRequested?.gitRef;const requestedCommitDiffers=Boolean(requestedSha&&requestedSha!==servedSha);add({kind:"repository_snapshot",target,requestedTarget:entry.requestedTarget,commitTarget:formatRepositoryTarget(served.repoUrl,servedSha.slice(0,8)),...served.committedAt?{servedCommitDate:served.committedAt.slice(0,10)}:{},...requestedCommitDiffers&&resolution?.resolvedRequested?.committedAt?{requestedCommitDate:resolution.resolvedRequested.committedAt.slice(0,10)}:{},...served.gitRef&&!/^[0-9a-f]{7,40}$/i.test(served.gitRef)?{indexedRef:served.gitRef}:{},requestedRef,requestedCommitDiffers,priorHead:hasRepositoryHits&&headIntent&&freshness==="fallback_recent"&&requestedCommitDiffers,...resolution?.freshnessReason==="requested_ref_indexing"&&requestedRef?{indexingRequestedRef:requestedRef}:{}})}const repositoryResolution=Boolean(served?.repoUrl||resolution?.requested?.kind?.startsWith("repo_"));if((entry.codeIndexState==="STALE"||freshness==="fallback_recent")&&!(servedSha&&requestedSha===servedSha)&&(!repositoryResolution||hasRepositoryHits)){add({kind:"stale",target,requestedTarget:entry.requestedTarget,freshTarget:entry.freshTarget,servedTarget:entry.servedTarget})}if(entry.codeIndexState==="PROVISIONAL"||freshness==="provisional"||entry.contributors?.some((contributor)=>contributor.freshness==="PROVISIONAL")){add({kind:"provisional",target,...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{}})}const kind=sourceKind(entry);addCoverage(add,kind,target,entry.requestedTarget,entry.coverage);for(const contributor of entry.contributors??[]){const contributorTargetValue=contributorIdentity(entry,contributor);if(contributor.freshness==="STALE"){add({kind:"stale",target:contributorTargetValue.target,...entry.requestedTarget?{requestedTarget:entry.requestedTarget}:{}})}addCoverage(add,contributor.kind==="DOCPACK"?"site_docs":"repository_docs",contributorTargetValue.target,entry.requestedTarget,contributor.coverage)}addConstraints(add,entry)}if(snapshot?.evidenceNotice!==undefined){add({kind:"mutable_evidence"})}return[...limits.values()]}function staleSpecificity(limit){return[limit.requestedTarget,limit.freshTarget,limit.servedTarget].filter(Boolean).length}function addCoverage(add,source,target,requestedTarget,coverage){if(!coverage||!["PARTIAL","CAPPED"].includes(coverage.coverageState)){return}add({kind:"coverage",source,state:coverage.coverageState.toLowerCase(),target,...requestedTarget?{requestedTarget}:{},pagesCrawled:coverage.pagesCrawled,frontierRemaining:typeof coverage.frontierRemaining==="number"?coverage.frontierRemaining:undefined,estimatedTotalPages:coverage.estimatedTotalPages})}function addConstraints(add,entry){const target=entry.targetLabel;for(const[constraint,values]of sourceConstraints(entry)){if(values?.length)add({kind:"constraint",constraint,source:normalizeSourceLane(entry.source),target:target||undefined,values})}}function sourceConstraints(entry){return[["ignored_filter",entry.ignoredFilters],["incompatible_filter",entry.incompatibleFilters],["ignored_query_feature",entry.ignoredQueryFeatures],["incompatible_query_feature",entry.incompatibleQueryFeatures]]}function projectWarnings(query,sourceStatus,targetGroups){const warnings=[];for(const message of query?.warnings??[]){warnings.push({kind:"query",message})}for(const entry of sourceStatus??[]){const source=normalizeSourceLane(entry.source);const target=entry.targetLabel||undefined;const aliases=uniqueAliases([entry.targetLabel,entry.requestedTarget,entry.freshTarget,entry.servedTarget]);const hasTargetOwner=findMatchingTargetGroup(targetGroups,aliases,entry.requestedTarget)!==undefined||targetGroups.length===1&&target===undefined;for(const[kind,values]of sourceConstraints(entry)){if(values?.length&&!hasTargetOwner){warnings.push({kind,source,target,values})}}}return warnings}function normalizeSourceLane(source){const normalized=source?.trim().toLowerCase();return normalized||undefined}function projectAlternatives(progress,sourceStatus){const candidates=[...(progress?.targets??[]).map((target)=>({target:target.requested??target.resolvedRequested??target.served,requestedTarget:target.requested,aliases:uniqueAliases([target.requested,target.resolvedRequested,target.served]),versions:target.targetResolution?.availableVersions??target.availableVersions??[],refs:target.targetResolution?.availableRefs??target.availableRefs??[],suggestedRefs:target.targetResolution?.suggestedRefs??target.suggestedRefs??[]})),...(sourceStatus??[]).flatMap((entry)=>{const resolution=entry.targetResolution;return resolution?[{target:entry.requestedTarget??sourceTarget(entry),requestedTarget:entry.requestedTarget,aliases:uniqueAliases([sourceTarget(entry),entry.targetLabel,entry.requestedTarget,entry.freshTarget,entry.servedTarget]),versions:resolution.availableVersions,refs:resolution.availableRefs,suggestedRefs:resolution.suggestedRefs??[]}]:[]})];return mergeAlternativeCandidates(candidates).filter((candidate)=>candidate.versions.length>0||candidate.refs.length>0||candidate.suggestedRefs.length>0).map((candidate)=>({target:candidate.target,...boundedAlternatives(candidate.versions,candidate.refs,candidate.suggestedRefs)}))}function projectTargetGroups(input){const groups=[];for(const identity of input.targets){const existing=groups.find((group)=>targetIdentitiesMatch(group.identity,identity));if(existing){existing.identity.requested??=identity.requested;existing.identity.fresh??=identity.fresh;existing.identity.served??=identity.served;existing.identity.freshness??=identity.freshness;existing.freshnessKind??=classifyTargetFreshness(identity.freshness);continue}groups.push({identity:{...identity},freshnessKind:classifyTargetFreshness(identity.freshness),sources:[],siteSuggestions:[],trustLimits:[]})}const findOrCreate=(target)=>{return findOrCreateForAliases(target?[target]:[],target)};const findOrCreateForAliases=(aliases,target,requestedTarget)=>{const existing=findMatchingTargetGroup(groups,aliases,requestedTarget);if(existing)return existing;const created={identity:requestedTarget||target?{requested:requestedTarget??target}:{},sources:[],siteSuggestions:[],trustLimits:[]};groups.push(created);return created};for(const limit of input.trustLimits){if(limit.kind!=="stale"||!limit.requestedTarget&&!limit.freshTarget&&!limit.servedTarget){continue}const aliases=uniqueAliases([limit.requestedTarget,limit.freshTarget,limit.servedTarget,limit.target]);const group=findMatchingTargetGroup(groups,aliases,limit.requestedTarget)??findOrCreateForAliases(aliases,aliases[0],limit.requestedTarget);if(limit.requestedTarget)group.identity.requested=limit.requestedTarget;if(limit.freshTarget)group.identity.fresh=limit.freshTarget;if(limit.servedTarget)group.identity.served=limit.servedTarget}for(const sourceGroup of input.sources){for(const entry of sourceGroup.entries){const aliases=entry.targetAliases??[entry.searchTarget];const group=findMatchingTargetGroup(groups,aliases,entry.requestedTarget)??findOrCreateForAliases(aliases,entry.searchTarget,entry.requestedTarget);if(entry.requestedTarget){group.identity.requested??=entry.requestedTarget}if(entry.freshTarget)group.identity.fresh??=entry.freshTarget;if(entry.servedTarget)group.identity.served??=entry.servedTarget;const existingSource=group.sources.find((candidate)=>candidate.kind===sourceGroup.kind);if(existingSource)existingSource.entries.push(entry);else group.sources.push({kind:sourceGroup.kind,entries:[entry]})}}for(const alternatives of input.alternatives){const aliases=uniqueAliases([alternatives.target]);const group=findMatchingTargetGroup(groups,aliases,alternatives.target)??findOrCreateForAliases(aliases,alternatives.target);group.alternatives=alternatives}for(const suggestion of input.siteSuggestions){findOrCreate(suggestion.target).siteSuggestions.push(suggestion)}for(const limit of input.trustLimits){if(limit.kind==="mutable_evidence"){continue}const target="target"in limit?limit.target:undefined;const requestedTarget="requestedTarget"in limit?limit.requestedTarget:undefined;const aliases=limit.kind==="stale"?uniqueAliases([limit.requestedTarget,limit.freshTarget,limit.servedTarget,limit.target]):uniqueAliases([requestedTarget,target]);const sourceGroup=findMatchingTargetGroup(groups,aliases,requestedTarget);const group=sourceGroup??(groups.length===1?groups[0]:undefined)??findOrCreateForAliases(aliases,target,requestedTarget);if(limit.kind==="stale"){if(limit.requestedTarget)group.identity.requested=limit.requestedTarget;if(limit.freshTarget)group.identity.fresh=limit.freshTarget;if(limit.servedTarget)group.identity.served=limit.servedTarget}group.trustLimits.push(limit)}for(const group of groups){const recovery=projectTargetRecovery(group,input.lifecycle,input.availability,input.snapshot);if(recovery)group.recovery=recovery}return groups.filter((group)=>targetIdentityValues(group.identity).length>0||group.sources.length>0||group.alternatives!==undefined||group.siteSuggestions.length>0||group.trustLimits.length>0||group.recovery!==undefined)}function targetIdentityValues(identity){return[identity.requested,identity.fresh,identity.served].filter((value)=>Boolean(value))}function targetGroupMatchesAliases(group,aliases){return targetIdentityValues(group.identity).some((value)=>aliases.includes(value))||group.sources.some((source)=>source.entries.some((entry)=>[...entry.targetAliases??[],entry.target,entry.searchTarget].some((value)=>value!==undefined&&aliases.includes(value))))}function findMatchingTargetGroup(groups,aliases,requestedTarget){if(requestedTarget){const requestedMatch=groups.find((group)=>group.identity.requested===requestedTarget);if(requestedMatch)return requestedMatch}const directRequestedMatches=groups.filter((group)=>group.identity.requested!==undefined&&aliases.includes(group.identity.requested));if(directRequestedMatches.length===1)return directRequestedMatches[0];const matches=groups.filter((group)=>targetGroupMatchesAliases(group,aliases));return matches.length===1?matches[0]:undefined}function targetIdentitiesMatch(left,right){if(left.requested!==undefined&&right.requested!==undefined&&left.requested!==right.requested){return false}return targetIdentityValues(left).some((target)=>targetIdentityValues(right).includes(target))}function uniqueAliases(values){return[...new Set(values.filter((value)=>Boolean(value)))]}function targetDisplayFamilyKey(target){if(!target)return"";const normalized=target.trim().replace(/\s+latest$/,"").replace(/#[^#]+$/,"");return normalized.startsWith("npm:")?normalized.replace(/@[^/@]+$/,""):normalized.replace(/@[^#]+$/,"")}function classifyTargetFreshness(freshness){switch(freshness?.toLowerCase()){case"current":case"indexed":return"current";case"stale":case"fallback_recent":return"stale";case"indexing":return"indexing";case"pending":return"pending";case"provisional":return"provisional";default:return}}function mergeAlternativeCandidates(candidates){const merged=[];for(const candidate of candidates){const existing=merged.find((value)=>!(candidate.requestedTarget&&value.requestedTarget&&candidate.requestedTarget!==value.requestedTarget)&&candidate.aliases.some((alias)=>value.aliases.includes(alias)));if(existing){existing.aliases=uniqueAliases([...existing.aliases,...candidate.aliases]);existing.versions.push(...candidate.versions);existing.refs.push(...candidate.refs);existing.suggestedRefs.push(...candidate.suggestedRefs);existing.requestedTarget??=candidate.requestedTarget}else{merged.push({target:candidate.target,requestedTarget:candidate.requestedTarget,aliases:[...candidate.aliases],versions:[...candidate.versions],refs:[...candidate.refs],suggestedRefs:[...candidate.suggestedRefs]})}}return merged}function boundedAlternatives(versions,refs,suggestedRefs){const bounded=(values)=>{const seen=new Set;const display=[];let remaining=0;for(const value of values){const key=`${value.version??""}\x00${value.ref}`;if(seen.has(key))continue;seen.add(key);if(display.length<MAX_ALTERNATIVES)display.push(value);else remaining++}return{values:display,remaining}};const versionFacts=bounded(versions.filter((alternative)=>alternative.version!==undefined));const refFacts=bounded([...refs,...versions.filter((alternative)=>alternative.version===undefined)]);const suggestedRefFacts=bounded(suggestedRefs);return{versions:versionFacts.values,versionsRemaining:versionFacts.remaining,refs:refFacts.values,refsRemaining:refFacts.remaining,suggestedRefs:suggestedRefFacts.values,suggestedRefsRemaining:suggestedRefFacts.remaining}}function projectAction(input){if(input.lifecycle.kind==="active"){return input.searchRef?{kind:"poll",searchRef:input.searchRef,waitTimeoutMs:indexingWaitMs(input.indexingEstimates),...input.availability.resultCount>0?{useResults:true}:{}}:{kind:"none"}}if(input.lifecycle.kind==="completed"&&input.snapshot?.evidenceNotice!==undefined){return{kind:"new_search",...input.availability.resultCount>0?{useResults:true}:{}}}const hasLocalRecovery=input.targetGroups.some((group)=>group.recovery!==undefined);const hasBareTerminalReason=input.targetGroups.some(hasBareTerminalReasonForGroup);if((input.lifecycle.kind==="terminal"||input.lifecycle.kind==="unknown")&&hasLocalRecovery){return{kind:"none"}}if(input.lifecycle.kind==="terminal"||input.lifecycle.kind==="unknown"){return{kind:"new_search",...input.availability.resultCount>0?{useResults:true}:{}}}if(!input.snapshot||input.availability.kind!=="empty"){return{kind:"none"}}if(hasLocalRecovery)return{kind:"none"};const hasIndexing=input.targetGroups.some((group)=>groupHasIndexing(group));if(hasIndexing)return{kind:"new_search"};if(hasBareTerminalReason){return projectQueryRewrite(input.snapshot.query)}if(input.targetGroups.some((group)=>group.trustLimits.some((limit)=>limit.kind==="source"||limit.kind==="coverage"||limit.kind==="mutable_evidence"||limit.kind==="stale"))){return{kind:"new_search"}}if(input.snapshot.sourceStatus?.length&&input.snapshot.sourceStatus.every((entry)=>isSiteTarget(entry.targetLabel,entry))){return{kind:"query_rewrite",rewrites:["site_shorter_or_broader"]}}return projectQueryRewrite(input.snapshot.query)}function projectQueryRewrite(query){const rewrites=["shorter_or_broader"];if(hasRestrictiveFilters(query))rewrites.push("remove_filters");const symbolSource=query?.sources?.some((source)=>source.toLowerCase()==="symbol");if(!symbolSource)rewrites.push("symbol");rewrites.push("code_grep");return{kind:"query_rewrite",rewrites}}function projectTargetRecovery(group,lifecycle,availability,snapshot){const hasTerminalReason=groupHasTerminalReason(group);const hasBareTerminalReason=hasBareTerminalReasonForGroup(group);const alternative=projectAlternativeRecovery(group);const site=projectSiteRecovery(group);const candidate=site??alternative;if(lifecycle.kind==="active"){return hasTerminalReason&&!hasBareTerminalReason?candidate??fixRecovery(group):undefined}if(lifecycle.kind==="terminal"||lifecycle.kind==="unknown"){if(hasBareTerminalReason)return;if(candidate)return candidate;return hasTerminalReason?fixRecovery(group):undefined}if(lifecycle.kind==="completed"&&hasTerminalReason){return hasBareTerminalReason?undefined:candidate??fixRecovery(group)}if(availability.kind!=="empty"||!snapshot)return;if(site)return site;return groupHasIndexing(group)?alternative:undefined}function projectAlternativeRecovery(group){const alternatives=group.alternatives;if(!alternatives)return;const identity=primaryTargetIdentity(group);if(!identity)return;const family=groupTerminalFamily(group)??familyForTarget(identity);if(family==="package"){const versions=alternatives.versions.map((alternative)=>composePackageTarget(identity,alternative.version)).filter((target)=>target!==undefined);const target=versions[0];if(!target)return;return{kind:"try",category:"version",target,additionalTargets:versions.slice(1),truncated:alternatives.versionsRemaining>0}}if(family==="repository"){const refs=[...alternatives.refs,...alternatives.suggestedRefs].map((alternative)=>composeRepositoryTarget(identity,alternative.ref)).filter((target)=>target!==undefined);const unique=[...new Set(refs)];const target=unique[0];if(!target)return;return{kind:"try",category:"ref",target,additionalTargets:unique.slice(1),truncated:alternatives.refsRemaining>0||alternatives.suggestedRefsRemaining>0}}return}function projectSiteRecovery(group){const suggestions=[...new Set(group.siteSuggestions.flatMap((suggestion)=>suggestion.suggestions))];const target=suggestions[0];if(!target)return;return{kind:"try",category:"site",target,additionalTargets:suggestions.slice(1),truncated:group.siteSuggestions.some((suggestion)=>suggestion.truncated)}}function fixRecovery(group){return{kind:"fix",family:groupTerminalFamily(group)??familyForTarget(primaryTargetIdentity(group))}}function primaryTargetIdentity(group){return group.identity.requested??group.identity.fresh??group.identity.served??group.alternatives?.target}function groupTerminalReason(group){for(const source of group.sources){for(const entry of source.entries){if(entry.terminalReason)return entry.terminalReason}}return}function groupTerminalFamily(group){return groupTerminalReason(group)?.family}function groupHasTerminalReason(group){return groupTerminalReason(group)!==undefined}function groupHasIndexing(group){return group.freshnessKind==="indexing"||group.freshnessKind==="pending"||group.sources.some((source)=>source.entries.some((entry)=>entry.state==="waiting"))}function hasBareTerminalReasonForGroup(group){return groupHasTerminalReason(group)&&group.sources.some((source)=>source.entries.some((entry)=>entry.state==="searched"||entry.state==="waiting"))}function familyForTarget(target){if(!target)return"unknown";if(isSiteTarget(target,{targetLabel:target,source:"docs"})){return"site"}const packageSeparator=target.indexOf(":");if(packageSeparator>0&&parsePkgseerRegistryArg(target.slice(0,packageSeparator))){return"package"}try{parseRepositoryTargetSpec(target);return"repository"}catch{return"unknown"}}function composePackageTarget(identity,version){if(!version)return;try{const parsed=parsePackageSpec(identity.trim().replace(/\s+latest$/,""));return`${parsed.registry}:${parsed.name}@${version}`}catch{return}}function composeRepositoryTarget(identity,ref){try{const parsed=parseRepositoryTargetSpec(identity);if(!parsed.repoUrl||!isCanonicalRepositoryUrl(parsed.repoUrl))return;return formatRepositoryTarget(parsed.repoUrl,ref)}catch{return}}function classifyTargetFamily(entry){if(isSiteTarget(entry.targetLabel,entry))return"site";const target=entry.targetLabel.trim().toLowerCase();const separator=target.indexOf(":");if(separator>0&&parsePkgseerRegistryArg(target.slice(0,separator))){return"package"}if(familyForTarget(target)==="repository"||entry.targetResolution?.requested?.repoUrl||entry.targetResolution?.resolvedRequested?.repoUrl||entry.targetResolution?.served?.repoUrl){return"repository"}return"unknown"}function hasRestrictiveFilters(query){const filters=query?.filters;return Boolean(filters?.kind||filters?.category||filters?.pathPrefix||filters?.fileIntent||filters?.publicOnly===true||query?.raw&&/(?:^|\s)(?:kind|category|path|lang|name|intent):/i.test(query.raw))}function isSiteTarget(target,entry){return Boolean(target.startsWith("site:")||entry.targetResolution?.requested?.site||entry.targetResolution?.resolvedRequested?.site||entry.targetResolution?.served?.site)}var DEFAULT_TEXT_WIDTH=80;function renderUnifiedSearchSuccess(payload,options={}){return renderUnifiedSearchPresentationText(projectUnifiedSearchPresentation(payload),payload,options)}function renderUnifiedSearchPresentationText(presentation,result,options={}){const settings=normalizeTextOptions(options);const lines=wrapTerminalProse(formatPresentationOutcome(presentation,result.results),settings.width).map((line)=>styleOutcome(line,presentation,settings.useColors));const notice=formatPresentationNotice(presentation);if(notice)lines.push(...wrapTerminalProse(notice,settings.width));appendPresentationContext(lines,presentation,settings);if(result.results.length>0){lines.push("");appendUnifiedSearchHits(lines,result.results,identifierQueryFragments(presentation.query?.raw),settings)}appendPresentationAction(lines,presentation,result,settings);return lines.join(`
|
|
197
202
|
`)}function normalizeTextOptions(options){return{useColors:options.useColors??false,actionSyntax:options.actionSyntax??"mcp",width:typeof options.width==="number"&&Number.isFinite(options.width)?Math.max(20,Math.floor(options.width)):DEFAULT_TEXT_WIDTH}}function formatPresentationOutcome(presentation,results){if(!results.length){if(presentation.hasMore)return"No results on this page.";if(presentation.lifecycle.kind==="active")return"No results available yet.";return presentation.availability.hasSnapshot?"No results found.":"No result snapshot available."}const counts=new Map;for(const result of results){const label=result.type==="repository_code"?"code result":result.type==="documentation_page"?"documentation result":result.type==="repository_doc"?"repository documentation result":result.type==="repository_symbol"?"symbol result":"result";counts.set(label,(counts.get(label)??0)+1)}const parts=[...counts].map(([label,count])=>`${count} ${label}${count===1?"":"s"}`);const last=parts.pop();return`Found ${parts.length?`${parts.join(", ")} and `:""}${last}.`}function formatPresentationNotice(presentation){const scopeExplanation=Boolean(presentation.indexingEstimates?.length)||presentation.targetGroups.some((group)=>group.recovery||group.sources.some((source)=>source.entries.some((entry)=>entry.state!=="searched"))||group.trustLimits.some((limit)=>["source","coverage","stale","provisional"].includes(limit.kind)||limit.kind==="repository_snapshot"&&(limit.requestedCommitDiffers||limit.indexingRequestedRef)));const incomplete=presentation.availability.partialResults&&!scopeExplanation;const lifecycle=presentation.lifecycle;const state=lifecycle.kind==="terminal"?lifecycle.status==="FAILED"?"Search failed":lifecycle.status==="TIMEOUT"?"Search timed out":"Search was deferred":lifecycle.kind==="unknown"?"Search status is unknown":lifecycle.kind==="active"&&!scopeExplanation&&!incomplete?lifecycle.status==="INDEXING"?"Requested sources are still indexing":lifecycle.status==="PENDING"?"Search is preparing requested sources":"Search is still running":undefined;if(state)return`${state}${incomplete?"; these results do not cover the full request":""}.`;return incomplete?"These results do not cover the full request.":undefined}function styleOutcome(value,presentation,useColors){if(!useColors)return value;if(presentation.lifecycle.kind==="active"||presentation.lifecycle.kind==="terminal"&&presentation.lifecycle.status!=="FAILED"){return`${colors.bold}${colors.yellow}${value}${colors.reset}`}if(presentation.lifecycle.kind==="terminal"&&presentation.lifecycle.status==="FAILED"){return`${colors.bold}${colors.red}${value}${colors.reset}`}return`${colors.bold}${value}${colors.reset}`}function appendPresentationContext(lines,presentation,options){const sources=presentation.provenance.flatMap((record)=>record.sources);if(sources.length)lines.push("",...renderSourceSection(sources,{width:options.width}));const historical=presentation.lifecycle.kind!=="active";const indexedAlternatives=presentation.targetGroups.flatMap((group)=>{const alternatives=group.alternatives;if(!alternatives?.target||group.recovery)return[];const summary=formatTargetAlternatives({...alternatives,suggestedRefs:[]});return summary?[{target:alternatives.target,summary}]:[]});lines.push(...renderPreparationSection(presentation.indexingEstimates,{indexedAlternatives,repositoryState:historical?"indexing when observed":"indexing",resolutions:presentation.provenance.flatMap((record)=>record.resolution?[record.resolution]:[]),width:options.width}));const resolutionDetails=[...new Set(presentation.provenance.flatMap((record)=>{return[formatRequestedProvenance(record.resolution,presentation.indexingEstimates),formatRequestedIndexingExplanation(record.resolution,presentation.indexingEstimates,historical?"indexing when observed":"indexing")].filter((fact)=>Boolean(fact))}))];for(const fact of resolutionDetails)lines.push(...wrapTerminalProse(fact,options.width," "));for(const group of presentation.targetGroups){const renderedSources=presentation.provenance.some((record)=>record.sources.length&&[group.identity.requested,group.identity.served,group.identity.fresh,...group.sources.flatMap((source)=>source.entries.flatMap((entry)=>[entry.searchTarget,entry.requestedTarget]))].includes(record.target));if(renderedSources&&!group.trustLimits.some((limit)=>limit.kind==="repository_snapshot")&&group.identity.fresh&&group.identity.fresh!==group.identity.served&&formatUsingSegment(group)){lines.push(...wrapTerminalProse(`Requested: ${formatProvenanceRow(group.identity.fresh,[historical?"indexing when observed":"indexing"])}`,options.width," "))}const preparingGroup=presentation.indexingEstimates?.some((entry)=>entry.targets.some((target)=>[group.identity.requested,group.identity.served,group.identity.fresh,...group.sources.flatMap((source)=>source.entries.flatMap((entry)=>[entry.target,entry.searchTarget,...entry.targetAliases??[]]))].includes(target)))??false;appendPresentationTargetGroup(lines,group,options,renderedSources,preparingGroup,historical,presentation.indexingEstimates?.some((entry)=>entry.targets.includes(group.alternatives?.target??""))??false)}appendPresentationWarnings(lines,presentation.warnings,options)}function sourceKindRank(kind){switch(kind){case"code":return 0;case"symbols":return 1;case"repository_docs":return 2;case"site_docs":return 3;case"docs":return 4}}function appendPresentationTargetGroup(lines,group,options,renderedSources,renderedPreparation,historical,renderedAlternatives){const identity=`- ${renderedSources||renderedPreparation?group.identity.requested??formatTargetGroupIdentity(group):formatTargetGroupIdentity(group)}`;const details=[];const using=renderedSources?undefined:formatUsingSegment(group);if(using)details.push(using);const snapshots=group.trustLimits.filter((limit)=>limit.kind==="repository_snapshot");for(const snapshot of renderedSources?[]:snapshots){if(snapshot.requestedCommitDiffers&&snapshot.requestedRef){details.push(`requested ${snapshot.requestedRef} resolves to a different commit${snapshot.requestedCommitDate?` (committed ${snapshot.requestedCommitDate})`:""}${snapshot.indexingRequestedRef===snapshot.requestedRef?" and is indexing":""}`)}if(snapshot.indexingRequestedRef&&!(snapshot.requestedCommitDiffers&&snapshot.indexingRequestedRef===snapshot.requestedRef))details.push(`${snapshot.indexingRequestedRef} is indexing`)}const searched=renderedSources?undefined:formatSourceStateSegment(group,"searched");if(searched)details.push(`searched: ${searched}`);const indexing=renderedPreparation?undefined:formatSourceStateSegment(group,"waiting");if(indexing)details.push(`${historical?"indexing when observed":"indexing"}: ${indexing}`);const unavailable=formatUnavailableSegment(group);if(unavailable)details.push(unavailable);const available=formatAvailableSegment(group);if(available)details.push(`available: ${available}`);if(group.recovery===undefined){const indexed=formatTargetAlternatives(renderedAlternatives&&group.alternatives?{...group.alternatives,versions:[],refs:[]}:group.alternatives);if(indexed)details.push(`indexed: ${indexed}`)}const constraints=formatTargetConstraints(group);if(constraints)details.push(constraints);if(!renderedSources&&!renderedPreparation&&details.length===0&&group.freshnessKind!==undefined){details.push(formatTargetStatus(group.freshnessKind))}if(details.length||group.recovery||!renderedSources&&!renderedPreparation){lines.push("",options.useColors?highlight(identity,true):identity)}if(details.length>0){lines.push(...wrapHangingText(details.join("; ")," ",options.width))}if(group.recovery){const recovery=formatTargetRecovery(group.recovery,group);lines.push(...wrapHangingText(recovery," ",options.width).map((line)=>options.useColors?`${colors.yellow}${line}${colors.reset}`:line))}}function formatTargetStatus(freshness){switch(freshness){case"current":return"ready";case"pending":return"pending";case"provisional":return"provisional";case"stale":return"older snapshot";case"indexing":return"indexing"}}function formatUsingSegment(group){const snapshots=group.trustLimits.filter((limit)=>limit.kind==="repository_snapshot");if(snapshots.length>0){return[...new Set(snapshots.map((snapshot)=>{const provenance=[...snapshot.servedCommitDate?[`committed ${snapshot.servedCommitDate}`]:[],...snapshot.indexedRef?[`indexed from ref ${snapshot.indexedRef}`]:[]];return`commit: ${snapshot.commitTarget}${provenance.length?` (${provenance.join(", ")})`:""}`}))].join("; ")}const stale=group.trustLimits.filter((limit)=>limit.kind==="stale").sort((left,right)=>Number(Boolean(right.servedTarget))+Number(Boolean(right.freshTarget))-Number(Boolean(left.servedTarget))-Number(Boolean(left.freshTarget)))[0];const identityIsStale=!stale&&Boolean(group.identity.served)&&(group.freshnessKind==="stale"||group.freshnessKind==="indexing")&&group.identity.served!==(group.identity.fresh??group.identity.requested);if(!stale&&!identityIsStale){return group.trustLimits.some((limit)=>limit.kind==="provisional")?"using: provisional snapshot":undefined}const served=stale?.servedTarget??stale?.target??group.identity.served;const fresh=stale?.freshTarget??group.identity.fresh;return`using: ${compactRelatedTarget(group.identity.requested,served??"older snapshot")}${fresh?` while ${compactRelatedTarget(group.identity.requested,fresh)} indexes`:" (older snapshot)"}`}function formatSourceStateSegment(group,state){const values=group.sources.flatMap((source)=>source.entries.filter((entry)=>entry.state===state).map((entry)=>({rank:sourceKindRank(source.kind),value:formatGroupedSource(source,entry,group.trustLimits)}))).sort((left,right)=>left.rank-right.rank).map((entry)=>entry.value);const unique=[...new Set(values)];return unique.length>0?unique.join(", "):undefined}function formatUnavailableSegment(group){const entries=group.sources.flatMap((source)=>source.entries.filter((entry)=>entry.state==="unavailable").map((entry)=>({source,entry})));if(entries.length===0)return;const mixed=group.sources.some((source)=>source.entries.some((entry)=>entry.state==="searched"||entry.state==="waiting"));const values=entries.map(({source,entry})=>{const lane=formatGroupedSource(source,entry,group.trustLimits);const reason=entry.terminalReason;const value=reason?`${formatTerminalReason(reason,mixed)}: ${lane}`:`unavailable: ${lane}`;return{rank:sourceKindRank(source.kind),value}}).sort((left,right)=>left.rank-right.rank).map((entry)=>entry.value);return[...new Set(values)].join("; ")}function formatAvailableSegment(group){const values=group.sources.flatMap((source)=>source.entries.filter((entry)=>entry.state==="available_not_searched").map((entry)=>({rank:sourceKindRank(source.kind),value:formatGroupedSource(source,entry,group.trustLimits)}))).sort((left,right)=>left.rank-right.rank).map((entry)=>entry.value);if(group.recovery===undefined){values.push(...group.siteSuggestions.flatMap((suggestion)=>suggestion.suggestions));if(group.siteSuggestions.some((suggestion)=>suggestion.truncated)){values.push("+more")}}const unique=[...new Set(values)];return unique.length>0?unique.join(", "):undefined}function formatTerminalReason(reason,mixed){const family=reason.family==="unknown"?"target":reason.family;if(reason.kind==="not_found"){return mixed?"not found":`${family} not found`}if(mixed)return"unresolved";if(reason.specificity==="version")return"version unavailable";if(reason.specificity==="ref")return"repository ref unresolved";return`${family} unresolved`}function formatTargetConstraints(group){const values=group.trustLimits.flatMap((limit)=>{if(limit.kind!=="constraint")return[];const label=limit.constraint.replaceAll("_"," ");const source=limit.source?` (${limit.source})`:"";return[`${label}${source}: ${limit.values.join(", ")}`]});const unique=[...new Set(values)];return unique.length>0?unique.join("; "):undefined}function formatTargetRecovery(recovery,group){if(recovery.kind==="fix"){switch(recovery.family){case"package":return"Fix: verify registry coordinate/version; use its public repository for repo-wide search.";case"repository":return"Fix: verify public repository/ref.";case"site":return"Fix: verify site host/path.";case"unknown":return"Fix: verify or replace target."}}if(recovery.additionalTargets.length===0&&!recovery.truncated){return`Try: ${recovery.target}`}const additional=recovery.additionalTargets.map((target)=>compactRelatedTarget(group.identity.requested,target));const remaining=recovery.category==="version"?group.alternatives?.versionsRemaining??0:recovery.category==="ref"?(group.alternatives?.refsRemaining??0)+(group.alternatives?.suggestedRefsRemaining??0):0;const label=recovery.category==="site"?"also suggested":"also indexed";const suffix=[...additional,...remaining>0?[`+${remaining}`]:recovery.truncated?["+more"]:[]];return`Try: ${recovery.target} (${label}: ${suffix.join(", ")})`}function formatGroupedSource(source,entry,trustLimits){const coverage=trustLimits.find((limit)=>limit.kind==="coverage"&&limit.source===source.kind&&limit.target===entry.target);const coverageDetails=coverage?formatCoverageLimit(coverage):undefined;const identity=source.kind==="code"?"code":source.kind==="symbols"?"symbols":source.kind==="repository_docs"?"repository docs":source.kind==="site_docs"?`${formatDocumentationSourceIdentity(source,entry)} docs`:"docs";const qualifiers=[];if(coverageDetails)qualifiers.push(coverageDetails);if(entry.state==="searched"&&hasProvisionalTrust(entry,trustLimits)){qualifiers.push("provisional")}return`${identity}${qualifiers.length>0?` (${qualifiers.join("; ")})`:""}`}function hasProvisionalTrust(entry,trustLimits){return trustLimits.some((limit)=>limit.kind==="provisional"&&(!limit.target||limit.target===entry.target||limit.target===entry.searchTarget))}function formatDocumentationSourceIdentity(group,entry){if(group.kind==="repository_docs"){return`${entry.repositoryUrl??entry.target}${entry.commitSha?` @ ${entry.commitSha}`:""}`}if(group.kind==="docs")return entry.target;const siteIdentity=formatDocumentationSiteIdentity(entry.siteUrl);return siteIdentity??entry.siteKey??entry.target}function formatCoverageLimit(limit){const details=[limit.state];if(typeof limit.pagesCrawled==="number"){details.unshift(`${limit.pagesCrawled.toLocaleString("en-US")} pages`)}return details.join("; ")}function formatTargetGroupIdentity(group){const primary=group.identity.requested??group.identity.fresh??group.identity.served??"target";if(formatUsingSegment(group))return primary;const resolved=group.identity.fresh??group.identity.served;if(resolved&&resolved!==primary){return`${primary} -> ${compactRelatedTarget(primary,resolved)}`}return primary}function compactRelatedTarget(base,value){if(!base)return value;if(targetDisplayFamilyKey(base)!==targetDisplayFamilyKey(value)){return value}try{const repository=parseRepositoryTargetSpec(value);if(repository.gitRef)return repository.gitRef}catch{}const version=value.match(/@([^/@]+)$/)?.[1];if(version)return version;return value}function formatTargetAlternatives(alternatives){if(!alternatives)return;const categories=[];if(alternatives.versions.length>0){categories.push(`versions ${alternatives.versions.map((entry)=>entry.version??entry.ref).join(", ")}${formatRemaining(alternatives.versionsRemaining)}`)}if(alternatives.refs.length>0){categories.push(`refs ${alternatives.refs.map((entry)=>entry.ref).join(", ")}${formatRemaining(alternatives.refsRemaining)}`)}if(alternatives.suggestedRefs.length>0){categories.push(`suggested refs ${alternatives.suggestedRefs.map((entry)=>entry.ref).join(", ")}${formatRemaining(alternatives.suggestedRefsRemaining)}`)}return categories.length>0?categories.join(", "):undefined}function wrapHangingText(text,prefix,width){return wrapText2(text,Math.max(1,width-prefix.length)).map((line)=>`${prefix}${line}`)}function appendPresentationWarnings(lines,warnings,options){if(warnings.length===0)return;lines.push(options.useColors?`${colors.bold}${colors.yellow}Warnings:${colors.reset}`:"Warnings:");for(const warning of warnings){if(warning.kind==="query")lines.push(options.useColors?` - ${colors.yellow}${warning.message}${colors.reset}`:` - ${warning.message}`);else{const label=warning.kind.replaceAll("_"," ");const attribution=[warning.source,warning.target].filter((value)=>Boolean(value)).join(" on ");const source=attribution?` (${attribution})`:"";const value=` - ${capitalize(label)}${source}: ${warning.values.join(", ")}`;lines.push(options.useColors?`${colors.yellow}${value}${colors.reset}`:value)}}}function formatRemaining(count){return count>0?` (+${count} more)`:""}function appendPresentationAction(lines,presentation,result,options){const action=presentation.action;const useResults="useResults"in action&&action.useResults;const read=[];const more=[];const followUp=[];const prose=(value)=>footerProse(value,options.width);const operand=(value)=>footerAction(value,options.useColors);const hit=result.results.find((hit)=>hit.readTarget);const priorHead=presentation.targetGroups.flatMap((group)=>group.trustLimits).find((limit)=>limit.kind==="repository_snapshot"&&limit.priorHead);if(hit?.readTarget){if(useResults)read.push(...prose("Use these results now; example read:"));read.push(operand(renderReadTarget(hit.readTarget,options.actionSyntax)))}else if(useResults)followUp.push(...prose("Use these results now."));if(useResults&&priorHead?.kind==="repository_snapshot"){(read.length?read:followUp).push(...prose(`For a specific ref, search ${priorHead.commitTarget.replace(/@[^@]+$/,"@<ref>")}.`))}if(presentation.hasMore){if(typeof result.nextOffset==="number"){more.push(...prose("Repeat the original search, adding:"),operand(options.actionSyntax==="cli"?`--offset ${result.nextOffset}`:`offset=${result.nextOffset}`))}else more.push(...prose("More results are available; repeat the original search."));if(presentation.lifecycle.kind==="active")more.push(...prose("Results may change while this search is running."))}if(action.kind==="poll"){if(useResults)followUp.push(...prose(priorHead?"If you need current HEAD, wait (hits and order may change):":"If you need updated results, wait (hits and order may change):"));followUp.push(operand(options.actionSyntax==="cli"?`githits search-status ${action.searchRef} --wait ${action.waitTimeoutMs}`:`search_status search_ref=${JSON.stringify(action.searchRef)} wait_timeout_ms=${action.waitTimeoutMs}`))}else if(action.kind==="new_search"){followUp.push(...prose(useResults?"For updated results, search again.":"Search again later."))}else if(action.kind==="query_rewrite"){followUp.push(...prose(`Try: ${action.rewrites.map((rewrite)=>formatRewrite(rewrite,options.actionSyntax)).join("; ")}.`))}appendSearchGrepFooter(lines,{read,more,followUp},options.useColors)}function formatRewrite(rewrite,syntax){switch(rewrite){case"shorter_or_broader":return"shorten or broaden query";case"remove_filters":return"remove restrictive filters";case"symbol":return syntax==="cli"?"use --source symbol":'use source="symbol"';case"code_grep":return syntax==="cli"?"use githits grep":"use grep";case"site_shorter_or_broader":return"shorten or broaden site query"}}function capitalize(value){return value.length>0?`${value[0]?.toUpperCase()}${value.slice(1)}`:value}function renderUnifiedSearchError(payload){return formatMappedErrorText({code:payload.code,message:payload.error,retryable:payload.retryable,details:payload.details})}function appendUnifiedSearchHits(lines,hits,queryFragments,options){hits.forEach((hit,idx)=>{if(idx>0)lines.push("");appendHit(lines,idx+1,hit,queryFragments,options)})}function appendHit(lines,index,hit,queryFragments,options){const header=formatHitHeader(hit,queryFragments);const rank=`[${index}] `;const prefix=renderHitHeaderPrefix(header,options.useColors);const title=header.title;const titleFits=title===undefined||!title.includes(`
|
|
198
203
|
`)&&rank.length+header.prefix.length+3+title.length<=options.width;if(titleFits){lines.push(`${rank}${prefix}${title===undefined?"":` - ${highlightRanges(title,header.titleHighlights,options.useColors)}`}`)}else{lines.push(`${rank}${prefix} -`);lines.push(...wrapHighlightedText(title,header.titleHighlights,Math.max(1,options.width-2),options.useColors).map((line)=>line.length===0?"":` ${line}`))}if(hit.type==="repository_code"||hit.type==="repository_doc"){appendStructuralEvidence(lines,hit,options);return}const preview=hit.type==="documentation_page"?hit.documentationPreview:undefined;const summary=prepareSummary(preview?.text,hit.title);const summaryHighlights=preview?graphemeHighlightRanges(preview.text,preview.highlights):undefined;if(summary){lines.push(...wrapHighlightedText(summary.text,shiftHighlightRanges(summaryHighlights,summary.offset),Math.max(1,options.width-2),options.useColors).map((line)=>line.length===0?"":` ${line}`))}}function appendStructuralEvidence(lines,hit,options){const evidence=hit.repositoryEvidence;const source=evidence?.matchedSource;if(!source){if(!evidence)lines.push(" Snippet unavailable");return}const context=evidence?.semanticContext;if(context){if(context.scopeChainTruncated)lines.push(" ... outer scopes omitted");context.scopes.forEach((scope,index)=>{const prefix=" ".repeat(index+1);const lineLabel=scope.declarationStartLine===scope.declarationEndLine?"line":"lines";lines.push(`${prefix}- ${scope.kind} ${scope.qualifiedPath} | ${lineLabel} ${formatBareLineRange(scope.declarationStartLine,scope.declarationEndLine)}`)})}if(source.linesOmittedBefore)lines.push(" ... lines omitted before");const gutterWidth=String(source.endLine).length;for(const line of source.lines){const marker=line.highlights.some(([from,to])=>to>from)?">":" ";const text=highlightSourceGraphemes(line.text,line.highlights,options.useColors);lines.push(`${marker} ${String(line.lineNumber).padStart(gutterWidth)} | ${line.prefixTruncated?"...":""}${text}${line.suffixTruncated?"...":""}`)}if(source.linesOmittedAfter)lines.push(" ... lines omitted after");if(source.matchSpansTruncated)lines.push(" Some matches are not highlighted")}var sourceGraphemeSegmenter=new Intl.Segmenter(undefined,{granularity:"grapheme"});function highlightSourceGraphemes(text,ranges,useColors){if(!useColors||ranges.length===0)return text;return highlightRanges(text,graphemeHighlightRanges(text,ranges),true)}function graphemeHighlightRanges(text,ranges){if(ranges.length===0)return ranges;const offsets=Array.from(sourceGraphemeSegmenter.segment(text),(segment)=>segment.index);offsets.push(text.length);return ranges.map(([from,to])=>[offsets[from],offsets[to]])}function wrapHighlightedText(text,ranges,width,useColors){const output=[];let lineOffset=0;for(const sourceLine of text.split(`
|
|
199
204
|
`)){const leading=sourceLine.match(/^\s*/)?.[0]??"";const content=sourceLine.slice(leading.length);if(content.length===0){output.push(leading);lineOffset+=sourceLine.length+1;continue}const continuationMarker=content.match(/^(?:\/\/[!/]?|#|--|\*)\s+/)?.[0]??"";let consumed=0;let isFirstSegment=true;let segmentLeading=leading;let available=Math.max(1,width-segmentLeading.length);while(content.length-consumed>available){let breakAt=content.lastIndexOf(" ",consumed+available);if(breakAt<=consumed){breakAt=content.indexOf(" ",consumed+available);if(breakAt<0)break}const chunk=content.slice(consumed,breakAt).trimEnd();output.push(highlightWrappedSegment(segmentLeading,chunk,lineOffset+leading.length+consumed,ranges,useColors));consumed=breakAt;while(content[consumed]===" ")consumed+=1;isFirstSegment=false;segmentLeading=`${leading}${continuationMarker}`;available=Math.max(1,width-segmentLeading.length)}output.push(highlightWrappedSegment(isFirstSegment?leading:segmentLeading,content.slice(consumed),lineOffset+leading.length+consumed,ranges,useColors));lineOffset+=sourceLine.length+1}return output}function highlightWrappedSegment(leading,content,contentOffset,ranges,useColors){const value=`${leading}${content}`;if(!useColors||!ranges||ranges.length===0)return value;const localRanges=ranges.flatMap(([from,to])=>{const segmentStart=contentOffset;const segmentEnd=contentOffset+content.length;const overlapStart=Math.max(from,segmentStart);const overlapEnd=Math.min(to,segmentEnd);return overlapStart<overlapEnd?[[leading.length+overlapStart-segmentStart,leading.length+overlapEnd-segmentStart]]:[]});return highlightRanges(value,localRanges,true)}function formatHitHeader(hit,queryFragments){const loc=hit.locator;if(hit.type==="documentation_page"){const docsReadTarget=hit.readTarget?.target||"documentation target unavailable";const type="[docs page]";const target=formatDocumentationTarget(hit);const sourceUrl=formatDocumentationSourceUrl(loc.sourceUrl,docsReadTarget);const sourceSuffix=sourceUrl?` - ${sourceUrl}`:"";return{prefix:`${docsReadTarget} ${type} ${target}${sourceSuffix}`,segments:[{text:docsReadTarget,style:"locator"},{text:" ",style:"plain"},{text:type,style:"secondary"},{text:" ",style:"plain"},{text:target,style:"secondary"},...sourceUrl?[{text:" - ",style:"plain"},{text:sourceUrl,style:"secondary"}]:[]],title:hit.title||"title unavailable",titleHighlights:hit.highlights?.title}}const evidence=formatRepositoryEvidence(hit);const location=evidence.filePath?`${evidence.filePath}${formatLineRange(evidence.startLine,evidence.endLine)}`:"location unavailable";const sourceStatus=candidateHeaderStatus(hit,queryFragments,evidence.filePath);const type=`[${shortType(hit.type)}${sourceStatus}]`;const candidateSymbol=candidateSymbolLabel(hit,evidence);const symbolSuffix=candidateSymbol?` - ${candidateSymbol}`:"";const target=hit.target;const title=formatRepositoryHitTitle(hit,evidence.startLine,evidence.endLine);return{prefix:`${target}${location?` ${location}`:""} ${type}${symbolSuffix}`,segments:[{text:target,style:"locator"},...location?[{text:" ",style:"plain"},{text:location,style:"locator"}]:[],{text:" ",style:"plain"},{text:type,style:"secondary"},...candidateSymbol?[{text:" - ",style:"plain"},{text:candidateSymbol,style:"secondary"}]:[]],title:title.text,titleHighlights:offsetHighlightRanges(hit.highlights?.title,title.highlightOffset)}}function isPathOnlyHit(hit){const evidence=hit.repositoryEvidence;return(hit.type==="repository_code"||hit.type==="repository_doc")&&!evidence?.matchedSource&&evidence?.bm25MatchFields?.length===1&&evidence.bm25MatchFields[0]==="FILE_PATH"}function identifierQueryFragments(raw){if(!raw||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(raw))return[];return[...new Set(raw.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").split(/[ _$]+/).filter(Boolean).map((fragment)=>fragment.toLowerCase()))]}var INDEXED_FIELD_SHORT_NAMES={SYMBOL_NAME:"name",FILE_PATH:"path",DOCUMENTATION:"docs",SOURCE_IDENTIFIER:"identifiers"};function candidateHeaderStatus(hit,queryFragments,displayedPath){const evidence=hit.repositoryEvidence;if(hit.type!=="repository_code"&&hit.type!=="repository_doc"||!evidence||evidence.matchedSource)return"";const fields=evidence.bm25MatchFields;const visibleValues=[];if(fields?.includes("SYMBOL_NAME")&&hit.title)visibleValues.push(hit.title.toLowerCase());if(fields?.includes("FILE_PATH")&&displayedPath)visibleValues.push(displayedPath.toLowerCase());const visible=queryFragments.filter((fragment)=>visibleValues.some((value)=>value.includes(fragment)));if(visible.length>0)return`, candidate; visible terms: ${visible.join(", ")}`;if(fields?.length)return`, candidate; indexed: ${fields.map((field)=>INDEXED_FIELD_SHORT_NAMES[field]).join("/")}`;return", candidate"}function formatRepositoryEvidence(hit){const loc=hit.locator;const source=hit.repositoryEvidence?.matchedSource;const preferredRead=hit.repositoryEvidence?.semanticContext?.preferredRead;const candidateRead=(hit.type==="repository_code"||hit.type==="repository_doc")&&!source?preferredRead:undefined;return{filePath:loc.filePath,startLine:source?.startLine??candidateRead?.startLine??loc.evidenceRange?.startLine??loc.startLine,endLine:source?.endLine??candidateRead?.endLine??loc.evidenceRange?.endLine??loc.endLine}}function candidateSymbolLabel(hit,location){if(hit.type!=="repository_code"||!hit.repositoryEvidence||hit.repositoryEvidence.matchedSource)return;const symbol=hit.locator.symbolContext;const definition=symbol?.definitionRange;if(!symbol?.kind||!symbol.qualifiedPath||!definition||!location.filePath||location.startLine===undefined||location.endLine===undefined||definition.filePath!==location.filePath&&definition.repositoryFilePath!==location.filePath||definition.startLine>location.startLine||definition.endLine<location.endLine)return;return`${symbol.kind} ${symbol.qualifiedPath}`}function formatRepositoryHitTitle(hit,evidenceStartLine,evidenceEndLine){if(isPathOnlyHit(hit))return{highlightOffset:0};if(hit.repositoryEvidence!==undefined&&(hit.type==="repository_code"||hit.type==="repository_doc")){const scopes=hit.repositoryEvidence?.semanticContext?.scopes??[];const duplicateTitle=scopes.some((scope)=>hit.title===scope.name||hit.title===scope.qualifiedPath);return{text:hit.type==="repository_code"||duplicateTitle?undefined:hit.title||undefined,highlightOffset:0}}if(hit.type!=="repository_code"&&hit.type!=="repository_symbol"){return{text:hit.title||undefined,highlightOffset:0}}const identity=formatRepositorySymbolIdentity(hit);const context=hit.locator.symbolContext;const definition=context?.definitionRange;const definitionSharesEvidenceFile=definition?.filePath===hit.locator.filePath;const definitionDiffers=definition!==undefined&&definitionSharesEvidenceFile&&(definition.startLine!==evidenceStartLine||definition.endLine!==evidenceEndLine);const indexed=hit.locator.indexedRange;const indexedDiffers=indexed!==undefined&&(indexed.startLine!==evidenceStartLine||indexed.endLine!==evidenceEndLine);const kind=context?.kind;const annotation=definition?definitionDiffers?formatRangeAnnotation(kind??"definition",definition):kind:indexedDiffers?formatRangeAnnotation("chunk",indexed):kind;const text=identity.text?annotation?`${identity.text} (${annotation})`:identity.text:annotation;return{text,highlightOffset:identity.highlightOffset}}function formatRepositorySymbolIdentity(hit){const title=hit.title||undefined;const context=hit.locator.symbolContext;const qualifiedPath=context?.qualifiedPath;const name=context?.name;if(!title){return{text:qualifiedPath&&!qualifiedPath.startsWith("<")?qualifiedPath:undefined,highlightOffset:0}}if(!qualifiedPath||!name||qualifiedPath.startsWith("<")||!hasQualifiedNameSuffix(qualifiedPath,name)){return{text:title,highlightOffset:0}}const titleSuffix=title.startsWith(name)?title.slice(name.length):undefined;if(titleSuffix===undefined||!isSymbolSignatureSuffix(titleSuffix)){return{text:title,highlightOffset:0}}return{text:`${qualifiedPath}${titleSuffix}`,highlightOffset:qualifiedPath.length-name.length}}function isSymbolSignatureSuffix(suffix){return suffix===""||/^\/\d+$/.test(suffix)||/^\([^\n]*\)$/.test(suffix)}function hasQualifiedNameSuffix(qualifiedPath,name){return qualifiedPath===name||[".","::","#","/"].some((separator)=>qualifiedPath.endsWith(`${separator}${name}`))}function formatRangeAnnotation(label,range){const lineLabel=range.startLine===range.endLine?"line":"lines";return`${label} at ${lineLabel} ${formatBareLineRange(range.startLine,range.endLine)}`}function offsetHighlightRanges(ranges,offset){if(!ranges||offset===0)return ranges;return ranges.map(([from,to])=>[from+offset,to+offset])}function renderHitHeaderPrefix(header,useColors){return header.segments.map((segment)=>{if(!useColors||segment.style==="plain")return segment.text;return segment.style==="locator"?highlight(segment.text,true):dim(segment.text,true)}).join("")}function formatDocumentationTarget(hit){const{registry,packageName}=hit.locator;if(registry&&packageName){return`${registry.toLowerCase()}:${packageName}`}return stripVersionFromTarget(hit.requestedTarget??hit.target)||"target unavailable"}function formatDocumentationSourceUrl(value,docsReadTarget){if(!value)return"source URL unavailable";const sourceUrl=value.replace(/^https?:\/\//,"");const target=docsReadTarget?.replace(/^https?:\/\//,"");if(!target)return sourceUrl;if(sourceUrl===target)return"";const fragmentIndex=sourceUrl.indexOf("#");if(fragmentIndex>0&&sourceUrl.slice(0,fragmentIndex)===target){return sourceUrl.slice(fragmentIndex)}return sourceUrl}function stripVersionFromTarget(value){if(!value)return"";const atIndex=value.lastIndexOf("@");return atIndex>0?value.slice(0,atIndex):value}function shortType(type){switch(type){case"repository_code":return"repo code";case"repository_symbol":return"repo symbol";case"repository_doc":return"repo doc";default:return type}}function prepareSummary(summary,title){if(!summary)return;const lines=summary.split(`
|
|
200
205
|
`);let offset=0;if(title&&normalizeHeading(lines[0])===normalizeHeading(title)){offset+=(lines[0]?.length??0)+1;lines.shift();if(lines[0]!==undefined&&isSetextUnderline(lines[0])){offset+=lines[0].length+1;lines.shift()}}const remaining=lines.join(`
|
|
201
|
-
`);const leadingNewline=remaining.match(/^\n+/)?.[0].length??0;const text=remaining.replace(/^\n+|\n+$/g,"");if(text.trim().length===0)return;return{text,offset:offset+leadingNewline}}function shiftHighlightRanges(ranges,offset){if(!ranges||offset===0)return ranges;return ranges.flatMap(([from,to])=>{const shiftedFrom=from-offset;const shiftedTo=to-offset;return shiftedTo>0?[[Math.max(0,shiftedFrom),shiftedTo]]:[]})}function normalizeHeading(value){return(value??"").trim().replace(/^#{1,6}\s+/,"")}function isSetextUnderline(value){return/^\s*(?:=+|-+)\s*$/.test(value)}function formatLineRange(start,end){if(typeof start!=="number")return"";if(typeof end!=="number"||end===start)return`:${start}`;return`:${start}-${end}`}function formatBareLineRange(start,end){if(typeof start!=="number")return"an unavailable range";if(typeof end!=="number"||end===start)return`${start}`;return`${start}-${end}`}function formatDocumentationSiteIdentity(value){if(!value)return;try{const url=new URL(value);if(!url.host)return;const path=url.pathname==="/"?"":url.pathname.replace(/\/$/,"");return`${url.host}${path}`}catch{return}}function wrapText2(text,width=DEFAULT_TEXT_WIDTH){const lines=[];for(const paragraph of text.split(/\n/)){if(paragraph.length===0){lines.push("");continue}let remaining=paragraph.trim();while(remaining.length>width){let breakAt=remaining.lastIndexOf(" ",width);if(breakAt<=0)breakAt=remaining.indexOf(" ",width);if(breakAt<0)breakAt=remaining.length;lines.push(remaining.slice(0,breakAt).trimEnd());remaining=remaining.slice(breakAt).trimStart()}if(remaining.length>0)lines.push(remaining)}return lines}var searchTargetSchema=z11.string().min(1).describe("Compact target: `npm:react@version`, `github:facebook/react@ref`, or `site:react.dev`. Omit the suffix for the latest package version or repository default branch; a ref may be a branch, tag, or commit. `#` is for semantic fragments.");var schema10={query:z11.string().min(1).describe("Focused discovery terms, API names, behaviors, or quoted phrases. Add constraints inline, for example `kind:function`, `category:callable`, `path:lib/`, `intent:production`, `name:Router`, or `lang:typescript`; qualifiers combine with terms using query boolean syntax."),target:searchTargetSchema.optional().describe("One compact target: `npm:react@version`, `github:facebook/react@ref`, or `site:react.dev`. Omit the suffix for the latest package version or repository default branch; a ref may be a branch, tag, or commit. `#` is for semantic fragments. Do not also pass `targets`."),targets:z11.array(searchTargetSchema).max(20).optional().describe("Up to 20 compact targets. Do not also pass `target`."),source:z11.enum(["docs","code","symbol"]).optional().describe("Optional result source: `docs` for guides/reference pages, `code` for source and tests, or `symbol` for APIs/entities. Omit to let GitHits select the best sources."),public_only:z11.boolean().optional().describe('Set true to restrict code and symbol results to public APIs. False is equivalent to omitting it; ignored for `source:"docs"`.'),allow_partial_results:z11.boolean().optional().describe("Default true returns a serveable subset while other target/source pairs prepare, with searchRef for continuation. Set false to keep hits atomic across runnable pairs; a complete serveable interim result may still accompany searchRef during refresh. Partial payloads support normal pagination via nextOffset."),limit:z11.coerce.number().int().min(1).max(100).optional().describe("Maximum results to return (default 10, max 100)."),offset:z11.coerce.number().int().min(0).optional().describe("Zero-based result offset (default 0). Continue pagination with the response's `nextOffset` when present."),wait_timeout_ms:z11.coerce.number().int().min(0).max(MAX_DISCOVERY_WAIT_TIMEOUT_MS).optional().describe(`Time to wait for results in ms. Default ${DEFAULT_WAIT_TIMEOUT_MS}, max ${MAX_DISCOVERY_WAIT_TIMEOUT_MS}.`),format:z11.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 DESCRIPTION11='Discover relevant docs, code, and symbols in a known public target. Start here for open-ended "how does", "where is", "find", or "locate" questions. '+"Required: `query` plus either `target` or `targets`; pass `target` or `targets`, not both. "+"Target indexed dependencies and repositories, or standalone docs with `site:<host[/path]>`. "+"Put search constraints in `query`; backend validation reports accepted values. Inspect returned warnings and `sourceStatus` when a qualifier is ignored or incompatible with a selected source. `public_only` remains structured and is ignored for docs. "+"A `search` call can return complete results directly. Use visible hits for lookup now. Follow `search_status` only if you need updated results and the response supplies both a `searchRef` and a `search_status` action; never repeat `search` to poll. Terminal or unrecognized statuses are not polled; follow the response's recovery guidance instead. If the response includes advisory `sourceStatus[].suggestedSiteTargets`, retry one explicitly; do not treat suggestions as aliases or retry automatically. "+"Use hit content directly when sufficient; otherwise replay its complete emitted read action or generated `followUp` unchanged, including supplied selector and bounds. A `[docs page]` header is a page locator; its action selects the hit's section. Hosted HTTP(S) page locators address mutable current content. Repository docs remain snapshot-addressed and keep returned ranges. For direct reads, explicit bounds select a caller-chosen range; a docs URL fragment without bounds returns its heading and full subtree through the next equal-or-higher heading."+`
|
|
206
|
+
`);const leadingNewline=remaining.match(/^\n+/)?.[0].length??0;const text=remaining.replace(/^\n+|\n+$/g,"");if(text.trim().length===0)return;return{text,offset:offset+leadingNewline}}function shiftHighlightRanges(ranges,offset){if(!ranges||offset===0)return ranges;return ranges.flatMap(([from,to])=>{const shiftedFrom=from-offset;const shiftedTo=to-offset;return shiftedTo>0?[[Math.max(0,shiftedFrom),shiftedTo]]:[]})}function normalizeHeading(value){return(value??"").trim().replace(/^#{1,6}\s+/,"")}function isSetextUnderline(value){return/^\s*(?:=+|-+)\s*$/.test(value)}function formatLineRange(start,end){if(typeof start!=="number")return"";if(typeof end!=="number"||end===start)return`:${start}`;return`:${start}-${end}`}function formatBareLineRange(start,end){if(typeof start!=="number")return"an unavailable range";if(typeof end!=="number"||end===start)return`${start}`;return`${start}-${end}`}function formatDocumentationSiteIdentity(value){if(!value)return;try{const url=new URL(value);if(!url.host)return;const path=url.pathname==="/"?"":url.pathname.replace(/\/$/,"");return`${url.host}${path}`}catch{return}}function wrapText2(text,width=DEFAULT_TEXT_WIDTH){const lines=[];for(const paragraph of text.split(/\n/)){if(paragraph.length===0){lines.push("");continue}let remaining=paragraph.trim();while(remaining.length>width){let breakAt=remaining.lastIndexOf(" ",width);if(breakAt<=0)breakAt=remaining.indexOf(" ",width);if(breakAt<0)breakAt=remaining.length;lines.push(remaining.slice(0,breakAt).trimEnd());remaining=remaining.slice(breakAt).trimStart()}if(remaining.length>0)lines.push(remaining)}return lines}var searchTargetSchema=z11.string().min(1).describe("Compact target: `npm:react@version`, `github:facebook/react@ref`, `launchpad:~owner/+git/repo@ref` (`lp:PROJECT` also accepted), or `site:react.dev`. Omit the suffix for the latest package version or repository default branch; a ref may be a branch, tag, or commit. `#` is for semantic fragments.");var schema10={query:z11.string().min(1).describe("Focused discovery terms, API names, behaviors, or quoted phrases. Add constraints inline, for example `kind:function`, `category:callable`, `path:lib/`, `intent:production`, `name:Router`, or `lang:typescript`; qualifiers combine with terms using query boolean syntax."),target:searchTargetSchema.optional().describe("One compact target: `npm:react@version`, `github:facebook/react@ref`, `launchpad:~owner/+git/repo@ref` (`lp:PROJECT` also accepted), or `site:react.dev`. Omit the suffix for the latest package version or repository default branch; a ref may be a branch, tag, or commit. `#` is for semantic fragments. Do not also pass `targets`."),targets:z11.array(searchTargetSchema).max(20).optional().describe("Up to 20 compact targets. Do not also pass `target`."),source:z11.enum(["docs","code","symbol"]).optional().describe("Optional result source: `docs` for guides/reference pages, `code` for source and tests, or `symbol` for APIs/entities. Omit to let GitHits select the best sources."),public_only:z11.boolean().optional().describe('Set true to restrict code and symbol results to public APIs. False is equivalent to omitting it; ignored for `source:"docs"`.'),allow_partial_results:z11.boolean().optional().describe("Default true returns a serveable subset while other target/source pairs prepare, with searchRef for continuation. Set false to keep hits atomic across runnable pairs; a complete serveable interim result may still accompany searchRef during refresh. Partial payloads support normal pagination via nextOffset."),limit:z11.coerce.number().int().min(1).max(100).optional().describe("Maximum results to return (default 10, max 100)."),offset:z11.coerce.number().int().min(0).optional().describe("Zero-based result offset (default 0). Continue pagination with the response's `nextOffset` when present."),wait_timeout_ms:z11.coerce.number().int().min(0).max(MAX_DISCOVERY_WAIT_TIMEOUT_MS).optional().describe(`Time to wait for results in ms. Default ${DEFAULT_WAIT_TIMEOUT_MS}, max ${MAX_DISCOVERY_WAIT_TIMEOUT_MS}.`),format:z11.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 DESCRIPTION11='Discover relevant docs, code, and symbols in a known public target. Start here for open-ended "how does", "where is", "find", or "locate" questions. '+"Required: `query` plus either `target` or `targets`; pass `target` or `targets`, not both. "+"Target indexed dependencies and repositories, or standalone docs with `site:<host[/path]>`. "+"Put search constraints in `query`; backend validation reports accepted values. Inspect returned warnings and `sourceStatus` when a qualifier is ignored or incompatible with a selected source. `public_only` remains structured and is ignored for docs. "+"A `search` call can return complete results directly. Use visible hits for lookup now. Follow `search_status` only if you need updated results and the response supplies both a `searchRef` and a `search_status` action; never repeat `search` to poll. Terminal or unrecognized statuses are not polled; follow the response's recovery guidance instead. If the response includes advisory `sourceStatus[].suggestedSiteTargets`, retry one explicitly; do not treat suggestions as aliases or retry automatically. "+"Use hit content directly when sufficient; otherwise replay its complete emitted read action or generated `followUp` unchanged, including supplied selector and bounds. A `[docs page]` header is a page locator; its action selects the hit's section. Hosted HTTP(S) page locators address mutable current content. Repository docs remain snapshot-addressed and keep returned ranges. For direct reads, explicit bounds select a caller-chosen range; a docs URL fragment without bounds returns its heading and full subtree through the next equal-or-higher heading."+`
|
|
202
207
|
|
|
203
208
|
${SEARCH_GUARDRAIL}`;function createSearchTool(service){return{name:"search",description:DESCRIPTION11,schema:schema10,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const effectiveTarget=isBlankSearchTarget(args.target)?undefined:args.target;const resolvedTarget=effectiveTarget?resolveSearchTarget(effectiveTarget,context,args.format):undefined;if(resolvedTarget&&"content"in resolvedTarget)return resolvedTarget;const effectiveTargets=args.targets?.filter((target)=>!isBlankSearchTarget(target));const nonEmptyTargets=effectiveTargets?.length?effectiveTargets:undefined;const resolvedTargets=nonEmptyTargets?.map((entry)=>resolveSearchTarget(entry,context,args.format));const resolvedTargetsError=resolvedTargets?.find((entry)=>("content"in entry));if(resolvedTargetsError){return resolvedTargetsError}const built=buildUnifiedSearchParams({target:resolvedTarget&&!("content"in resolvedTarget)?resolvedTarget:undefined,targets:resolvedTargets?.filter(isResolvedSearchTarget),query:args.query,sources:args.source?[args.source.toUpperCase()]:undefined,publicOnly:args.public_only,allowPartialResults:args.allow_partial_results,limit:args.limit,offset:args.offset,waitTimeoutMs:args.wait_timeout_ms});const outcome=await service.search(built.params,{signal:context?.signal});const payload=buildUnifiedSearchSuccessPayload(built.params,built.rawQuery,built.compiledQuery,outcome);if(isTextFormat7(args.format)){return textResult(renderUnifiedSearchSuccess(payload))}return textResult(JSON.stringify(projectUnifiedSearchSuccessPayload(payload)))}catch(error){throwIfCallerCancellation(error,context?.signal);const basePayload=buildUnifiedSearchErrorPayload(error);const indexingMapped=withIndexingRetryAction({code:basePayload.code,message:basePayload.error,retryable:basePayload.retryable,details:basePayload.details},"search","mcp");const mapped=withVersionRefRecovery(indexingMapped,{syntax:"mcp",tool:"search",args});const payload=addLocalMcpAuthAction({...basePayload,...mapped.details?{details:mapped.details}:{}},context);if(isTextFormat7(args.format)){return errorResult(renderUnifiedSearchError(payload))}return errorResult(JSON.stringify(payload))}}}}function isBlankSearchTarget(target){if(target===undefined)return true;return target.trim().length===0}function isResolvedSearchTarget(target){return!("content"in target)}function resolveSearchTarget(target,context,format){try{return parseUnifiedSearchTargetSpec(target)}catch(error){const mapped=mapCodeNavigationError(error);return mcpMappedErrorResult(mapped,context,format)}}function isTextFormat7(format){return format===undefined||format==="text"}import{z as z12}from"zod";function renderUnifiedSearchStatusText(payload,options={}){const presentation=projectUnifiedSearchPresentation(payload);const result=payload.result;return renderUnifiedSearchPresentationText(presentation,{results:result?.results??[],nextOffset:result?.nextOffset},options)}var schema11={search_ref:z12.string().min(1).describe("The `searchRef` field from a prior `search` response (camelCase in the response, snake_case as this parameter). Pass it through unchanged."),wait_timeout_ms:z12.coerce.number().int().min(0).max(MAX_DISCOVERY_WAIT_TIMEOUT_MS).optional().describe(`Time to wait for results in ms. Default ${DEFAULT_WAIT_TIMEOUT_MS}, max ${MAX_DISCOVERY_WAIT_TIMEOUT_MS}.`),format:z12.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 DESCRIPTION12="Continue an explicit search reference for progress and results. Call this only after a prior `search` response explicitly supplies both a `searchRef` and a `search_status` action; otherwise the initial result is complete or has its own recovery guidance. "+"Pass that response's `searchRef` as `search_ref` here (response field is camelCase; this parameter is snake_case), only for active `PENDING`, `INDEXING`, or `SEARCHING` progress when updated results matter. Visible hits can be used for lookup while indexing continues. Fetch partial hits from a serveable subset when the original request allowed partial results (the default; set `allow_partial_results: false` to require all runnable pairs). `COMPLETED`, `DEFERRED`, `TIMEOUT`, and `FAILED` are terminal; unrecognized statuses are not polled. Preserve any disclosed evidence from those stopped references and follow the rendered new-search action.";function createSearchStatusTool(service){return{name:"search_status",description:DESCRIPTION12,schema:schema11,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const outcome=await service.searchStatus(args.search_ref,args.wait_timeout_ms??DEFAULT_WAIT_TIMEOUT_MS,{signal:context?.signal});const payload=buildUnifiedSearchStatusPayload(outcome);if(isTextFormat8(args.format)){return textResult(renderUnifiedSearchStatusText(payload))}return textResult(JSON.stringify(projectUnifiedSearchStatusPayload(payload)))}catch(error){throwIfCallerCancellation(error,context?.signal);const basePayload=buildUnifiedSearchErrorPayload(error);const mapped=withIndexingRetryAction({code:basePayload.code,message:basePayload.error,retryable:basePayload.retryable,details:basePayload.details},"search","mcp");const payload=addLocalMcpAuthAction({...basePayload,...mapped.details?{details:mapped.details}:{}},context);if(isTextFormat8(args.format)){return errorResult(renderUnifiedSearchError(payload))}return errorResult(JSON.stringify(payload))}}}}function isTextFormat8(format){return format===undefined||format==="text"}var STABLE_MCP_OPERATION_FACTORIES=[(services)=>eraseMcpTool(createGetExampleTool2(services.githitsService)),(services)=>eraseMcpTool(createSearchTool(services.codeNavigationService)),(services)=>eraseMcpTool(createSearchStatusTool(services.codeNavigationService)),(services)=>eraseMcpTool(createListTool(services.listService)),(services)=>eraseMcpTool(createReadTool(services)),(services)=>eraseMcpTool(createGrepTool(services.grepService)),(services)=>eraseMcpTool(createResolveTargetTool2(services.resolveTargetService)),(services)=>eraseMcpTool(createCodeDiffTool(services.codeNavigationService)),(services)=>eraseMcpTool(createPackageSummaryTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageVulnerabilitiesTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageDependenciesTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageChangelogTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageUpgradeReviewTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createResearchTool2(services.agenticAskService))];function createStableMcpToolFactories(quickStartGuide=buildMcpQuickStart()){return[()=>eraseMcpTool(createQuickStartTool(quickStartGuide)),...STABLE_MCP_OPERATION_FACTORIES]}var STABLE_MCP_TOOL_FACTORIES=createStableMcpToolFactories();function getMcpToolDefinitions(services){return getToolDefinitionsFromFactories(services,STABLE_MCP_TOOL_FACTORIES)}function getToolDefinitionsFromFactories(services,toolFactories){return toolFactories.map((createTool)=>addMcpSessionPrerequisite(createTool(services)))}function addMcpSessionPrerequisite(tool){if(tool.name==="quick_start")return tool;return{...tool,description:`${tool.description}
|
|
204
209
|
|