@githits/mcp 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{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-660sdzfg.js";import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-1bad2znr.js";import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2}from"./shared/chunk-jemh0eym.js";var GUIDE=`# GitHits
1
+ import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-jatk4vrs.js";import{EXTERNAL_CONTENT_POSTURE,PKG_VULNS_GUARDRAIL,PKG_INFO_GUARDRAIL,PKG_CHANGELOG_GUARDRAIL,PKG_UPGRADE_REVIEW_GUARDRAIL,CODE_READ_GUARDRAIL,CODE_GREP_GUARDRAIL,SEARCH_GUARDRAIL,KNOWN_REGISTRIES,UnsupportedRegistryError,InvalidPackageSpecError,InvalidArgumentError,parsePackageSpec,isKnownRegistry,LegacyRepositoryRefError,isRepositoryTargetSpec,parseRepositoryTargetSpec,isCanonicalRepositoryUrl,formatRepositoryTarget,formatRepositoryTargetLabel,buildInvalidTargetSpecError,terminalWidth,sanitizeTerminalText,wrapTerminalProse,projectTargetResolution,buildTargetResolutionNotes,buildRetryCandidateLine,buildSuggestedRefsLine,buildResolutionFromRetryCandidates,formatTargetResolutionIdentity,buildSourceCorrespondenceNotes,buildSourceCorrespondenceNote,toCodeNavigationRegistry,AuthRequiredError,mapSessionIdError,mapTermsAcceptanceError,shellQuote,shellQuoteExact,mapVersionRefRecovery,withVersionRefRecovery,mapCodeNavigationError,buildUpdateRequiredError,serviceRequestArgs,MAX_WAIT_TIMEOUT_MS,MAX_DISCOVERY_WAIT_TIMEOUT_MS,MCP_READ_DEFAULT_SPAN,MCP_READ_MAX_SPAN,formatProvenanceRow,formatSourceRow,renderSourceSection,sameRepositoryCommit,resolutionSourceFacts,formatRequestedIndexingExplanation,renderResolutionDetails,formatRequestedProvenance,formatPreparationRow,renderPreparationSection,formatPreparationRetry,indexingWaitMs,withIndexingRetryAction,formatMappedErrorText,READ_ONLY_TOOL_ANNOTATIONS,OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,textResult,errorResult,withErrorHandling,mcpMappedErrorResult,addLocalMcpAuthAction,throwIfCallerCancellation,createGetExampleTool2,colors,colorize,highlight,highlightMatch,highlightRanges,dim,mapPackageIntelligenceError,formatCompactNumber,createResearchTool2,parseUnifiedSearchTargetSpec,createResolveTargetTool2}from"./shared/chunk-9t5xntmf.js";import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2}from"./shared/chunk-33zcd460.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,
@@ -61,10 +61,11 @@ unverified paths.
61
61
  - Packages: \`<registry>:<name>@version\` such as \`npm:express\` or
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
- including in monorepos.
64
+ including in monorepos. Paths and path filters are relative to that package root.
65
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. Launchpad accepts \`lp:project\`, \`lp:distro/+source/source\`,
67
+ a provider. Paths and path filters are relative to the repository root.
68
+ Launchpad accepts \`lp:project\`, \`lp:distro/+source/source\`,
68
69
  \`lp:~owner/project\`, \`lp:~owner/distro/+source/source\`, and complete
69
70
  \`launchpad:~owner/[project/]+git/repo\` or
70
71
  \`launchpad:~owner/distro/+source/source/+git/repo\` paths. Case-insensitive
@@ -81,13 +82,14 @@ unverified paths.
81
82
  - Omit \`format\`: text serves model reading and follow-ups. Use JSON only when
82
83
  code consumes the raw response or a required field is missing from text;
83
84
  calling through MCP or code is not a reason.
84
- - Reuse returned targets, paths, locators, references, and ranges unchanged;
85
- never invent them.
85
+ - Reuse returned target/path pairs, locators, references, and ranges unchanged;
86
+ never invent them or combine a path from one target with another target.
86
87
  - Follow rendered continuation and recovery actions instead of repeating or
87
88
  polling calls. Counts cover one page.
88
89
  - Omit \`wait_timeout_ms\` for the default; \`0\` returns without waiting. While
89
90
  indexing, use the displayed estimate to wait longer or pick a listed
90
- already-indexed version or ref.
91
+ already-indexed version or ref. Keep the original target and path filters
92
+ when retrying the same scope.
91
93
  - Cite tool-owned provenance, including example source repositories, and
92
94
  report coverage, truncation, and other evidence limits.
93
95
 
@@ -107,17 +109,17 @@ lacks a detail you need. Sources default to MCP read calls; use
107
109
  \`source_format:"url"\` for original upstream URLs. Do not invent or rewrite
108
110
  sources.`;function buildMcpQuickStart(options={}){const includeExternalContentPosture=options.includeExternalContentPosture??true;return includeExternalContentPosture?`${GUIDE}
109
111
 
110
- ${EXTERNAL_CONTENT_POSTURE}`:GUIDE}function buildMcpInstructions(options={}){return buildMcpQuickStart(options)}import{McpServer}from"@modelcontextprotocol/sdk/server/mcp.js";var BITS=[[1,8],[2,16],[4,32],[64,128]];var CANDIDATES=14;var CONVERGE=0.75;function seeded(n){const s=Math.sin(n*127.1)*43758.5453;return s-Math.floor(s)}function narrowingFrame(frame,options={}){const width=options.width??6;const period=options.period??30;const focus=Math.min(1,Math.max(0,options.focus??0));const codes=new Array(width).fill(0);const tones=new Array(width).fill(0);const light=(x,y,tone)=>{const cell=Math.floor(x/2);if(cell<0||cell>=width||y<0||y>3)return;codes[cell]=(codes[cell]??0)|(BITS[y]?.[x%2]??0);tones[cell]=Math.max(tones[cell]??0,tone)};const cx=width-1;const phase=(frame%period+period)%period/period;if(focus>=1||phase>=CONVERGE){light(cx,1,1);light(cx,2,1)}else{const spread=(1-focus*0.7)*(1-phase/CONVERGE);for(let i=0;i<CANDIDATES;i++){const x=Math.round(cx+(seeded(i)*2-1)*width*spread);const y=Math.round(1.5+(seeded(i+50)*4-2)*spread);light(x,y,0.2+0.6*(1-spread))}}return codes.map((code,i)=>({char:String.fromCharCode(10240+code),tone:tones[i]??0}))}function narrowingText(frame,options){return narrowingFrame(frame,options).map((cell)=>cell.char).join("")}function focusForStage(stage){switch(stage){case"searching":return 0.2;case"searching_related":return 0.35;case"reading":return 0.45;case"ranking":return 0.6;case"verifying":return 0.75;case"answering":case"generating":case"explaining":return 0.85;case"completed":return 1;default:return 0}}var DEFAULT_INTERVAL_MS=500;var FRAMES_PER_CYCLE=6;async function beginAnimatedProgress(hook,emit,initialMessage,animation){let base=0;let framesSinceUpdate=0;let frame=0;let message=initialMessage;let stage;let ended=false;let timer;const decorate=()=>`${narrowingText(frame,{period:FRAMES_PER_CYCLE,focus:focusForStage(stage)})} ${message}`;const onUpdate=(update)=>{if(ended)return;base=update.progress;framesSinceUpdate=0;message=update.message;stage=update.stage;emit(base,animation?decorate():message)};const live=hook?await hook.begin(onUpdate):undefined;if(!animation&&!live)return;if(animation){emit(base,decorate());timer=setInterval(()=>{framesSinceUpdate+=1;frame+=1;emit(base+framesSinceUpdate/(framesSinceUpdate+1),decorate())},animation.intervalMs??DEFAULT_INTERVAL_MS);timer.unref?.()}return{headers:live?.headers??{},rejected:(code)=>live?.rejected(code),end:()=>{if(ended)return;ended=true;if(timer)clearInterval(timer);live?.end()}}}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(`
111
- `)}
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(`
112
+ ${EXTERNAL_CONTENT_POSTURE}`:GUIDE}function buildMcpInstructions(options={}){return buildMcpQuickStart(options)}import{McpServer}from"@modelcontextprotocol/sdk/server/mcp.js";var BITS=[[1,8],[2,16],[4,32],[64,128]];var CANDIDATES=14;var CONVERGE=0.75;function seeded(n){const s=Math.sin(n*127.1)*43758.5453;return s-Math.floor(s)}function narrowingFrame(frame,options={}){const width=options.width??6;const period=options.period??30;const focus=Math.min(1,Math.max(0,options.focus??0));const codes=new Array(width).fill(0);const tones=new Array(width).fill(0);const light=(x,y,tone)=>{const cell=Math.floor(x/2);if(cell<0||cell>=width||y<0||y>3)return;codes[cell]=(codes[cell]??0)|(BITS[y]?.[x%2]??0);tones[cell]=Math.max(tones[cell]??0,tone)};const cx=width-1;const phase=(frame%period+period)%period/period;if(focus>=1||phase>=CONVERGE){light(cx,1,1);light(cx,2,1)}else{const spread=(1-focus*0.7)*(1-phase/CONVERGE);for(let i=0;i<CANDIDATES;i++){const x=Math.round(cx+(seeded(i)*2-1)*width*spread);const y=Math.round(1.5+(seeded(i+50)*4-2)*spread);light(x,y,0.2+0.6*(1-spread))}}return codes.map((code,i)=>({char:String.fromCharCode(10240+code),tone:tones[i]??0}))}function narrowingText(frame,options){return narrowingFrame(frame,options).map((cell)=>cell.char).join("")}function focusForStage(stage){switch(stage){case"searching":return 0.2;case"searching_related":return 0.35;case"reading":return 0.45;case"ranking":return 0.6;case"verifying":return 0.75;case"answering":case"generating":case"explaining":return 0.85;case"completed":return 1;default:return 0}}var DEFAULT_INTERVAL_MS=500;var OPENING_STAGE="started";var FRAMES_PER_CYCLE=6;async function beginAnimatedProgress(hook,emit,initialMessage,animation){let base=0;let framesSinceUpdate=0;let frame=0;let message=initialMessage;let stage;let ended=false;let timer;const decorate=()=>`${narrowingText(frame,{period:FRAMES_PER_CYCLE,focus:focusForStage(stage)})} ${message}`;const onUpdate=(update)=>{if(ended)return;if(update.stage===OPENING_STAGE)return;base=update.progress;framesSinceUpdate=0;message=update.message;stage=update.stage;emit(base,animation?decorate():message)};const live=hook?await hook.begin(onUpdate):undefined;if(!animation&&!live)return;if(animation){emit(base,decorate());timer=setInterval(()=>{framesSinceUpdate+=1;frame+=1;emit(base+framesSinceUpdate/(framesSinceUpdate+1),decorate())},animation.intervalMs??DEFAULT_INTERVAL_MS);timer.unref?.()}return{headers:live?.headers??{},rejected:(code)=>live?.rejected(code),end:()=>{if(ended)return;ended=true;if(timer)clearInterval(timer);live?.end()}}}import{z}from"zod";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={...resolution.releaseCorrespondence!==undefined?{releaseCorrespondence:resolution.releaseCorrespondence}:{},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(`
113
113
  `);if(firstEnd<0)return patch;const secondStart=firstEnd+1;const secondEnd=patch.indexOf(`
114
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}
115
115
  ${to}
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(`
116
+ ${patch.slice(secondEnd+1)}`}function lower(value){return value.toLowerCase()}function buildCodeDiffCorrespondenceNotes(envelope){return["from","to"].flatMap((side)=>{const resolution=envelope[side];const note=buildSourceCorrespondenceNote({...envelope.target.kind==="package"?{registry:envelope.target.registry,packageName:envelope.target.name}:{},version:resolution.resolvedVersion,repoUrl:envelope.target.repoUrl,gitRef:resolution.ref,commitSha:resolution.commitSha,releaseCorrespondence:resolution.releaseCorrespondence},{sourceRole:side});return note?[note]:[]})}var MAX_FILE_ROWS=20;var MAX_PATCH_PREVIEW_BYTES=320;var UTF8_ENCODER=new TextEncoder;function formatCodeDiffMcpText(envelope){const lines=[`Code diff: ${formatTarget(envelope)}`,`Requested endpoints: ${safe(envelope.from.requested)} -> ${safe(envelope.to.requested)}`,`Resolved endpoints: ${formatResolution(envelope.from)} -> ${formatResolution(envelope.to)}`,`Scope: ${formatScope(envelope)}`,`Summary: ${formatSummary(envelope)}`,`Content: ${safe(envelope.contentCoverage)}`];for(const note of buildCodeDiffCorrespondenceNotes(envelope))lines.push(...wrapTerminalProse(note));appendWarnings(lines,envelope);const displayTruncatedPreviews=appendFiles(lines,envelope);lines.push(nextAction(envelope,displayTruncatedPreviews));return`${lines.join(`
117
+ `)}
118
+ `}function appendWarnings(lines,envelope){if(envelope.scope.status==="unknown"){lines.push("Warning: legacy unknown scope metadata; treat this diff as repository-wide, so unrelated paths may be included.")}if(!envelope.summary.inventoryComplete){lines.push("Warning: the authoritative file inventory is incomplete.")}if(envelope.summary.unprojectableFiles>0){lines.push(`Warning: ${envelope.summary.unprojectableFiles} matching path(s) could not be projected safely.`)}if(envelope.hasMoreFiles){lines.push(`Warning: more matching files exist than the ${envelope.files.length} returned.`)}if(envelope.contentCoverage==="partial"){lines.push("Warning: requested content is partial.")}else if(envelope.contentCoverage==="failed"){const failure=envelope.contentFailure;const detail=failure?` (${[failure.code,failure.stage,failure.limitKind].filter((value)=>Boolean(value)).map(safe).join(", ")})`:"";lines.push(`Warning: requested content failed after inventory completed${detail}.`)}const byteEscaped=envelope.files.filter((file)=>file.pathEncoding==="byte_escaped").length;if(byteEscaped>0){lines.push(`Warning: ${byteEscaped} path(s) are display-only byte escapes and cannot be reused as exact identities.`)}const filtered=envelope.files.filter((file)=>("contentSafety"in file)&&file.contentSafety.filtered).length;if(filtered>0){lines.push(`Warning: ${filtered} patch(es) were modified for content safety.`)}if(envelope.view==="patch"&&patchIsNotAuthoritative(envelope)){lines.push("Warning: patch content is not presented as authoritative or safely applicable; use inventory/stat evidence or JSON details.")}}function appendFiles(lines,envelope){if(envelope.files.length===0){lines.push(envelope.summary.filesChanged===0?"No changes between the requested endpoints.":"No file rows were returned; inspect the structured JSON evidence.");return 0}lines.push("Files:");const shown=envelope.files.slice(0,MAX_FILE_ROWS);let displayTruncatedPreviews=0;for(const file of shown){if(appendFile(lines,file,envelope.view))displayTruncatedPreviews+=1}if(envelope.files.length>shown.length){lines.push(` ... ${envelope.files.length-shown.length} additional file(s) omitted from compact text; use format=json for the complete list.`)}return displayTruncatedPreviews}function appendFile(lines,file,view){const path=safe(file.path);if(view==="name-only"){lines.push(` ${path}`);return false}const status="status"in file?safe(file.status):"unknown";let detail=`status=${status}`;if(view==="stat"||view==="patch"){const stat=file;detail+=`, content=${safe(stat.contentStatus)}`;if(stat.additions!==undefined||stat.deletions!==undefined){detail+=`, +${stat.additions??0}/-${stat.deletions??0}`}}lines.push(` ${path} [${detail}]`);if(view==="patch"){const patch=file;if(canShowPatch(patch)){const previewLines=formatPatchPreview(patch.patch??"",MAX_PATCH_PREVIEW_BYTES);if(previewLines.lines.length>0){const label=previewLines.truncated?"patch preview (truncated)":"patch preview";lines.push(` ${label}: ${previewLines.lines[0]}`);lines.push(...previewLines.lines.slice(1).map((line)=>` ${line}`))}return previewLines.truncated}else if(patch.contentOmissionReason){lines.push(` patch omitted: ${safe(patch.contentOmissionReason)}`)}}return false}function formatTarget(envelope){if(envelope.target.kind==="package"){return`${safe(envelope.target.registry)}:${safe(envelope.target.name)}`}return safe(envelope.target.repoUrl)}function formatResolution(resolution){const resolved=resolution.resolvedVersion?`, version ${safe(resolution.resolvedVersion)}`:"";return`${safe(resolution.ref)} (${safe(resolution.commitSha)}${resolved})`}function formatScope(envelope){const scope=envelope.scope;const roots=scope.fromSubpath||scope.toSubpath?`, roots ${safe(scope.fromSubpath||"?")} -> ${safe(scope.toSubpath||"?")}`:"";const glob=scope.pathGlob?`, glob ${safe(scope.pathGlob)}`:"";return`${safe(scope.status)}${roots}${glob}`}function formatSummary(envelope){const summary=envelope.summary;return`${summary.filesChanged} changed, ${summary.added} added, ${summary.deleted} deleted, ${summary.modified} modified`}function nextAction(envelope,displayTruncatedPreviews){const target=formatTarget(envelope);const from=safe(envelope.from.requested);const to=safe(envelope.to.requested);const needsScopeRecovery=envelope.scope.status==="unknown"||!envelope.summary.inventoryComplete||envelope.summary.unprojectableFiles>0||envelope.hasMoreFiles;const needsContentRecovery=envelope.contentCoverage==="partial"||envelope.contentCoverage==="failed"||envelope.view==="patch"&&patchIsNotAuthoritative(envelope);if(needsScopeRecovery||needsContentRecovery||displayTruncatedPreviews>0){const recovery=[];if(needsScopeRecovery){recovery.push("narrow `path_glob` or set `max_files` to a larger bound")}if(needsContentRecovery&&displayTruncatedPreviews===0){recovery.push('use view "stat" or format "json" for structured evidence')}if(displayTruncatedPreviews>0){recovery.push(`use format "json" for the full returned patch content (${displayTruncatedPreviews} preview${displayTruncatedPreviews===1?"":"s"} truncated); still subject to max_patch_bytes/backend coverage, and JSON cannot recover backend-omitted content`)}return`Next: call code_diff again with target ${target}, from "${from}", to "${to}"; ${recovery.join("; ")}. Raw diffs do not prove compatibility or upgrade safety.`}const nextView=envelope.view==="name-only"||envelope.view==="name-status"?"stat":envelope.view==="stat"?"patch":"stat";return`Next: call code_diff again with target ${target}, from "${from}", to "${to}", and view "${nextView}" as needed; raw diffs do not prove compatibility or upgrade safety.`}function patchIsNotAuthoritative(envelope){if(!envelope.summary.inventoryComplete||envelope.summary.unprojectableFiles>0||envelope.hasMoreFiles||envelope.contentCoverage!=="complete"){return true}return envelope.files.some((file)=>{if(!("contentSafety"in file))return true;return file.pathEncoding==="byte_escaped"||file.contentSafety.filtered||file.patch===undefined})}function canShowPatch(file){return file.pathEncoding==="utf8"&&file.contentSafety.filtered===false&&file.contentStatus==="patch"&&file.patch!==undefined}function safe(value){return sanitizeTerminalText(value).replace(/\s+/g," ").trim()}function formatPatchPreview(value,maxBytes){const sanitizedLines=value.split(/\r?\n/).map((line)=>sanitizeTerminalText(line));while(sanitizedLines.at(-1)==="")sanitizedLines.pop();const retained=[];let byteLength=0;for(const line of sanitizedLines){const separatorBytes=retained.length>0?1:0;const lineBytes=UTF8_ENCODER.encode(line).byteLength;const available=maxBytes-byteLength-separatorBytes;if(available<lineBytes){const truncated=truncateUtf8(line,Math.max(available,0));if(truncated)retained.push(truncated);return{lines:retained,truncated:true}}retained.push(line);byteLength+=separatorBytes+lineBytes}return{lines:retained,truncated:false}}function truncateUtf8(value,maxBytes){let result="";let byteLength=0;for(const character of value){const characterBytes=UTF8_ENCODER.encode(character).byteLength;if(byteLength+characterBytes>maxBytes)break;result+=character;byteLength+=characterBytes}return result}function parseCodeNavigationTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidArgumentError("Target spec cannot be empty.")}if(isRepositoryTargetSpec(trimmed)){return parseRepositoryTargetSpec(trimmed)}let parsed;try{parsed=parsePackageSpec(trimmed)}catch(error){if(error instanceof InvalidPackageSpecError||error instanceof UnsupportedRegistryError){throw buildInvalidTargetSpecError(trimmed,error.message)}throw error}return{registry:toCodeNavigationRegistry(parsed.registry),packageName:parsed.name,version:parsed.version}}var VIEW_TO_MODE={patch:"patches",stat:"stats","name-only":"inventory","name-status":"inventory"};var MAX_PATH_GLOB_BYTES=1024;var CODE_DIFF_MAX_FILES_MIN=1;var CODE_DIFF_MAX_FILES_MAX=300;var CODE_DIFF_MAX_PATCH_BYTES_MIN=1024;var CODE_DIFF_MAX_PATCH_BYTES_MAX=2097152;function buildCodeDiffMcpParams(input){const target=buildMcpTarget(input.target);const from=normaliseMcpEndpoint(input.from,"from");const to=normaliseMcpEndpoint(input.to,"to");return buildCodeDiffParamsFromParts(target,from,to,input)}function buildCodeDiffParamsFromParts(target,from,to,input){const view=normaliseView(input.view);const pathGlob=normalisePathGlob(input.pathGlob);const maxFiles=normaliseIntegerOption(input.maxFiles,"Maximum files",CODE_DIFF_MAX_FILES_MIN,CODE_DIFF_MAX_FILES_MAX);const maxPatchBytes=normaliseIntegerOption(input.maxPatchBytes,"Maximum patch bytes",CODE_DIFF_MAX_PATCH_BYTES_MIN,CODE_DIFF_MAX_PATCH_BYTES_MAX);if(maxPatchBytes!==undefined&&view!=="patch"){throw invalid("The maximum patch byte limit is valid only when the view is patch.")}const options=buildOptions({maxFiles,maxPatchBytes,pathGlob});const params={target,from,to,mode:VIEW_TO_MODE[view]};if(options!==undefined)params.options=options;return{params,view}}function buildMcpTarget(raw){return buildTargetFromRaw(raw,"mcpTarget")}function buildTargetFromRaw(raw,source){const parsed=parseTarget(raw);if((source==="target"||source==="mcpTarget")&&parsed.version){throw invalid(source==="target"?"Package targets must not include a version; put both versions in `range`.":"Package targets must not include a version; put both versions in the comparison endpoints.")}if(parsed.gitRef!==undefined){throw invalid(source==="target"||source==="repoUrl"?"Repository targets must not include a ref; put both refs in `range`.":"Repository targets must not include a ref; put both refs in the comparison endpoints.")}const hasPackageKeys=Object.hasOwn(parsed,"registry")||Object.hasOwn(parsed,"packageName");const hasRepoKey=Object.hasOwn(parsed,"repoUrl");if(source==="repoUrl"&&hasPackageKeys){throw invalid("Repository target must identify a repository, not a package.")}if(hasPackageKeys&&hasRepoKey){throw invalid("Diff target cannot combine package and repository keys.")}if(hasPackageKeys){if(!Object.hasOwn(parsed,"registry")||!Object.hasOwn(parsed,"packageName")||parsed.registry===undefined||parsed.packageName===undefined){throw invalid("Diff package target must include a registry and name.")}return{registry:parsed.registry,packageName:parsed.packageName}}if(hasRepoKey&&parsed.repoUrl!==undefined){return{repoUrl:parsed.repoUrl}}throw invalid("Diff target must be a package or repository target.")}function parseTarget(raw){try{return parseCodeNavigationTargetSpec(raw)}catch(error){if(error instanceof LegacyRepositoryRefError){throw invalid(error.message)}throw invalid(`Invalid Diff target. Expected an unversioned package target \`<registry>:<name>\` (for example \`npm:express\`; supported registries: ${KNOWN_REGISTRIES.join(", ")}) or an unversioned repository target (for example \`github:expressjs/express\`, \`codeberg:owner/repo\`, \`gitlab:group/subgroup/project\`, or \`launchpad:~owner/+git/repo\` (\`lp:PROJECT\` also accepted)).`)}}function normaliseMcpEndpoint(raw,name){if(typeof raw!=="string"||!raw.trim()){throw invalid(`Diff ${name} endpoint must not be empty.`)}return raw.trim()}function normaliseView(raw){if(raw===undefined)return"patch";if(typeof raw==="string"&&Object.hasOwn(VIEW_TO_MODE,raw)){return raw}throw invalid("Diff view must be patch, stat, name-only, or name-status.")}function normalisePathGlob(raw){if(raw===undefined)return;if(typeof raw!=="string"){throw invalid("Path glob must be a string when supplied.")}const pathGlob=raw;if(pathGlob.length===0){throw invalid("Path glob must not be empty when supplied.")}if(hasInvalidUtf16(pathGlob)){throw invalid("Path glob must be valid UTF-8.")}if(new TextEncoder().encode(pathGlob).byteLength>MAX_PATH_GLOB_BYTES){throw invalid(`Path glob must be at most ${MAX_PATH_GLOB_BYTES} UTF-8 bytes.`)}validatePathGlobGrammar(pathGlob);return pathGlob}function validatePathGlobGrammar(pathGlob){if(pathGlob===":"||pathGlob.startsWith(":(")||pathGlob.startsWith(":/")||pathGlob.startsWith(":!")||pathGlob.startsWith(":^")){throw invalid("Path glob does not support Git pathspec magic; pass one bounded glob.")}const components=[];let component=[];const characters=Array.from(pathGlob);for(let index=0;index<characters.length;index+=1){const character=characters[index];if(character===undefined)break;if(character==="/"){addGlobComponent(components,component);component=[];continue}if(character==="\\"){const escaped=characters[index+1];if(escaped===undefined||escaped==="/"){throw invalid("Path glob backslashes must escape one following non-slash character.")}component.push({char:escaped,escaped:true});index+=1;continue}if(character==="["||character==="]"||character==="{"||character==="}"||character==="!"){throw invalid("Path glob does not support unescaped brackets, braces, or `!`.")}component.push({char:character,escaped:false})}addGlobComponent(components,component);for(const tokens of components){const isGlobstar=tokens.length===2&&tokens.every(({char,escaped})=>char==="*"&&!escaped);if(isGlobstar)continue;let previous;for(const token of tokens){if(previous?.char==="*"&&!previous.escaped&&token.char==="*"&&!token.escaped){throw invalid("Path glob allows adjacent stars only as an exact `**` component.")}previous=token}}}function addGlobComponent(components,component){if(component.length===0){throw invalid("Path glob must use non-empty repository-relative components.")}const literal=component.map(({char})=>char).join("");if(literal==="."||literal===".."){throw invalid("Path glob must not contain `.` or `..` components.")}components.push(component)}function hasInvalidUtf16(value){for(let index=0;index<value.length;index+=1){const code=value.charCodeAt(index);if(code>=55296&&code<=56319){const next=value.charCodeAt(index+1);if(next>=56320&&next<=57343){index+=1;continue}return true}if(code>=56320&&code<=57343)return true}return false}function normaliseIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(!Number.isInteger(value)||value<minimum||value>maximum){throw invalid(`${name} must be an integer from ${minimum} through ${maximum}.`)}return value}function buildOptions(input){if(input.maxFiles===undefined&&input.maxPatchBytes===undefined&&input.pathGlob===undefined){return}const options={};if(input.maxFiles!==undefined)options.maxFiles=input.maxFiles;if(input.maxPatchBytes!==undefined){options.maxPatchBytes=input.maxPatchBytes}if(input.pathGlob!==undefined)options.pathGlob=input.pathGlob;return options}function invalid(message){return new InvalidPackageSpecError(message)}var schema={target:z.string().describe("One unversioned compact target string such as `npm:express`, `github:expressjs/express`, or `launchpad:~owner/+git/repo` (`lp:PROJECT` also accepted). Do not embed a version or ref."),from:z.string().describe("Required starting package version or public repository ref."),to:z.string().describe("Required ending package version or public repository ref."),view:z.enum(["name-status","name-only","stat","patch"]).optional().default("name-status").describe("Projection: `name-status` (default, bounded inventory), `name-only`, `stat`, or `patch`. `max_patch_bytes` is valid only for `patch`."),path_glob:z.string().optional().describe("Optional single non-empty repository-relative glob. Supports literals, `*`, `?`, whole-component `**`, and backslash escapes (for example `lib/**/*.js`); no braces, character classes, `!`, or Git pathspec magic."),max_files:z.number().int().min(1).max(300).optional().describe("Optional relevance-ranked returned-file bound from 1 through 300."),max_patch_bytes:z.number().int().min(1024).max(2097152).optional().describe("Optional aggregate patch-byte bound from 1024 through 2097152; patch view only."),format:z.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, fields are absent from text, or the full returned patch is required. Text patch previews are bounded at 320 UTF-8 bytes; JSON remains subject to backend limits and content coverage.")};var DESCRIPTION='Compare source across exact package versions or public repository refs. Pass an unversioned canonical `target`, with endpoints in `from` and `to`. Package targets 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";case"repository_not_found":return"repository was not found";case"package_not_found":return"package was not found";case"package_source_not_found":return"package source was not found";case"repository_ref_not_found":return"repository ref was not found";case"ref_not_found":return"repository ref was not found";case"package_source_ref_not_found":return"package source ref was not found";case"package_version_not_found":return"package source ref could not be resolved";case"package_version_unresolved":return"package version could not be resolved";case"repository_ref_ambiguous":return"repository ref is ambiguous";case"repository_legally_blocked":return"repository access is legally blocked";case"repository_resolution_error":return"repository resolution failed";case"repository_unavailable":return"repository is unavailable";case"package_source_unsupported":return"package source is unsupported";case"package_security_removed":return"package source was removed for security reasons";case"package_scope_unavailable":return"package source scope is unavailable";case"package_release_unusable":return"package release is unusable";case"no_site_pages":return"no searchable documentation pages are available";case"site_ambiguous":return"documentation site is ambiguous";case"site_not_indexed":return"documentation site is not indexed";case"site_no_docs":return"documentation site has no searchable pages";case"site_redirected":return"documentation site has moved";case"site_failed":return"documentation site preparation failed";case"site_v6_required":return"documentation site requires a publication format update";case"documentation_site_not_admitted":return"documentation site has not been admitted";case"documentation_source_resolution_required":return"documentation source must be resolved";case"documentation_site_no_docs":return"documentation site has no searchable pages";case"documentation_site_identity_blocked":return"documentation site identity needs resolution";case"documentation_site_failed":return"documentation site preparation failed";case"documentation_discovery":return"documentation sources are being discovered";case"documentation_unavailable":return"documentation is unavailable";case"starting_url_pending":return"requested documentation URL is being prepared";case"starting_url_missed_at_cap":return"requested documentation URL was not reached before the crawl limit";case"starting_url_absent_from_current_corpus":return"requested documentation URL is absent from the current corpus";default:return reason}}var MAX_TARGETS=20;var MAX_PATTERN_BYTES=200;var MAX_PATH_SELECTORS=1000;class InvalidGrepRequestError extends InvalidArgumentError{field;constructor(field,message){super(message);this.field=field;this.name="InvalidGrepRequestError"}}function buildGrepParams(input){if(!isRecord(input)){throw invalid2("request","A grep request is required.")}if(!Array.isArray(input.targets)||input.targets.length===0){throw invalid2("targets","`targets` must contain at least one target.")}if(input.targets.length>MAX_TARGETS){throw invalid2("targets",`Targets may contain at most ${MAX_TARGETS} entries.`)}if(typeof input.pattern!=="string"){throw invalid2("pattern","`pattern` must be a string.")}validateUnicode(input.pattern,"pattern","`pattern` must contain valid Unicode.");if(input.pattern.includes("\x00")){throw invalid2("pattern","`pattern` cannot contain NUL.")}const patternBytes=Buffer.byteLength(input.pattern,"utf8");if(patternBytes<1||patternBytes>MAX_PATTERN_BYTES){throw invalid2("pattern",`Pattern must be 1 to ${MAX_PATTERN_BYTES} UTF-8 bytes.`)}if(typeof input.includeDetailedFields!=="boolean"){throw invalid2("includeDetailedFields","`includeDetailedFields` must be a boolean.")}const patternType=normalizePatternType(input.patternType);const ignoreCase=normalizeBoolean(input.ignoreCase,"ignoreCase");const contextLinesBefore=normalizeGrepContextLines(input.contextLinesBefore,"contextLinesBefore");const contextLinesAfter=normalizeGrepContextLines(input.contextLinesAfter,"contextLinesAfter");const maxMatches=normalizeInteger(input.maxMatches,"maxMatches",1,1000);const waitTimeoutMs=normalizeInteger(input.waitTimeoutMs,"waitTimeoutMs",0,300000);const cursor=normalizeCursor(input.cursor);const targets=input.targets.map((targetInput,index)=>{const field=`targets[${index}]`;if(!isRecord(targetInput)||typeof targetInput.target!=="string"){throw invalid2(`${field}.target`,"Each target must include a string `target`.")}const target=targetInput.target;validateUnicode(target,`${field}.target`,"Target must contain valid Unicode.");if(target.trim().length===0){throw invalid2(`${field}.target`,"Target cannot be blank.")}const corpus=normalizeCorpus(targetInput.corpus,`${field}.corpus`);const pathSelectors=normalizePathSelectors(targetInput.pathSelectors,`${field}.pathSelectors`);if(isGrepSiteTarget(target)){if(targetInput.corpus!==undefined){throw invalid2(`${field}.corpus`,"Corpus cannot be used with a site target.")}if(pathSelectors.length>0){throw invalid2(`${field}.pathSelectors`,"Path selectors cannot be used with a site target.")}return{target}}return{target,corpus:corpus??"ALL",allowUnscoped:true,...pathSelectors.length>0?{pathSelectors}:{}}});return{targets,pattern:input.pattern,patternType,caseSensitive:!(ignoreCase??false),contextLinesBefore:contextLinesBefore??0,contextLinesAfter:contextLinesAfter??0,...maxMatches!==undefined?{maxMatches}:{},...cursor!==undefined?{cursor}:{},waitTimeoutMs:waitTimeoutMs??(cursor?0:DEFAULT_WAIT_TIMEOUT_MS),includeDetailedFields:input.includeDetailedFields}}function normalizePatternType(value){if(value===undefined||value==="regex")return"REGEX";if(value==="literal")return"LITERAL";throw invalid2("patternType","`patternType` must be `literal` or `regex`.")}function normalizeCorpus(value,field){if(value===undefined)return;if(typeof value!=="string"){throw invalid2(field,"Corpus must be `source`, `documentation`, or `all`.")}const normalized=value.toUpperCase();if(normalized==="SOURCE"||normalized==="DOCUMENTATION"||normalized==="ALL"){return normalized}throw invalid2(field,"Corpus must be `source`, `documentation`, or `all`.")}function normalizePathSelectors(value,field){if(value===undefined)return[];if(!Array.isArray(value)){throw invalid2(field,"Path selectors must be an array.")}if(value.length===0)return[];if(value.length>MAX_PATH_SELECTORS){throw invalid2(field,`A target may contain at most ${MAX_PATH_SELECTORS} path selectors.`)}return value.map((selector,index)=>{const itemField=`${field}[${index}]`;if(!isRecord(selector)){throw invalid2(itemField,"A path selector must be an object.")}const kind=normalizeSelectorKind(selector.kind,`${itemField}.kind`);if(typeof selector.value!=="string"){throw invalid2(`${itemField}.value`,"Selector value must be a string.")}const selectorValue=selector.value;validateUnicode(selectorValue,`${itemField}.value`,"Selector values must contain valid Unicode.");if(selectorValue.trim().length===0){throw invalid2(`${itemField}.value`,"Selector values cannot be blank.")}if(selectorValue.includes("\x00")){throw invalid2(`${itemField}.value`,"Selector values cannot contain NUL.")}return{kind,value:selectorValue}})}function normalizeSelectorKind(value,field){if(typeof value!=="string"){throw invalid2(field,"Selector kind must be `exact`, `prefix`, or `glob`.")}const normalized=value.toUpperCase();if(normalized==="EXACT"||normalized==="PREFIX"||normalized==="GLOB"){return normalized}throw invalid2(field,"Selector kind must be `exact`, `prefix`, or `glob`.")}function normalizeBoolean(value,field){if(value===undefined)return;if(typeof value!=="boolean"){throw invalid2(field,`${field} must be a boolean.`)}return value}function normalizeInteger(value,field,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isSafeInteger(value)||value<minimum||value>maximum){throw invalid2(field,`${field} must be a safe integer from ${minimum} to ${maximum}.`)}return value}function normalizeGrepContextLines(value,field){return normalizeInteger(value,field,0,10)}function normalizeCursor(value){if(value===undefined)return;if(typeof value!=="string"){throw invalid2("cursor","`cursor` must be a string.")}return value.trim().length===0?undefined:value}function isGrepSiteTarget(target){return target.trim().toLowerCase().startsWith("site:")}function validateUnicode(value,field,message){if(hasLoneSurrogate(value))throw invalid2(field,message)}function hasLoneSurrogate(value){for(let index=0;index<value.length;index+=1){const codeUnit=value.charCodeAt(index);if(codeUnit>=55296&&codeUnit<=56319){const nextCodeUnit=value.charCodeAt(index+1);if(!(nextCodeUnit>=56320&&nextCodeUnit<=57343))return true;index+=1}else if(codeUnit>=56320&&codeUnit<=57343){return true}}return false}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function invalid2(field,message){return new InvalidGrepRequestError(field,message)}function mapGrepError(error){const sessionError=mapSessionIdError(error);if(sessionError)return sessionError;const terms=mapTermsAcceptanceError(error);if(terms)return terms;if(error instanceof ClientUpdateRequiredError)return buildUpdateRequiredError(error.reason,error.currentVersion);if(error instanceof AuthenticationError2||error instanceof AuthRequiredError)return{code:"AUTH_REQUIRED",message:error.message,retryable:false,details:{authSource:error instanceof AuthenticationError2?error.source:"local"}};if(error instanceof InvalidGrepRequestError)return{code:"INVALID_ARGUMENT",message:error.message,retryable:false};if(error instanceof GrepAccessError2)return{code:"ACCESS_DENIED",message:error.message,retryable:false};if(error instanceof GrepNetworkError2)return{code:"NETWORK",message:error.message,retryable:true};if(error instanceof MalformedGrepResponseError2)return{code:"PROTOCOL_ERROR",message:error.message,retryable:false};if(error instanceof GrepBackendError2){const code=error.graphqlCode==="TIMEOUT"?"TIMEOUT":error.status===429?"RATE_LIMITED":"BACKEND_ERROR";return{code,message:error.message,retryable:error.retryable??(code==="TIMEOUT"||code==="RATE_LIMITED"||error.status!==undefined&&error.status>=500),details:{...error.status!==undefined?{status:error.status}:{},...error.graphqlCode?{graphqlCode:error.graphqlCode}:{}}}}if(error instanceof GrepGraphQLError2){const ext=error.extensions;const recovery=parseVersionRefRecovery(ext);if(recovery)return mapVersionRefRecovery(error.message,recovery);const graphqlCode=typeof ext.code==="string"?ext.code:undefined;const code=graphqlCode==="GREP_TARGET_PREPARATION_REQUIRED"?preparationErrorCode(ext.target_issues,ext.retryable):graphqlCode==="GREP_CURSOR_INVALID"||graphqlCode==="VALIDATION_ERROR"||graphqlCode==="INVALID_ARGUMENT"?"INVALID_ARGUMENT":graphqlCode==="GREP_BACKEND_PROTOCOL_ERROR"?"PROTOCOL_ERROR":graphqlCode==="TIMEOUT"?"TIMEOUT":graphqlCode==="RATE_LIMITED"?"RATE_LIMITED":"BACKEND_ERROR";const details={graphqlCode};if(Array.isArray(ext.target_issues)){details.targetIssues=ext.target_issues.slice(0,20).filter(isRecord2).map((issue)=>Object.fromEntries(Object.entries(issue).filter(([key])=>PUBLIC_ISSUE_KEYS.has(key))));const hints=details.targetIssues.flatMap((issue,index)=>{const target=typeof issue.target==="string"?issue.target:typeof issue.input_index==="number"?`Input ${issue.input_index}`:undefined;const translatedReason=typeof issue.reason==="string"?grepPreparationReason(issue.reason):undefined;const reason=translatedReason&&translatedReason!==issue.reason?translatedReason:code==="INDEXING"?"target is being prepared":"target is unavailable";const message=typeof issue.message==="string"?typeof issue.reason==="string"&&issue.message.endsWith(`Reason: ${issue.reason}.`)?reason:issue.message:undefined;const diagnostic=code==="INDEXING"?reason:graphqlCode==="GREP_TARGET_PREPARATION_REQUIRED"&&index===0?undefined:message!==undefined?typeof issue.message==="string"&&error.message.includes(issue.message)?undefined:message:reason;const path=typeof issue.file_path==="string"?`path ${issue.file_path}`:undefined;const text=[diagnostic,path].filter(Boolean).join("; ");return text?[`${target?`${target}: `:""}${text}`]:[]});if(hints.length)details.hint=hints.join(`
119
+ `)}if(graphqlCode==="GREP_CURSOR_INVALID")details.hint="Restart explicitly without the cursor, using the same targets and controls.";return{code,message:error.message,retryable:typeof ext.retryable==="boolean"?ext.retryable:code==="INDEXING"||code==="TIMEOUT"||code==="RATE_LIMITED",details}}return{code:"UNKNOWN",message:error instanceof Error?error.message:"Unknown error",retryable:false}}function preparationErrorCode(issues,retryable){if(!Array.isArray(issues)||issues.length===0)return"UNRESOLVABLE";for(const issue of issues){const code=isRecord2(issue)?preparationIssueCode(issue):"UNRESOLVABLE";if(code!=="INDEXING")return code}return retryable===false?"UNRESOLVABLE":"INDEXING"}function preparationIssueCode(issue){switch(issue.reason){case"repository_indexing":case"documentation_publishing":case"documentation_discovery":case"site_v6_required":case"starting_url_pending":return issue.retryable===false?"UNRESOLVABLE":"INDEXING";case"repository_not_found":case"package_not_found":case"package_source_not_found":return"NOT_FOUND";case"repository_ref_not_found":case"ref_not_found":return"REF_NOT_FOUND";case"package_version_not_found":case"package_version_unresolved":case"package_source_ref_not_found":return"VERSION_NOT_FOUND";case"repository_ref_ambiguous":case"site_ambiguous":return"INVALID_ARGUMENT";case"repository_resolution_error":case"repository_unavailable":return"BACKEND_ERROR";case"no_grep_scopes":case"no_site_pages":case"repository_legally_blocked":case"package_source_unsupported":case"package_security_removed":case"package_scope_unavailable":case"package_release_unusable":case"site_not_indexed":case"site_no_docs":case"site_redirected":case"site_failed":case"documentation_site_not_admitted":case"documentation_source_resolution_required":case"documentation_site_no_docs":case"documentation_site_identity_blocked":case"documentation_site_failed":case"documentation_unavailable":case"starting_url_missed_at_cap":case"starting_url_absent_from_current_corpus":return"UNRESOLVABLE";default:return typeof issue.reason==="string"&&issue.reason.trim()&&issue.retryable===true&&typeof issue.progress_ref==="string"&&issue.progress_ref.trim()?"INDEXING":"UNRESOLVABLE"}}var PUBLIC_ISSUE_KEYS=new Set(["input_index","target","reason","retryable","progress_ref","file_path","repo_url","git_ref","requested_ref","available_refs","available_versions","message","suggested_refs","published_versions","published_versions_truncated","suggested_site_targets","registry","package"]);function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function summarizeGrepPathWarnings(warnings){return[...new Set(warnings.map((warning)=>{const suggestion=warning.suggestions.find((entry)=>entry.target===warning.target);return`Path is prefixed with package path ${JSON.stringify(warning.repositorySubpath)}.${suggestion?` Did you mean ${JSON.stringify(suggestion.path)}?`:""}`.replace(/[\u007f-\u009f]/g,(character)=>`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`)}))]}function projectGrepResult(result){const projected=parseGrepResult({...result,indexingEstimates:result.indexingEstimates??[],targetResolutions:result.targetResolutions===undefined?[]:result.targetResolutions});if(result.indexingEstimates===undefined)delete projected.indexingEstimates;if(result.targetResolutions===undefined)delete projected.targetResolutions;return{...projected,pathWarnings:summarizeGrepPathWarnings(projected.pathWarnings)}}function appendSearchGrepFooter(lines,footer,useColors){for(const[label,body]of[["Read:",footer.read],["More results:",footer.more],["Follow-up:",footer.followUp]]){if(!body?.length)continue;lines.push("",useColors?`${colors.bold}${label}${colors.reset}`:label,...body.map((line)=>` ${line}`))}}function footerAction(value,useColors){return dim(value,useColors)}function footerProse(value,width){return wrapTerminalProse(value,Math.max(20,width)-2)}function formatGrepText(result,options={}){const lines=[];const prose=(value)=>{lines.push(...wrap(escapeText(value),options.width??80))};const groups=groupFiles(result.hits);const isPreparing=(reason)=>["repository_indexing","documentation_publishing"].includes(reason);const scopeCoverageGap=result.targets.some(hasPageCoverageGap);const pageCoverageGap=scopeCoverageGap||result.unavailableTargets.length>0||!["COMPLETE","RESUMABLE_LIMIT"].includes(result.traversal);const omissionsOnly=result.unavailableTargets.length>0&&!scopeCoverageGap&&!["FAILED","CURSOR_EXPIRED"].includes(result.traversal);const preparationOnly=omissionsOnly&&result.unavailableTargets.every((target)=>target.retryable&&isPreparing(target.reason));const nothingSearched=(result.targets.length>0||result.unavailableTargets.length>0)&&result.targets.every((scope)=>scope.filesScanned===0&&(scope.traversal==="FAILED"||!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness)));const matchingLines=new Set(result.hits.map((hit)=>JSON.stringify([...fileIdentity(hit),hit.line]))).size;const kinds=new Set(result.hits.map((hit)=>hit.__typename));const noun=kinds.size>1?"files/pages":kinds.has("GrepSiteHit")?`page${groups.length===1?"":"s"}`:`file${groups.length===1?"":"s"}`;prose(result.hits.length?`Found ${result.totalMatches} match${result.totalMatches===1?"":"es"} on ${matchingLines} line${matchingLines===1?"":"s"} in ${groups.length} ${noun}.`:result.nextCursor?preparationOnly?"No matches on this page; some requested content is still being prepared.":pageCoverageGap?"No matches on this page; some requested content could not be searched.":"No matches on this page.":preparationOnly?`No matches available yet; ${nothingSearched?"requested":"some requested"} content is still being prepared.`:nothingSearched?"None of the requested content could be searched.":isExhaustive(result)?"No matches found.":"No matches returned; some requested content could not be searched.");if(options.useColors)lines[0]=`${colors.bold}${lines[0]}${colors.reset}`;if(result.targets.length){lines.push("","Sources:");const matchedScopes=new Set(result.hits.map((hit)=>hit.targetIndex));for(const source of formatSources(result.targets,matchedScopes,isExhaustive(result)))prose(` - ${source}`)}const repositoryHits=new Set(result.hits.filter((hit)=>hit.__typename==="GrepRepositoryHit").map((hit)=>hit.targetIndex));const searchedInputs=new Set(result.targets.filter((scope)=>scope.kind==="REPOSITORY"&&(scope.readiness==="CURRENT"||scope.readiness==="STALE"||repositoryHits.has(scope.targetIndex))).flatMap((scope)=>scope.requestedInputIndices));const correspondence=new Set((result.targetResolutions??[]).flatMap((entry)=>buildSourceCorrespondenceNotes(entry.targetResolution,searchedInputs.has(entry.inputIndex)?"served":"selected")));for(const note of correspondence)prose(note);const pending=result.unavailableTargets.filter((entry)=>entry.retryable&&isPreparing(entry.reason));const attached=new Set;if(pending.length||result.indexingEstimates?.length)lines.push("","Preparing:");for(const entry of result.indexingEstimates??[]){prose(` - ${formatPreparationRow(entry)}`);const inputs=pending.filter((omitted)=>entry.targets.includes(omitted.target)&&entry.kind===(omitted.reason==="repository_indexing"?"REPOSITORY":"DOCUMENTATION"));for(const omitted of inputs)attached.add(omitted);for(const target of new Set(inputs.map((omitted)=>omitted.target))){const targetInputs=inputs.filter((omitted)=>omitted.target===target);const needsAlias=inputs.length>1||entry.targets.length>1||Boolean(entry.repositoryUrl&&entry.commitSha)||targetInputs.some((omitted)=>Boolean(omitted.suggestedSiteTargets?.length));if(needsAlias)prose(` Requested: ${target}`);for(const omitted of targetInputs)for(const suggested of omitted.suggestedSiteTargets??[])prose(` Search hosted documentation instead: ${suggested}`)}if(entry.repositoryUrl&&entry.commitSha){const remaining=entry.targets.filter((target)=>!inputs.some((input)=>input.target===target));if(remaining.length)prose(` Requested: ${remaining.join(", ")}`)}}for(const omitted of pending.filter((entry)=>!attached.has(entry))){prose(` - ${formatProvenanceRow(omitted.target,[omitted.reason==="repository_indexing"?"indexing":"preparing documentation"])}`);for(const target of omitted.suggestedSiteTargets??[])prose(` Search hosted documentation instead: ${target}`)}const otherOmissions=result.unavailableTargets.filter((entry)=>!pending.includes(entry));if(otherOmissions.length)lines.push("","Not searched:");for(const omitted of otherOmissions){prose(` - ${omitted.target}: ${grepPreparationReason(omitted.reason)}; ${omitted.retryable?"you can retry":"do not retry unchanged"}${omitted.reason==="no_grep_scopes"&&!omitted.retryable&&!omitted.suggestedSiteTargets?.length?"; choose a different package, repository or site target":""}`);for(const target of omitted.suggestedSiteTargets??[])prose(` Search hosted documentation instead: ${target}`)}for(const scope of result.targets)renderCoverage(scope,prose);if(result.traversal==="CURSOR_EXPIRED")prose("Cursor expired; the search could not continue.");else if(result.traversal!=="COMPLETE"&&(!result.nextCursor||result.traversal!=="RESUMABLE_LIMIT")&&(result.unavailableTargets.length===0||result.traversal==="FAILED")&&!result.targets.some((scope)=>!["COMPLETE","RESUMABLE_LIMIT"].includes(scope.traversal)||!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness)))prose(result.nextCursor?`${result.hits.length?"Some requested content could not be searched; the":"The"} service did not explain why or whether retrying would help.`:"The search did not finish, and no continuation cursor was returned. The service did not explain why the full search stopped or whether retrying would help.");if(result.pathWarnings.length)lines.push("");for(const warning of summarizeGrepPathWarnings(result.pathWarnings))lines.push(`Warning: ${escapeControls(warning)}`);for(const[index,group]of groups.entries()){const first=group.first;const target=first.read.target;const path=first.read.path!==null?` ${quoteLocator(first.read.path,options.syntax)}`:"";const display=first.__typename==="GrepSiteHit"&&first.pageUrl!==first.read.target?` [page: ${escapeText(first.pageUrl)}]`:"";lines.push("",`[${index+1}] ${quoteLocator(target,options.syntax)}${path}${display}`);const rows=groupRows(group.hits);const gutter=Math.max(...rows.map((row)=>String(row.number).length));const hasContext=rows.some((row)=>!row.match);let previous;for(const row of rows){if(hasContext&&previous!==undefined&&row.number>previous+1)lines.push("--");lines.push(`${String(row.number).padStart(gutter)}${row.match?":":"-"} ${renderSlice(row,options.useColors??false)}`);previous=row.number}if(group.hits.some((hit)=>hit.contentSafety.filtered))prose("Safety normalization applied; physical source coordinates remain in JSON.")}const read=[];const more=[];const followUp=[];const proseLines=(value)=>footerProse(escapeText(value),options.width??80);const operand=(value)=>footerAction(value,options.useColors===true);if(groups.length){if(kinds.has("GrepRepositoryHit"))read.push(operand(options.syntax==="mcp"?"Files: read target=$target path=$path start_line=$start end_line=$end":"Files: githits read --lines $start-$end -- $target $path"));if(kinds.has("GrepSiteHit"))read.push(operand(options.syntax==="mcp"?"Pages: read target=$url start_line=$start end_line=$end":"Pages: githits read --lines $start-$end -- $url"))}if(result.nextCursor)more.push(...proseLines("Repeat the original grep, adding:"),operand(options.syntax==="mcp"?`cursor=${JSON.stringify(result.nextCursor)}`:`--cursor ${shellQuoteExact(result.nextCursor)}`));const cursorOption=options.syntax==="mcp"?"cursor":"--cursor";if(result.traversal==="CURSOR_EXPIRED"){followUp.push(...proseLines(`To restart the full search, repeat the original grep and omit ${cursorOption}.`))}else{const retryableOmissions=result.unavailableTargets.filter((target)=>target.retryable);const retryableScopes=result.targets.filter((scope)=>scope.retryable&&hasPageCoverageGap(scope));if(retryableOmissions.length||retryableScopes.length){const indices=new Set([...retryableOmissions.map((target)=>target.inputIndex),...retryableScopes.flatMap((scope)=>scope.requestedInputIndices)]);const requestedTargets=options.requestedTargets;const targets=requestedTargets?requestedTargets.flatMap((target,index)=>indices.has(index)?[`${quoteLocator(target,options.syntax)}${requestedTargets.indexOf(target)!==requestedTargets.lastIndexOf(target)?` (target ${index+1})`:""}`]:[]):[...new Set([...retryableOmissions.map((target)=>target.target),...retryableScopes.map((scope)=>scope.target)])].map((target)=>quoteLocator(target,options.syntax));followUp.push(...proseLines(requestedTargets?"Repeat the same pattern and options for:":"Repeat the original grep inputs for these sources:"),...targets.map((target)=>operand(` ${target}`)));if(pending.length){const wait=indexingWaitMs(result.indexingEstimates);const waitOption=options.syntax==="mcp"?`wait_timeout_ms=${wait}`:`--wait ${wait}`;followUp.push(...proseLines(`Omit ${cursorOption}; set ${waitOption} to wait up to ${wait/1000}s for preparation.`))}else{followUp.push(...proseLines(`Omit ${cursorOption} to start a new search.`))}}}appendSearchGrepFooter(lines,{read,more,followUp},options.useColors===true);return lines.join(`
118
120
  `)}function renderCoverage(scope,prose){const prefix=`${scope.kind==="REPOSITORY"?"Repository":"Hosted docs"} ${scope.target}`;const notes=[];if(scope.readiness==="UNSPECIFIED"&&scope.traversal!=="RESUMABLE_LIMIT")notes.push("source readiness unknown");else if(scope.readiness!=="UNSPECIFIED"&&scope.readiness!=="CURRENT")notes.push(readinessNote(scope));if(scope.traversal!=="COMPLETE"&&scope.traversal!=="RESUMABLE_LIMIT")notes.push(traversalNote(scope));if(hasPageCoverageGap(scope))notes.push(scope.retryable?"you can retry":"do not retry unchanged");const details=[];if(scope.publicMessage)details.push(`Reason: ${scope.publicMessage}${scope.errorCode?` [${scope.errorCode}]`:""}`);else if(scope.errorCode)details.push(`Error: ${scope.errorCode}.`);else if(scope.traversal==="FAILED")details.push("No further failure details were provided.");if(notes.length||details.length){if(scope.readiness==="STALE"&&scope.commitSha)details.push(...scope.repoUrl?scope.requestedRef?[`Requested ref: ${scope.requestedRef}.`]:[]:[`Served ${scope.commitSha}${scope.requestedRef?`; requested ${scope.requestedRef}`:""}.`]);if(scope.filesScanned!==null&&scope.filesInScope!==null&&scope.filesScanned!==scope.filesInScope)details.push(`Searched ${scope.filesScanned} of ${scope.filesInScope} file${scope.filesInScope===1?"":"s"}.`)}if(scope.binaryFilesSkipped)details.push(`Skipped ${scope.binaryFilesSkipped} binary file${scope.binaryFilesSkipped===1?"":"s"}.`);if(scope.filesTooLargeSkipped)details.push(`Skipped ${scope.filesTooLargeSkipped} oversized file${scope.filesTooLargeSkipped===1?"":"s"}.`);for(const issue of scope.fileIssues??[])details.push(`File issue ${issue.filePath}${issue.line>0?`:${issue.line}`:" (aggregate)"}; ${issue.code}${issue.contentSafety.filtered?"; safety normalization applied":""}.`);if(scope.fileIssuesOmitted)details.push(`${scope.fileIssuesOmitted} additional file issue(s) omitted.`);if(notes.length||details.length){const note=notes.join("; ");prose(`${prefix}:${note?` ${note}${/[.!?]$/.test(note)?"":"."}`:""}`);for(const detail of details)prose(` ${detail}`)}}function readinessNote(scope){switch(scope.readiness){case"STALE":return"stale snapshot";case"NOT_AVAILABLE":return"unavailable";case"MISSING_REF":return"requested ref missing";case"READER_OPEN_FAILED":return"could not open repository reader";case"INCOMPLETE":return"incomplete index";case"RESOURCE_LIMIT":return"resource limit reached";case"VERSION_UNSUPPORTED":return"unsupported documentation version";case"READ_FAILED":return"could not read documentation";default:return scope.readiness}}function traversalNote(scope){switch(scope.traversal){case"FAILED":return"search failed";case"CURSOR_EXPIRED":return"cursor expired";default:return"incomplete search"}}function isExhaustive(result){return result.traversal==="COMPLETE"&&result.unavailableTargets.length===0&&result.targets.every((scope)=>!hasCoverageGap(scope))}function hasPageCoverageGap(scope){return scope.readiness!=="CURRENT"&&!(scope.readiness==="UNSPECIFIED"&&scope.traversal==="RESUMABLE_LIMIT")||!["COMPLETE","RESUMABLE_LIMIT"].includes(scope.traversal)||scope.errorCode!==null||Boolean(scope.binaryFilesSkipped||scope.filesTooLargeSkipped||scope.fileIssues?.length||scope.fileIssuesOmitted)}function hasCoverageGap(scope){return scope.readiness!=="CURRENT"||scope.traversal!=="COMPLETE"||hasPageCoverageGap(scope)}function formatSources(scopes,matchedScopes,exhaustive){const sources=new Map;for(const scope of scopes){let target=scope.target;let identity=JSON.stringify([scope.kind,scope.target]);const hostedDocumentation=scope.kind==="SITE"&&Boolean(scope.canonicalSite);if(scope.kind==="SITE"&&scope.canonicalSite){target=`site:${scope.canonicalSite.replace(/^https?:\/\//i,"").replace(/\/$/,"")}`;identity=JSON.stringify([scope.kind,scope.canonicalSite])}const qualifiers=[];if(scope.kind==="REPOSITORY"&&scope.repoUrl&&scope.commitSha){if(scope.corpus==="SOURCE")qualifiers.push("source files");if(scope.corpus==="DOCUMENTATION")qualifiers.push("repository docs");identity=JSON.stringify([scope.kind,scope.repoUrl,scope.commitSha,scope.corpus])}if(scope.readiness==="STALE")qualifiers.push("older snapshot");const unsearched=!matchedScopes.has(scope.targetIndex)&&scope.filesScanned===0&&(scope.traversal==="FAILED"||!["CURRENT","STALE","UNSPECIFIED"].includes(scope.readiness));if(unsearched)qualifiers.push("not searched");if(scope.readiness==="UNSPECIFIED"&&scope.traversal==="RESUMABLE_LIMIT")qualifiers.push("not reached on this page");identity=JSON.stringify([identity,scope.readiness,scope.traversal,scope.filesScanned,scope.filesInScope,scope.errorCode,scope.binaryFilesSkipped,scope.filesTooLargeSkipped,scope.fileIssues,scope.fileIssuesOmitted,scope.urlPrefixes]);const source=sources.get(identity)??{facts:{target,identity:scope.kind==="REPOSITORY"?{repoUrl:scope.repoUrl,commitSha:scope.commitSha}:undefined,qualifiers},requested:new Set,matched:false,hostedDocumentation};if(scope.kind==="REPOSITORY"&&scope.commitSha&&scope.requestedRef&&/^[a-f0-9]{40}$/i.test(scope.requestedRef)&&scope.requestedRef.toLowerCase()!==scope.commitSha.toLowerCase())source.requested.add(scope.target);source.matched||=matchedScopes.has(scope.targetIndex);sources.set(identity,source)}return[...sources.values()].map((source)=>formatSourceRow({...source.facts,qualifiers:[...source.facts.qualifiers??[],...source.requested.size?[`requested: ${[...source.requested].join(", ")}`]:[],...!source.matched&&!source.facts.qualifiers?.some((qualifier)=>["not searched","not reached on this page"].includes(qualifier))?[exhaustive?"no results":"no matches returned"]:[],...source.hostedDocumentation?["hosted documentation"]:[]]}))}function quoteLocator(value,syntax){if(/^[A-Za-z0-9_./:@%+=-][A-Za-z0-9_./:@%#+=-]*$/.test(value))return value;return syntax==="mcp"?JSON.stringify(value):shellQuoteExact(value)}function fileIdentity(hit){return[hit.targetIndex,hit.__typename,hit.read.target,hit.read.path]}function groupFiles(hits){const groups=new Map;for(const hit of hits){const key=JSON.stringify(fileIdentity(hit));const group=groups.get(key);if(group)group.hits.push(hit);else groups.set(key,{first:hit,hits:[hit]})}return[...groups.values()]}function groupRows(hits){const rows=new Map;const add=(number,slice,span)=>{const key=JSON.stringify([number,slice.startByte,slice.endByte,slice.content]);const row=rows.get(key);if(row){if(span){row.match=true;row.spans.push(span)}}else rows.set(key,{number,slice,match:span!==undefined,spans:span?[span]:[]})};for(const hit of hits){hit.contextBeforeSlices.forEach((slice,index)=>{add(hit.line-hit.contextBeforeSlices.length+index,slice)});add(hit.line,hit.lineSlice,{start:hit.matchStartByte,end:hit.matchEndByte});hit.contextAfterSlices.forEach((slice,index)=>{add(hit.line+index+1,slice)})}return[...rows.values()].sort((a,b)=>a.number-b.number||a.slice.startByte-b.slice.startByte||a.slice.endByte-b.slice.endByte)}function renderSlice(row,useColors){const{slice}=row;let content;if(!useColors)content=escapeSource(slice.content);else{const bytes=new TextEncoder().encode(slice.content);const decoder=new TextDecoder("utf-8",{ignoreBOM:true});const merged=[];for(const span of[...row.spans].sort((a,b)=>a.start-b.start||a.end-b.end)){if(span.start===span.end)continue;const previous=merged[merged.length-1];if(previous&&span.start<=previous.end)previous.end=Math.max(previous.end,span.end);else merged.push({...span})}let cursor=0;content="";for(const span of merged){content+=escapeSource(decoder.decode(bytes.subarray(cursor,span.start)));content+=highlightMatch(escapeSource(decoder.decode(bytes.subarray(span.start,span.end))),true);cursor=span.end}content+=escapeSource(decoder.decode(bytes.subarray(cursor)))}return`${slice.startByte>0?"[...] ":""}${content}${slice.endByte<slice.originalLineBytes?" [...]":""}`}function escapeText(value){return escapeControls(value.replace(/\\/g,"\\\\"))}function escapeSource(value){return escapeControls(value,true)}function escapeControls(value,preserveTabs=false){return value.replace(/[\u0000-\u001f\u007f-\u009f]/g,(character)=>preserveTabs&&character==="\t"?character:`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`)}function wrap(text,width){const lines=[];const prefix=text.match(/^ *(?:- )?/)?.[0]??"";const indent=" ".repeat(prefix.length);let current=prefix;for(const word of text.slice(prefix.length).split(" ")){const hasWord=current.length>indent.length;if(hasWord&&terminalWidth(`${current} ${word}`)>width){lines.push(current);current=`${indent}${word}`}else current=hasWord?`${current} ${word}`:`${current}${word}`}if(current)lines.push(current);return lines}var targetSchema=z2.object({target:z2.string().describe("Package `npm:express@5.2.1`, repository `github:expressjs/express@v5.2.1` or `launchpad:~owner/+git/repo@ref` (`lp:PROJECT` also accepted), or hosted docs `site:expressjs.com/en/5x`."),corpus:z2.enum(["source","documentation","all"]).optional().describe("Filters repository files (default all); selected hosted docs are unaffected. Omit for sites."),path_selectors:z2.array(z2.object({kind:z2.enum(["exact","prefix","glob"]),value:z2.string()})).optional().describe("OR-ed file scopes relative to the package/repository root. Empty applies no path filter; corpus still applies. Hosted docs are unaffected; omit for sites.")});var schema2={targets:z2.array(targetSchema).min(1).max(20).describe("One to 20 ordered package, repository, or site targets."),pattern:z2.string().describe("RE2 regex (default), or text with pattern_type literal (1-200 UTF-8 bytes). No lookaround or backreferences; multi-file regex needs a literal anchor."),pattern_type:z2.enum(["regex","literal"]).optional().describe("Regex (default) or literal substring matching."),ignore_case:z2.boolean().optional().describe("true ignores case with Unicode folding; false (default) is case-sensitive."),context_lines_before:z2.number().int().min(0).max(10).optional().describe("Lines before each match (0-10; default 0)."),context_lines_after:z2.number().int().min(0).max(10).optional().describe("Lines after each match (0-10; default 0)."),max_matches:z2.number().int().min(1).max(1000).optional().describe("Maximum occurrences across all scopes on this page (default 100)."),cursor:z2.string().optional().describe("Continue with the same ordered targets, pattern, and matching controls. Empty starts page one. Hosted pages can change between grep and read."),wait_timeout_ms:z2.number().int().min(0).max(300000).optional().describe(`First-page preparation wait in milliseconds (default ${DEFAULT_WAIT_TIMEOUT_MS}). Continuation never waits.`),format:z2.enum(["text","json"]).default("text").describe("Omit for text: grouped matches, read locators, and coverage. Use json only when code consumes raw hit and scope fields.")};var DESCRIPTION2="Find regex or literal matches across source and documentation. "+"Search ordered package, repository, and site targets; packages include selected hosted docs. "+"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."+`
119
121
 
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(`
122
+ ${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 result=await service.grep(params,...serviceRequestArgs(context?.signal));const projected=projectGrepResult(result);return textResult(args.format==="json"?JSON.stringify(projected):formatGrepText(result,{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}:{},...identity.releaseCorrespondence!==undefined?{releaseCorrespondence:identity.releaseCorrespondence}:{},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(`
121
123
  `);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(`
122
124
  `)}function formatSourceReadAction(target,syntax){return syntax==="mcp"?`read target=${JSON.stringify(target)} path=$path`:`read -- ${shellQuoteExact(target)} $path`}function formatSiteReadGuidance(target,syntax){return syntax==="mcp"?`Read pages: read target=${JSON.stringify(target)} path=$path`:`Read pages: read -- ${shellQuoteExact(target)} $path`}function formatPath(entry,inventoryKind){if(inventoryKind==="SITE"){return formatSitePath(entry)}if(entry.kind==="PAGE"&&entry.read?.target!==undefined){return escapePath(entry.read.target)}const path=entry.kind==="DIRECTORY"&&!entry.path.endsWith("/")?`${entry.path}/`:entry.path;return escapePath(path)}function formatSitePath(entry){if(entry.kind==="PAGE"&&entry.read!==null&&entry.read!==undefined){if(isSiteReadAction(entry.read.target,entry.read.path)){return escapePath(entry.read.path)}return escapePath(entry.read.target)}const path=entry.kind==="DIRECTORY"&&!entry.path.endsWith("/")?`${entry.path}/`:entry.path;return escapePath(path)}function findSharedSiteReadTarget(result){if(result.inventoryKind!=="SITE")return;let sharedTarget;for(const entry of result.entries){if(entry.kind!=="PAGE"||entry.read===null||entry.read===undefined||!isSiteReadAction(entry.read.target,entry.read.path)){continue}if(sharedTarget===undefined){sharedTarget=entry.read.target}else if(entry.read.target!==sharedTarget){return}}return sharedTarget}function isSiteReadAction(target,path){return target.startsWith("site:")&&path!==null}function escapePath(path){return escapeLineValue(path)}function escapeLineValue(value){let escaped="";for(const character of value){if(character==="\\"){escaped+="\\\\";continue}const shortEscape=SHORT_ESCAPES.get(character);if(shortEscape!==undefined){escaped+=shortEscape;continue}const codePoint=character.codePointAt(0)??0;if(codePoint<=31||codePoint>=127&&codePoint<=159||codePoint===8232||codePoint===8233||codePoint>=55296&&codePoint<=57343){escaped+=`\\u${codePoint.toString(16).padStart(4,"0")}`;continue}escaped+=character}return escaped}var SHORT_ESCAPES=new Map([["\b","\\b"],["\t","\\t"],[`
123
125
  `,"\\n"],["\f","\\f"],["\r","\\r"]]);var LIST_INTENTS=["PRODUCTION","TEST","BENCHMARK","EXAMPLE","GENERATED","FIXTURE","BUILD","VENDOR"];var schema3={target:z3.string().describe("Known package such as `npm:express@5.2.1`, repository such as `github:expressjs/express` or `launchpad:~owner/+git/repo` (`lp:PROJECT` also accepted), or hosted docs site such as `site:expressjs.com`."),paths:z3.array(z3.string()).max(1000).optional().describe("Target-relative literal paths and globs form a union for packages, repositories, and sites. Site paths with one leading `/` stay within the supplied target; `/` alone selects its root. Omit or pass `[]` to browse the root."),recursive:z3.boolean().optional().describe("Expand selected directories to descendant leaves. Without this, selected directories show immediate children. Glob depth is independent of recursion."),file_types:z3.array(z3.string()).max(64).optional().describe("Source inventories only; classifications such as `source` or `doc`, case-insensitive. Select file extensions with a `paths` glob such as `lib/**/*.js`."),languages:z3.array(z3.string()).max(64).optional().describe("Source inventories only; language names such as `javascript`, `typescript`, or `rust`, case-insensitive."),intents:z3.array(z3.enum(LIST_INTENTS)).max(64).optional().describe("Source inventories only; filter by file intent: PRODUCTION, TEST, BENCHMARK, EXAMPLE, GENERATED, FIXTURE, BUILD, or VENDOR."),limit:z3.number().int().min(1).max(500).optional().describe("Maximum entries to return (1-500)."),after:z3.string().optional().describe("Opaque `nextCursor` from a prior list response. Reuse the same target, paths, filters, recursion, and limit; empty is omitted."),wait_timeout_ms:z3.number().int().min(0).max(300000).optional().describe(`Maximum wait for indexing in milliseconds (0-300000; default ${DEFAULT_WAIT_TIMEOUT_MS}).`),format:z3.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or follows read and continuation guidance. Set `json` for exact entry kinds or actions, or when code consumes the raw response instead of the model by parsing or filtering it programmatically.")};var DESCRIPTION3="List files and documentation paths in a known package, repository, or site. "+"Use it to browse structure or find an exact path before `read`; use `search` "+`for topics.
@@ -193,13 +195,13 @@ ${PKG_VULNS_GUARDRAIL}`;function createPackageVulnerabilitiesTool(service){retur
193
195
  `),endLine:startLine+maxOutputLines-1}}function formatReadPackageDocTerminal(envelope,options){if(!(options.verbose??false)){return envelope.content??""}const lines=[];lines.push(buildHeader3(envelope,options.useColors));if(envelope.docsReadTarget!==envelope.pageId){lines.push(`docsReadTarget: ${envelope.docsReadTarget}`)}lines.push(`pageId: ${envelope.pageId}`);if(envelope.sourceUrl&&envelope.sourceUrl!==envelope.docsReadTarget){lines.push(`source: ${envelope.sourceUrl}`)}if(envelope.filePath){const ref=envelope.requestedRef??envelope.gitRef;lines.push(`file: ${envelope.filePath}${ref?` @ ${ref}`:""}`)}if(envelope.lastUpdatedAt)lines.push(`updated: ${envelope.lastUpdatedAt}`);if(envelope.startLine!==undefined&&envelope.endLine!==undefined){lines.push(`range: ${envelope.startLine}-${envelope.endLine}/${envelope.totalLines}`)}else{lines.push(`range: empty/0`)}if(envelope.anchor)lines.push(`anchor: ${envelope.anchor}`);if(envelope.breadcrumbs&&envelope.breadcrumbs.length>0){lines.push(`breadcrumbs: ${envelope.breadcrumbs.join(" > ")}`)}lines.push("");if(envelope.content)lines.push(envelope.content);return`${lines.join(`
194
196
  `)}
195
197
  `}function buildHeader3(envelope,useColors){const badge=envelope.sourceKind==="repo"?"[repo]":"[crawled]";const title=envelope.title??envelope.pageId;const prefix=envelope.registry&&envelope.name?`${envelope.registry}:${envelope.name}${envelope.version?`@${envelope.version}`:""}`:"documentation";return`${colorize(`${prefix} ${badge}`,"bold",useColors)}${title?` - ${title}`:""}`}var SEP2=" | ";function renderReadPackageDocText(envelope){const lines=[];lines.push(buildHeader4(envelope));if(envelope.sourceUrl&&envelope.sourceUrl!==envelope.docsReadTarget){lines.push(`source: ${envelope.sourceUrl}`)}if(envelope.filePath){const ref=envelope.gitRef;lines.push(`file: ${envelope.filePath}${ref?` @ ${ref}`:""}`)}lines.push("");if(envelope.content)lines.push(envelope.content);if(envelope.hint){lines.push("");lines.push(`hint: ${envelope.hint}`)}return lines.join(`
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(`
198
+ `)}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 --in ${shellQuoteExact(followUpTarget)} --source symbol -- ${shellQuoteExact(selector)}`:`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}`];if(result.candidates.length||result.suggestions.length)lines.push(`Paths are relative to ${followUpTarget}.`);lines.push(`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(`
197
199
  `)}
198
200
  `}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(`
199
201
  `);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}
200
202
 
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&&params.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&&params.limit!==DEFAULT_LIMIT){echo.limit=params.limit}if(params.offset!==undefined&&params.offset!==DEFAULT_OFFSET){echo.offset=params.offset}if(params.waitTimeoutMs!==undefined&&params.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"&&notes.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(`
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(`
203
+ ${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&&params.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&&params.limit!==DEFAULT_LIMIT){echo.limit=params.limit}if(params.offset!==undefined&&params.offset!==DEFAULT_OFFSET){echo.offset=params.offset}if(params.waitTimeoutMs!==undefined&&params.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});const correspondence=buildSourceCorrespondenceNotes(entry.targetResolution);if(freshness)return[freshness,...correspondence].join(" ");const terminalLifecycleReason=terminalLifecycleWarningReason(entry);if(terminalLifecycleReason){reasons.push(terminalLifecycleReason,...correspondence)}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){const notes=entry.targetResolution?.freshness==="indexing"&&options.completed?buildSourceCorrespondenceNotes(entry.targetResolution):buildTargetResolutionNotes(entry.targetResolution);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 hasCorrespondence=[targetResolution.requested,targetResolution.resolvedRequested,targetResolution.served].some((identity)=>identity?.releaseCorrespondence!=null);const targetResolutionIsInteresting=hasCorrespondence||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(`
204
+ `)}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[...buildSourceCorrespondenceNotes(record.resolution),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(`
203
205
  `)&&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(`
204
206
  `)){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(`
205
207
  `);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(`
@@ -207,4 +209,4 @@ ${CODE_READ_GUARDRAIL}`;function createReadTool(services){return{name:"read",des
207
209
 
208
210
  ${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}
209
211
 
210
- ${QUICK_START_PREREQUISITE}`}}function getMcpToolDescriptors(){return getMcpToolDefinitions(createDescriptorServices()).map(({name,description,schema,annotations})=>({name,description,schema,annotations}))}function eraseMcpTool(tool){return{...tool,handler:(args,context)=>tool.handler(args,context)}}function registerMcpTools(server,options){registerMcpToolsWithFactories(server,STABLE_MCP_TOOL_FACTORIES,{...options,descriptorServices:createDescriptorServices()})}function registerMcpToolsWithFactories(server,toolFactories,options){const animation=resolveAnimation(options.progressAnimation,options.progress);for(const createTool of toolFactories){const descriptor=addMcpSessionPrerequisite(createTool(options.descriptorServices));server.registerTool(descriptor.name,{description:descriptor.description,inputSchema:descriptor.schema,annotations:descriptor.annotations},async(args,extra)=>{const progress=bindProgress(options.progress,animation,extra);const context={authAction:options.authAction,termsRemediation:options.termsRemediation,signal:extra?.signal,...progress?{progress}:{}};const runHandler=async()=>{const services=await withErrorHandling("resolve MCP services",()=>resolveMcpToolServices(options.services,{extra}),context,args.format==="json"?"json":"text");if(isToolResult(services))return services;return createTool(services).handler(args,context)};return options.traceTool?await options.traceTool(descriptor.name,runHandler):runHandler()})}}function createMcpServer(options){const toolFactories=createStableMcpToolFactories(buildMcpQuickStart(options.quickStartOptions??options.instructionOptions));return createMcpServerWithFactories({...options,toolFactories,descriptorServices:createDescriptorServices()})}function createMcpServerWithFactories(options){const server=new McpServer(options.metadata,options.instructions===undefined?undefined:{instructions:options.instructions});registerMcpToolsWithFactories(server,options.toolFactories,{authAction:options.authAction,termsRemediation:options.termsRemediation,services:options.services,traceTool:options.traceTool,progress:options.progress,progressAnimation:options.progressAnimation,descriptorServices:options.descriptorServices});return server}function resolveAnimation(option,hook){if(option===false)return false;if(option===true)return{};if(option)return option;return hook?{}:false}function bindProgress(hook,animation,extra){const progressToken=extra?._meta?.progressToken;if(!hook&&!animation||progressToken===undefined||!extra?.sendNotification){return}const{sendNotification}=extra;const emit=(progress,message)=>{sendNotification({method:"notifications/progress",params:{progressToken,progress,message}}).catch(()=>{})};return{begin:(initialMessage="Working…")=>beginAnimatedProgress(hook,emit,initialMessage,animation)}}async function resolveMcpToolServices(provider,context){if(typeof provider==="function"){return provider(context)}return provider}function createDescriptorServices(){const fail=()=>{throw new Error("Descriptor services must not execute tool handlers.")};return{githitsService:{search:fail},codeNavigationService:{search:fail,searchStatus:fail,listFiles:fail,readFile:fail,grepRepo:fail,codeDiff:fail},packageIntelligenceService:{packageSummary:fail,packageVulnerabilities:fail,packageDependencies:fail,packageUpgradeDependencyProbe:fail,packageUpgradeReview:fail,packageChangelog:fail,listPackageDocs:fail,readPackageDoc:fail},listService:{list:fail},readService:{read:fail},grepService:{grep:fail},resolveTargetService:{resolveTarget:fail},agenticAskService:{ask:fail}}}function isToolResult(value){return"content"in value}import WebSocket from"ws";class RelayUnavailableError extends Error{backoffMs;constructor(backoffMs){super("Progress relay unavailable");this.backoffMs=backoffMs}}var SETUP_TIMEOUT_MS=5000;var RENEW_BEFORE_EXPIRY_MS=60000;var MIN_RENEW_DELAY_MS=1e4;var RECONNECT_BASE_MS=1000;var RECONNECT_MAX_MS=30000;var NETWORK_BACKOFF_MS=30000;var UNAVAILABLE_BACKOFF_MS=5*60000;var MAX_MESSAGE_LENGTH=200;class RelayReceiver{options;fetchFn;createSocket;relayId;idleCloseMs;reconnectBaseMs;minRenewDelayMs;now;createId;routes=new Map;relay;socket;connecting;unavailableUntil=0;reconnectAttempts=0;renewTimer;reconnectTimer;idleTimer;closed=false;constructor(options){this.options=options;this.fetchFn=options.fetchFn??globalThis.fetch;this.createSocket=options.createSocket??((url)=>new WebSocket(url));this.idleCloseMs=options.idleCloseMs??5*60000;this.reconnectBaseMs=options.reconnectBaseMs??RECONNECT_BASE_MS;this.minRenewDelayMs=options.minRenewDelayMs??MIN_RENEW_DELAY_MS;this.now=options.now??Date.now;this.createId=options.createId??(()=>globalThis.crypto.randomUUID());this.relayId=this.createId().toLowerCase()}async begin(notify){if(this.closed||this.now()<this.unavailableUntil)return;this.clearTimer("idleTimer");this.ensureConnected();const operationId=this.createId().toLowerCase();this.routes.set(operationId,{notify,lastSequence:0});let ended=false;return{headers:{"X-GitHits-Progress-Id":operationId,"X-GitHits-Relay-Id":this.relayId,...this.serviceHeaders()},rejected:()=>{this.unavailableUntil=this.now()+UNAVAILABLE_BACKOFF_MS},end:()=>{if(ended)return;ended=true;this.routes.delete(operationId);this.scheduleIdleClose()}}}warm(){if(this.closed||this.now()<this.unavailableUntil)return;this.ensureConnected().then(()=>this.scheduleIdleClose())}close(){this.closed=true;this.routes.clear();this.clearTimer("renewTimer");this.clearTimer("reconnectTimer");this.clearTimer("idleTimer");this.closeSocket()}ensureConnected(){if(this.socket&&this.relay&&this.now()<this.relay.expiresAt){return Promise.resolve()}this.connecting??=this.connect().finally(()=>{this.connecting=undefined});return this.connecting}async connect(){let relay;try{relay=await this.setup()}catch(error){this.unavailableUntil=this.now()+(error instanceof RelayUnavailableError?error.backoffMs:NETWORK_BACKOFF_MS);return}if(this.closed)return;this.relay=relay;this.scheduleRenewal(relay);await this.openSocket(relay.url)}openSocket(url){return new Promise((resolve)=>{let socket;try{socket=this.createSocket(url)}catch{this.socketFailed();resolve();return}let opened=false;socket.onmessage=(event)=>this.deliver(event.data);socket.onerror=()=>{};socket.onopen=()=>{opened=true;this.reconnectAttempts=0;const previous=this.socket;this.socket=socket;if(previous)this.detach(previous);if(this.closed)this.closeSocket();resolve()};socket.onclose=()=>{if(!opened){this.detach(socket);if(!this.socket)this.socketFailed();resolve();return}if(this.socket!==socket)return;this.socket=undefined;if(!this.closed&&this.routes.size>0)this.scheduleReconnect()}})}socketFailed(){const delay=Math.min(RECONNECT_MAX_MS,this.reconnectBaseMs*2**this.reconnectAttempts);this.unavailableUntil=Math.max(this.unavailableUntil,this.now()+delay);if(this.routes.size>0)this.scheduleReconnect();else this.reconnectAttempts+=1}deliver(data){const event=parseEvent(data);if(!event)return;const route=this.routes.get(event.operationId);if(!route||event.sequence<=route.lastSequence)return;route.lastSequence=event.sequence;try{route.notify({progress:event.sequence,message:event.message,...event.stage?{stage:event.stage}:{}})}catch{}}async setup(){const headers={...this.options.clientHeaders?.(),...await this.authHeaders(),"Content-Type":"application/json"};const response=await this.fetchFn(`${this.options.apiUrl.replace(/\/+$/,"")}/progress/relays/renew`,{method:"POST",headers,body:JSON.stringify({relay_id:this.relayId}),signal:AbortSignal.timeout(SETUP_TIMEOUT_MS)});if(!response.ok){await response.body?.cancel().catch(()=>{});throw new RelayUnavailableError(backoffFor(response))}const access=parseRelayAccess(await response.json(),this.relayId);if(!access)throw new RelayUnavailableError(UNAVAILABLE_BACKOFF_MS);return access}async authHeaders(){const{auth}=this.options;if(auth.kind==="service")return this.serviceHeaders();const token=await auth.getToken();if(!token)throw new RelayUnavailableError(UNAVAILABLE_BACKOFF_MS);return{Authorization:`Bearer ${token}`}}serviceHeaders(){const{auth}=this.options;return auth.kind==="service"?{"X-GitHits-Relay-Service":auth.serviceId,"X-GitHits-Relay-Key":auth.key}:{}}scheduleRenewal(relay){this.clearTimer("renewTimer");const delay=Math.max(this.minRenewDelayMs,relay.expiresAt-RENEW_BEFORE_EXPIRY_MS-this.now());this.renewTimer=setTimeout(()=>{this.renewTimer=undefined;if(this.routes.size===0){this.closeSocket();return}this.ensureFresh()},delay);unrefTimer(this.renewTimer)}ensureFresh(){this.connecting??=this.connect().finally(()=>{this.connecting=undefined});return this.connecting}scheduleReconnect(){if(this.reconnectTimer||this.closed)return;const delay=Math.min(RECONNECT_MAX_MS,this.reconnectBaseMs*2**this.reconnectAttempts);this.reconnectAttempts+=1;this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=undefined;if(this.closed||this.routes.size===0)return;this.ensureFresh().then(()=>{if(!this.socket&&this.routes.size>0)this.scheduleReconnect()})},delay);unrefTimer(this.reconnectTimer)}scheduleIdleClose(){if(this.routes.size>0||this.closed)return;this.clearTimer("idleTimer");this.idleTimer=setTimeout(()=>{this.idleTimer=undefined;if(this.routes.size===0){this.clearTimer("renewTimer");this.closeSocket()}},this.idleCloseMs);unrefTimer(this.idleTimer)}closeSocket(){const socket=this.socket;this.socket=undefined;if(socket)this.detach(socket)}detach(socket){socket.onopen=null;socket.onmessage=null;socket.onclose=null;socket.onerror=()=>{};try{socket.close()}catch{}}clearTimer(name){const timer=this[name];if(timer)clearTimeout(timer);this[name]=undefined}}function backoffFor(response){if(response.status===429){const seconds=Number(response.headers.get("Retry-After"));if(Number.isFinite(seconds)&&seconds>0)return seconds*1000}return UNAVAILABLE_BACKOFF_MS}function parseRelayAccess(value,relayId){if(!value||typeof value!=="object")return;const body=value;const{relay_id,connection_url,expires_at}=body;if(typeof relay_id!=="string"||relay_id.toLowerCase()!==relayId||typeof connection_url!=="string"||!connection_url.startsWith("wss://")||typeof expires_at!=="number"){return}return{url:connection_url,expiresAt:expires_at*1000}}function parseEvent(data){let text;if(typeof data==="string")text=data;else if(data instanceof ArrayBuffer||data instanceof Uint8Array)text=new TextDecoder().decode(data);else return;let value;try{value=JSON.parse(text)}catch{return}if(!value||typeof value!=="object")return;const event=value;if(event.version!==1||typeof event.operation_id!=="string"||typeof event.message!=="string"||typeof event.sequence!=="number"||!Number.isInteger(event.sequence)||event.sequence<1){return}const stage=typeof event.stage==="string"&&/^[a-z_]{1,32}$/.test(event.stage)?event.stage:undefined;return{operationId:event.operation_id.toLowerCase(),sequence:event.sequence,message:event.message.slice(0,MAX_MESSAGE_LENGTH),...stage?{stage}:{}}}function unrefTimer(timer){timer.unref?.()}export{RelayReceiver,buildMcpInstructions,buildMcpQuickStart,createMcpServer,focusForStage,getMcpToolDescriptors,narrowingFrame,narrowingText,registerMcpTools};
212
+ ${QUICK_START_PREREQUISITE}`}}function getMcpToolDescriptors(){return getMcpToolDefinitions(createDescriptorServices()).map(({name,description,schema,annotations})=>({name,description,schema,annotations}))}function eraseMcpTool(tool){return{...tool,handler:(args,context)=>tool.handler(args,context)}}function registerMcpTools(server,options){registerMcpToolsWithFactories(server,STABLE_MCP_TOOL_FACTORIES,{...options,descriptorServices:createDescriptorServices()})}function registerMcpToolsWithFactories(server,toolFactories,options){const animation=resolveAnimation(options.progressAnimation,options.progress);for(const createTool of toolFactories){const descriptor=addMcpSessionPrerequisite(createTool(options.descriptorServices));server.registerTool(descriptor.name,{description:descriptor.description,inputSchema:descriptor.schema,annotations:descriptor.annotations},async(args,extra)=>{const progress=bindProgress(options.progress,animation,extra);const context={authAction:options.authAction,termsRemediation:options.termsRemediation,signal:extra?.signal,...progress?{progress}:{}};const runHandler=async()=>{const services=await withErrorHandling("resolve MCP services",()=>resolveMcpToolServices(options.services,{extra}),context,args.format==="json"?"json":"text");if(isToolResult(services))return services;return createTool(services).handler(args,context)};return options.traceTool?await options.traceTool(descriptor.name,runHandler):runHandler()})}}function createMcpServer(options){const toolFactories=createStableMcpToolFactories(buildMcpQuickStart(options.quickStartOptions??options.instructionOptions));return createMcpServerWithFactories({...options,toolFactories,descriptorServices:createDescriptorServices()})}function createMcpServerWithFactories(options){const server=new McpServer(options.metadata,options.instructions===undefined?undefined:{instructions:options.instructions});registerMcpToolsWithFactories(server,options.toolFactories,{authAction:options.authAction,termsRemediation:options.termsRemediation,services:options.services,traceTool:options.traceTool,progress:options.progress,progressAnimation:options.progressAnimation,descriptorServices:options.descriptorServices});return server}function resolveAnimation(option,hook){if(option===false)return false;if(option===true)return{};if(option)return option;return hook?{}:false}function bindProgress(hook,animation,extra){const progressToken=extra?._meta?.progressToken;if(!hook&&!animation||progressToken===undefined||!extra?.sendNotification){return}const{sendNotification}=extra;const emit=(progress,message)=>{sendNotification({method:"notifications/progress",params:{progressToken,progress,message}}).catch(()=>{})};return{begin:(initialMessage="Working…")=>beginAnimatedProgress(hook,emit,initialMessage,animation)}}async function resolveMcpToolServices(provider,context){if(typeof provider==="function"){return provider(context)}return provider}function createDescriptorServices(){const fail=()=>{throw new Error("Descriptor services must not execute tool handlers.")};return{githitsService:{search:fail},codeNavigationService:{search:fail,searchStatus:fail,listFiles:fail,readFile:fail,grepRepo:fail,codeDiff:fail},packageIntelligenceService:{packageSummary:fail,packageVulnerabilities:fail,packageDependencies:fail,packageUpgradeDependencyProbe:fail,packageUpgradeReview:fail,packageChangelog:fail,listPackageDocs:fail,readPackageDoc:fail},listService:{list:fail},readService:{read:fail},grepService:{grep:fail},resolveTargetService:{resolveTarget:fail},agenticAskService:{ask:fail}}}function isToolResult(value){return"content"in value}import WebSocket from"ws";class RelayUnavailableError extends Error{backoffMs;constructor(backoffMs){super("Progress relay unavailable");this.backoffMs=backoffMs}}var SETUP_TIMEOUT_MS=5000;var RENEW_BEFORE_EXPIRY_MS=60000;var MIN_RENEW_DELAY_MS=1e4;var RECONNECT_BASE_MS=1000;var RECONNECT_MAX_MS=30000;var NETWORK_BACKOFF_MS=30000;var UNAVAILABLE_BACKOFF_MS=5*60000;var MAX_MESSAGE_LENGTH=200;class RelayReceiver{options;fetchFn;createSocket;relayId;idleCloseMs;reconnectBaseMs;minRenewDelayMs;now;createId;routes=new Map;relay;socket;connecting;unavailableUntil=0;reconnectAttempts=0;renewTimer;reconnectTimer;idleTimer;closed=false;constructor(options){this.options=options;this.fetchFn=options.fetchFn??globalThis.fetch;this.createSocket=options.createSocket??((url)=>new WebSocket(url));this.idleCloseMs=options.idleCloseMs??5*60000;this.reconnectBaseMs=options.reconnectBaseMs??RECONNECT_BASE_MS;this.minRenewDelayMs=options.minRenewDelayMs??MIN_RENEW_DELAY_MS;this.now=options.now??Date.now;this.createId=options.createId??(()=>globalThis.crypto.randomUUID());this.relayId=this.createId().toLowerCase()}async begin(notify){if(this.closed||this.now()<this.unavailableUntil)return;this.clearTimer("idleTimer");this.ensureConnected();const operationId=this.createId().toLowerCase();this.routes.set(operationId,{notify,lastSequence:0});let ended=false;return{headers:{"X-GitHits-Progress-Id":operationId,"X-GitHits-Relay-Id":this.relayId,...this.serviceHeaders()},rejected:()=>{this.unavailableUntil=this.now()+UNAVAILABLE_BACKOFF_MS},end:()=>{if(ended)return;ended=true;this.routes.delete(operationId);this.scheduleIdleClose()}}}warm(){if(this.closed||this.now()<this.unavailableUntil)return;this.ensureConnected().then(()=>this.scheduleIdleClose())}close(){this.closed=true;this.routes.clear();this.clearTimer("renewTimer");this.clearTimer("reconnectTimer");this.clearTimer("idleTimer");this.closeSocket()}ensureConnected(){if(this.socket&&this.relay&&this.now()<this.relay.expiresAt){return Promise.resolve()}this.connecting??=this.connect().finally(()=>{this.connecting=undefined});return this.connecting}async connect(){let relay;try{relay=await this.setup()}catch(error){this.unavailableUntil=this.now()+(error instanceof RelayUnavailableError?error.backoffMs:NETWORK_BACKOFF_MS);return}if(this.closed)return;this.relay=relay;this.scheduleRenewal(relay);await this.openSocket(relay.url)}openSocket(url){return new Promise((resolve)=>{let socket;try{socket=this.createSocket(url)}catch{this.socketFailed();resolve();return}let opened=false;socket.onmessage=(event)=>this.deliver(event.data);socket.onerror=()=>{};socket.onopen=()=>{opened=true;this.reconnectAttempts=0;const previous=this.socket;this.socket=socket;if(previous)this.detach(previous);if(this.closed)this.closeSocket();resolve()};socket.onclose=()=>{if(!opened){this.detach(socket);if(!this.socket)this.socketFailed();resolve();return}if(this.socket!==socket)return;this.socket=undefined;if(!this.closed&&this.routes.size>0)this.scheduleReconnect()}})}socketFailed(){const delay=Math.min(RECONNECT_MAX_MS,this.reconnectBaseMs*2**this.reconnectAttempts);this.unavailableUntil=Math.max(this.unavailableUntil,this.now()+delay);if(this.routes.size>0)this.scheduleReconnect();else this.reconnectAttempts+=1}deliver(data){const event=parseEvent(data);if(!event)return;const route=this.routes.get(event.operationId);if(!route||event.sequence<=route.lastSequence)return;route.lastSequence=event.sequence;try{route.notify({progress:event.sequence,message:event.message,...event.stage?{stage:event.stage}:{}})}catch{}}async setup(){const headers={...this.options.clientHeaders?.(),...await this.authHeaders(),"Content-Type":"application/json"};const response=await this.fetchFn(`${this.options.apiUrl.replace(/\/+$/,"")}/progress/relays/renew`,{method:"POST",headers,body:JSON.stringify({relay_id:this.relayId}),signal:AbortSignal.timeout(SETUP_TIMEOUT_MS)});if(!response.ok){await response.body?.cancel().catch(()=>{});throw new RelayUnavailableError(backoffFor(response))}const access=parseRelayAccess(await response.json(),this.relayId);if(!access)throw new RelayUnavailableError(UNAVAILABLE_BACKOFF_MS);return access}async authHeaders(){const{auth}=this.options;if(auth.kind==="service")return this.serviceHeaders();const token=await auth.getToken();if(!token)throw new RelayUnavailableError(UNAVAILABLE_BACKOFF_MS);return{Authorization:`Bearer ${token}`}}serviceHeaders(){const{auth}=this.options;return auth.kind==="service"?{"X-GitHits-Relay-Service":auth.serviceId,"X-GitHits-Relay-Key":auth.key}:{}}scheduleRenewal(relay){this.clearTimer("renewTimer");const delay=Math.max(this.minRenewDelayMs,relay.expiresAt-RENEW_BEFORE_EXPIRY_MS-this.now());this.renewTimer=setTimeout(()=>{this.renewTimer=undefined;if(this.routes.size===0){this.closeSocket();return}this.ensureFresh()},delay);unrefTimer(this.renewTimer)}ensureFresh(){this.connecting??=this.connect().finally(()=>{this.connecting=undefined});return this.connecting}scheduleReconnect(){if(this.reconnectTimer||this.closed)return;const delay=Math.min(RECONNECT_MAX_MS,this.reconnectBaseMs*2**this.reconnectAttempts);this.reconnectAttempts+=1;this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=undefined;if(this.closed||this.routes.size===0)return;this.ensureFresh().then(()=>{if(!this.socket&&this.routes.size>0)this.scheduleReconnect()})},delay);unrefTimer(this.reconnectTimer)}scheduleIdleClose(){if(this.routes.size>0||this.closed)return;this.clearTimer("idleTimer");this.idleTimer=setTimeout(()=>{this.idleTimer=undefined;if(this.routes.size===0){this.clearTimer("renewTimer");this.closeSocket()}},this.idleCloseMs);unrefTimer(this.idleTimer)}closeSocket(){const socket=this.socket;this.socket=undefined;if(socket)this.detach(socket)}detach(socket){socket.onopen=null;socket.onmessage=null;socket.onclose=null;socket.onerror=()=>{};try{socket.close()}catch{}}clearTimer(name){const timer=this[name];if(timer)clearTimeout(timer);this[name]=undefined}}function backoffFor(response){if(response.status===429){const seconds=Number(response.headers.get("Retry-After"));if(Number.isFinite(seconds)&&seconds>0)return seconds*1000}return UNAVAILABLE_BACKOFF_MS}function parseRelayAccess(value,relayId){if(!value||typeof value!=="object")return;const body=value;const{relay_id,connection_url,expires_at}=body;if(typeof relay_id!=="string"||relay_id.toLowerCase()!==relayId||typeof connection_url!=="string"||!connection_url.startsWith("wss://")||typeof expires_at!=="number"){return}return{url:connection_url,expiresAt:expires_at*1000}}function parseEvent(data){let text;if(typeof data==="string")text=data;else if(data instanceof ArrayBuffer||data instanceof Uint8Array)text=new TextDecoder().decode(data);else return;let value;try{value=JSON.parse(text)}catch{return}if(!value||typeof value!=="object")return;const event=value;if(event.version!==1||typeof event.operation_id!=="string"||typeof event.message!=="string"||typeof event.sequence!=="number"||!Number.isInteger(event.sequence)||event.sequence<1){return}const stage=typeof event.stage==="string"&&/^[a-z_]{1,32}$/.test(event.stage)?event.stage:undefined;return{operationId:event.operation_id.toLowerCase(),sequence:event.sequence,message:event.message.slice(0,MAX_MESSAGE_LENGTH),...stage?{stage}:{}}}function unrefTimer(timer){timer.unref?.()}export{OPENING_STAGE,RelayReceiver,buildMcpInstructions,buildMcpQuickStart,createMcpServer,focusForStage,getMcpToolDescriptors,narrowingFrame,narrowingText,registerMcpTools};