@githits/mcp 0.34.0 → 0.35.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/README.md +1 -1
- package/dist/index.d.ts +63 -13
- package/dist/index.js +4 -4
- package/dist/shared/{chunk-hmvv1js7.js → chunk-660sdzfg.js} +4 -4
- package/dist/tools.d.ts +5 -2
- package/dist/tools.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -157,7 +157,7 @@ boundary is authenticated and reached.
|
|
|
157
157
|
|
|
158
158
|
The package expects callers to provide service implementations through `McpToolServices` or a request-scoped `McpToolServicesProvider`. `McpToolServices.readService` is required for the advertised compact `read` tool; remote hosts should construct the `ReadServiceImpl` instance per request with that request's endpoint, token, headers, fetch function, and diagnostics. GitHits does not populate MCP initialize instructions because hosts expose them inconsistently; `quick_start` owns shared guidance instead. Callers may still pass their own `instructions` explicitly. Use `quickStartOptions` to configure the guide. Servers can pass `traceTool` to `createMcpServer()` or `registerMcpTools()` to wrap public tool execution for instrumentation without receiving arguments or auth data.
|
|
159
159
|
|
|
160
|
-
Servers can pass an optional `progress` hook to `createMcpServer()` or `registerMcpTools()` to forward live status for `research` and `get_example`. It is used only when the client sends a progress token (including `0`); updates become `notifications/progress` and stop before the tool returns. `RelayReceiver` is the bundled hook: it receives GitHits operation progress over one shared WebSocket, authorized either by the caller's own GitHits token (`{ kind: "caller", getToken }`) or by a service credential supplied at runtime (`{ kind: "service", serviceId, key }`). The package ships no credentials. Progress is best effort: if it is unavailable or rejected, the tool runs unchanged, resending a rejected request once without progress, and the final result is always authoritative. Call `close()` on shutdown.
|
|
160
|
+
Servers can pass an optional `progress` hook to `createMcpServer()` or `registerMcpTools()` to forward live status for `research` and `get_example`. It is used only when the client sends a progress token (including `0`); updates become `notifications/progress` and stop before the tool returns. `RelayReceiver` is the bundled hook: it receives GitHits operation progress over one shared WebSocket, authorized either by the caller's own GitHits token (`{ kind: "caller", getToken }`) or by a service credential supplied at runtime (`{ kind: "service", serviceId, key }`). The package ships no credentials. Calls never wait for the progress connection: the receiver chooses its relay ID locally and connects in the background, so updates published before it is ready are skipped. Progress is best effort: if it is unavailable or rejected, the tool runs unchanged, resending a rejected request once without progress, and the final result is always authoritative. Call `close()` on shutdown. With a `progress` hook, messages are also animated locally with the GitHits narrowing mark (`narrowingFrame` / `narrowingText`); set `progressAnimation: false` to disable it or `{ intervalMs }` to change the frame rate. Frames are generated by the MCP server and sent only to that call's client.
|
|
161
161
|
|
|
162
162
|
Network-backed tools forward the MCP request's abort signal to their service call as an optional trailing `ServiceRequestOptions` argument (`{ signal }`), so a cancelled call or closed connection aborts the backend request. The bundled service implementations behind these tools honor it; custom service implementations should forward `options?.signal` to their own requests. Calls without a signal keep their single-argument shape.
|
|
163
163
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1930,6 +1930,8 @@ interface McpProgressUpdate {
|
|
|
1930
1930
|
progress: number;
|
|
1931
1931
|
/** Fixed, server-allowlisted status text. */
|
|
1932
1932
|
message: string;
|
|
1933
|
+
/** Coarse backend stage, such as `searching` or `reading`, when provided. */
|
|
1934
|
+
stage?: string;
|
|
1933
1935
|
}
|
|
1934
1936
|
/** One correlated backend call; `end()` stops delivery before the result returns. */
|
|
1935
1937
|
interface McpProgressOperation extends ProgressRequest {
|
|
@@ -1978,13 +1980,9 @@ interface RelayReceiverOptions {
|
|
|
1978
1980
|
createSocket?: (url: string) => RelaySocket;
|
|
1979
1981
|
/** Extra headers for relay setup requests, such as client attribution. */
|
|
1980
1982
|
clientHeaders?: () => Record<string, string>;
|
|
1981
|
-
/**
|
|
1983
|
+
/** @deprecated Ignored: calls never wait for the relay socket. */
|
|
1982
1984
|
connectWaitMs?: number;
|
|
1983
|
-
/**
|
|
1984
|
-
* Longest a call waits while the first relay is minted and its socket opens.
|
|
1985
|
-
* Minting takes about a second, so a shorter wait would skip progress for the
|
|
1986
|
-
* first call of every process.
|
|
1987
|
-
*/
|
|
1985
|
+
/** @deprecated Ignored: calls never wait for the relay socket. */
|
|
1988
1986
|
firstConnectWaitMs?: number;
|
|
1989
1987
|
/** Close an unused socket after this long. */
|
|
1990
1988
|
idleCloseMs?: number;
|
|
@@ -1999,15 +1997,19 @@ interface RelayReceiverOptions {
|
|
|
1999
1997
|
* Receives backend operation progress over one shared WebSocket and routes it
|
|
2000
1998
|
* to the MCP call that supplied each operation ID.
|
|
2001
1999
|
*
|
|
2002
|
-
*
|
|
2003
|
-
*
|
|
2000
|
+
* Calls never wait for the relay. The relay ID is chosen locally, so a call's
|
|
2001
|
+
* progress headers are known immediately; minting the receive URL and opening
|
|
2002
|
+
* the socket run in the background, and updates are delivered once the socket
|
|
2003
|
+
* joins. Updates published before that are missed, which only affects the
|
|
2004
|
+
* first call of a process. Every failure degrades to "no progress": relay setup
|
|
2005
|
+
* errors back off, socket drops reconnect in the background, and late or
|
|
2006
|
+
* unknown events are dropped.
|
|
2004
2007
|
*/
|
|
2005
2008
|
declare class RelayReceiver implements McpProgressHook {
|
|
2006
2009
|
private readonly options;
|
|
2007
2010
|
private readonly fetchFn;
|
|
2008
2011
|
private readonly createSocket;
|
|
2009
|
-
private readonly
|
|
2010
|
-
private readonly firstConnectWaitMs;
|
|
2012
|
+
private readonly relayId;
|
|
2011
2013
|
private readonly idleCloseMs;
|
|
2012
2014
|
private readonly reconnectBaseMs;
|
|
2013
2015
|
private readonly minRenewDelayMs;
|
|
@@ -2025,6 +2027,11 @@ declare class RelayReceiver implements McpProgressHook {
|
|
|
2025
2027
|
private closed;
|
|
2026
2028
|
constructor(options: RelayReceiverOptions);
|
|
2027
2029
|
begin(notify: (update: McpProgressUpdate) => void): Promise<McpProgressOperation | undefined>;
|
|
2030
|
+
/**
|
|
2031
|
+
* Starts minting and connecting in the background before the first call,
|
|
2032
|
+
* for hosts that know a progress call is about to start. Never waits.
|
|
2033
|
+
*/
|
|
2034
|
+
warm(): void;
|
|
2028
2035
|
/** Stops all timers and closes the socket; later calls get no progress. */
|
|
2029
2036
|
close(): void;
|
|
2030
2037
|
private ensureConnected;
|
|
@@ -2034,6 +2041,7 @@ declare class RelayReceiver implements McpProgressHook {
|
|
|
2034
2041
|
/** A socket that cannot open (e.g. a proxy blocking WebSockets) backs off. */
|
|
2035
2042
|
private socketFailed;
|
|
2036
2043
|
private deliver;
|
|
2044
|
+
/** Mints a receive URL for this receiver's locally chosen relay ID. */
|
|
2037
2045
|
private setup;
|
|
2038
2046
|
private authHeaders;
|
|
2039
2047
|
private serviceHeaders;
|
|
@@ -2046,6 +2054,11 @@ declare class RelayReceiver implements McpProgressHook {
|
|
|
2046
2054
|
private detach;
|
|
2047
2055
|
private clearTimer;
|
|
2048
2056
|
}
|
|
2057
|
+
/** Local animation of MCP progress messages; `false` disables it. */
|
|
2058
|
+
interface McpProgressAnimationOptions {
|
|
2059
|
+
/** Time between frames. Hosts render each frame as a notification. */
|
|
2060
|
+
intervalMs?: number;
|
|
2061
|
+
}
|
|
2049
2062
|
import { z as z3 } from "zod";
|
|
2050
2063
|
/** Annotation fields required by OpenAI's MCP marketplace validation. */
|
|
2051
2064
|
interface CompleteToolAnnotations {
|
|
@@ -2071,8 +2084,11 @@ interface ToolProgressOperation extends ProgressRequest {
|
|
|
2071
2084
|
}
|
|
2072
2085
|
/** Progress already bound to the current MCP request's progress token. */
|
|
2073
2086
|
interface ToolProgress {
|
|
2074
|
-
/**
|
|
2075
|
-
|
|
2087
|
+
/**
|
|
2088
|
+
* Starts progress for one backend call, showing `initialMessage` until the
|
|
2089
|
+
* first live update. Returns `undefined` when progress is unavailable.
|
|
2090
|
+
*/
|
|
2091
|
+
begin(initialMessage?: string): Promise<ToolProgressOperation | undefined>;
|
|
2076
2092
|
}
|
|
2077
2093
|
/** Host-provided execution state shared by MCP and direct tool callers. */
|
|
2078
2094
|
interface ToolExecutionContext {
|
|
@@ -2143,6 +2159,11 @@ interface CreateMcpServerOptions<TExtra = unknown> {
|
|
|
2143
2159
|
traceTool?: McpToolExecutionHook;
|
|
2144
2160
|
/** Optional progress source; used only when the client sends a progress token. */
|
|
2145
2161
|
progress?: McpProgressHook;
|
|
2162
|
+
/**
|
|
2163
|
+
* Animates progress messages locally with the GitHits narrowing mark.
|
|
2164
|
+
* Defaults to on (500 ms frames) when `progress` is set; `false` disables.
|
|
2165
|
+
*/
|
|
2166
|
+
progressAnimation?: McpProgressAnimationOptions | boolean;
|
|
2146
2167
|
}
|
|
2147
2168
|
interface McpToolDescriptor<TSchema extends ZodRawShape = ZodRawShape> {
|
|
2148
2169
|
name: string;
|
|
@@ -2157,9 +2178,38 @@ declare function registerMcpTools<TExtra = unknown>(server: McpServer, options:
|
|
|
2157
2178
|
services: McpToolServicesProvider<TExtra>;
|
|
2158
2179
|
traceTool?: McpToolExecutionHook;
|
|
2159
2180
|
progress?: McpProgressHook;
|
|
2181
|
+
progressAnimation?: McpProgressAnimationOptions | boolean;
|
|
2160
2182
|
}): void;
|
|
2161
2183
|
/**
|
|
2162
2184
|
* Creates the transport-neutral MCP server with injected services.
|
|
2163
2185
|
*/
|
|
2164
2186
|
declare function createMcpServer<TExtra = unknown>(options: CreateMcpServerOptions<TExtra>): McpServer;
|
|
2165
|
-
|
|
2187
|
+
/**
|
|
2188
|
+
* "Narrowing scatter" progress mark: candidate dots converge on one precise
|
|
2189
|
+
* hit, mirroring how research narrows from many sources to specific files and
|
|
2190
|
+
* symbols. Drawn with braille cells (2x4 dots each) so it renders as plain
|
|
2191
|
+
* text in terminals and MCP hosts.
|
|
2192
|
+
*/
|
|
2193
|
+
/** One rendered braille cell; `tone` runs from 0 (dim candidate) to 1 (hit). */
|
|
2194
|
+
interface NarrowingCell {
|
|
2195
|
+
char: string;
|
|
2196
|
+
tone: number;
|
|
2197
|
+
}
|
|
2198
|
+
interface NarrowingFrameOptions {
|
|
2199
|
+
/** Width in braille cells. */
|
|
2200
|
+
width?: number;
|
|
2201
|
+
/** Frames per converge-and-hit cycle. */
|
|
2202
|
+
period?: number;
|
|
2203
|
+
/**
|
|
2204
|
+
* How far the run has narrowed, from 0 (just started) to 1 (answer ready).
|
|
2205
|
+
* Later stages start each cycle from a tighter cluster; 1 holds the hit.
|
|
2206
|
+
*/
|
|
2207
|
+
focus?: number;
|
|
2208
|
+
}
|
|
2209
|
+
/** Renders frame `frame` of the narrowing mark. */
|
|
2210
|
+
declare function narrowingFrame(frame: number, options?: NarrowingFrameOptions): NarrowingCell[];
|
|
2211
|
+
/** Plain-text frame for hosts without colour, such as MCP clients. */
|
|
2212
|
+
declare function narrowingText(frame: number, options?: NarrowingFrameOptions): string;
|
|
2213
|
+
/** How far a backend progress stage has narrowed the work, for `focus`. */
|
|
2214
|
+
declare function focusForStage(stage: string | undefined): number;
|
|
2215
|
+
export { BuildMcpInstructionsOptions, BuildMcpQuickStartOptions, CreateMcpServerOptions, McpAuthAction, McpAuthActionContext, McpProgressAnimationOptions, McpProgressHook, McpProgressOperation, McpProgressUpdate, McpRequestContext, McpServerMetadata, McpToolDescriptor, McpToolExecutionHook, McpToolServices, McpToolServicesProvider, NarrowingCell, NarrowingFrameOptions, RelayAuth, RelayReceiver, RelayReceiverOptions, RelaySocket, ToolExecutionContext, ToolTermsRemediation, buildMcpInstructions, buildMcpQuickStart, createMcpServer, focusForStage, getMcpToolDescriptors, narrowingFrame, narrowingText, registerMcpTools };
|
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-
|
|
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
|
|
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,
|
|
@@ -22,7 +22,7 @@ Match the question, then discover that tool and read its schema before calling.
|
|
|
22
22
|
| Find release notes and changelog history for a package | \`pkg_changelog\` |
|
|
23
23
|
| Compare raw source across package versions or repository refs | \`code_diff\` |
|
|
24
24
|
| Compare current and target dependency versions for an upgrade | \`pkg_upgrade_review\` |
|
|
25
|
-
| Find
|
|
25
|
+
| Find code examples from projects across open source | \`get_example\` |
|
|
26
26
|
| Answer a question about an OSS package or repository with sources | \`research\` |
|
|
27
27
|
| Check progress of an earlier search reference | \`search_status\` |
|
|
28
28
|
|
|
@@ -107,7 +107,7 @@ lacks a detail you need. Sources default to MCP read calls; use
|
|
|
107
107
|
\`source_format:"url"\` for original upstream URLs. Do not invent or rewrite
|
|
108
108
|
sources.`;function buildMcpQuickStart(options={}){const includeExternalContentPosture=options.includeExternalContentPosture??true;return includeExternalContentPosture?`${GUIDE}
|
|
109
109
|
|
|
110
|
-
${EXTERNAL_CONTENT_POSTURE}`:GUIDE}function buildMcpInstructions(options={}){return buildMcpQuickStart(options)}import{McpServer}from"@modelcontextprotocol/sdk/server/mcp.js";import{z}from"zod";var MAX_FILE_ROWS=20;var MAX_PATCH_PREVIEW_BYTES=320;var UTF8_ENCODER=new TextEncoder;function formatCodeDiffMcpText(envelope){const lines=[`Code diff: ${formatTarget(envelope)}`,`Requested endpoints: ${safe(envelope.from.requested)} -> ${safe(envelope.to.requested)}`,`Resolved endpoints: ${formatResolution(envelope.from)} -> ${formatResolution(envelope.to)}`,`Scope: ${formatScope(envelope)}`,`Summary: ${formatSummary(envelope)}`,`Content: ${safe(envelope.contentCoverage)}`];appendWarnings(lines,envelope);const displayTruncatedPreviews=appendFiles(lines,envelope);lines.push(nextAction(envelope,displayTruncatedPreviews));return`${lines.join(`
|
|
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
111
|
`)}
|
|
112
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(`
|
|
113
113
|
`);if(firstEnd<0)return patch;const secondStart=firstEnd+1;const secondEnd=patch.indexOf(`
|
|
@@ -207,4 +207,4 @@ ${CODE_READ_GUARDRAIL}`;function createReadTool(services){return{name:"read",des
|
|
|
207
207
|
|
|
208
208
|
${SEARCH_GUARDRAIL}`;function createSearchTool(service){return{name:"search",description:DESCRIPTION11,schema:schema10,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const effectiveTarget=isBlankSearchTarget(args.target)?undefined:args.target;const resolvedTarget=effectiveTarget?resolveSearchTarget(effectiveTarget,context,args.format):undefined;if(resolvedTarget&&"content"in resolvedTarget)return resolvedTarget;const effectiveTargets=args.targets?.filter((target)=>!isBlankSearchTarget(target));const nonEmptyTargets=effectiveTargets?.length?effectiveTargets:undefined;const resolvedTargets=nonEmptyTargets?.map((entry)=>resolveSearchTarget(entry,context,args.format));const resolvedTargetsError=resolvedTargets?.find((entry)=>("content"in entry));if(resolvedTargetsError){return resolvedTargetsError}const built=buildUnifiedSearchParams({target:resolvedTarget&&!("content"in resolvedTarget)?resolvedTarget:undefined,targets:resolvedTargets?.filter(isResolvedSearchTarget),query:args.query,sources:args.source?[args.source.toUpperCase()]:undefined,publicOnly:args.public_only,allowPartialResults:args.allow_partial_results,limit:args.limit,offset:args.offset,waitTimeoutMs:args.wait_timeout_ms});const outcome=await service.search(built.params,{signal:context?.signal});const payload=buildUnifiedSearchSuccessPayload(built.params,built.rawQuery,built.compiledQuery,outcome);if(isTextFormat7(args.format)){return textResult(renderUnifiedSearchSuccess(payload))}return textResult(JSON.stringify(projectUnifiedSearchSuccessPayload(payload)))}catch(error){throwIfCallerCancellation(error,context?.signal);const basePayload=buildUnifiedSearchErrorPayload(error);const indexingMapped=withIndexingRetryAction({code:basePayload.code,message:basePayload.error,retryable:basePayload.retryable,details:basePayload.details},"search","mcp");const mapped=withVersionRefRecovery(indexingMapped,{syntax:"mcp",tool:"search",args});const payload=addLocalMcpAuthAction({...basePayload,...mapped.details?{details:mapped.details}:{}},context);if(isTextFormat7(args.format)){return errorResult(renderUnifiedSearchError(payload))}return errorResult(JSON.stringify(payload))}}}}function isBlankSearchTarget(target){if(target===undefined)return true;return target.trim().length===0}function isResolvedSearchTarget(target){return!("content"in target)}function resolveSearchTarget(target,context,format){try{return parseUnifiedSearchTargetSpec(target)}catch(error){const mapped=mapCodeNavigationError(error);return mcpMappedErrorResult(mapped,context,format)}}function isTextFormat7(format){return format===undefined||format==="text"}import{z as z12}from"zod";function renderUnifiedSearchStatusText(payload,options={}){const presentation=projectUnifiedSearchPresentation(payload);const result=payload.result;return renderUnifiedSearchPresentationText(presentation,{results:result?.results??[],nextOffset:result?.nextOffset},options)}var schema11={search_ref:z12.string().min(1).describe("The `searchRef` field from a prior `search` response (camelCase in the response, snake_case as this parameter). Pass it through unchanged."),wait_timeout_ms:z12.coerce.number().int().min(0).max(MAX_DISCOVERY_WAIT_TIMEOUT_MS).optional().describe(`Time to wait for results in ms. Default ${DEFAULT_WAIT_TIMEOUT_MS}, max ${MAX_DISCOVERY_WAIT_TIMEOUT_MS}.`),format:z12.enum(["text","json"]).default("text").describe("Omit `format` to use token-efficient text when the model reads the result or chooses follow-up tools. Set `json` only when code consumes the raw response instead of the model, or a required field is absent from text.")};var DESCRIPTION12="Continue an explicit search reference for progress and results. Call this only after a prior `search` response explicitly supplies both a `searchRef` and a `search_status` action; otherwise the initial result is complete or has its own recovery guidance. "+"Pass that response's `searchRef` as `search_ref` here (response field is camelCase; this parameter is snake_case), only for active `PENDING`, `INDEXING`, or `SEARCHING` progress when updated results matter. Visible hits can be used for lookup while indexing continues. Fetch partial hits from a serveable subset when the original request allowed partial results (the default; set `allow_partial_results: false` to require all runnable pairs). `COMPLETED`, `DEFERRED`, `TIMEOUT`, and `FAILED` are terminal; unrecognized statuses are not polled. Preserve any disclosed evidence from those stopped references and follow the rendered new-search action.";function createSearchStatusTool(service){return{name:"search_status",description:DESCRIPTION12,schema:schema11,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const outcome=await service.searchStatus(args.search_ref,args.wait_timeout_ms??DEFAULT_WAIT_TIMEOUT_MS,{signal:context?.signal});const payload=buildUnifiedSearchStatusPayload(outcome);if(isTextFormat8(args.format)){return textResult(renderUnifiedSearchStatusText(payload))}return textResult(JSON.stringify(projectUnifiedSearchStatusPayload(payload)))}catch(error){throwIfCallerCancellation(error,context?.signal);const basePayload=buildUnifiedSearchErrorPayload(error);const mapped=withIndexingRetryAction({code:basePayload.code,message:basePayload.error,retryable:basePayload.retryable,details:basePayload.details},"search","mcp");const payload=addLocalMcpAuthAction({...basePayload,...mapped.details?{details:mapped.details}:{}},context);if(isTextFormat8(args.format)){return errorResult(renderUnifiedSearchError(payload))}return errorResult(JSON.stringify(payload))}}}}function isTextFormat8(format){return format===undefined||format==="text"}var STABLE_MCP_OPERATION_FACTORIES=[(services)=>eraseMcpTool(createGetExampleTool2(services.githitsService)),(services)=>eraseMcpTool(createSearchTool(services.codeNavigationService)),(services)=>eraseMcpTool(createSearchStatusTool(services.codeNavigationService)),(services)=>eraseMcpTool(createListTool(services.listService)),(services)=>eraseMcpTool(createReadTool(services)),(services)=>eraseMcpTool(createGrepTool(services.grepService)),(services)=>eraseMcpTool(createResolveTargetTool2(services.resolveTargetService)),(services)=>eraseMcpTool(createCodeDiffTool(services.codeNavigationService)),(services)=>eraseMcpTool(createPackageSummaryTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageVulnerabilitiesTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageDependenciesTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageChangelogTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createPackageUpgradeReviewTool(services.packageIntelligenceService)),(services)=>eraseMcpTool(createResearchTool2(services.agenticAskService))];function createStableMcpToolFactories(quickStartGuide=buildMcpQuickStart()){return[()=>eraseMcpTool(createQuickStartTool(quickStartGuide)),...STABLE_MCP_OPERATION_FACTORIES]}var STABLE_MCP_TOOL_FACTORIES=createStableMcpToolFactories();function getMcpToolDefinitions(services){return getToolDefinitionsFromFactories(services,STABLE_MCP_TOOL_FACTORIES)}function getToolDefinitionsFromFactories(services,toolFactories){return toolFactories.map((createTool)=>addMcpSessionPrerequisite(createTool(services)))}function addMcpSessionPrerequisite(tool){if(tool.name==="quick_start")return tool;return{...tool,description:`${tool.description}
|
|
209
209
|
|
|
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){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,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,descriptorServices:options.descriptorServices});return server}function bindProgress(hook,extra){const progressToken=extra?._meta?.progressToken;if(!hook||progressToken===undefined||!extra?.sendNotification){return}const{sendNotification}=extra;return{begin:()=>hook.begin(({progress,message})=>{sendNotification({method:"notifications/progress",params:{progressToken,progress,message}}).catch(()=>{})})}}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;connectWaitMs;firstConnectWaitMs;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.connectWaitMs=options.connectWaitMs??1000;this.firstConnectWaitMs=options.firstConnectWaitMs??3000;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())}async begin(notify){if(this.closed||this.now()<this.unavailableUntil)return;this.clearTimer("idleTimer");const wait=this.relay?this.connectWaitMs:this.firstConnectWaitMs;const ready=this.ensureConnected();let waitTimer;await Promise.race([ready,new Promise((resolve)=>{waitTimer=setTimeout(resolve,wait)})]);clearTimeout(waitTimer);const relay=this.relay;if(!relay||this.closed){this.scheduleIdleClose();return}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":relay.relayId,...this.serviceHeaders()},rejected:()=>{this.unavailableUntil=this.now()+UNAVAILABLE_BACKOFF_MS},end:()=>{if(ended)return;ended=true;this.routes.delete(operationId);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(this.relay?.relayId)}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})}catch{}}async setup(relayId){const path=relayId?"/progress/relays/renew":"/progress/relays";const headers={...this.options.clientHeaders?.(),...await this.authHeaders(),"Content-Type":"application/json"};const response=await this.fetchFn(`${this.options.apiUrl.replace(/\/+$/,"")}${path}`,{method:"POST",headers,body:relayId?JSON.stringify({relay_id:relayId}):undefined,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());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){if(!value||typeof value!=="object")return;const body=value;const{relay_id,connection_url,expires_at}=body;if(typeof relay_id!=="string"||typeof connection_url!=="string"||!connection_url.startsWith("wss://")||typeof expires_at!=="number"){return}return{relayId:relay_id.toLowerCase(),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}return{operationId:event.operation_id.toLowerCase(),sequence:event.sequence,message:event.message.slice(0,MAX_MESSAGE_LENGTH)}}function unrefTimer(timer){timer.unref?.()}export{RelayReceiver,buildMcpInstructions,buildMcpQuickStart,createMcpServer,getMcpToolDescriptors,registerMcpTools};
|
|
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};
|
|
@@ -16,16 +16,16 @@ Claims about embargoes, legal restrictions, coordinated disclosure, or disputes
|
|
|
16
16
|
`).includes(details.action))output.push("",...details.action.split(`
|
|
17
17
|
`).map(sanitizeTerminalText));if(!details.action&&mapped.retryable&&!hasRetryGuidance(lines.join(`
|
|
18
18
|
`)))output.push("",rateLimitAdvice?`Try again in ${Math.ceil(retryAfterSeconds)} seconds.`:"Try again.");return output.join(`
|
|
19
|
-
`)}function hasRetryGuidance(message){return/\b(?:retry|try again)\b/i.test(message)}function recoveryList(values,truncated=false){const omitted=Math.max(0,values.length-5);const suffix=truncated?omitted?` (+${omitted}+ more)`:" (+more)":omitted?` (+${omitted} more)`:"";return values.slice(0,5).join(", ")+suffix}var READ_ONLY_TOOL_ANNOTATIONS={readOnlyHint:true,openWorldHint:false,destructiveHint:false};var OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS={readOnlyHint:true,openWorldHint:true,destructiveHint:false};function textResult(text){return{content:[{type:"text",text}]}}function errorResult(message){return{content:[{type:"text",text:message}],isError:true}}var LOCAL_MCP_AUTH_ACTION="Run `githits login`, or set GITHITS_API_TOKEN, then retry this tool call.";var SERVER_MCP_AUTH_ACTION="Re-authenticate with `githits login` or update GITHITS_API_TOKEN if set. If this persists, contact support@githits.com.";async function withErrorHandling(operation,fn,context,format){try{return await fn()}catch(error){throwIfCallerCancellation(error,context?.signal);return mcpMappedErrorResult(mapGitHitsServiceError(operation,error),context,format)}}function mcpMappedErrorResult(mapped,context,format,options){if(options?.recovery)mapped=withVersionRefRecovery(mapped,options.recovery);const payload=buildMcpErrorPayload(mapped,context);return errorResult(format==="json"?JSON.stringify(payload):formatMappedErrorText({...mapped,message:payload.error,details:payload.details},options))}function buildMcpErrorPayload(mapped,context){const termsRemediation=getTermsRemediation(mapped,context);return{error:termsRemediation?.message??mapped.message,code:mapped.code,retryable:mapped.retryable??false,...mapped.code==="AUTH_REQUIRED"||termsRemediation?{details:{...termsRemediation?{action:termsRemediation.action,...mapped.details??{}}:{...mapped.details??{},action:mcpAuthAction(mapped.details?.authSource,context)}}}:mapped.details?{details:mapped.details}:{}}}function addLocalMcpAuthAction(payload,context){const termsRemediation=payload.code==="TERMS_ACCEPTANCE_REQUIRED"?getTermsRemediation(payload,context):undefined;if(payload.code!=="AUTH_REQUIRED"&&!termsRemediation)return payload;return{...payload,details:{...termsRemediation?{action:termsRemediation.action,...payload.details??{}}:{...payload.details??{},action:mcpAuthAction(payload.details?.authSource,context)}},...termsRemediation?{error:termsRemediation.message}:{}}}function mcpAuthAction(authSource,context){const defaultAction=authSource==="server"?SERVER_MCP_AUTH_ACTION:LOCAL_MCP_AUTH_ACTION;const configuredAction=context?.authAction;if(!configuredAction)return defaultAction;if(typeof configuredAction==="string")return configuredAction;return configuredAction({authSource,defaultAction})}function getTermsRemediation(mapped,context){if(mapped.code!=="TERMS_ACCEPTANCE_REQUIRED")return;if(context?.termsRemediation)return context.termsRemediation;const acceptanceUrl=mapped.details?.acceptanceUrl;if(!acceptanceUrl)return;return{message:`Terms acceptance required. Review and accept the current terms at ${acceptanceUrl}, then retry.`,action:acceptanceUrl}}function throwIfCallerCancellation(error,signal){if(signal?.aborted&&(error===signal.reason||isAbortError(error))){throw error}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}import{z}from"zod";var SOLUTION_URL_RE=/solutions\/([0-9a-fA-F-]{36})/;function extractSolutionId(markdown){const match=SOLUTION_URL_RE.exec(markdown);return match?.[1]}var schema={query:z.string().min(1).describe("Natural-language
|
|
19
|
+
`)}function hasRetryGuidance(message){return/\b(?:retry|try again)\b/i.test(message)}function recoveryList(values,truncated=false){const omitted=Math.max(0,values.length-5);const suffix=truncated?omitted?` (+${omitted}+ more)`:" (+more)":omitted?` (+${omitted} more)`:"";return values.slice(0,5).join(", ")+suffix}var READ_ONLY_TOOL_ANNOTATIONS={readOnlyHint:true,openWorldHint:false,destructiveHint:false};var OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS={readOnlyHint:true,openWorldHint:true,destructiveHint:false};function textResult(text){return{content:[{type:"text",text}]}}function errorResult(message){return{content:[{type:"text",text:message}],isError:true}}var LOCAL_MCP_AUTH_ACTION="Run `githits login`, or set GITHITS_API_TOKEN, then retry this tool call.";var SERVER_MCP_AUTH_ACTION="Re-authenticate with `githits login` or update GITHITS_API_TOKEN if set. If this persists, contact support@githits.com.";async function withErrorHandling(operation,fn,context,format){try{return await fn()}catch(error){throwIfCallerCancellation(error,context?.signal);return mcpMappedErrorResult(mapGitHitsServiceError(operation,error),context,format)}}function mcpMappedErrorResult(mapped,context,format,options){if(options?.recovery)mapped=withVersionRefRecovery(mapped,options.recovery);const payload=buildMcpErrorPayload(mapped,context);return errorResult(format==="json"?JSON.stringify(payload):formatMappedErrorText({...mapped,message:payload.error,details:payload.details},options))}function buildMcpErrorPayload(mapped,context){const termsRemediation=getTermsRemediation(mapped,context);return{error:termsRemediation?.message??mapped.message,code:mapped.code,retryable:mapped.retryable??false,...mapped.code==="AUTH_REQUIRED"||termsRemediation?{details:{...termsRemediation?{action:termsRemediation.action,...mapped.details??{}}:{...mapped.details??{},action:mcpAuthAction(mapped.details?.authSource,context)}}}:mapped.details?{details:mapped.details}:{}}}function addLocalMcpAuthAction(payload,context){const termsRemediation=payload.code==="TERMS_ACCEPTANCE_REQUIRED"?getTermsRemediation(payload,context):undefined;if(payload.code!=="AUTH_REQUIRED"&&!termsRemediation)return payload;return{...payload,details:{...termsRemediation?{action:termsRemediation.action,...payload.details??{}}:{...payload.details??{},action:mcpAuthAction(payload.details?.authSource,context)}},...termsRemediation?{error:termsRemediation.message}:{}}}function mcpAuthAction(authSource,context){const defaultAction=authSource==="server"?SERVER_MCP_AUTH_ACTION:LOCAL_MCP_AUTH_ACTION;const configuredAction=context?.authAction;if(!configuredAction)return defaultAction;if(typeof configuredAction==="string")return configuredAction;return configuredAction({authSource,defaultAction})}function getTermsRemediation(mapped,context){if(mapped.code!=="TERMS_ACCEPTANCE_REQUIRED")return;if(context?.termsRemediation)return context.termsRemediation;const acceptanceUrl=mapped.details?.acceptanceUrl;if(!acceptanceUrl)return;return{message:`Terms acceptance required. Review and accept the current terms at ${acceptanceUrl}, then retry.`,action:acceptanceUrl}}function throwIfCallerCancellation(error,signal){if(signal?.aborted&&(error===signal.reason||isAbortError(error))){throw error}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}import{z}from"zod";var SOLUTION_URL_RE=/solutions\/([0-9a-fA-F-]{36})/;function extractSolutionId(markdown){const match=SOLUTION_URL_RE.exec(markdown);return match?.[1]}var schema={query:z.string().min(1).describe("Natural-language query describing the code example you need."),language:z.string().min(1).optional().describe("Optional programming language. Omit to infer it. If GitHits cannot match it, retry with a suggested language from the error, or omit this field."),license_mode:z.enum(["strict","yolo","custom"]).optional().describe("License filtering: `strict` (default) excludes copyleft or undeclared licenses; `custom` uses your account blocklist; `yolo` disables filtering and may return incompatible licenses."),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, or a required field is absent from text.")};var DESCRIPTION=`Find code examples from projects across open source. Use when no single target is the answer: usage patterns, unfamiliar errors, multi-library combinations, or when target-scoped search came up short. Examples come from many unrelated projects; check version-sensitive code against the target's docs or source.
|
|
20
20
|
|
|
21
21
|
Default output is markdown with source repository provenance and generated references, plus a trailing \`solution_id: ...\` when available. JSON returns \`{result, solution_id?}\`.
|
|
22
22
|
|
|
23
|
-
${GET_EXAMPLE_GUARDRAIL}`;function createGetExampleTool2(service){return{name:"get_example",description:DESCRIPTION,schema,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{return withErrorHandling("get example",async()=>{const searchParams={query:args.query,sourceFormat:"mcp",language:args.language,licenseMode:args.license_mode,includeExplanation:false};const progress=await context?.progress?.begin();let markdown;try{markdown=context?.signal||progress?await service.search(searchParams,{...context?.signal?{signal:context.signal}:{},...progress?{progress}:{}}):await service.search(searchParams)}finally{progress?.end()}const solutionId=extractSolutionId(markdown);const payload=solutionId?{result:markdown,solution_id:solutionId}:{result:markdown};if(isTextFormat(args.format)){return textResult(solutionId?`${markdown.trimEnd()}
|
|
23
|
+
${GET_EXAMPLE_GUARDRAIL}`;function createGetExampleTool2(service){return{name:"get_example",description:DESCRIPTION,schema,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{return withErrorHandling("get example",async()=>{const searchParams={query:args.query,sourceFormat:"mcp",language:args.language,licenseMode:args.license_mode,includeExplanation:false};const progress=await context?.progress?.begin("Searching source code and docs…");let markdown;try{markdown=context?.signal||progress?await service.search(searchParams,{...context?.signal?{signal:context.signal}:{},...progress?{progress}:{}}):await service.search(searchParams)}finally{progress?.end()}const solutionId=extractSolutionId(markdown);const payload=solutionId?{result:markdown,solution_id:solutionId}:{result:markdown};if(isTextFormat(args.format)){return textResult(solutionId?`${markdown.trimEnd()}
|
|
24
24
|
|
|
25
|
-
solution_id: ${solutionId}`:markdown)}return textResult(JSON.stringify(payload))},context,args.format)}}}function isTextFormat(format){return format===undefined||format==="text"}var colors={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",red:"\x1B[31m"};function colorize(text,color,useColors){if(!useColors)return text;return`${colors[color]}${text}${colors.reset}`}function highlight(text,useColors){if(!useColors)return text;return`${colors.bold}${colors.cyan}${text}${colors.reset}`}function highlightMatch(text,useColors){if(!useColors)return text;return`${colors.bold}${colors.yellow}${text}${colors.reset}`}function highlightRanges(text,ranges,useColors){if(!useColors||!text||!ranges||ranges.length===0)return text;const normalised=ranges.filter((range)=>Array.isArray(range)&&range.length===2&&Number.isInteger(range[0])&&Number.isInteger(range[1])).map(([start,end])=>{const safeStart=Math.max(0,Math.min(text.length,start));const safeEnd=Math.max(safeStart,Math.min(text.length,end));return[safeStart,safeEnd]}).filter(([start,end])=>end>start).sort((left,right)=>left[0]-right[0]||left[1]-right[1]);if(normalised.length===0)return text;const merged=[];for(const current of normalised){const previous=merged[merged.length-1];if(!previous||current[0]>previous[1]){merged.push(current);continue}merged[merged.length-1]=[previous[0],Math.max(previous[1],current[1])]}let result="";let cursor=0;for(const[start,end]of merged){if(cursor<start)result+=text.slice(cursor,start);result+=highlightMatch(text.slice(start,end),useColors);cursor=end}if(cursor<text.length)result+=text.slice(cursor);return result}function dim(text,useColors){if(!useColors)return text;return`${colors.dim}${text}${colors.reset}`}function mapPackageIntelligenceError(error){return classify2(error)}function classify2(error){if((error instanceof PackageIntelligenceVersionNotFoundError||error instanceof PackageIntelligenceBackendError)&&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 PackageIntelligenceTargetNotFoundError){return{code:"NOT_FOUND",message:error.message,retryable:false}}if(error instanceof PackageIntelligenceDocumentationSectionUnresolvedError){return{code:"DOCUMENTATION_SECTION_UNRESOLVED",message:error.message,retryable:false,details:error.reason?{reason:error.reason}:undefined}}if(error instanceof PackageIntelligenceVersionNotFoundError){const details={};if(error.packageName)details.package=error.packageName;if(error.requestedVersion){details.requestedVersion=error.requestedVersion}if(error.availableVersions&&error.availableVersions.length>0){details.availablePackageVersions=error.availableVersions}return{code:"VERSION_NOT_FOUND",message:error.message,retryable:false,details:Object.keys(details).length>0?details:undefined}}if(error instanceof PackageIntelligenceValidationError){return{code:"INVALID_ARGUMENT",message:error.message,retryable:false}}if(error instanceof PackageIntelligenceAccessError||error instanceof PackageIntelligenceFeatureFlagRequiredError){return{code:"ACCESS_DENIED",message:error.message,retryable:false}}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 PackageIntelligenceNetworkError){return{code:"NETWORK",message:error.message,retryable:true}}if(error instanceof PackageIntelligenceBackendError){return classifyBackendError2(error)}if(error instanceof PackageIntelligenceGraphQLError){return{code:"BACKEND_ERROR",message:error.message,retryable:false,details:error.code?{graphqlCode:error.code}:undefined}}if(error instanceof MalformedPackageIntelligenceResponseError){return{code:"PROTOCOL_ERROR",message:error.message,retryable:false}}if(isInvalidArgumentError2(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 classifyBackendError2(error){const details={};if(typeof error.status==="number")details.status=error.status;if(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);case"UPSTREAM_ERROR":return build("BACKEND_ERROR",true);default:return build("BACKEND_ERROR",false)}}function isInvalidArgumentError2(error){if(!(error instanceof Error))return false;return error.name.startsWith("Invalid")||error.name.startsWith("Unsupported")}function formatCompactNumber(n){if(!Number.isFinite(n)){throw new RangeError(`formatCompactNumber: non-finite input (${String(n)})`)}if(n===0)return"0";const negative=n<0;const abs=Math.abs(n);const formatted=formatAbs(abs);return negative?`-${formatted}`:formatted}function formatAbs(abs){if(abs<1000){return String(Math.trunc(abs))}if(abs<1e6){return withSuffix(abs,1000,"k")}if(abs<1e9){return withSuffix(abs,1e6,"M")}return withSuffix(abs,1e9,"B")}function withSuffix(abs,divisor,suffix){const scaled=abs/divisor;if(scaled<10){const oneDp=Math.floor(scaled*10)/10;return`${oneDp.toFixed(1)}${suffix}`}return`${Math.floor(scaled)}${suffix}`}import{z as z2}from"zod";function mapAgenticAskError(error){const sessionError=mapSessionIdError(error);if(sessionError)return{mapped:sessionError};const termsError=mapTermsAcceptanceError(error);if(termsError)return{mapped:termsError};if(error instanceof AgenticAskHttpError){return{mapped:{code:mapHttpErrorCode(error),message:error.message,retryable:error.retryable,details:{status:error.status,...error.targetError?{targetErrorCode:error.targetError.code,hint:error.targetError.hint,...error.targetError.reason!==undefined?{reason:error.targetError.reason}:{}}:{},...error.retryAfterSeconds!==undefined?{retryAfterSeconds:error.retryAfterSeconds}:{},...error.rateLimitScope!==undefined?{rateLimitScope:error.rateLimitScope}:{},...error.code==="AUTH_REQUIRED"?{authSource:"server"}:{}}},toolCallId:error.toolCallId,threadId:error.threadId}}if(error instanceof AuthenticationError2){return{mapped:{code:"AUTH_REQUIRED",message:error.message,retryable:false,details:{authSource:error.source}}}}if(error instanceof AgenticAskRequestTimeoutError){return{mapped:{code:"TIMEOUT",message:error.message,retryable:true,details:{timeoutMs:error.timeoutMs}}}}if(error instanceof AgenticAskConnectionError){return{mapped:{code:"NETWORK",message:error.message,retryable:true}}}if(error instanceof MalformedAgenticAskResponseError||error instanceof AgenticAskResponseTooLargeError){return{mapped:{code:"PROTOCOL_ERROR",message:error.message,retryable:false}}}return{mapped:{code:"UNKNOWN",message:"Research failed unexpectedly.",retryable:false}}}function mapHttpErrorCode(error){switch(error.code){case"INVALID_TARGET":case"INVALID_REQUEST":return"INVALID_ARGUMENT";case"THREAD_NOT_FOUND":return"NOT_FOUND";case"AUTH_REQUIRED":return"AUTH_REQUIRED";case"ACCESS_DENIED":return"ACCESS_DENIED";case"RATE_LIMITED":return"RATE_LIMITED";case"TIMEOUT":return"TIMEOUT";case"EXECUTION_FAILED":case"SERVICE_UNAVAILABLE":case"HTTP_ERROR":return"BACKEND_ERROR"}}function extractAgenticAskDisplay(response){if(typeof response!=="object"||response===null||!("display_markdown"in response)||typeof response.display_markdown!=="string"){throw new MalformedAgenticAskResponseError}return response.display_markdown}var RESEARCH_VERIFIED_ANSWER_GUIDANCE="Returns a verified answer that always includes its sources, so ask the question directly without requesting citations, an overview or a source-cited answer. Cite those sources directly; read one only when the answer lacks a detail you need.";var schema2={target:z2.string().min(1).optional().describe("Optional canonical open-source package or repository target, such as npm:express or github:expressjs/express. Never a docs site (site:): research covers the project's code and docs. Omit target and thread_id to identify the target from the question."),thread_id:z2.string().min(1).optional().describe("Thread UUID returned by an earlier research call. Cannot be combined with target. Reuse it for follow-ups; name a new project or version in the question to change scope."),question:z2.string().min(1).describe("One research question to answer from indexed public evidence, asked directly; sources are always included. Do not include credentials, personal data, private code, or proprietary content."),source_format:z2.enum(["mcp","url"]).default("mcp").describe("Source pointer format. `mcp` returns read calls for opening a source only when needed; `url` returns original upstream HTTP URLs."),format:z2.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 DESCRIPTION2=`Research a public repository or package to answer a question with sources. Omit target and thread_id to identify the target from the question. If Research returns candidates, retry with the one matching the question's project as target. Supply at most one of target or thread_id. Continue a prior thread by its returned thread_id. Follow-ups can change project, version, or topic; state changes in the question. ${RESEARCH_VERIFIED_ANSWER_GUIDANCE} Sources default to MCP read calls; request source_format=url for original upstream URLs.`;function createResearchTool2(service){return{name:"research",description:DESCRIPTION2,schema:schema2,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{const subject=resolveResearchSubject(args);if("error"in subject){return mcpMappedErrorResult({message:subject.error,code:"INVALID_ARGUMENT",retryable:false},context,args.format)}const progress=await context?.progress?.begin();try{const requestOptions=context?.signal||progress?{...context?.signal?{signal:context.signal}:{},...progress?{progress}:{}}:undefined;const response=args.source_format==="url"?await service.ask({...subject,question:args.question,sourceFormat:"url"},requestOptions):await service.ask({...subject,question:args.question,sourceFormat:"mcp"},requestOptions);return textResult(isTextFormat2(args.format)?formatResearchMcpText(response):JSON.stringify(response))}catch(error){throwIfCallerCancellation(error,context?.signal);const failure=mapAgenticAskError(error);if(isTextFormat2(args.format)){const result=mcpMappedErrorResult(failure.mapped,context,args.format);const locators=[failure.threadId?`Thread: ${sanitizeTerminalText(failure.threadId)}`:undefined,failure.toolCallId?`Tool call: ${sanitizeTerminalText(failure.toolCallId)}`:undefined].filter(Boolean);const content=result.content[0];if(content?.type==="text"&&locators.length)content.text+=`
|
|
25
|
+
solution_id: ${solutionId}`:markdown)}return textResult(JSON.stringify(payload))},context,args.format)}}}function isTextFormat(format){return format===undefined||format==="text"}var colors={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",red:"\x1B[31m"};function colorize(text,color,useColors){if(!useColors)return text;return`${colors[color]}${text}${colors.reset}`}function highlight(text,useColors){if(!useColors)return text;return`${colors.bold}${colors.cyan}${text}${colors.reset}`}function highlightMatch(text,useColors){if(!useColors)return text;return`${colors.bold}${colors.yellow}${text}${colors.reset}`}function highlightRanges(text,ranges,useColors){if(!useColors||!text||!ranges||ranges.length===0)return text;const normalised=ranges.filter((range)=>Array.isArray(range)&&range.length===2&&Number.isInteger(range[0])&&Number.isInteger(range[1])).map(([start,end])=>{const safeStart=Math.max(0,Math.min(text.length,start));const safeEnd=Math.max(safeStart,Math.min(text.length,end));return[safeStart,safeEnd]}).filter(([start,end])=>end>start).sort((left,right)=>left[0]-right[0]||left[1]-right[1]);if(normalised.length===0)return text;const merged=[];for(const current of normalised){const previous=merged[merged.length-1];if(!previous||current[0]>previous[1]){merged.push(current);continue}merged[merged.length-1]=[previous[0],Math.max(previous[1],current[1])]}let result="";let cursor=0;for(const[start,end]of merged){if(cursor<start)result+=text.slice(cursor,start);result+=highlightMatch(text.slice(start,end),useColors);cursor=end}if(cursor<text.length)result+=text.slice(cursor);return result}function dim(text,useColors){if(!useColors)return text;return`${colors.dim}${text}${colors.reset}`}function mapPackageIntelligenceError(error){return classify2(error)}function classify2(error){if((error instanceof PackageIntelligenceVersionNotFoundError||error instanceof PackageIntelligenceBackendError)&&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 PackageIntelligenceTargetNotFoundError){return{code:"NOT_FOUND",message:error.message,retryable:false}}if(error instanceof PackageIntelligenceDocumentationSectionUnresolvedError){return{code:"DOCUMENTATION_SECTION_UNRESOLVED",message:error.message,retryable:false,details:error.reason?{reason:error.reason}:undefined}}if(error instanceof PackageIntelligenceVersionNotFoundError){const details={};if(error.packageName)details.package=error.packageName;if(error.requestedVersion){details.requestedVersion=error.requestedVersion}if(error.availableVersions&&error.availableVersions.length>0){details.availablePackageVersions=error.availableVersions}return{code:"VERSION_NOT_FOUND",message:error.message,retryable:false,details:Object.keys(details).length>0?details:undefined}}if(error instanceof PackageIntelligenceValidationError){return{code:"INVALID_ARGUMENT",message:error.message,retryable:false}}if(error instanceof PackageIntelligenceAccessError||error instanceof PackageIntelligenceFeatureFlagRequiredError){return{code:"ACCESS_DENIED",message:error.message,retryable:false}}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 PackageIntelligenceNetworkError){return{code:"NETWORK",message:error.message,retryable:true}}if(error instanceof PackageIntelligenceBackendError){return classifyBackendError2(error)}if(error instanceof PackageIntelligenceGraphQLError){return{code:"BACKEND_ERROR",message:error.message,retryable:false,details:error.code?{graphqlCode:error.code}:undefined}}if(error instanceof MalformedPackageIntelligenceResponseError){return{code:"PROTOCOL_ERROR",message:error.message,retryable:false}}if(isInvalidArgumentError2(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 classifyBackendError2(error){const details={};if(typeof error.status==="number")details.status=error.status;if(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);case"UPSTREAM_ERROR":return build("BACKEND_ERROR",true);default:return build("BACKEND_ERROR",false)}}function isInvalidArgumentError2(error){if(!(error instanceof Error))return false;return error.name.startsWith("Invalid")||error.name.startsWith("Unsupported")}function formatCompactNumber(n){if(!Number.isFinite(n)){throw new RangeError(`formatCompactNumber: non-finite input (${String(n)})`)}if(n===0)return"0";const negative=n<0;const abs=Math.abs(n);const formatted=formatAbs(abs);return negative?`-${formatted}`:formatted}function formatAbs(abs){if(abs<1000){return String(Math.trunc(abs))}if(abs<1e6){return withSuffix(abs,1000,"k")}if(abs<1e9){return withSuffix(abs,1e6,"M")}return withSuffix(abs,1e9,"B")}function withSuffix(abs,divisor,suffix){const scaled=abs/divisor;if(scaled<10){const oneDp=Math.floor(scaled*10)/10;return`${oneDp.toFixed(1)}${suffix}`}return`${Math.floor(scaled)}${suffix}`}import{z as z2}from"zod";function mapAgenticAskError(error){const sessionError=mapSessionIdError(error);if(sessionError)return{mapped:sessionError};const termsError=mapTermsAcceptanceError(error);if(termsError)return{mapped:termsError};if(error instanceof AgenticAskHttpError){return{mapped:{code:mapHttpErrorCode(error),message:error.message,retryable:error.retryable,details:{status:error.status,...error.targetError?{targetErrorCode:error.targetError.code,hint:error.targetError.hint,...error.targetError.reason!==undefined?{reason:error.targetError.reason}:{}}:{},...error.retryAfterSeconds!==undefined?{retryAfterSeconds:error.retryAfterSeconds}:{},...error.rateLimitScope!==undefined?{rateLimitScope:error.rateLimitScope}:{},...error.code==="AUTH_REQUIRED"?{authSource:"server"}:{}}},toolCallId:error.toolCallId,threadId:error.threadId}}if(error instanceof AuthenticationError2){return{mapped:{code:"AUTH_REQUIRED",message:error.message,retryable:false,details:{authSource:error.source}}}}if(error instanceof AgenticAskRequestTimeoutError){return{mapped:{code:"TIMEOUT",message:error.message,retryable:true,details:{timeoutMs:error.timeoutMs}}}}if(error instanceof AgenticAskConnectionError){return{mapped:{code:"NETWORK",message:error.message,retryable:true}}}if(error instanceof MalformedAgenticAskResponseError||error instanceof AgenticAskResponseTooLargeError){return{mapped:{code:"PROTOCOL_ERROR",message:error.message,retryable:false}}}return{mapped:{code:"UNKNOWN",message:"Research failed unexpectedly.",retryable:false}}}function mapHttpErrorCode(error){switch(error.code){case"INVALID_TARGET":case"INVALID_REQUEST":return"INVALID_ARGUMENT";case"THREAD_NOT_FOUND":return"NOT_FOUND";case"AUTH_REQUIRED":return"AUTH_REQUIRED";case"ACCESS_DENIED":return"ACCESS_DENIED";case"RATE_LIMITED":return"RATE_LIMITED";case"TIMEOUT":return"TIMEOUT";case"EXECUTION_FAILED":case"SERVICE_UNAVAILABLE":case"HTTP_ERROR":return"BACKEND_ERROR"}}function extractAgenticAskDisplay(response){if(typeof response!=="object"||response===null||!("display_markdown"in response)||typeof response.display_markdown!=="string"){throw new MalformedAgenticAskResponseError}return response.display_markdown}var RESEARCH_VERIFIED_ANSWER_GUIDANCE="Returns a verified answer that always includes its sources, so ask the question directly without requesting citations, an overview or a source-cited answer. Cite those sources directly; read one only when the answer lacks a detail you need.";var schema2={target:z2.string().min(1).optional().describe("Optional canonical open-source package or repository target, such as npm:express or github:expressjs/express. Never a docs site (site:): research covers the project's code and docs. Omit target and thread_id to identify the target from the question."),thread_id:z2.string().min(1).optional().describe("Thread UUID returned by an earlier research call. Cannot be combined with target. Reuse it for follow-ups; name a new project or version in the question to change scope."),question:z2.string().min(1).describe("One research question to answer from indexed public evidence, asked directly; sources are always included. Do not include credentials, personal data, private code, or proprietary content."),source_format:z2.enum(["mcp","url"]).default("mcp").describe("Source pointer format. `mcp` returns read calls for opening a source only when needed; `url` returns original upstream HTTP URLs."),format:z2.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 DESCRIPTION2=`Research a public repository or package to answer a question with sources. Omit target and thread_id to identify the target from the question. If Research returns candidates, retry with the one matching the question's project as target. Supply at most one of target or thread_id. Continue a prior thread by its returned thread_id. Follow-ups can change project, version, or topic; state changes in the question. ${RESEARCH_VERIFIED_ANSWER_GUIDANCE} Sources default to MCP read calls; request source_format=url for original upstream URLs.`;function createResearchTool2(service){return{name:"research",description:DESCRIPTION2,schema:schema2,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{const subject=resolveResearchSubject(args);if("error"in subject){return mcpMappedErrorResult({message:subject.error,code:"INVALID_ARGUMENT",retryable:false},context,args.format)}const progress=await context?.progress?.begin(openingResearchMessage("target"in subject?subject.target:undefined));try{const requestOptions=context?.signal||progress?{...context?.signal?{signal:context.signal}:{},...progress?{progress}:{}}:undefined;const response=args.source_format==="url"?await service.ask({...subject,question:args.question,sourceFormat:"url"},requestOptions):await service.ask({...subject,question:args.question,sourceFormat:"mcp"},requestOptions);return textResult(isTextFormat2(args.format)?formatResearchMcpText(response):JSON.stringify(response))}catch(error){throwIfCallerCancellation(error,context?.signal);const failure=mapAgenticAskError(error);if(isTextFormat2(args.format)){const result=mcpMappedErrorResult(failure.mapped,context,args.format);const locators=[failure.threadId?`Thread: ${sanitizeTerminalText(failure.threadId)}`:undefined,failure.toolCallId?`Tool call: ${sanitizeTerminalText(failure.toolCallId)}`:undefined].filter(Boolean);const content=result.content[0];if(content?.type==="text"&&locators.length)content.text+=`
|
|
26
26
|
|
|
27
27
|
${locators.join(`
|
|
28
|
-
`)}`;return result}return errorResult(JSON.stringify({...buildMcpErrorPayload(failure.mapped,context),...failure.toolCallId?{tool_call_id:failure.toolCallId}:{},...failure.threadId?{thread_id:failure.threadId}:{}}))}finally{progress?.end()}}}}function formatResearchMcpText(response){return extractAgenticAskDisplay(response)}function isTextFormat2(format){return format===undefined||format==="text"}function resolveResearchSubject(args){if(args.target!==undefined&&args.thread_id!==undefined){return{error:"Provide at most one of target or thread_id."}}if(args.target!==undefined){if(isRepositoryTargetSpec(args.target)){try{parseRepositoryTargetSpec(args.target)}catch(error){if(error instanceof LegacyRepositoryRefError){return{error:error.message}}}}return{target:args.target}}if(args.thread_id===undefined)return{};const threadId=normalizeAgenticAskThreadId(args.thread_id);return threadId?{threadId}:{error:"thread_id must be one valid thread UUID."}}import{z as z3}from"zod";function parseUnifiedSearchTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidArgumentError("Target spec cannot be empty.")}if(isSiteTargetSpec(trimmed)){return{site:normaliseSiteTargetSpec(trimmed)}}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}}function isSiteTargetSpec(spec){return spec.toLowerCase().startsWith("site:")}function normaliseSiteTargetSpec(spec){const value=spec.slice("site:".length).trim();if(value.length===0){throw new InvalidArgumentError("Site target cannot be empty. Expected site:<host[/path]> for an exact documentation site.")}let host;let path;try{if(/^https?:\/\//i.test(value)){const url=new URL(value);host=url.host;path=url.pathname}else{const slashIndex=value.indexOf("/");host=slashIndex===-1?value:value.slice(0,slashIndex);path=slashIndex===-1?"":value.slice(slashIndex)}}catch{throw new InvalidArgumentError(`Invalid site target ${JSON.stringify(spec)}. Expected site:<host[/path]> or site:https://<host[/path]>.`)}const canonical=`${host.toLowerCase()}${path}`.replace(/\/+$/,"");if(canonical.length===0||/\s/.test(canonical)){throw new InvalidArgumentError(`Invalid site target ${JSON.stringify(spec)}. Expected site:<host[/path]> for an exact documentation site.`)}return`site:${canonical}`}var RESOLVE_TARGET_DEFAULT_LIMIT=8;var RESOLVE_TARGET_MAX_LIMIT=20;function buildResolveTargetParams(input){const name=input.name?.trim()??"";if(!name)throw new InvalidPackageSpecError("Target name is required.");rejectCanonicalTarget(name);const limit=input.limit??RESOLVE_TARGET_DEFAULT_LIMIT;if(!Number.isInteger(limit)||limit<1||limit>RESOLVE_TARGET_MAX_LIMIT){throw new InvalidPackageSpecError(`limit expects an integer between 1 and ${RESOLVE_TARGET_MAX_LIMIT}. Got ${String(limit)}.`)}const params={name,limit,includeDetailedFields:input.includeDetailedFields,includeNameSimilarity:input.includeNameSimilarity??false};const query=input.query?.trim();if(query)params.query=query;const registries=parseRegistries(input.registries??input.registry);if(registries.length>0)params.registries=registries;const preferredKind=parsePreferredKind(input.preferKind);if(preferredKind)params.preferredKinds=[preferredKind];const intentHints=normaliseStrings(input.intentHints);if(intentHints.length>0)params.intentHints=intentHints;return params}function rejectCanonicalTarget(name){if(isRepositoryTargetSpec(name)){try{const parsed=parseRepositoryTargetSpec(name);if(parsed.repoUrl&&!isCanonicalRepositoryUrl(parsed.repoUrl))return}catch(error){if(error instanceof LegacyRepositoryRefError)throw error;if(error instanceof InvalidArgumentError)return;throw error}throw canonicalTargetError(name)}try{parseUnifiedSearchTargetSpec(name)}catch(error){if(error instanceof InvalidArgumentError)return;throw error}throw canonicalTargetError(name)}function canonicalTargetError(name){return new InvalidArgumentError(`Canonical target ${JSON.stringify(name)} does not need resolution. Pass it directly to the next GitHits tool.`)}function parseRegistries(value){if(value===undefined)return[];const registries=[];const values=Array.isArray(value)?value:value.split(",");for(const raw of values){const trimmed=raw.trim();if(!trimmed)continue;const registry=parsePkgseerRegistryArg(trimmed);if(!registry){throw new InvalidPackageSpecError(`Unsupported registry '${trimmed}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const mapped=toPkgseerRegistry2(registry);if(!registries.includes(mapped))registries.push(mapped)}return registries}function parsePreferredKind(value){const kind=value?.trim().toLowerCase();if(!kind)return;if(kind==="package")return"PACKAGE";if(kind==="repository")return"REPOSITORY";if(kind==="site")return"SITE";throw new InvalidPackageSpecError(`Preferred kind expects package, repository, or site. Got '${value}'.`)}function normaliseStrings(values){const result=[];const seen=new Set;for(const raw of values??[]){const value=raw.trim();const key=value.toLowerCase();if(!value||seen.has(key))continue;seen.add(key);result.push(value)}return result}function buildResolveTargetSuccessPayload(result){const candidates=result.targets.map(projectTarget);const payload={ambiguous:result.ambiguous,candidates,protectedMatches:dedupeTargets(result.protectedMatches).map((target)=>target.canonicalKey),targetsTruncated:result.targetsTruncated};if(result.best)payload.best=result.best.canonicalKey;if(result.ambiguous){payload.ambiguousReason=result.ambiguousReason.toLowerCase()}return payload}function projectTarget(target){const payload={target:target.canonicalKey,kind:target.kind.toLowerCase(),direct:target.match!==undefined};assign(payload,"confidence",target.match?.confidence.toLowerCase());assign(payload,"groupKey",target.groupKey);assign(payload,"name",target.displayName);assign(payload,"description",target.description);assign(payload,"registry",target.registry?.toLowerCase());assign(payload,"packageName",target.packageName);assign(payload,"latestVersion",target.latestVersion);assign(payload,"latestVersionMaliciousStatus",target.latestVersionMaliciousStatus.toLowerCase());if(target.latestVersionMaliciousEvidence){payload.latestVersionMaliciousEvidence={advisories:target.latestVersionMaliciousEvidence.advisories.map((advisory)=>({osvId:advisory.osvId,classificationReasons:advisory.classificationReasons.map((reason)=>reason.toLowerCase())})),totalCount:target.latestVersionMaliciousEvidence.totalCount,truncated:target.latestVersionMaliciousEvidence.truncated}}assign(payload,"repositoryUrl",target.repositoryUrl);assign(payload,"repositoryOwner",target.repositoryOwner);assign(payload,"repositoryName",target.repositoryName);assign(payload,"stars",target.stars);assign(payload,"downloadsLastMonth",target.downloadsLastMonth);assign(payload,"downloadsTotal",target.downloadsTotal);assign(payload,"documentationUrl",target.documentationUrl);assign(payload,"matchedAliases",target.match?.matchedAliases);assign(payload,"docsAvailable",target.docsAvailable);assign(payload,"codeAvailable",target.codeAvailable);assign(payload,"nameSimilarity",target.match?.nameSimilarity);assign(payload,"docsPageCount",target.docsPageCount);assign(payload,"codeFileCount",target.codeFileCount);assign(payload,"license",target.license);assign(payload,"matchTier",target.match?.matchTier);assign(payload,"score",target.match?.score);return payload}function groupResolveTargets(targets){const groups=[];for(const target of targets){const previous=groups.at(-1);if(target.groupKey!==undefined&&previous?.groupKey===target.groupKey){previous.targets.push(target)}else{groups.push({...target.groupKey!==undefined?{groupKey:target.groupKey}:{},targets:[target]})}}return groups}function buildResolveTargetEvidencePlan(targets,includeNameSimilarity=false){const hasRepositoryTarget=targets.some((target)=>target.kind==="REPOSITORY");const hasSiteTarget=targets.some((target)=>target.kind==="SITE");const hasPackageLicense=targets.some((target)=>target.kind==="PACKAGE"&&formatLicense(target.license)!==undefined);return(target)=>{switch(target.kind){case"PACKAGE":return{stars:!hasRepositoryTarget,downloads:true,repository:!hasRepositoryTarget,license:true,docs:!hasSiteTarget,code:true,nameSimilarity:includeNameSimilarity};case"REPOSITORY":return{stars:true,downloads:false,repository:false,license:!hasPackageLicense,docs:false,code:true,nameSimilarity:includeNameSimilarity};case"SITE":return{stars:false,downloads:false,repository:false,license:false,docs:true,code:false,nameSimilarity:includeNameSimilarity};default:return{stars:true,downloads:true,repository:true,license:true,docs:true,code:true,nameSimilarity:includeNameSimilarity}}}}function isResolveTargetActionable(result){return isResolveTargetIdentityActionable(result)&&isLatestVersionMaliciousStatusActionable(findResolveTargetBestTarget(result)?.latestVersionMaliciousStatus)}var KNOWN_CONFIDENCE_VALUES=new Set(["exact","high","medium","low"]);var KNOWN_KIND_VALUES=new Set(["package","repository","site"]);function formatResolveTargetEvidence(target,options){const fields=[];if(options.stars&&target.stars!==undefined){fields.push(`${formatCompactNumber(target.stars)} stars`)}if(options.downloads&&target.downloadsLastMonth!==undefined){fields.push(`${formatCompactNumber(target.downloadsLastMonth)} downloads/mo`)}else if(options.downloads&&target.downloadsTotal!==undefined){fields.push(`${formatCompactNumber(target.downloadsTotal)} downloads`)}if(options.repository&&target.kind==="PACKAGE"&&target.repositoryUrl){fields.push(`repo ${compactRepositoryUrl(target.repositoryUrl)}`)}const license=options.license?formatLicense(target.license):undefined;if(license)fields.push(`license ${license}`);const docs=options.docs&&target.kind==="SITE"&&!target.docsAvailable?"docs: crawled on demand":formatDocsAvailability(target.docsAvailable,target.docsPageCount,options.docs&&target.kind!=="REPOSITORY");if(docs)fields.push(docs);const code=formatResolveTargetCodeAvailability(target,options.code&&target.kind!=="SITE");if(code)fields.push(code);const nameSimilarity=options.nameSimilarity?formatResolveTargetNameSimilarity(target.match?.nameSimilarity):undefined;if(nameSimilarity)fields.push(nameSimilarity);return fields.map(sanitizeTerminalText).join(" · ")}function formatResolveTargetCodeAvailability(target,applicable=true){if(!applicable||!target.codeAvailable)return;const scope=target.kind==="PACKAGE"?"indexed package snapshot":target.kind==="REPOSITORY"?"indexed repository snapshot":"indexed code snapshot";return target.codeFileCount===undefined?scope:`${scope} (${formatCompactNumber(target.codeFileCount)} files)`}function formatResolveTargetNameSimilarity(value){return value===undefined?undefined:`${Math.round(value*100)}% name similarity`}function formatResolveTargetEvidenceNotes(targets,includeNameSimilarity=false){const notes=[];if(includeNameSimilarity&&targets.some((target)=>target.match?.nameSimilarity!==undefined)){notes.push("Name similarity is coarse lexical support; candidate order follows broader backend policy.")}return notes}function formatLicense(value){const license=sanitizeTerminalText(value??"").trim();if(!license)return;return license==="mit"?"MIT":license}function formatDocsAvailability(available,count,applicable){if(!applicable||!available)return;if(count!==undefined){return`docs ${formatCompactNumber(count)} pages`}return"docs available"}function formatLatestVersionMaliciousStatus(status,evidence){switch(status){case"AFFECTED":return withMaliciousEvidence("Malicious content affects the latest version","Do not use the latest version. Verify another version against the linked evidence.",evidence,false);case"UNKNOWN":return withMaliciousEvidence("Malicious-content status is uncertain","Verify the advisory details before using this version.",evidence,true);case"CLEAR":case"NOT_APPLICABLE":case undefined:return;default:return`Unrecognized malicious-content status: ${sanitizeTerminalText(status)}. Do not use this target.`}}function withMaliciousEvidence(message,guidance,evidence,includeReasons){if(!evidence||evidence.advisories.length===0){return`${message}. ${guidance}`}const details=evidence.advisories.map((advisory)=>{const id=sanitizeTerminalText(advisory.osvId);const reasons=includeReasons?formatMaliciousClassificationReasons(advisory.classificationReasons):undefined;const label=reasons?`${id} (${reasons})`:id;return`${label}: https://osv.dev/vulnerability/${encodeURIComponent(advisory.osvId)}`});const omitted=evidence.totalCount-evidence.advisories.length;if(evidence.truncated&&omitted>0)details.push(`+${omitted} more`);return`${message} — ${details.join("; ")}. ${guidance}`}var MALICIOUS_CLASSIFICATION_REASON_LABELS={AFFECTED_VERSION_RANGE_MATCH:"affected range matched",MISSING_DISPLAYED_VERSION:"latest version missing",INVALID_DISPLAYED_VERSION:"latest version invalid",MISSING_AFFECTED_RANGES:"affected ranges missing",EMPTY_AFFECTED_RANGES:"affected ranges empty",INVALID_AFFECTED_RANGE:"affected range invalid"};function formatMaliciousClassificationReasons(reasons){if(reasons.length===0)return;return reasons.map((reason)=>MALICIOUS_CLASSIFICATION_REASON_LABELS[reason]??`unrecognized reason ${sanitizeTerminalText(reason)}`).join(", ")}function isResolveTargetIdentityActionable(result){return!result.ambiguous&&result.best!==undefined&&(result.best.confidence==="EXACT"||result.best.confidence==="HIGH")}function isLatestVersionMaliciousStatusActionable(status){return status==="CLEAR"||status==="NOT_APPLICABLE"}function findResolveTargetBestTarget(result){if(!result.best)return;const best=result.best;return result.targets.find((target)=>target.kind===best.kind&&target.canonicalKey===best.canonicalKey)}function compactRepositoryUrl(value){return sanitizeTerminalText(formatRepositoryTarget(value))}function dedupeTargets(candidates){const seen=new Set;return candidates.filter((candidate)=>{const key=targetKey(candidate);if(seen.has(key))return false;seen.add(key);return true})}function targetKey(candidate){return`${candidate.kind}:${candidate.canonicalKey}`}function assign(target,key,value){if(value!==undefined)target[key]=value}var schema3={name:z3.string().describe("Human-friendly package, repository, or standalone documentation-site name to resolve, including mutable Launchpad defaults such as lp:PROJECT. Do not use canonical registry:name, github:owner/repo, codeberg:owner/repo, gitlab:group/subgroup/project, launchpad:~owner/+git/repo, or site:<host[/path]> targets."),query:z3.string().optional().describe("Optional task context used to rank retrieved candidates and does not expand candidate retrieval. Do not include credentials, personal data, private code, or proprietary content."),registries:z3.array(z3.string()).optional().describe(`Optional registry filter that constrains package candidates only; repository and site candidates remain eligible. Accepted registries: ${PKGSEER_REGISTRY_LIST2}. An empty list deliberately means no filter.`),preferred_kind:z3.string().optional().describe("Optional preference: package, repository, or site. An empty string means no preference; other values are rejected as invalid arguments."),intent_hints:z3.array(z3.string()).optional().describe("Optional hints that rank retrieved candidates and do not expand candidate retrieval. Empty, blank, and duplicate hints are ignored. Do not include credentials, personal data, private code, or proprietary content."),limit:z3.number().optional().describe("Optional integer candidate limit from 1 through 20."),verbose:z3.boolean().optional().describe("When true, text output includes coarse lexical name-similarity evidence. Default false. JSON always includes available numeric similarity."),format:z3.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 DESCRIPTION3='Resolve OSS dependency names to canonical package, repository, or docs targets. Use known canonical targets directly. Only a non-ambiguous EXACT or HIGH best with CLEAR or NOT_APPLICABLE malicious-content status permits direct continuation; other or missing statuses are non-actionable. CLEAR is not a vulnerability-free claim. MEDIUM and LOW require narrowing or an explicit choice; never auto-select an ambiguous result. A selected `site:` is docs-only: use `list` or `search` with `source: "docs"`, then reuse returned read locators. Inputs leave this machine; open-source targets only.';function createResolveTargetTool2(service){return{name:"resolve_target",description:DESCRIPTION3,schema:schema3,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const textFormat=isTextFormat3(args.format);const params=buildResolveTargetParams({name:args.name,query:args.query,registries:args.registries,preferKind:args.preferred_kind,intentHints:args.intent_hints,limit:args.limit,includeDetailedFields:!textFormat,includeNameSimilarity:args.verbose===true||!textFormat});const result=await service.resolveTarget(params,...serviceRequestArgs(context?.signal));if(textFormat){return textResult(formatResolveTargetMcpText(result,{name:params.name,verbose:args.verbose}))}return textResult(JSON.stringify(buildResolveTargetSuccessPayload(result)))}catch(error){throwIfCallerCancellation(error,context?.signal);return mcpMappedErrorResult(mapPackageIntelligenceError(error),context,args.format,{recovery:{syntax:"mcp",tool:"resolve_target",args}})}}}}function formatResolveTargetMcpText(result,options){const actionable=isResolveTargetActionable(result);const identityActionable=isResolveTargetIdentityActionable(result);const bestTarget=findResolveTargetBestTarget(result);const blockedBest=identityActionable&&!actionable;const protectedKeys=new Set(result.protectedMatches.map((target)=>targetKey2(target)));const hasBlockedDirectTarget=result.targets.some((target)=>target.match!==undefined&&!isLatestVersionMaliciousStatusActionable(target.latestVersionMaliciousStatus));const groups=groupResolveTargets(result.targets);const lines=[];if(result.ambiguous){lines.push(`Ambiguous: ${formatAmbiguousReason(result.ambiguousReason)}`)}else if(actionable&&result.best){lines.push(`Best match: ${formatReference(result.best)}.`)}else if(blockedBest&&result.best){lines.push(`Best identity match: ${formatReference(result.best)}.`)}else if(!result.best){lines.push(`No targets found for "${sanitizeTerminalText(options.name)}".`)}if(groups.length>0){lines.push("Targets:");groups.forEach((group,index)=>{lines.push(...formatMcpGroup(group.targets,index+1,protectedKeys,options.verbose===true))})}if(result.targetsTruncated){lines.push("Note: Additional related targets were omitted; direct matches are complete.")}lines.push(...formatResolveTargetEvidenceNotes(result.targets,options.verbose===true));if(blockedBest){if(!bestTarget){lines.push("Warning: Malicious-content status is unavailable for the best match. Do not use this target.")}}else if(result.ambiguous&&hasBlockedDirectTarget){lines.push("Warning: Some candidates are not actionable. Narrow the result before continuing.")}else if(result.ambiguous){lines.push("Next: narrow the name or filters, or explicitly choose a candidate; pass its exact canonical target to the next MCP tool, never auto-select.")}else if(actionable&&result.best){const target=sanitizeTerminalText(result.best.canonicalKey);lines.push(result.best.kind==="SITE"?`Next: call search with target "${target}" and source "docs", then call read for relevant results.`:`Next: pass the canonical target "${target}" to the next MCP tool.`)}else if(result.best&&hasBlockedDirectTarget){lines.push("Warning: Some candidates are not actionable. Narrow the result before continuing.")}else if(result.best){lines.push("Next: narrow the name or filters, or explicitly choose a candidate; never auto-select the best match.")}else{lines.push("Next: check spelling or registry filters; query, preferred kind, and intent hints only rank existing candidates.")}return`${lines.join(`
|
|
28
|
+
`)}`;return result}return errorResult(JSON.stringify({...buildMcpErrorPayload(failure.mapped,context),...failure.toolCallId?{tool_call_id:failure.toolCallId}:{},...failure.threadId?{thread_id:failure.threadId}:{}}))}finally{progress?.end()}}}}function formatResearchMcpText(response){return extractAgenticAskDisplay(response)}function isTextFormat2(format){return format===undefined||format==="text"}function resolveResearchSubject(args){if(args.target!==undefined&&args.thread_id!==undefined){return{error:"Provide at most one of target or thread_id."}}if(args.target!==undefined){if(isRepositoryTargetSpec(args.target)){try{parseRepositoryTargetSpec(args.target)}catch(error){if(error instanceof LegacyRepositoryRefError){return{error:error.message}}}}return{target:args.target}}if(args.thread_id===undefined)return{};const threadId=normalizeAgenticAskThreadId(args.thread_id);return threadId?{threadId}:{error:"thread_id must be one valid thread UUID."}}function openingResearchMessage(target){return target&&/^[A-Za-z0-9][A-Za-z0-9@/._:+#~-]{0,79}$/.test(target)?`Resolving ${target}…`:"Researching…"}import{z as z3}from"zod";function parseUnifiedSearchTargetSpec(spec){const trimmed=spec.trim();if(trimmed.length===0){throw new InvalidArgumentError("Target spec cannot be empty.")}if(isSiteTargetSpec(trimmed)){return{site:normaliseSiteTargetSpec(trimmed)}}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}}function isSiteTargetSpec(spec){return spec.toLowerCase().startsWith("site:")}function normaliseSiteTargetSpec(spec){const value=spec.slice("site:".length).trim();if(value.length===0){throw new InvalidArgumentError("Site target cannot be empty. Expected site:<host[/path]> for an exact documentation site.")}let host;let path;try{if(/^https?:\/\//i.test(value)){const url=new URL(value);host=url.host;path=url.pathname}else{const slashIndex=value.indexOf("/");host=slashIndex===-1?value:value.slice(0,slashIndex);path=slashIndex===-1?"":value.slice(slashIndex)}}catch{throw new InvalidArgumentError(`Invalid site target ${JSON.stringify(spec)}. Expected site:<host[/path]> or site:https://<host[/path]>.`)}const canonical=`${host.toLowerCase()}${path}`.replace(/\/+$/,"");if(canonical.length===0||/\s/.test(canonical)){throw new InvalidArgumentError(`Invalid site target ${JSON.stringify(spec)}. Expected site:<host[/path]> for an exact documentation site.`)}return`site:${canonical}`}var RESOLVE_TARGET_DEFAULT_LIMIT=8;var RESOLVE_TARGET_MAX_LIMIT=20;function buildResolveTargetParams(input){const name=input.name?.trim()??"";if(!name)throw new InvalidPackageSpecError("Target name is required.");rejectCanonicalTarget(name);const limit=input.limit??RESOLVE_TARGET_DEFAULT_LIMIT;if(!Number.isInteger(limit)||limit<1||limit>RESOLVE_TARGET_MAX_LIMIT){throw new InvalidPackageSpecError(`limit expects an integer between 1 and ${RESOLVE_TARGET_MAX_LIMIT}. Got ${String(limit)}.`)}const params={name,limit,includeDetailedFields:input.includeDetailedFields,includeNameSimilarity:input.includeNameSimilarity??false};const query=input.query?.trim();if(query)params.query=query;const registries=parseRegistries(input.registries??input.registry);if(registries.length>0)params.registries=registries;const preferredKind=parsePreferredKind(input.preferKind);if(preferredKind)params.preferredKinds=[preferredKind];const intentHints=normaliseStrings(input.intentHints);if(intentHints.length>0)params.intentHints=intentHints;return params}function rejectCanonicalTarget(name){if(isRepositoryTargetSpec(name)){try{const parsed=parseRepositoryTargetSpec(name);if(parsed.repoUrl&&!isCanonicalRepositoryUrl(parsed.repoUrl))return}catch(error){if(error instanceof LegacyRepositoryRefError)throw error;if(error instanceof InvalidArgumentError)return;throw error}throw canonicalTargetError(name)}try{parseUnifiedSearchTargetSpec(name)}catch(error){if(error instanceof InvalidArgumentError)return;throw error}throw canonicalTargetError(name)}function canonicalTargetError(name){return new InvalidArgumentError(`Canonical target ${JSON.stringify(name)} does not need resolution. Pass it directly to the next GitHits tool.`)}function parseRegistries(value){if(value===undefined)return[];const registries=[];const values=Array.isArray(value)?value:value.split(",");for(const raw of values){const trimmed=raw.trim();if(!trimmed)continue;const registry=parsePkgseerRegistryArg(trimmed);if(!registry){throw new InvalidPackageSpecError(`Unsupported registry '${trimmed}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const mapped=toPkgseerRegistry2(registry);if(!registries.includes(mapped))registries.push(mapped)}return registries}function parsePreferredKind(value){const kind=value?.trim().toLowerCase();if(!kind)return;if(kind==="package")return"PACKAGE";if(kind==="repository")return"REPOSITORY";if(kind==="site")return"SITE";throw new InvalidPackageSpecError(`Preferred kind expects package, repository, or site. Got '${value}'.`)}function normaliseStrings(values){const result=[];const seen=new Set;for(const raw of values??[]){const value=raw.trim();const key=value.toLowerCase();if(!value||seen.has(key))continue;seen.add(key);result.push(value)}return result}function buildResolveTargetSuccessPayload(result){const candidates=result.targets.map(projectTarget);const payload={ambiguous:result.ambiguous,candidates,protectedMatches:dedupeTargets(result.protectedMatches).map((target)=>target.canonicalKey),targetsTruncated:result.targetsTruncated};if(result.best)payload.best=result.best.canonicalKey;if(result.ambiguous){payload.ambiguousReason=result.ambiguousReason.toLowerCase()}return payload}function projectTarget(target){const payload={target:target.canonicalKey,kind:target.kind.toLowerCase(),direct:target.match!==undefined};assign(payload,"confidence",target.match?.confidence.toLowerCase());assign(payload,"groupKey",target.groupKey);assign(payload,"name",target.displayName);assign(payload,"description",target.description);assign(payload,"registry",target.registry?.toLowerCase());assign(payload,"packageName",target.packageName);assign(payload,"latestVersion",target.latestVersion);assign(payload,"latestVersionMaliciousStatus",target.latestVersionMaliciousStatus.toLowerCase());if(target.latestVersionMaliciousEvidence){payload.latestVersionMaliciousEvidence={advisories:target.latestVersionMaliciousEvidence.advisories.map((advisory)=>({osvId:advisory.osvId,classificationReasons:advisory.classificationReasons.map((reason)=>reason.toLowerCase())})),totalCount:target.latestVersionMaliciousEvidence.totalCount,truncated:target.latestVersionMaliciousEvidence.truncated}}assign(payload,"repositoryUrl",target.repositoryUrl);assign(payload,"repositoryOwner",target.repositoryOwner);assign(payload,"repositoryName",target.repositoryName);assign(payload,"stars",target.stars);assign(payload,"downloadsLastMonth",target.downloadsLastMonth);assign(payload,"downloadsTotal",target.downloadsTotal);assign(payload,"documentationUrl",target.documentationUrl);assign(payload,"matchedAliases",target.match?.matchedAliases);assign(payload,"docsAvailable",target.docsAvailable);assign(payload,"codeAvailable",target.codeAvailable);assign(payload,"nameSimilarity",target.match?.nameSimilarity);assign(payload,"docsPageCount",target.docsPageCount);assign(payload,"codeFileCount",target.codeFileCount);assign(payload,"license",target.license);assign(payload,"matchTier",target.match?.matchTier);assign(payload,"score",target.match?.score);return payload}function groupResolveTargets(targets){const groups=[];for(const target of targets){const previous=groups.at(-1);if(target.groupKey!==undefined&&previous?.groupKey===target.groupKey){previous.targets.push(target)}else{groups.push({...target.groupKey!==undefined?{groupKey:target.groupKey}:{},targets:[target]})}}return groups}function buildResolveTargetEvidencePlan(targets,includeNameSimilarity=false){const hasRepositoryTarget=targets.some((target)=>target.kind==="REPOSITORY");const hasSiteTarget=targets.some((target)=>target.kind==="SITE");const hasPackageLicense=targets.some((target)=>target.kind==="PACKAGE"&&formatLicense(target.license)!==undefined);return(target)=>{switch(target.kind){case"PACKAGE":return{stars:!hasRepositoryTarget,downloads:true,repository:!hasRepositoryTarget,license:true,docs:!hasSiteTarget,code:true,nameSimilarity:includeNameSimilarity};case"REPOSITORY":return{stars:true,downloads:false,repository:false,license:!hasPackageLicense,docs:false,code:true,nameSimilarity:includeNameSimilarity};case"SITE":return{stars:false,downloads:false,repository:false,license:false,docs:true,code:false,nameSimilarity:includeNameSimilarity};default:return{stars:true,downloads:true,repository:true,license:true,docs:true,code:true,nameSimilarity:includeNameSimilarity}}}}function isResolveTargetActionable(result){return isResolveTargetIdentityActionable(result)&&isLatestVersionMaliciousStatusActionable(findResolveTargetBestTarget(result)?.latestVersionMaliciousStatus)}var KNOWN_CONFIDENCE_VALUES=new Set(["exact","high","medium","low"]);var KNOWN_KIND_VALUES=new Set(["package","repository","site"]);function formatResolveTargetEvidence(target,options){const fields=[];if(options.stars&&target.stars!==undefined){fields.push(`${formatCompactNumber(target.stars)} stars`)}if(options.downloads&&target.downloadsLastMonth!==undefined){fields.push(`${formatCompactNumber(target.downloadsLastMonth)} downloads/mo`)}else if(options.downloads&&target.downloadsTotal!==undefined){fields.push(`${formatCompactNumber(target.downloadsTotal)} downloads`)}if(options.repository&&target.kind==="PACKAGE"&&target.repositoryUrl){fields.push(`repo ${compactRepositoryUrl(target.repositoryUrl)}`)}const license=options.license?formatLicense(target.license):undefined;if(license)fields.push(`license ${license}`);const docs=options.docs&&target.kind==="SITE"&&!target.docsAvailable?"docs: crawled on demand":formatDocsAvailability(target.docsAvailable,target.docsPageCount,options.docs&&target.kind!=="REPOSITORY");if(docs)fields.push(docs);const code=formatResolveTargetCodeAvailability(target,options.code&&target.kind!=="SITE");if(code)fields.push(code);const nameSimilarity=options.nameSimilarity?formatResolveTargetNameSimilarity(target.match?.nameSimilarity):undefined;if(nameSimilarity)fields.push(nameSimilarity);return fields.map(sanitizeTerminalText).join(" · ")}function formatResolveTargetCodeAvailability(target,applicable=true){if(!applicable||!target.codeAvailable)return;const scope=target.kind==="PACKAGE"?"indexed package snapshot":target.kind==="REPOSITORY"?"indexed repository snapshot":"indexed code snapshot";return target.codeFileCount===undefined?scope:`${scope} (${formatCompactNumber(target.codeFileCount)} files)`}function formatResolveTargetNameSimilarity(value){return value===undefined?undefined:`${Math.round(value*100)}% name similarity`}function formatResolveTargetEvidenceNotes(targets,includeNameSimilarity=false){const notes=[];if(includeNameSimilarity&&targets.some((target)=>target.match?.nameSimilarity!==undefined)){notes.push("Name similarity is coarse lexical support; candidate order follows broader backend policy.")}return notes}function formatLicense(value){const license=sanitizeTerminalText(value??"").trim();if(!license)return;return license==="mit"?"MIT":license}function formatDocsAvailability(available,count,applicable){if(!applicable||!available)return;if(count!==undefined){return`docs ${formatCompactNumber(count)} pages`}return"docs available"}function formatLatestVersionMaliciousStatus(status,evidence){switch(status){case"AFFECTED":return withMaliciousEvidence("Malicious content affects the latest version","Do not use the latest version. Verify another version against the linked evidence.",evidence,false);case"UNKNOWN":return withMaliciousEvidence("Malicious-content status is uncertain","Verify the advisory details before using this version.",evidence,true);case"CLEAR":case"NOT_APPLICABLE":case undefined:return;default:return`Unrecognized malicious-content status: ${sanitizeTerminalText(status)}. Do not use this target.`}}function withMaliciousEvidence(message,guidance,evidence,includeReasons){if(!evidence||evidence.advisories.length===0){return`${message}. ${guidance}`}const details=evidence.advisories.map((advisory)=>{const id=sanitizeTerminalText(advisory.osvId);const reasons=includeReasons?formatMaliciousClassificationReasons(advisory.classificationReasons):undefined;const label=reasons?`${id} (${reasons})`:id;return`${label}: https://osv.dev/vulnerability/${encodeURIComponent(advisory.osvId)}`});const omitted=evidence.totalCount-evidence.advisories.length;if(evidence.truncated&&omitted>0)details.push(`+${omitted} more`);return`${message} — ${details.join("; ")}. ${guidance}`}var MALICIOUS_CLASSIFICATION_REASON_LABELS={AFFECTED_VERSION_RANGE_MATCH:"affected range matched",MISSING_DISPLAYED_VERSION:"latest version missing",INVALID_DISPLAYED_VERSION:"latest version invalid",MISSING_AFFECTED_RANGES:"affected ranges missing",EMPTY_AFFECTED_RANGES:"affected ranges empty",INVALID_AFFECTED_RANGE:"affected range invalid"};function formatMaliciousClassificationReasons(reasons){if(reasons.length===0)return;return reasons.map((reason)=>MALICIOUS_CLASSIFICATION_REASON_LABELS[reason]??`unrecognized reason ${sanitizeTerminalText(reason)}`).join(", ")}function isResolveTargetIdentityActionable(result){return!result.ambiguous&&result.best!==undefined&&(result.best.confidence==="EXACT"||result.best.confidence==="HIGH")}function isLatestVersionMaliciousStatusActionable(status){return status==="CLEAR"||status==="NOT_APPLICABLE"}function findResolveTargetBestTarget(result){if(!result.best)return;const best=result.best;return result.targets.find((target)=>target.kind===best.kind&&target.canonicalKey===best.canonicalKey)}function compactRepositoryUrl(value){return sanitizeTerminalText(formatRepositoryTarget(value))}function dedupeTargets(candidates){const seen=new Set;return candidates.filter((candidate)=>{const key=targetKey(candidate);if(seen.has(key))return false;seen.add(key);return true})}function targetKey(candidate){return`${candidate.kind}:${candidate.canonicalKey}`}function assign(target,key,value){if(value!==undefined)target[key]=value}var schema3={name:z3.string().describe("Human-friendly package, repository, or standalone documentation-site name to resolve, including mutable Launchpad defaults such as lp:PROJECT. Do not use canonical registry:name, github:owner/repo, codeberg:owner/repo, gitlab:group/subgroup/project, launchpad:~owner/+git/repo, or site:<host[/path]> targets."),query:z3.string().optional().describe("Optional task context used to rank retrieved candidates and does not expand candidate retrieval. Do not include credentials, personal data, private code, or proprietary content."),registries:z3.array(z3.string()).optional().describe(`Optional registry filter that constrains package candidates only; repository and site candidates remain eligible. Accepted registries: ${PKGSEER_REGISTRY_LIST2}. An empty list deliberately means no filter.`),preferred_kind:z3.string().optional().describe("Optional preference: package, repository, or site. An empty string means no preference; other values are rejected as invalid arguments."),intent_hints:z3.array(z3.string()).optional().describe("Optional hints that rank retrieved candidates and do not expand candidate retrieval. Empty, blank, and duplicate hints are ignored. Do not include credentials, personal data, private code, or proprietary content."),limit:z3.number().optional().describe("Optional integer candidate limit from 1 through 20."),verbose:z3.boolean().optional().describe("When true, text output includes coarse lexical name-similarity evidence. Default false. JSON always includes available numeric similarity."),format:z3.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 DESCRIPTION3='Resolve OSS dependency names to canonical package, repository, or docs targets. Use known canonical targets directly. Only a non-ambiguous EXACT or HIGH best with CLEAR or NOT_APPLICABLE malicious-content status permits direct continuation; other or missing statuses are non-actionable. CLEAR is not a vulnerability-free claim. MEDIUM and LOW require narrowing or an explicit choice; never auto-select an ambiguous result. A selected `site:` is docs-only: use `list` or `search` with `source: "docs"`, then reuse returned read locators. Inputs leave this machine; open-source targets only.';function createResolveTargetTool2(service){return{name:"resolve_target",description:DESCRIPTION3,schema:schema3,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const textFormat=isTextFormat3(args.format);const params=buildResolveTargetParams({name:args.name,query:args.query,registries:args.registries,preferKind:args.preferred_kind,intentHints:args.intent_hints,limit:args.limit,includeDetailedFields:!textFormat,includeNameSimilarity:args.verbose===true||!textFormat});const result=await service.resolveTarget(params,...serviceRequestArgs(context?.signal));if(textFormat){return textResult(formatResolveTargetMcpText(result,{name:params.name,verbose:args.verbose}))}return textResult(JSON.stringify(buildResolveTargetSuccessPayload(result)))}catch(error){throwIfCallerCancellation(error,context?.signal);return mcpMappedErrorResult(mapPackageIntelligenceError(error),context,args.format,{recovery:{syntax:"mcp",tool:"resolve_target",args}})}}}}function formatResolveTargetMcpText(result,options){const actionable=isResolveTargetActionable(result);const identityActionable=isResolveTargetIdentityActionable(result);const bestTarget=findResolveTargetBestTarget(result);const blockedBest=identityActionable&&!actionable;const protectedKeys=new Set(result.protectedMatches.map((target)=>targetKey2(target)));const hasBlockedDirectTarget=result.targets.some((target)=>target.match!==undefined&&!isLatestVersionMaliciousStatusActionable(target.latestVersionMaliciousStatus));const groups=groupResolveTargets(result.targets);const lines=[];if(result.ambiguous){lines.push(`Ambiguous: ${formatAmbiguousReason(result.ambiguousReason)}`)}else if(actionable&&result.best){lines.push(`Best match: ${formatReference(result.best)}.`)}else if(blockedBest&&result.best){lines.push(`Best identity match: ${formatReference(result.best)}.`)}else if(!result.best){lines.push(`No targets found for "${sanitizeTerminalText(options.name)}".`)}if(groups.length>0){lines.push("Targets:");groups.forEach((group,index)=>{lines.push(...formatMcpGroup(group.targets,index+1,protectedKeys,options.verbose===true))})}if(result.targetsTruncated){lines.push("Note: Additional related targets were omitted; direct matches are complete.")}lines.push(...formatResolveTargetEvidenceNotes(result.targets,options.verbose===true));if(blockedBest){if(!bestTarget){lines.push("Warning: Malicious-content status is unavailable for the best match. Do not use this target.")}}else if(result.ambiguous&&hasBlockedDirectTarget){lines.push("Warning: Some candidates are not actionable. Narrow the result before continuing.")}else if(result.ambiguous){lines.push("Next: narrow the name or filters, or explicitly choose a candidate; pass its exact canonical target to the next MCP tool, never auto-select.")}else if(actionable&&result.best){const target=sanitizeTerminalText(result.best.canonicalKey);lines.push(result.best.kind==="SITE"?`Next: call search with target "${target}" and source "docs", then call read for relevant results.`:`Next: pass the canonical target "${target}" to the next MCP tool.`)}else if(result.best&&hasBlockedDirectTarget){lines.push("Warning: Some candidates are not actionable. Narrow the result before continuing.")}else if(result.best){lines.push("Next: narrow the name or filters, or explicitly choose a candidate; never auto-select the best match.")}else{lines.push("Next: check spelling or registry filters; query, preferred kind, and intent hints only rank existing candidates.")}return`${lines.join(`
|
|
29
29
|
`)}
|
|
30
30
|
`}function isTextFormat3(format){return format===undefined||format==="text"}function formatReference(target){const kind=sanitizeTerminalText(target.kind.toLowerCase());const confidence=sanitizeTerminalText(target.confidence.toLowerCase());return[sanitizeTerminalText(target.canonicalKey),`[${confidence}; ${kind}]`].join(" ")}function formatMcpGroup(targets,groupNumber,protectedKeys,includeNameSimilarity){const[lead,...members]=targets;if(!lead)return[];const evidencePlan=buildResolveTargetEvidencePlan(targets,includeNameSimilarity);const lines=[` ${groupNumber}. ${formatMcpTargetLine(lead,evidencePlan(lead),protectedKeys)}`,...formatMcpTargetDetails(lead," ")];if(members.length>0)lines.push(" Related targets:");for(const member of members){lines.push(` ${formatMcpTargetLine(member,evidencePlan(member),protectedKeys)}`,...formatMcpTargetDetails(member," "))}return lines}function formatMcpTargetLine(target,evidenceOptions,protectedKeys){const evidence=formatResolveTargetEvidence(target,evidenceOptions);return`${formatMcpTarget(target)}${formatProtectedMarker(target,protectedKeys)}${evidence?` · ${evidence}`:""}`}function formatMcpTarget(target){const kind=sanitizeTerminalText(target.kind.toLowerCase());const relationship=target.match?sanitizeTerminalText(target.match.confidence.toLowerCase()):"related";return`${sanitizeTerminalText(target.canonicalKey)} [${relationship}; ${kind}]`}function formatProtectedMarker(target,protectedKeys){return protectedKeys.has(targetKey2(target))?" · protected exact-name match":""}function formatMcpTargetDetails(target,indent){const lines=[];const description=compactDescription(target.description);if(description)lines.push(`${indent}${description}`);const maliciousWarning=formatLatestVersionMaliciousStatus(target.latestVersionMaliciousStatus,target.latestVersionMaliciousEvidence);if(maliciousWarning)lines.push(`${indent}Warning: ${maliciousWarning}`);return lines}function compactDescription(value){const normalized=sanitizeTerminalText(value??"").replace(/\s+/g," ").trim();if(!normalized)return;return normalized.length>240?`${normalized.slice(0,237).trimEnd()}...`:normalized}function formatAmbiguousReason(reason){const message=sanitizeTerminalText(reason.toLowerCase().replaceAll("_"," "));return message?`${message}.`:"review identity before use."}function targetKey2(target){return`${target.kind}:${target.canonicalKey}`}
|
|
31
31
|
export{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};
|
package/dist/tools.d.ts
CHANGED
|
@@ -167,8 +167,11 @@ interface ToolProgressOperation extends ProgressRequest {
|
|
|
167
167
|
}
|
|
168
168
|
/** Progress already bound to the current MCP request's progress token. */
|
|
169
169
|
interface ToolProgress {
|
|
170
|
-
/**
|
|
171
|
-
|
|
170
|
+
/**
|
|
171
|
+
* Starts progress for one backend call, showing `initialMessage` until the
|
|
172
|
+
* first live update. Returns `undefined` when progress is unavailable.
|
|
173
|
+
*/
|
|
174
|
+
begin(initialMessage?: string): Promise<ToolProgressOperation | undefined>;
|
|
172
175
|
}
|
|
173
176
|
/** Host-provided execution state shared by MCP and direct tool callers. */
|
|
174
177
|
interface ToolExecutionContext {
|
package/dist/tools.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TermsAcceptanceRequiredError2,FetchTimeoutError2,AuthenticationError2,ApiRateLimitError2}from"./shared/chunk-1bad2znr.js";import{createGetExampleTool2,createResearchTool2,createResolveTargetTool2}from"./shared/chunk-
|
|
1
|
+
import{TermsAcceptanceRequiredError2,FetchTimeoutError2,AuthenticationError2,ApiRateLimitError2}from"./shared/chunk-1bad2znr.js";import{createGetExampleTool2,createResearchTool2,createResolveTargetTool2}from"./shared/chunk-660sdzfg.js";import{z}from"zod";function toCallableTool(definition){const input=z.object(definition.schema);const inputSchema=z.toJSONSchema(input,{io:"input"});return{name:definition.name,description:definition.description,inputSchema,annotations:definition.annotations,execute:async(value,options)=>{const args=input.parse(value);const context={authAction:"Authenticate with GitHits, then retry.",...options?.signal?{signal:options.signal}:{}};return definition.handler(args,context)}}}var AuthenticationError=AuthenticationError2;var ApiRateLimitError=ApiRateLimitError2;var FetchTimeoutError=FetchTimeoutError2;var TermsAcceptanceRequiredError=TermsAcceptanceRequiredError2;export{ApiRateLimitError,AuthenticationError,FetchTimeoutError,TermsAcceptanceRequiredError,createGetExampleTool2 as createGetExampleTool,createResearchTool2 as createResearchTool,createResolveTargetTool2 as createResolveTargetTool,toCallableTool};
|