@draht/coding-agent 2026.11.14-1 → 2026.11.18-1
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/CHANGELOG.md +6 -0
- package/dist/bundle/chunks/{anthropic-messages-C5ZJVCKX.js → anthropic-messages-AFT3AY2S.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-TNRID5YC.js → azure-openai-responses-A52AJ5P5.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-XWZLYE4L.js → chunk-2XOICIOV.js} +1 -1
- package/dist/bundle/chunks/{chunk-MPJIXESS.js → chunk-5PDANNKW.js} +1 -1
- package/dist/bundle/chunks/{chunk-SXHVGWCU.js → chunk-6EVZEBYO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OUXJRC2W.js → chunk-ACQFXG5D.js} +1 -1
- package/dist/bundle/chunks/{chunk-5WEOWREV.js → chunk-CAOOVEOM.js} +1 -1
- package/dist/bundle/chunks/{chunk-JHKMYVPC.js → chunk-CP35SXCN.js} +7 -8
- package/dist/bundle/chunks/{chunk-5C4MAPF6.js → chunk-CXCOVS2M.js} +1 -1
- package/dist/bundle/chunks/{chunk-O2XYFH2E.js → chunk-HTSLUWLE.js} +3 -3
- package/dist/bundle/chunks/{chunk-RVXTPNXQ.js → chunk-JMYX7QEX.js} +1 -1
- package/dist/bundle/chunks/{chunk-B6S2UR4T.js → chunk-LKMWSNTE.js} +1 -1
- package/dist/bundle/chunks/{chunk-2IQVBLH6.js → chunk-O2P5SYXT.js} +3 -2
- package/dist/bundle/chunks/{chunk-LCTFXH4P.js → chunk-TUIWJI22.js} +1 -1
- package/dist/bundle/chunks/{chunk-YSE3VKKB.js → chunk-YFDWS2SA.js} +1 -1
- package/dist/bundle/chunks/{cli-2QKCAPPD.js → cli-L6U4GJHK.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-UCG6T3XP.js → cloudflare-workers-ai-system-one-KYAP5L2X.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-GPBKPOXA.js → google-generative-ai-WR6OZ27M.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-USZY53NF.js → google-vertex-FUYYVM54.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-7DEQ4ZUF.js → llama-cpp-classify-6LLMLBUC.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-UOGXPDZ3.js → mistral-conversations-WVGS4PN2.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-VUDXQ3EU.js → openai-codex-responses-CTLT3QUI.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-UQOOS7NM.js → openai-completions-V37FD5ZZ.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-24WNXO2R.js → openai-decisions-WTY6DQT4.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-5AF6MZ5L.js → openai-responses-R7W5BVUV.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-OUXVVTYQ.js → openrouter-images-7GGRYAYP.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-DRMOEO6B.js → pi-messages-O7OXMCNL.js} +1 -1
- package/dist/bundle/chunks/{runtime-L23MZBKL.js → runtime-73OLLYOI.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-K63EBJDD.js → typesafe-system-one-FGISCLX2.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-JZV35VDE.js → virtual-modules-JL2BFG57.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +4 -7
- package/dist/extensions/mcp/index.js.map +1 -1
- package/package.json +9 -9
package/CHANGELOG.md
CHANGED
package/dist/bundle/chunks/{anthropic-messages-C5ZJVCKX.js → anthropic-messages-AFT3AY2S.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-WNZ64GW3.js";import{registerSessionResourceCleanup}from"./chunk-Y7QE2R34.js";import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-5OXIAQP5.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-HTJ3L72O.js";import{shortHash}from"./chunk-HJ72RANT.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-
|
|
2
|
+
import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-WNZ64GW3.js";import{registerSessionResourceCleanup}from"./chunk-Y7QE2R34.js";import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-5OXIAQP5.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-HTJ3L72O.js";import{shortHash}from"./chunk-HJ72RANT.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-LKMWSNTE.js";import{sanitizeSurrogates}from"./chunk-63BK6WK2.js";import{retryProviderRequest}from"./chunk-RCRGGYLW.js";import{withCauseDetail}from"./chunk-ACQFXG5D.js";import{headersToRecord}from"./chunk-EBVYI75P.js";import{getProviderEnvValue}from"./chunk-2N4I6WXC.js";import{ToolCallArgumentsStream,parseJsonWithRepair}from"./chunk-KFREX3FS.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,resolveTranscript}from"./chunk-YFDWS2SA.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-USCN7R2E.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-2XOICIOV.js";import{Anthropic}from"./chunk-GQXRTK54.js";import"./chunk-HZ2UHMBT.js";var STRICT_TOOL_LIMIT_ERROR_MESSAGES=["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("];function isStrictToolLimitErrorMessage(message){return STRICT_TOOL_LIMIT_ERROR_MESSAGES.some(limitMessage=>message.includes(limitMessage))}var sessionsOverStrictToolLimits=new Set,MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS=1e4;function markStrictToolLimitsExceeded(sessionId){if(sessionId!==void 0&&(sessionsOverStrictToolLimits.add(sessionId),sessionsOverStrictToolLimits.size>MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS)){let oldest=sessionsOverStrictToolLimits.values().next().value;oldest!==void 0&&sessionsOverStrictToolLimits.delete(oldest)}}function hasExceededStrictToolLimits(sessionId){return sessionId!==void 0&&sessionsOverStrictToolLimits.has(sessionId)}registerSessionResourceCleanup(sessionId=>{sessionId?sessionsOverStrictToolLimits.delete(sessionId):sessionsOverStrictToolLimits.clear()});function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("DRAHT_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemeral",...ttl&&{ttl}}}}var claudeCodeVersion="2.1.322",claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),matchedTool=tools.find(tool=>tool.name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertImageBlock(image){return{type:"image",source:{type:"base64",media_type:image.mimeType,data:image.data}}}function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
|
|
3
3
|
`));let blocks=content.map(block=>block.type==="text"?{type:"text",text:sanitizeSurrogates(block.text)}:convertImageBlock(block));return blocks.some(b=>b.type==="text")||blocks.unshift({type:"text",text:"(see attached image)"}),blocks}var FINE_GRAINED_TOOL_STREAMING_BETA="fine-grained-tool-streaming-2025-05-14",INTERLEAVED_THINKING_BETA="interleaved-thinking-2025-05-14",SERVER_SIDE_FALLBACK_BETA="server-side-fallback-2026-07-01",MID_CONVERSATION_OUTPUT_CONFIG_BETA="mid-conversation-output-config-2026-07-01",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",INLINE_TOOLS_BETA="inline-tools-2026-09-15",MESSAGE_THREADS_BETA="message-threads-2026-08-12",DEFERRED_TOOL_PLACEHOLDER={name:"__draht_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function shouldUseServerSideFallbackBeta(model){return(model.compat?.allowedFallbackModels?.length??0)>0}function getAnthropicCompat(model){let isOpenRouter=model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:model.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:model.compat?.sendSessionAffinityHeaders??isOpenRouter,sessionAffinityFormat:model.compat?.sessionAffinityFormat??(isOpenRouter?"openrouter":void 0),supportsCacheControlOnTools:model.compat?.supportsCacheControlOnTools??!0,supportsTemperature:model.compat?.supportsTemperature??!0,allowEmptySignature:model.compat?.allowEmptySignature??!1,supportsStrictTools:model.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:model.compat?.supportsMidConvoToolChanges??!1,supportsMessageThreads:model.compat?.supportsMessageThreads??model.baseUrl.includes("api.anthropic.com")}}var threadState=new Map,MAX_THREAD_STATE_ENTRIES=1e4,NEW_THREAD_ERRORS=new Set(["thread_not_found","thread_already_continued","thread_continue_in_flight","thread_fingerprint_mismatch"]);function setThreadState(sessionId,value){if(threadState.delete(sessionId),threadState.set(sessionId,value),threadState.size>MAX_THREAD_STATE_ENTRIES){let oldest=threadState.keys().next().value;oldest!==void 0&&threadState.delete(oldest)}}registerSessionResourceCleanup(sessionId=>{sessionId?threadState.delete(sessionId):threadState.clear()});function hashThreadPrefix(model,params,messages){let{system,tools,thinking,output_config,tool_choice,betas,fallbacks}=params,settings=JSON.stringify([model.provider,model.baseUrl,params.model,system,tools,thinking,output_config,tool_choice,betas,fallbacks]),conversation=JSON.stringify(messages,(key,value)=>{if(key!=="cache_control")return key==="content"&&typeof value=="string"?[{type:"text",text:value}]:value});return shortHash(settings+conversation)}function createThreadRequest(sessionId,params){return{sessionId,body:{...params,thread:{type:"create"}}}}function prepareThreadRequest(model,sessionId,params){let state=threadState.get(sessionId);if(state!=="off"){if(state!==void 0&¶ms.messages.length>state.prefixCount&&hashThreadPrefix(model,params,params.messages.slice(0,state.prefixCount))===state.prefixHash){threadState.delete(sessionId);let{system:_system,tools:_tools,...rest}=params;return{body:{...rest,messages:params.messages.slice(state.prefixCount),thread:{type:"continue",previous_message_id:state.replyId}},sessionId}}return createThreadRequest(sessionId,params)}}function getThreadErrorCode(error){let code=error.error?.error?.details?.error_code;return typeof code=="string"?code:void 0}async function sendThreadRequest(thread,params,send,output,signal){try{return{response:await send(thread.body),thread}}catch(error){if(signal?.aborted||!(error instanceof Anthropic.APIError))throw error;let errorCode=getThreadErrorCode(error),startNewThread=errorCode!==void 0&&NEW_THREAD_ERRORS.has(errorCode),threadsUnsupported=errorCode==="thread_unsupported_request"||errorCode===void 0&&error.status===400&&error.message.includes("thread");if(!startNewThread&&!threadsUnsupported)throw error;if(appendAssistantMessageDiagnostic(output,{type:"anthropic_thread_fallback",timestamp:Date.now(),error:{message:error.message},details:{reason:errorCode??String(error.status)}}),startNewThread){let created=createThreadRequest(thread.sessionId,params);return{response:await send(created.body),thread:created}}let response=await send(params);return setThreadState(thread.sessionId,"off"),{response,thread:void 0}}}function recordThreadReply(model,thread,params,output,isOAuth,allowEmptySignature){if(output.responseId===void 0||output.responseModel!==void 0)return;let reply=convertMessages(transformMessages([output],model,normalizeToolCallId),isOAuth,void 0,allowEmptySignature).messages.filter(message=>message.role==="assistant"),prefix=[...params.messages,...reply];setThreadState(thread.sessionId,{prefixCount:prefix.length,prefixHash:hashThreadPrefix(model,params,prefix),replyId:output.responseId})}function mergeHeaders(...headerSources){let merged={};for(let headers of headerSources)headers&&Object.assign(merged,headers);return merged}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-key")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var PiAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function flushSseEvent(state){if(!state.event&&state.data.length===0)return null;let event={event:state.event,data:state.data.join(`
|
|
4
4
|
`),raw:[...state.raw]};return state.event=null,state.data=[],state.raw=[],event}function decodeSseLine(line,state){if(line==="")return flushSseEvent(state);if(state.raw.push(line),line.startsWith(":"))return null;let delimiterIndex=line.indexOf(":"),fieldName=delimiterIndex===-1?line:line.slice(0,delimiterIndex),value=delimiterIndex===-1?"":line.slice(delimiterIndex+1);return value.startsWith(" ")&&(value=value.slice(1)),fieldName==="event"?state.event=value:fieldName==="data"&&state.data.push(value),null}function nextLineBreakIndex(text){let carriageReturnIndex=text.indexOf("\r"),newlineIndex=text.indexOf(`
|
|
5
5
|
`);return carriageReturnIndex===-1?newlineIndex:newlineIndex===-1?carriageReturnIndex:Math.min(carriageReturnIndex,newlineIndex)}function consumeLine(text){let lineBreakIndex=nextLineBreakIndex(text);if(lineBreakIndex===-1)return null;let nextIndex=lineBreakIndex+1;return text[lineBreakIndex]==="\r"&&text[nextIndex]===`
|
package/dist/bundle/chunks/{azure-openai-responses-TNRID5YC.js → azure-openai-responses-A52AJ5P5.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-
|
|
2
|
+
import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-5PDANNKW.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-ZRPAOMVB.js";import{clampOpenAIPromptCacheKey}from"./chunk-2FBJKY7F.js";import{AzureOpenAI}from"./chunk-6WESOD4H.js";import"./chunk-HJ72RANT.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-LKMWSNTE.js";import"./chunk-63BK6WK2.js";import{retryProviderRequest}from"./chunk-RCRGGYLW.js";import{formatProviderError,normalizeProviderError}from"./chunk-ACQFXG5D.js";import{headersToRecord}from"./chunk-EBVYI75P.js";import"./chunk-2N4I6WXC.js";import"./chunk-KFREX3FS.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-YFDWS2SA.js";import{AssistantMessageEventStream}from"./chunk-USCN7R2E.js";import{getIdentityHeaders}from"./chunk-2XOICIOV.js";import"./chunk-HZ2UHMBT.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options){let headers={...getIdentityHeaders(model,options?.identity),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,getResponsesToolSupport({supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch})),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:model.compat?.promptCacheKeyMode==="disabled"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};
|
|
@@ -73,7 +73,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
|
|
|
73
73
|
\r `.includes(jsonString[index]);)index++};return parseAny()},parse2=parseJSON;exports.parse=parse2}});var import_client_bedrock_runtime=__toESM(require_dist_cjs21(),1),import_node_http_handler5=__toESM(require_dist_cjs8(),1),import_http_proxy_agent=__toESM(require_dist2(),1),import_https_proxy_agent=__toESM(require_dist3(),1);var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event)));let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function appendAssistantMessageDiagnostic(message,diagnostic){message.diagnostics=[...message.diagnostics??[],diagnostic]}var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS=300*1e3;async function startNoopSpan(_options,callback){return callback(noopTelemetrySpan)}var noopCounter=Object.freeze({add:()=>{}}),noopUpDownCounter=Object.freeze({add:()=>{}}),noopHistogram=Object.freeze({record:()=>{}}),NOOP_TELEMETRY_METRICS=Object.freeze({counter:()=>noopCounter,upDownCounter:()=>noopUpDownCounter,histogram:()=>noopHistogram}),NOOP_TELEMETRY_PROPAGATION=Object.freeze({inject:()=>{},extract:()=>NOOP_TELEMETRY_CONTEXT}),noopTelemetrySpan={metrics:NOOP_TELEMETRY_METRICS,propagation:NOOP_TELEMETRY_PROPAGATION,startSpan:startNoopSpan,addLink:()=>{},addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(noopTelemetrySpan);var NOOP_TELEMETRY_CONTEXT=noopTelemetrySpan;var anchor=performance.timeOrigin;function contentText(content,separator=`
|
|
74
74
|
`){return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(separator)}function getSystemMessageText(message){let parts=[contentText(message.content)];for(let text of Object.values(message.sections??{}))text!==null&&parts.push(text);return parts.filter(part=>part.length>0).join(`
|
|
75
75
|
|
|
76
|
-
`)}function ownedSlice(text,start,end2=text.length){return`${text.slice(start,end2)} `.slice(0,-1)}var provider={type:"string",description:"Provider identifier.",required:!0},model={type:"string",description:"Requested model identifier.",required:!0},stop={type:"string",description:"Normalized stop reason.",values:["pending","stop","length","toolUse","error","aborted","deferred"]},request={description:"One logical model request, including authentication and provider setup.",parents:{kind:"any"},startAttributes:{provider,api:{type:"string",description:"API identifier.",required:!0},model,reasoning:{type:"string",description:"Scalar requested reasoning level.",required:!1}},endAttributes:{stop,"usage.input":{type:"number",description:"Uncached input tokens."},"usage.output":{type:"number",description:"Output tokens."},"usage.cache_read":{type:"number",description:"Cache-read tokens."},"usage.cache_write":{type:"number",description:"Cache-write tokens."},"cost.total":{type:"number",description:"Total request cost in USD."},"response.id":{type:"string",description:"Provider response identifier.",cardinality:"high"}},events:{"pi.ai.first_chunk":{description:"First normalized stream event delivered.",attributes:{}},"pi.ai.block":{description:"A completed content block; content is never recorded.",attributes:{type:{type:"string",description:"Block kind.",values:["text","thinking","tool_call"],required:!0},index:{type:"number",description:"Content block index.",required:!0},chars:{type:"number",description:"UTF-16 character count.",required:!0},tool:{type:"string",description:"Tool name, for tool-call blocks only.",required:!1}}}},status:{default:"ok",errorWhen:"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."}},AI_TELEMETRY_SCHEMA={version:1,spans:{"pi.ai.request":request,"pi.ai.poll":{...request,description:"One deferred-response poll, not the deferred request's lifetime."}},metrics:{"pi.ai.request.duration":{kind:"histogram",description:"Logical request or poll duration.",unit:"ms",attributes:{provider,model,stop:{...stop,required:!0}}},"pi.ai.first_chunk.duration":{kind:"histogram",description:"Time to the first normalized stream event.",unit:"ms",attributes:{provider,model}},"pi.ai.tokens":{kind:"counter",description:"Reported model token usage; pending and deferred polls are excluded.",unit:"token",attributes:{provider,model,kind:{type:"string",description:"Token usage category.",values:["input","output","cache_read","cache_write"],required:!0}}},"pi.ai.cost":{kind:"counter",description:"Reported model cost; pending and deferred polls are excluded.",unit:"USD",attributes:{provider,model}}}};var DRAHT_AI_VERSION="2026.11.
|
|
76
|
+
`)}function ownedSlice(text,start,end2=text.length){return`${text.slice(start,end2)} `.slice(0,-1)}var provider={type:"string",description:"Provider identifier.",required:!0},model={type:"string",description:"Requested model identifier.",required:!0},stop={type:"string",description:"Normalized stop reason.",values:["pending","stop","length","toolUse","error","aborted","deferred"]},request={description:"One logical model request, including authentication and provider setup.",parents:{kind:"any"},startAttributes:{provider,api:{type:"string",description:"API identifier.",required:!0},model,reasoning:{type:"string",description:"Scalar requested reasoning level.",required:!1}},endAttributes:{stop,"usage.input":{type:"number",description:"Uncached input tokens."},"usage.output":{type:"number",description:"Output tokens."},"usage.cache_read":{type:"number",description:"Cache-read tokens."},"usage.cache_write":{type:"number",description:"Cache-write tokens."},"cost.total":{type:"number",description:"Total request cost in USD."},"response.id":{type:"string",description:"Provider response identifier.",cardinality:"high"}},events:{"pi.ai.first_chunk":{description:"First normalized stream event delivered.",attributes:{}},"pi.ai.block":{description:"A completed content block; content is never recorded.",attributes:{type:{type:"string",description:"Block kind.",values:["text","thinking","tool_call"],required:!0},index:{type:"number",description:"Content block index.",required:!0},chars:{type:"number",description:"UTF-16 character count.",required:!0},tool:{type:"string",description:"Tool name, for tool-call blocks only.",required:!1}}}},status:{default:"ok",errorWhen:"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."}},AI_TELEMETRY_SCHEMA={version:1,spans:{"pi.ai.request":request,"pi.ai.poll":{...request,description:"One deferred-response poll, not the deferred request's lifetime."}},metrics:{"pi.ai.request.duration":{kind:"histogram",description:"Logical request or poll duration.",unit:"ms",attributes:{provider,model,stop:{...stop,required:!0}}},"pi.ai.first_chunk.duration":{kind:"histogram",description:"Time to the first normalized stream event.",unit:"ms",attributes:{provider,model}},"pi.ai.tokens":{kind:"counter",description:"Reported model token usage; pending and deferred polls are excluded.",unit:"token",attributes:{provider,model,kind:{type:"string",description:"Token usage category.",values:["input","output","cache_read","cache_write"],required:!0}}},"pi.ai.cost":{kind:"counter",description:"Reported model cost; pending and deferred polls are excluded.",unit:"USD",attributes:{provider,model}}}};var DRAHT_AI_VERSION="2026.11.18-1";function getClientVersion(identity){return identity?.version??DRAHT_AI_VERSION}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
77
77
|
|
|
78
78
|
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model2,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model2.cost,matchedThreshold=-1;for(let tier of model2.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model2){return model2.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model2.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model2,level){let availableLevels=getSupportedThinkingLevels(model2);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error2.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error2):error2.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error2){let deepest,current=error2.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&¤t instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error2.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error2.message.includes(detail)?error2.message:error2.message?`${error2.message}: ${detail}`:detail}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env2){return env2?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env2){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env2?.[lowercaseKey]||env2?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env2){let noProxy=getProxyEnv("no_proxy",env2).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env2){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env2))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env2)||getProxyEnv("all_proxy",env2);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env2){let proxy=getProxyForUrl(targetUrl,env2);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error2){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error2 instanceof Error?error2.message:String(error2)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var import_partial_json=__toESM(require_dist4(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function isControlCharacter(char){let codePoint=char.codePointAt(0);return codePoint!==void 0&&codePoint>=0&&codePoint<=31}function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
79
79
|
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",inString=!1;for(let index=0;index<json.length;index++){let char=json[index];if(!inString){repaired+=char,char==='"'&&(inString=!0);continue}if(char==='"'){repaired+=char,inString=!1;continue}if(char==="\\"){let nextChar=json[index+1];if(nextChar===void 0){repaired+="\\\\";continue}if(nextChar==="u"){let unicodeDigits=json.slice(index+2,index+6);if(/^[0-9a-fA-F]{4}$/.test(unicodeDigits)){repaired+=`\\u${unicodeDigits}`,index+=5;continue}}if(VALID_JSON_ESCAPES.has(nextChar)){repaired+=`\\${nextChar}`,index+=1;continue}repaired+="\\\\";continue}repaired+=isControlCharacter(char)?escapeControlCharacter(char):char}return repaired}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseToolCallArguments(json){if(!json?.trim())return{arguments:{}};try{let parsed=parseJsonWithRepair(json);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Tool arguments must be a JSON object");return{arguments:parsed}}catch(error2){return{arguments:{},argumentsError:`${error2 instanceof Error?error2.message:String(error2)}
|
|
@@ -6,4 +6,4 @@ function contentText(content,separator=`
|
|
|
6
6
|
|
|
7
7
|
${value}`);return parts.join(`
|
|
8
8
|
|
|
9
|
-
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}var DRAHT_AI_VERSION="2026.11.
|
|
9
|
+
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}var DRAHT_AI_VERSION="2026.11.18-1";var DRAHT_ATTRIBUTION={name:"draht",url:"https://github.com/draht-dev/draht",categories:["cli-agent"]},NVIDIA_NIM_HOST="integrate.api.nvidia.com",OPENCODE_HOST="opencode.ai";function mergeClientIdentity(...sources){let merged;for(let source of sources)source&&(merged={...merged},source.userAgent!==void 0&&(merged.userAgent=source.userAgent),source.attribution!==void 0&&(merged.attribution=source.attribution),source.version!==void 0&&(merged.version=source.version));return merged}function getClientVersion(identity){return identity?.version??DRAHT_AI_VERSION}function runtimeDescription(){if(typeof process>"u")return;let versions=process.versions;if(versions?.bun)return`bun/${versions.bun}`;if(versions?.node)return`node/${process.version}`}function formatUserAgent(identity){let mode=identity?.userAgent??"detailed";if(typeof mode=="object")return mode.custom;if(mode==="short")return"draht";let product=`draht/${getClientVersion(identity)}`,runtime=runtimeDescription();return runtime?`${product} (${process.platform}; ${runtime}; ${process.arch})`:`${product} (browser)`}function matchesHost(baseUrl,expectedHost){try{return new URL(baseUrl).hostname===expectedHost}catch{return!1}}function isOpenRouter(target){return target.provider==="openrouter"||target.baseUrl.includes("openrouter.ai")}function isNvidiaNim(target){return target.provider==="nvidia"||matchesHost(target.baseUrl,NVIDIA_NIM_HOST)}function isOpenCode(target){return target.provider==="opencode"||target.provider==="opencode-go"||matchesHost(target.baseUrl,OPENCODE_HOST)}function getAttributionHeaders(target,identity){let attribution=identity?.attribution;if(!attribution)return{};let{name,url,categories}=attribution;return isOpenRouter(target)?{"HTTP-Referer":url,"X-OpenRouter-Title":name,...categories===void 0||categories.length===0?{}:{"X-OpenRouter-Categories":categories.join(",")}}:isNvidiaNim(target)?{"X-BILLING-INVOKE-ORIGIN":name.charAt(0).toUpperCase()+name.slice(1)}:isOpenCode(target)?{"x-opencode-client":name}:{}}function getOpenCodeSessionHeaders(target,sessionId){return sessionId&&isOpenCode(target)?{"x-opencode-session":sessionId}:void 0}function getIdentityHeaders(target,identity){return{"User-Agent":formatUserAgent(identity),...getAttributionHeaders(target,identity)}}function isMutableModels(models){return"setProvider"in models&&"deleteProvider"in models&&"clearProviders"in models}function withClientIdentity(models,identity){let withIdentity=options=>({...options,identity:mergeClientIdentity(identity,options?.identity)}),wrapped={getProviders:()=>models.getProviders(),getProvider:id=>models.getProvider(id),getModels:provider=>models.getModels(provider),getModel:(provider,id)=>models.getModel(provider,id),getModelsOfType:(type,provider)=>models.getModelsOfType(type,provider),getModelOfType:(type,provider,id)=>models.getModelOfType(type,provider,id),getAllModels:provider=>models.getAllModels(provider),refresh:options=>models.refresh(options),checkAuth:(providerId,options)=>models.checkAuth(providerId,options),getAvailable:(providerId,options)=>models.getAvailable(providerId,options),getAvailableOfType:(type,providerId,options)=>models.getAvailableOfType(type,providerId,options),getAllAvailable:(providerId,options)=>models.getAllAvailable(providerId,options),getAuth:models.getAuth.bind(models),login:(providerId,type,interaction,options)=>models.login(providerId,type,interaction,options),logout:(providerId,options)=>models.logout(providerId,options),stream:(model,context,options)=>models.stream(model,context,withIdentity(options)),complete:(model,context,options)=>models.complete(model,context,withIdentity(options)),streamSimple:(model,context,options)=>models.streamSimple(model,context,withIdentity(options)),completeSimple:(model,context,options)=>models.completeSimple(model,context,withIdentity(options)),streamDeferred:(model,handle,options)=>models.streamDeferred(model,handle,withIdentity(options)),fetchDeferred:(model,handle,options)=>models.fetchDeferred(model,handle,withIdentity(options)),cancelDeferred:(model,handle,options)=>models.cancelDeferred(model,handle,withIdentity(options)),generateImages:(model,context,options)=>models.generateImages(model,context,withIdentity(options)),classify:(model,context,options)=>models.classify(model,context,withIdentity(options))};return isMutableModels(models)?{...wrapped,setProvider:provider=>models.setProvider(provider),deleteProvider:id=>models.deleteProvider(id),clearProviders:()=>models.clearProviders()}:wrapped}export{contentText,getSystemMessageText,renderSystemMessageUpdate,ownedSlice,DRAHT_AI_VERSION,DRAHT_ATTRIBUTION,mergeClientIdentity,getClientVersion,formatUserAgent,getAttributionHeaders,getOpenCodeSessionHeaders,getIdentityHeaders,withClientIdentity};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{shortHash}from"./chunk-HJ72RANT.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-
|
|
2
|
+
import{shortHash}from"./chunk-HJ72RANT.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-LKMWSNTE.js";import{sanitizeSurrogates}from"./chunk-63BK6WK2.js";import{ToolCallArgumentsStream}from"./chunk-KFREX3FS.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-YFDWS2SA.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-2XOICIOV.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
3
3
|
`),images=content.filter(c=>c.type==="image"),hasText=textResult.trim().length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function getResponsesToolSupport(options){return options.supportsMidConvoSystemMessages&&options.supportsAdditionalTools?"changes":options.supportsToolSearch?"additions":"none"}function renderIncrementalToolsNotice(unavailable){let notice="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return unavailable.size>0?`${notice}
|
|
4
4
|
Still unavailable: ${[...unavailable].join(", ")}.`:notice}function renderToolRemovalNotice(names){return`The following tools are no longer available. Do not call them:
|
|
5
5
|
${names.map(name=>`- ${name}`).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-
|
|
2
|
+
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-CXCOVS2M.js";import{formatProviderError,normalizeProviderError}from"./chunk-ACQFXG5D.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{ownedSlice}from"./chunk-
|
|
2
|
+
import{ownedSlice}from"./chunk-2XOICIOV.js";var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error):error.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error){let deepest,current=error.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&¤t instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error.message.includes(detail)?error.message:error.message?`${error.message}: ${detail}`:detail}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}export{normalizeProviderError,withCauseDetail,formatProviderError,truncateErrorText};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isClientMetadataDocumentCallback,isObject,mcpNamespace,parseClientMetadataBaseUrl,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-2IQVBLH6.js";import{sliceTail}from"./chunk-4FPBO5KP.js";import{require_proper_lockfile}from"./chunk-2JZLKNZ4.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-6M3D4XVD.js";import{__toESM}from"./chunk-HZ2UHMBT.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createHash}from"node:crypto";var MemoryOAuthStateStore=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(state){this.value=structuredClone(state)}},McpOAuthProvider=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();selectedClientMetadata;constructor(options){if(this.serverUrl=String(new URL(options.serverUrl)),this.redirectUrl=String(options.redirectUrl),this.clientMetadata={...options.clientMetadata,redirect_uris:options.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:options.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:options.clientMetadata.response_types??["code"],token_endpoint_auth_method:options.clientMetadata.token_endpoint_auth_method??(options.clientSecret?"client_secret_post":"none")},options.clientMetadataDocument){let selectDocument=options.clientMetadataDocument;this.clientMetadataDocument=metadata=>{let document=selectDocument(metadata);return this.selectedClientMetadata={url:document?.url},document}}this.configuredClient=options.clientId?{client_id:options.clientId,...options.clientSecret?{client_secret:options.clientSecret}:{}}:void 0,this.store=options.store??new MemoryOAuthStateStore,this.onRedirect=options.onRedirect}async state(){let existing=(await this.load()).oauthState;if(existing)return existing;let state=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(value=>({...value,oauthState:state})),state}async clientInformation(){let state=await this.load();if(!(!this.selectCachedClientDocument(state)||this.selectedClientMetadata?.url))return this.configuredClient??(state.clientMetadataUrl?void 0:state.clientInformation)}async saveClientInformation(information){this.configuredClient||await this.update(value=>({...value,clientInformation:information}))}async tokens(){let state=await this.load();if(this.selectCachedClientDocument(state)&&state.clientMetadataUrl===this.selectedClientMetadata?.url)return state.tokens}selectCachedClientDocument(state){if(!this.clientMetadataDocument||this.selectedClientMetadata)return!0;let metadata=state.discovery?.authorizationServerMetadata;return metadata?(this.clientMetadataDocument(metadata),!0):!1}async saveTokens(tokens){let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1e3;await this.update(value=>{let next={...value,tokens};return this.selectedClientMetadata?.url?(next.clientMetadataUrl=this.selectedClientMetadata.url,delete next.clientInformation):delete next.clientMetadataUrl,expiresAt===void 0?delete next.tokensExpireAt:next.tokensExpireAt=expiresAt,next})}async redirectToAuthorization(url){await this.onRedirect(url)}async saveCodeVerifier(verifier){await this.update(value=>({...value,codeVerifier:verifier}))}async saveAuthorizationRequest(request){await this.update(value=>({...value,authorizationRequest:request}))}async codeVerifier(){let verifier=(await this.load()).codeVerifier;if(!verifier)throw new Error("No OAuth PKCE code verifier is stored");return verifier}async invalidateCredentials(kind){await this.update(value=>{let next={...value};return(kind==="all"||kind==="client")&&delete next.clientInformation,(kind==="all"||kind==="tokens")&&(delete next.tokens,delete next.tokensExpireAt,delete next.clientMetadataUrl),(kind==="all"||kind==="verifier")&&(delete next.codeVerifier,delete next.authorizationRequest,delete next.oauthState),(kind==="all"||kind==="discovery")&&delete next.discovery,next})}async saveDiscoveryState(discovery){await this.update(value=>({...value,discovery}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(update){this.writes=this.writes.then(async()=>{await this.store.save(update(this.own(await this.store.load())))}),await this.writes}own(state){return state?.serverUrl===this.serverUrl?state:{serverUrl:this.serverUrl}}};function clientMetadataBaseUrl(settings){let registration=settings.clientRegistration;if(registration!==void 0&®istration!=="dcr"&®istration!=="cimd")throw new Error('oauth.clientRegistration must be "dcr" or "cimd"');if(registration!=="cimd"){if(settings.clientMetadataBaseUrl!==void 0)throw new Error('oauth.clientMetadataBaseUrl requires oauth.clientRegistration "cimd"');return}if(settings.clientId!==void 0||settings.clientName!==void 0||settings.clientSecret!==void 0)throw new Error('oauth.clientRegistration "cimd" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret');if(settings.clientMetadataBaseUrl===void 0)throw new Error('oauth.clientMetadataBaseUrl is required for "cimd"');let base=parseClientMetadataBaseUrl(settings.clientMetadataBaseUrl);if(!base)throw new Error('oauth.clientMetadataBaseUrl is required for "cimd" and must be an absolute HTTPS URL without userinfo, query, or fragment');return base}function createOAuthClientProvider(options,redirectUrl,onRedirect=()=>{}){let{serverUrl,settings,clientMetadataDocuments:documents}=options,baseUrl=clientMetadataBaseUrl(settings);return new McpOAuthProvider({serverUrl,redirectUrl,clientMetadata:{client_name:settings.clientName??options.clientName},clientMetadataDocument:baseUrl?metadata=>{if(!documents?.listsRedirectUrl(redirectUrl))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${redirectUrl}`);return clientMetadataDocument(baseUrl,serverUrl,redirectUrl,metadata)}:void 0,clientId:settings.clientId,clientSecret:settings.clientSecret,store:options.store,onRedirect})}function offersClientMetadataDocument(settings){return clientMetadataBaseUrl(settings)!==void 0}function clientMetadataDocument(baseUrl,serverUrl,redirectUrl,metadata){if(!metadata?.client_id_metadata_document_supported||!metadata.token_endpoint_auth_methods_supported?.includes("none"))throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');let[shared,serverSpecific]=clientMetadataDocumentUrls(baseUrl,serverUrl);if(metadata.authorization_response_iss_parameter_supported)return{url:shared,redirectUrl};let redirect=new URL(redirectUrl);return redirect.pathname=serverSpecificPath(redirect.pathname,serverUrl),{url:serverSpecific,redirectUrl:redirect.href}}function clientMetadataDocumentUrls(baseUrl,serverUrl){return[new URL("client.json",baseUrl).href,new URL(`${callbackId(serverUrl)}/client.json`,baseUrl).href]}function matchesClient(state,serverUrl,baseUrl){return!state||state.serverUrl!==new URL(serverUrl).href?!1:baseUrl?state.clientMetadataUrl!==void 0&&clientMetadataDocumentUrls(baseUrl,serverUrl).includes(state.clientMetadataUrl):state.clientMetadataUrl===void 0}function serverSpecificPath(path,serverUrl){return`${path.replace(/\/$/,"")}/${callbackId(serverUrl)}`}function callbackId(serverUrl){let url=new URL(serverUrl);return url.hash="",createHash("sha256").update(url.href).digest().subarray(0,9).toString("base64url")}function registeredRedirectUrls(client){return client&&"redirect_uris"in client?client.redirect_uris:[]}var OAUTH_REQUEST_TIMEOUT_MS=15e3;function timedFetch(fetch=globalThis.fetch){return(input,init)=>{let timeout=AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);return fetch(input,{...init,signal:init?.signal?AbortSignal.any([init.signal,timeout]):timeout})}}var CALLBACK_HOST="127.0.0.1",CALLBACK_PATH="/callback",DEFAULT_REDIRECT_URL=`http://${CALLBACK_HOST}${CALLBACK_PATH}`;function loopbackSettings(settings){let configured=settings.callbackUrl??DEFAULT_REDIRECT_URL,url=new URL(configured),address=url.hostname.replace(/^\[|\]$/g,""),port=url.port?Number(url.port):settings.callbackPort,fixedRedirectUrl;return url.port?fixedRedirectUrl=settings.callbackUrl:port!==void 0&&(url.port=String(port),fixedRedirectUrl=url.href),{url:configured,host:address==="localhost"?CALLBACK_HOST:address,redirectHost:address,port,path:url.pathname,fixedRedirectUrl}}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRegistrationError=class extends Error{status;body;constructor(status,body){super(`OAuth dynamic client registration failed with status ${status}: ${body}`),this.name="OAuthRegistrationError",this.status=status,this.body=body}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},McpRefreshLockBusyError=class extends Error{constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function object(value,name){if(!isObject(value))throw new Error(`Invalid ${name}`);return value}function compact(value){return Object.fromEntries(Object.entries(value).filter(([,item])=>item!==void 0))}function requiredString(value,name){if(typeof value!="string"||value.length===0)throw new Error(`Invalid ${name}`);return value}function absent(value){return value==null||value===""}function optionalString(value,name){if(!absent(value))return requiredString(value,name)}function optionalStrings(value,name){if(value!=null){if(!Array.isArray(value)||value.some(item=>typeof item!="string"))throw new Error(`Invalid ${name}`);return[...value]}}function safeUrl(value,name){let text=requiredString(value,name);if(!URL.canParse(text)||!isHttpUrl(new URL(text)))throw new Error(`Invalid ${name}`);return text}function isHttpUrl(url){return url.protocol==="http:"||url.protocol==="https:"}function optionalUrl(value,name){return absent(value)?void 0:safeUrl(value,name)}function parseProtectedResourceMetadata(value){let input=object(value,"OAuth protected resource metadata");return compact({...input,resource:safeUrl(input.resource,"OAuth protected resource metadata resource"),authorization_servers:optionalStrings(input.authorization_servers,"authorization_servers")?.map(url=>safeUrl(url,"authorization server URL")),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported")})}function parseAuthorizationServerMetadata(value){let input=object(value,"authorization server metadata"),responseTypes=optionalStrings(input.response_types_supported,"response_types_supported");if(!responseTypes)throw new Error("Invalid response_types_supported");return compact({...input,issuer:safeUrl(input.issuer,"authorization server issuer"),authorization_endpoint:safeUrl(input.authorization_endpoint,"authorization endpoint"),token_endpoint:safeUrl(input.token_endpoint,"token endpoint"),registration_endpoint:optionalUrl(input.registration_endpoint,"registration endpoint"),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported"),response_types_supported:responseTypes,grant_types_supported:optionalStrings(input.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:optionalStrings(input.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:optionalStrings(input.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof input.client_id_metadata_document_supported=="boolean"?input.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof input.authorization_response_iss_parameter_supported=="boolean"?input.authorization_response_iss_parameter_supported:void 0})}function parseOAuthTokens(value){let input=object(value,"OAuth token response"),expires=absent(input.expires_in)?void 0:Number(input.expires_in);if(expires!==void 0&&!Number.isFinite(expires))throw new Error("Invalid expires_in");return compact({access_token:requiredString(input.access_token,"access_token"),token_type:requiredString(input.token_type,"token_type"),expires_in:expires,scope:optionalString(input.scope,"scope"),refresh_token:optionalString(input.refresh_token,"refresh_token"),id_token:optionalString(input.id_token,"id_token")})}function parseClientInformation(value){let input=object(value,"OAuth client registration response");return compact({...input,client_id:requiredString(input.client_id,"client_id"),client_secret:optionalString(input.client_secret,"client_secret"),client_id_issued_at:typeof input.client_id_issued_at=="number"?input.client_id_issued_at:void 0,client_secret_expires_at:typeof input.client_secret_expires_at=="number"?input.client_secret_expires_at:void 0,redirect_uris:optionalStrings(input.redirect_uris,"redirect_uris")??[]})}function discard(response){response?.body?.cancel().catch(()=>{})}function isDiscoveryMiss(status){return status>=400&&status<500||status===502}function pathSuffix(pathname){return pathname.endsWith("/")?pathname.slice(0,-1):pathname}function field(header,name){let match=header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`,"i"));return match?.[1]||match?.[2]||void 0}function parseWwwAuthenticate(header){if(!header)return{};let scheme=header.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(scheme!=="bearer"&&scheme!=="dpop")return{};let resourceMetadata=field(header,"resource_metadata"),resourceMetadataUrl;if(resourceMetadata)try{resourceMetadataUrl=new URL(resourceMetadata)}catch{}return{resourceMetadataUrl,scope:field(header,"scope"),error:field(header,"error"),errorDescription:field(header,"error_description")}}async function fetchMetadata(url,fetch,protocolVersion,signal){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion},signal})}async function discoverProtectedResourceMetadata(serverUrl,options={}){let server=new URL(serverUrl),fetch=options.fetch??globalThis.fetch,version=options.protocolVersion??LATEST_PROTOCOL_VERSION,response=await fetchMetadata(options.resourceMetadataUrl?new URL(options.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,server.origin),fetch,version,options.signal);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version,options.signal)),!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);return parseProtectedResourceMetadata(await response.json())}function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl){let issuer=new URL(authorizationServerUrl),path=pathSuffix(issuer.pathname),urls=[{url:new URL(`/.well-known/oauth-authorization-server${path}`,issuer.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${path}`,issuer.origin),type:"oidc"}];return path&&urls.push({url:new URL(`${path}/.well-known/openid-configuration`,issuer.origin),type:"oidc"}),urls}async function discoverAuthorizationServerMetadata(authorizationServerUrl,options={}){let fetch=options.fetch??globalThis.fetch;for(let{url}of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)){let response=await fetchMetadata(url,fetch,options.protocolVersion??LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok){if(discard(response),isDiscoveryMiss(response.status))continue;throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`)}let metadata=parseAuthorizationServerMetadata(await response.json());if(!options.skipIssuerValidation){let expected=String(authorizationServerUrl),trim=value=>value.endsWith("/")?value.slice(0,-1):value;if(trim(metadata.issuer)!==trim(expected))throw new OAuthIssuerMismatchError(expected,metadata.issuer)}return metadata}}async function discoverOAuthServerInfo(serverUrl,options={}){let resourceMetadata;try{resourceMetadata=await discoverProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,fetch:options.fetch,signal:options.signal})}catch(error){if(error instanceof TypeError)throw error}if(options.authorizationServerMetadataUrl){let url=options.authorizationServerMetadataUrl,response=await fetchMetadata(url,options.fetch??globalThis.fetch,LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);let metadata=parseAuthorizationServerMetadata(await response.json());return{authorizationServerUrl:metadata.issuer,authorizationServerMetadata:metadata,resourceMetadata}}let authorizationServerUrl=resourceMetadata?.authorization_servers?.[0]??String(new URL("/",serverUrl));return{authorizationServerUrl,authorizationServerMetadata:await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata}}function resourceUrlFromServerUrl(value){let url=new URL(value);return url.hash="",url}function selectResource(serverUrl,metadata){if(!metadata)return;let requested=resourceUrlFromServerUrl(serverUrl),configured=new URL(metadata.resource);if(requested.origin!==configured.origin)throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);let requestedPath=requested.pathname.endsWith("/")?requested.pathname:`${requested.pathname}/`,configuredPath=configured.pathname.endsWith("/")?configured.pathname:`${configured.pathname}/`;if(!requestedPath.startsWith(configuredPath))throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);return metadata.resource}function loopback(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function applicationType(redirectUris){return redirectUris.some(uri=>{if(!URL.canParse(uri))return!1;let url=new URL(uri);return url.protocol!=="http:"&&url.protocol!=="https:"||loopback(url.hostname)})?"native":"web"}function secureEndpoint(value){let url=new URL(value);if(url.protocol!=="https:"&&!loopback(url.hostname))throw new OAuthInsecureEndpointError(url.href);return url}function selectClientAuthMethod(information,supported){let hinted="token_endpoint_auth_method"in information?information.token_endpoint_auth_method:void 0;return hinted&&["client_secret_basic","client_secret_post","none"].includes(hinted)&&(supported.length===0||supported.includes(hinted))?hinted:supported.length===0?information.client_secret?"client_secret_basic":"none":information.client_secret&&supported.includes("client_secret_basic")?"client_secret_basic":information.client_secret&&supported.includes("client_secret_post")?"client_secret_post":supported.includes("none")?"none":information.client_secret?"client_secret_post":"none"}function applyClientAuthentication(method,information,headers,params){if(method==="client_secret_basic"){if(!information.client_secret)throw new Error("client_secret_basic requires a client secret");headers.set("Authorization",`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`)}else params.set("client_id",information.client_id),method==="client_secret_post"&&information.client_secret&¶ms.set("client_secret",information.client_secret)}async function pkce(){let bytes=crypto.getRandomValues(new Uint8Array(32)),verifier=Buffer.from(bytes).toString("base64url"),digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:Buffer.from(digest).toString("base64url")}}async function startAuthorization(authorizationServerUrl,options){let metadata=options.metadata;if(metadata&&!metadata.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(metadata?.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let url=new URL(metadata?.authorization_endpoint??new URL("/authorize",authorizationServerUrl));if(!isHttpUrl(url))throw new Error(`Invalid authorization endpoint ${url.href}`);let{verifier,challenge}=await pkce();return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",options.clientInformation.client_id),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("redirect_uri",String(options.redirectUrl)),options.state&&url.searchParams.set("state",options.state),options.scope&&url.searchParams.set("scope",options.scope),options.scope?.split(/\s+/).includes("offline_access")&&url.searchParams.set("prompt","consent"),options.resource&&url.searchParams.set("resource",options.resource),{authorizationUrl:url,codeVerifier:verifier}}function tokenEndpoint(authorizationServerUrl,metadata){return new URL(metadata?.token_endpoint??new URL("/token",authorizationServerUrl))}async function tokenRequest(authorizationServerUrl,options,params){let url=secureEndpoint(tokenEndpoint(authorizationServerUrl,options.metadata)),headers=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});options.resource&¶ms.set("resource",options.resource),options.addClientAuthentication?await options.addClientAuthentication(headers,params,url,options.metadata):applyClientAuthentication(selectClientAuthMethod(options.clientInformation,options.metadata?.token_endpoint_auth_methods_supported??[]),options.clientInformation,headers,params);let response=await(options.fetch??globalThis.fetch)(url,{method:"POST",headers,body:params,signal:options.signal}),text=await response.text(),value;try{value=JSON.parse(text)}catch{}if(isObject(value)&&typeof value.error=="string")throw new OAuthError(value.error,typeof value.error_description=="string"?value.error_description:value.error,typeof value.error_uri=="string"?value.error_uri:void 0);if(!response.ok)throw new OAuthError("server_error",`HTTP ${response.status}: ${text}`);return parseOAuthTokens(value)}async function registerClient(authorizationServerUrl,options){let endpoint=options.metadata?.registration_endpoint;if(options.metadata&&!endpoint)throw new Error("Authorization server does not support dynamic client registration");let response=await(options.fetch??globalThis.fetch)(new URL(endpoint??new URL("/register",authorizationServerUrl)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...options.clientMetadata,application_type:options.clientMetadata.application_type??applicationType(options.clientMetadata.redirect_uris),...options.scope?{scope:options.scope}:{}}),signal:options.signal});if(!response.ok)throw new OAuthRegistrationError(response.status,await response.text());return parseClientInformation(await response.json())}async function exchangeAuthorizationCode(authorizationServerUrl,options){return tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"authorization_code",code:options.code,code_verifier:options.codeVerifier,redirect_uri:String(options.redirectUrl)}))}async function refreshAuthorization(authorizationServerUrl,options){let tokens=await tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"refresh_token",refresh_token:options.refreshToken}));return{refresh_token:options.refreshToken,...tokens}}function withScope(tokens,scope){return tokens.scope===void 0&&scope?{...tokens,scope}:tokens}function stepUpScope(granted,challenged){if(!challenged)return;let scopes=[granted,challenged].flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]);return[...new Set(scopes)].join(" ")}async function runFlow(provider,options,use={}){let metadataUrl=options.authorizationServerMetadataUrl&&secureEndpoint(options.authorizationServerMetadataUrl),cached=metadataUrl?void 0:await provider.discoveryState?.(),discovered=cached?.authorizationServerUrl?{authorizationServerUrl:cached.authorizationServerUrl,authorizationServerMetadata:cached.authorizationServerMetadata??await discoverAuthorizationServerMetadata(cached.authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal});metadataUrl||await provider.saveDiscoveryState?.({...discovered,...options.resourceMetadataUrl?{resourceMetadataUrl:options.resourceMetadataUrl.href}:{}});let metadata=discovered.authorizationServerMetadata,resource=selectResource(options.serverUrl,discovered.resourceMetadata),scope=options.scope||discovered.resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,clientDocument=provider.clientMetadataDocument?.(metadata),stored=clientDocument?void 0:await provider.clientInformation();if(use.storedClientId=stored?.client_id,clientDocument){let url=new URL(clientDocument.url);if(url.protocol!=="https:"||url.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let redirectUrl=clientDocument?.redirectUrl??String(provider.redirectUrl);if(options.authorizationCode&&options.authorizationRedirectUrl!==void 0&&redirectUrl!==options.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);let client=stored??(clientDocument&&{client_id:clientDocument.url});if(!client){if(options.refreshOnly)return"REDIRECT";if(options.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!provider.saveClientInformation)throw new Error("OAuth client information cannot be persisted");client=await registerClient(discovered.authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope,fetch:options.fetch,signal:options.signal}),await provider.saveClientInformation(client)}let tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch,signal:options.signal};if(options.authorizationCode){let request=options.authorizationRequest;if(request){let current=[["client",client.client_id,request.clientId],["authorization server",discovered.authorizationServerUrl,request.authorizationServerUrl],["token endpoint",tokenEndpoint(discovered.authorizationServerUrl,metadata).href,request.tokenEndpoint]];for(let[name,actual,expected]of current)if(actual!==expected)throw new Error(`The code exchange would use the ${name} ${actual}, but the authorization request used ${expected}; sign in again`)}let iss=options.iss;if((iss!==void 0||metadata?.authorization_response_iss_parameter_supported)&&iss!==metadata?.issuer)throw new OAuthIssuerMismatchError(metadata?.issuer,iss);let tokens=await exchangeAuthorizationCode(discovered.authorizationServerUrl,{...tokenOptions,code:options.authorizationCode,codeVerifier:await provider.codeVerifier(),redirectUrl});return await provider.saveTokens(withScope(tokens,request?request.scope:scope)),await provider.invalidateCredentials?.("verifier"),"AUTHORIZED"}let existing=options.skipRefresh?void 0:await provider.tokens();if(existing?.refresh_token)try{let tokens=await refreshAuthorization(discovered.authorizationServerUrl,{...tokenOptions,refreshToken:existing.refresh_token});return await provider.saveTokens(withScope(tokens,existing.scope)),"AUTHORIZED"}catch(error){if(options.signal?.aborted||error instanceof OAuthInsecureEndpointError||error instanceof OAuthError&&error.code!=="server_error")throw error}if(options.refreshOnly)return"REDIRECT";let state=await provider.state?.(),authorization=await startAuthorization(discovered.authorizationServerUrl,{metadata,clientInformation:client,redirectUrl,scope,state,resource});return await provider.saveAuthorizationRequest?.({clientId:client.client_id,authorizationServerUrl:discovered.authorizationServerUrl,tokenEndpoint:tokenEndpoint(discovered.authorizationServerUrl,metadata).href,...scope?{scope}:{}}),await provider.saveCodeVerifier(authorization.codeVerifier),await provider.redirectToAuthorization(authorization.authorizationUrl),"REDIRECT"}async function authorizeMcp(provider,options){let use={};try{return await runFlow(provider,options,use)}catch(error){if(error instanceof OAuthError&&["invalid_client","unauthorized_client"].includes(error.code)){if(options.refreshOnly){if((await provider.clientInformation())?.client_id===use.storedClientId)for(let kind of["client","tokens","discovery"])await provider.invalidateCredentials?.(kind)}else await provider.invalidateCredentials?.("all");return runFlow(provider,options)}if(error instanceof OAuthError&&error.code==="invalid_grant")return await provider.invalidateCredentials?.("tokens"),runFlow(provider,options);throw error}}var REFRESH_SKEW_MS=3e4;function createMcpAuthProvider(options){let{serverUrl,store,redirectUrl}=options,baseUrl=options.clientMetadataBaseUrl===void 0?void 0:parseClientMetadataBaseUrl(options.clientMetadataBaseUrl);if(options.clientMetadataBaseUrl!==void 0&&!baseUrl)throw new Error("oauth.clientMetadataBaseUrl must be an absolute HTTPS URL without userinfo, query, or fragment");let owns=state=>matchesClient(state,serverUrl,baseUrl),refreshing,refresh=(staleToken,fetch=globalThis.fetch,challenge)=>(refreshing??=store.withRefreshLock(async()=>{let state=await store.load();if(!owns(state))throw new McpOAuthAuthorizationRequiredError;if(state?.tokens?.access_token!==staleToken)return;if(!state?.tokens?.refresh_token)throw new McpOAuthAuthorizationRequiredError;let client={...options,settings:options.settings()};if(await refreshStoredTokens(client,state,{fetch,challenge,redirectUrl})==="REDIRECT")throw new McpOAuthAuthorizationRequiredError}).finally(()=>{refreshing=void 0}),refreshing);return{token:async()=>{await refreshing?.catch(()=>{});let state=await store.load();if(!owns(state))return;let token=state?.tokens?.access_token;if(!(state?.tokensExpireAt!==void 0&&state.tokensExpireAt-REFRESH_SKEW_MS<=Date.now())||!state?.tokens?.refresh_token)return token;await refresh(token).catch(()=>{});let refreshed=await store.load();return owns(refreshed)?refreshed?.tokens?.access_token:void 0},onUnauthorized:async context=>{let challenge=parseWwwAuthenticate(context.response.headers.get("www-authenticate"));if(options.onChallenge(challenge),challenge.error==="insufficient_scope")throw new McpOAuthAuthorizationRequiredError;await refresh(context.token,context.fetch,challenge)},settled:async()=>{await refreshing?.catch(()=>{})}}}async function refreshStoredTokens(client,state,options={}){if(!matchesClient(state,client.serverUrl,clientMetadataBaseUrl(client.settings)))return"REDIRECT";let redirectUrl=[options.redirectUrl,loopbackSettings(client.settings).fixedRedirectUrl,registeredRedirectUrls(state.clientInformation)[0]].filter(url=>url!==void 0).find(url=>client.clientMetadataDocuments?.listsRedirectUrl(url))??DEFAULT_REDIRECT_URL;return authorizeMcp(createOAuthClientProvider(client,redirectUrl),{serverUrl:client.serverUrl,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:client.settings.authServerMetadataUrl,fetch:timedFetch(options.fetch),refreshOnly:!0})}import{createServer}from"node:http";function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
|
|
2
|
+
import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isClientMetadataDocumentCallback,isObject,mcpNamespace,parseClientMetadataBaseUrl,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-O2P5SYXT.js";import{sliceTail}from"./chunk-4FPBO5KP.js";import{require_proper_lockfile}from"./chunk-2JZLKNZ4.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-6M3D4XVD.js";import{__toESM}from"./chunk-HZ2UHMBT.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createHash}from"node:crypto";var MemoryOAuthStateStore=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(state){this.value=structuredClone(state)}},McpOAuthProvider=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();selectedClientMetadata;constructor(options){if(this.serverUrl=String(new URL(options.serverUrl)),this.redirectUrl=String(options.redirectUrl),this.clientMetadata={...options.clientMetadata,redirect_uris:options.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:options.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:options.clientMetadata.response_types??["code"],token_endpoint_auth_method:options.clientMetadata.token_endpoint_auth_method??(options.clientSecret?"client_secret_post":"none")},options.clientMetadataDocument){let selectDocument=options.clientMetadataDocument;this.clientMetadataDocument=metadata=>{let document=selectDocument(metadata);return this.selectedClientMetadata={url:document?.url},document}}this.configuredClient=options.clientId?{client_id:options.clientId,...options.clientSecret?{client_secret:options.clientSecret}:{}}:void 0,this.store=options.store??new MemoryOAuthStateStore,this.onRedirect=options.onRedirect}async state(){let existing=(await this.load()).oauthState;if(existing)return existing;let state=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(value=>({...value,oauthState:state})),state}async clientInformation(){let state=await this.load();if(!(!this.selectCachedClientDocument(state)||this.selectedClientMetadata?.url))return this.configuredClient??(state.clientMetadataUrl?void 0:state.clientInformation)}async saveClientInformation(information){this.configuredClient||await this.update(value=>({...value,clientInformation:information}))}async tokens(){let state=await this.load();if(this.selectCachedClientDocument(state)&&state.clientMetadataUrl===this.selectedClientMetadata?.url)return state.tokens}selectCachedClientDocument(state){if(!this.clientMetadataDocument||this.selectedClientMetadata)return!0;let metadata=state.discovery?.authorizationServerMetadata;return metadata?(this.clientMetadataDocument(metadata),!0):!1}async saveTokens(tokens){let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1e3;await this.update(value=>{let next={...value,tokens};return this.selectedClientMetadata?.url?(next.clientMetadataUrl=this.selectedClientMetadata.url,delete next.clientInformation):delete next.clientMetadataUrl,expiresAt===void 0?delete next.tokensExpireAt:next.tokensExpireAt=expiresAt,next})}async redirectToAuthorization(url){await this.onRedirect(url)}async saveCodeVerifier(verifier){await this.update(value=>({...value,codeVerifier:verifier}))}async saveAuthorizationRequest(request){await this.update(value=>({...value,authorizationRequest:request}))}async codeVerifier(){let verifier=(await this.load()).codeVerifier;if(!verifier)throw new Error("No OAuth PKCE code verifier is stored");return verifier}async invalidateCredentials(kind){await this.update(value=>{let next={...value};return(kind==="all"||kind==="client")&&delete next.clientInformation,(kind==="all"||kind==="tokens")&&(delete next.tokens,delete next.tokensExpireAt,delete next.clientMetadataUrl),(kind==="all"||kind==="verifier")&&(delete next.codeVerifier,delete next.authorizationRequest,delete next.oauthState),(kind==="all"||kind==="discovery")&&delete next.discovery,next})}async saveDiscoveryState(discovery){await this.update(value=>({...value,discovery}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(update){this.writes=this.writes.then(async()=>{await this.store.save(update(this.own(await this.store.load())))}),await this.writes}own(state){return state?.serverUrl===this.serverUrl?state:{serverUrl:this.serverUrl}}};function clientMetadataBaseUrl(settings){let registration=settings.clientRegistration;if(registration!==void 0&®istration!=="dcr"&®istration!=="cimd")throw new Error('oauth.clientRegistration must be "dcr" or "cimd"');if(registration!=="cimd"){if(settings.clientMetadataBaseUrl!==void 0)throw new Error('oauth.clientMetadataBaseUrl requires oauth.clientRegistration "cimd"');return}if(settings.clientId!==void 0||settings.clientName!==void 0||settings.clientSecret!==void 0)throw new Error('oauth.clientRegistration "cimd" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret');if(settings.clientMetadataBaseUrl===void 0)throw new Error('oauth.clientMetadataBaseUrl is required for "cimd"');let base=parseClientMetadataBaseUrl(settings.clientMetadataBaseUrl);if(!base)throw new Error('oauth.clientMetadataBaseUrl is required for "cimd" and must be an absolute HTTPS URL without userinfo, query, or fragment');return base}function createOAuthClientProvider(options,redirectUrl,onRedirect=()=>{}){let{serverUrl,settings,clientMetadataDocuments:documents}=options,baseUrl=clientMetadataBaseUrl(settings);return new McpOAuthProvider({serverUrl,redirectUrl,clientMetadata:{client_name:settings.clientName??options.clientName},clientMetadataDocument:baseUrl?metadata=>{if(!documents?.listsRedirectUrl(redirectUrl))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${redirectUrl}`);return clientMetadataDocument(baseUrl,serverUrl,redirectUrl,metadata)}:void 0,clientId:settings.clientId,clientSecret:settings.clientSecret,store:options.store,onRedirect})}function offersClientMetadataDocument(settings){return clientMetadataBaseUrl(settings)!==void 0}function clientMetadataDocument(baseUrl,serverUrl,redirectUrl,metadata){if(!metadata?.client_id_metadata_document_supported||!metadata.token_endpoint_auth_methods_supported?.includes("none"))throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');let[shared,serverSpecific]=clientMetadataDocumentUrls(baseUrl,serverUrl);if(metadata.authorization_response_iss_parameter_supported)return{url:shared,redirectUrl};let redirect=new URL(redirectUrl);return redirect.pathname=serverSpecificPath(redirect.pathname,serverUrl),{url:serverSpecific,redirectUrl:redirect.href}}function clientMetadataDocumentUrls(baseUrl,serverUrl){return[new URL("client.json",baseUrl).href,new URL(`${callbackId(serverUrl)}/client.json`,baseUrl).href]}function matchesClient(state,serverUrl,baseUrl){return!state||state.serverUrl!==new URL(serverUrl).href?!1:baseUrl?state.clientMetadataUrl!==void 0&&clientMetadataDocumentUrls(baseUrl,serverUrl).includes(state.clientMetadataUrl):state.clientMetadataUrl===void 0}function serverSpecificPath(path,serverUrl){return`${path.replace(/\/$/,"")}/${callbackId(serverUrl)}`}function callbackId(serverUrl){let url=new URL(serverUrl);return url.hash="",createHash("sha256").update(url.href).digest().subarray(0,9).toString("base64url")}function registeredRedirectUrls(client){return client&&"redirect_uris"in client?client.redirect_uris:[]}var OAUTH_REQUEST_TIMEOUT_MS=15e3;function timedFetch(fetch=globalThis.fetch){return(input,init)=>{let timeout=AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);return fetch(input,{...init,signal:init?.signal?AbortSignal.any([init.signal,timeout]):timeout})}}var CALLBACK_HOST="127.0.0.1",CALLBACK_PATH="/callback",DEFAULT_REDIRECT_URL=`http://${CALLBACK_HOST}${CALLBACK_PATH}`;function loopbackSettings(settings){let configured=settings.callbackUrl??DEFAULT_REDIRECT_URL,url=new URL(configured),address=url.hostname.replace(/^\[|\]$/g,""),port=url.port?Number(url.port):settings.callbackPort,fixedRedirectUrl;return url.port?fixedRedirectUrl=settings.callbackUrl:port!==void 0&&(url.port=String(port),fixedRedirectUrl=url.href),{url:configured,host:address==="localhost"?CALLBACK_HOST:address,redirectHost:address,port,path:url.pathname,fixedRedirectUrl}}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRegistrationError=class extends Error{status;body;constructor(status,body){super(`OAuth dynamic client registration failed with status ${status}: ${body}`),this.name="OAuthRegistrationError",this.status=status,this.body=body}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},McpRefreshLockBusyError=class extends Error{constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function object(value,name){if(!isObject(value))throw new Error(`Invalid ${name}`);return value}function compact(value){return Object.fromEntries(Object.entries(value).filter(([,item])=>item!==void 0))}function requiredString(value,name){if(typeof value!="string"||value.length===0)throw new Error(`Invalid ${name}`);return value}function absent(value){return value==null||value===""}function optionalString(value,name){if(!absent(value))return requiredString(value,name)}function optionalStrings(value,name){if(value!=null){if(!Array.isArray(value)||value.some(item=>typeof item!="string"))throw new Error(`Invalid ${name}`);return[...value]}}function safeUrl(value,name){let text=requiredString(value,name);if(!URL.canParse(text)||!isHttpUrl(new URL(text)))throw new Error(`Invalid ${name}`);return text}function isHttpUrl(url){return url.protocol==="http:"||url.protocol==="https:"}function optionalUrl(value,name){return absent(value)?void 0:safeUrl(value,name)}function parseProtectedResourceMetadata(value){let input=object(value,"OAuth protected resource metadata");return compact({...input,resource:safeUrl(input.resource,"OAuth protected resource metadata resource"),authorization_servers:optionalStrings(input.authorization_servers,"authorization_servers")?.map(url=>safeUrl(url,"authorization server URL")),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported")})}function parseAuthorizationServerMetadata(value){let input=object(value,"authorization server metadata"),responseTypes=optionalStrings(input.response_types_supported,"response_types_supported");if(!responseTypes)throw new Error("Invalid response_types_supported");return compact({...input,issuer:safeUrl(input.issuer,"authorization server issuer"),authorization_endpoint:safeUrl(input.authorization_endpoint,"authorization endpoint"),token_endpoint:safeUrl(input.token_endpoint,"token endpoint"),registration_endpoint:optionalUrl(input.registration_endpoint,"registration endpoint"),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported"),response_types_supported:responseTypes,grant_types_supported:optionalStrings(input.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:optionalStrings(input.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:optionalStrings(input.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof input.client_id_metadata_document_supported=="boolean"?input.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof input.authorization_response_iss_parameter_supported=="boolean"?input.authorization_response_iss_parameter_supported:void 0})}function parseOAuthTokens(value){let input=object(value,"OAuth token response"),expires=absent(input.expires_in)?void 0:Number(input.expires_in);if(expires!==void 0&&!Number.isFinite(expires))throw new Error("Invalid expires_in");return compact({access_token:requiredString(input.access_token,"access_token"),token_type:requiredString(input.token_type,"token_type"),expires_in:expires,scope:optionalString(input.scope,"scope"),refresh_token:optionalString(input.refresh_token,"refresh_token"),id_token:optionalString(input.id_token,"id_token")})}function parseClientInformation(value){let input=object(value,"OAuth client registration response");return compact({...input,client_id:requiredString(input.client_id,"client_id"),client_secret:optionalString(input.client_secret,"client_secret"),client_id_issued_at:typeof input.client_id_issued_at=="number"?input.client_id_issued_at:void 0,client_secret_expires_at:typeof input.client_secret_expires_at=="number"?input.client_secret_expires_at:void 0,redirect_uris:optionalStrings(input.redirect_uris,"redirect_uris")??[]})}function discard(response){response?.body?.cancel().catch(()=>{})}function isDiscoveryMiss(status){return status>=400&&status<500||status===502}function pathSuffix(pathname){return pathname.endsWith("/")?pathname.slice(0,-1):pathname}function field(header,name){let match=header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`,"i"));return match?.[1]||match?.[2]||void 0}function parseWwwAuthenticate(header){if(!header)return{};let scheme=header.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(scheme!=="bearer"&&scheme!=="dpop")return{};let resourceMetadata=field(header,"resource_metadata"),resourceMetadataUrl;if(resourceMetadata)try{resourceMetadataUrl=new URL(resourceMetadata)}catch{}return{resourceMetadataUrl,scope:field(header,"scope"),error:field(header,"error"),errorDescription:field(header,"error_description")}}async function fetchMetadata(url,fetch,protocolVersion,signal){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion},signal})}async function discoverProtectedResourceMetadata(serverUrl,options={}){let server=new URL(serverUrl),fetch=options.fetch??globalThis.fetch,version=options.protocolVersion??LATEST_PROTOCOL_VERSION,response=await fetchMetadata(options.resourceMetadataUrl?new URL(options.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,server.origin),fetch,version,options.signal);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version,options.signal)),!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);return parseProtectedResourceMetadata(await response.json())}function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl){let issuer=new URL(authorizationServerUrl),path=pathSuffix(issuer.pathname),urls=[{url:new URL(`/.well-known/oauth-authorization-server${path}`,issuer.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${path}`,issuer.origin),type:"oidc"}];return path&&urls.push({url:new URL(`${path}/.well-known/openid-configuration`,issuer.origin),type:"oidc"}),urls}async function discoverAuthorizationServerMetadata(authorizationServerUrl,options={}){let fetch=options.fetch??globalThis.fetch;for(let{url}of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)){let response=await fetchMetadata(url,fetch,options.protocolVersion??LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok){if(discard(response),isDiscoveryMiss(response.status))continue;throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`)}let metadata=parseAuthorizationServerMetadata(await response.json());if(!options.skipIssuerValidation){let expected=String(authorizationServerUrl),trim=value=>value.endsWith("/")?value.slice(0,-1):value;if(trim(metadata.issuer)!==trim(expected))throw new OAuthIssuerMismatchError(expected,metadata.issuer)}return metadata}}async function discoverOAuthServerInfo(serverUrl,options={}){let resourceMetadata;try{resourceMetadata=await discoverProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,fetch:options.fetch,signal:options.signal})}catch(error){if(error instanceof TypeError)throw error}if(options.authorizationServerMetadataUrl){let url=options.authorizationServerMetadataUrl,response=await fetchMetadata(url,options.fetch??globalThis.fetch,LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);let metadata=parseAuthorizationServerMetadata(await response.json());return{authorizationServerUrl:metadata.issuer,authorizationServerMetadata:metadata,resourceMetadata}}let authorizationServerUrl=resourceMetadata?.authorization_servers?.[0]??String(new URL("/",serverUrl));return{authorizationServerUrl,authorizationServerMetadata:await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata}}function resourceUrlFromServerUrl(value){let url=new URL(value);return url.hash="",url}function selectResource(serverUrl,metadata){if(!metadata)return;let requested=resourceUrlFromServerUrl(serverUrl),configured=new URL(metadata.resource);if(requested.origin!==configured.origin)throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);let requestedPath=requested.pathname.endsWith("/")?requested.pathname:`${requested.pathname}/`,configuredPath=configured.pathname.endsWith("/")?configured.pathname:`${configured.pathname}/`;if(!requestedPath.startsWith(configuredPath))throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);return metadata.resource}function loopback(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function applicationType(redirectUris){return redirectUris.some(uri=>{if(!URL.canParse(uri))return!1;let url=new URL(uri);return url.protocol!=="http:"&&url.protocol!=="https:"||loopback(url.hostname)})?"native":"web"}function secureEndpoint(value){let url=new URL(value);if(url.protocol!=="https:"&&!loopback(url.hostname))throw new OAuthInsecureEndpointError(url.href);return url}function selectClientAuthMethod(information,supported){let hinted="token_endpoint_auth_method"in information?information.token_endpoint_auth_method:void 0;return hinted&&["client_secret_basic","client_secret_post","none"].includes(hinted)&&(supported.length===0||supported.includes(hinted))?hinted:supported.length===0?information.client_secret?"client_secret_basic":"none":information.client_secret&&supported.includes("client_secret_basic")?"client_secret_basic":information.client_secret&&supported.includes("client_secret_post")?"client_secret_post":supported.includes("none")?"none":information.client_secret?"client_secret_post":"none"}function applyClientAuthentication(method,information,headers,params){if(method==="client_secret_basic"){if(!information.client_secret)throw new Error("client_secret_basic requires a client secret");headers.set("Authorization",`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`)}else params.set("client_id",information.client_id),method==="client_secret_post"&&information.client_secret&¶ms.set("client_secret",information.client_secret)}async function pkce(){let bytes=crypto.getRandomValues(new Uint8Array(32)),verifier=Buffer.from(bytes).toString("base64url"),digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:Buffer.from(digest).toString("base64url")}}async function startAuthorization(authorizationServerUrl,options){let metadata=options.metadata;if(metadata&&!metadata.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(metadata?.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let url=new URL(metadata?.authorization_endpoint??new URL("/authorize",authorizationServerUrl));if(!isHttpUrl(url))throw new Error(`Invalid authorization endpoint ${url.href}`);let{verifier,challenge}=await pkce();return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",options.clientInformation.client_id),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("redirect_uri",String(options.redirectUrl)),options.state&&url.searchParams.set("state",options.state),options.scope&&url.searchParams.set("scope",options.scope),options.scope?.split(/\s+/).includes("offline_access")&&url.searchParams.set("prompt","consent"),options.resource&&url.searchParams.set("resource",options.resource),{authorizationUrl:url,codeVerifier:verifier}}function tokenEndpoint(authorizationServerUrl,metadata){return new URL(metadata?.token_endpoint??new URL("/token",authorizationServerUrl))}async function tokenRequest(authorizationServerUrl,options,params){let url=secureEndpoint(tokenEndpoint(authorizationServerUrl,options.metadata)),headers=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});options.resource&¶ms.set("resource",options.resource),options.addClientAuthentication?await options.addClientAuthentication(headers,params,url,options.metadata):applyClientAuthentication(selectClientAuthMethod(options.clientInformation,options.metadata?.token_endpoint_auth_methods_supported??[]),options.clientInformation,headers,params);let response=await(options.fetch??globalThis.fetch)(url,{method:"POST",headers,body:params,signal:options.signal}),text=await response.text(),value;try{value=JSON.parse(text)}catch{}if(isObject(value)&&typeof value.error=="string")throw new OAuthError(value.error,typeof value.error_description=="string"?value.error_description:value.error,typeof value.error_uri=="string"?value.error_uri:void 0);if(!response.ok)throw new OAuthError("server_error",`HTTP ${response.status}: ${text}`);return parseOAuthTokens(value)}async function registerClient(authorizationServerUrl,options){let endpoint=options.metadata?.registration_endpoint;if(options.metadata&&!endpoint)throw new Error("Authorization server does not support dynamic client registration");let response=await(options.fetch??globalThis.fetch)(new URL(endpoint??new URL("/register",authorizationServerUrl)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...options.clientMetadata,application_type:options.clientMetadata.application_type??applicationType(options.clientMetadata.redirect_uris),...options.scope?{scope:options.scope}:{}}),signal:options.signal});if(!response.ok)throw new OAuthRegistrationError(response.status,await response.text());return parseClientInformation(await response.json())}async function exchangeAuthorizationCode(authorizationServerUrl,options){return tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"authorization_code",code:options.code,code_verifier:options.codeVerifier,redirect_uri:String(options.redirectUrl)}))}async function refreshAuthorization(authorizationServerUrl,options){let tokens=await tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"refresh_token",refresh_token:options.refreshToken}));return{refresh_token:options.refreshToken,...tokens}}function withScope(tokens,scope){return tokens.scope===void 0&&scope?{...tokens,scope}:tokens}function stepUpScope(granted,challenged){if(!challenged)return;let scopes=[granted,challenged].flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]);return[...new Set(scopes)].join(" ")}async function runFlow(provider,options,use={}){let metadataUrl=options.authorizationServerMetadataUrl&&secureEndpoint(options.authorizationServerMetadataUrl),cached=metadataUrl?void 0:await provider.discoveryState?.(),discovered=cached?.authorizationServerUrl?{authorizationServerUrl:cached.authorizationServerUrl,authorizationServerMetadata:cached.authorizationServerMetadata??await discoverAuthorizationServerMetadata(cached.authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal});metadataUrl||await provider.saveDiscoveryState?.({...discovered,...options.resourceMetadataUrl?{resourceMetadataUrl:options.resourceMetadataUrl.href}:{}});let metadata=discovered.authorizationServerMetadata,resource=selectResource(options.serverUrl,discovered.resourceMetadata),scope=options.scope||discovered.resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,clientDocument=provider.clientMetadataDocument?.(metadata),stored=clientDocument?void 0:await provider.clientInformation();if(use.storedClientId=stored?.client_id,clientDocument){let url=new URL(clientDocument.url);if(url.protocol!=="https:"||url.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let redirectUrl=clientDocument?.redirectUrl??String(provider.redirectUrl);if(options.authorizationCode&&options.authorizationRedirectUrl!==void 0&&redirectUrl!==options.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);let client=stored??(clientDocument&&{client_id:clientDocument.url});if(!client){if(options.refreshOnly)return"REDIRECT";if(options.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!provider.saveClientInformation)throw new Error("OAuth client information cannot be persisted");client=await registerClient(discovered.authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope,fetch:options.fetch,signal:options.signal}),await provider.saveClientInformation(client)}let tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch,signal:options.signal};if(options.authorizationCode){let request=options.authorizationRequest;if(request){let current=[["client",client.client_id,request.clientId],["authorization server",discovered.authorizationServerUrl,request.authorizationServerUrl],["token endpoint",tokenEndpoint(discovered.authorizationServerUrl,metadata).href,request.tokenEndpoint]];for(let[name,actual,expected]of current)if(actual!==expected)throw new Error(`The code exchange would use the ${name} ${actual}, but the authorization request used ${expected}; sign in again`)}let iss=options.iss;if((iss!==void 0||metadata?.authorization_response_iss_parameter_supported)&&iss!==metadata?.issuer)throw new OAuthIssuerMismatchError(metadata?.issuer,iss);let tokens=await exchangeAuthorizationCode(discovered.authorizationServerUrl,{...tokenOptions,code:options.authorizationCode,codeVerifier:await provider.codeVerifier(),redirectUrl});return await provider.saveTokens(withScope(tokens,request?request.scope:scope)),await provider.invalidateCredentials?.("verifier"),"AUTHORIZED"}let existing=options.skipRefresh?void 0:await provider.tokens();if(existing?.refresh_token)try{let tokens=await refreshAuthorization(discovered.authorizationServerUrl,{...tokenOptions,refreshToken:existing.refresh_token});return await provider.saveTokens(withScope(tokens,existing.scope)),"AUTHORIZED"}catch(error){if(options.signal?.aborted||error instanceof OAuthInsecureEndpointError||error instanceof OAuthError&&error.code!=="server_error")throw error}if(options.refreshOnly)return"REDIRECT";let state=await provider.state?.(),authorization=await startAuthorization(discovered.authorizationServerUrl,{metadata,clientInformation:client,redirectUrl,scope,state,resource});return await provider.saveAuthorizationRequest?.({clientId:client.client_id,authorizationServerUrl:discovered.authorizationServerUrl,tokenEndpoint:tokenEndpoint(discovered.authorizationServerUrl,metadata).href,...scope?{scope}:{}}),await provider.saveCodeVerifier(authorization.codeVerifier),await provider.redirectToAuthorization(authorization.authorizationUrl),"REDIRECT"}async function authorizeMcp(provider,options){let use={};try{return await runFlow(provider,options,use)}catch(error){if(error instanceof OAuthError&&["invalid_client","unauthorized_client"].includes(error.code)){if(options.refreshOnly){if((await provider.clientInformation())?.client_id===use.storedClientId)for(let kind of["client","tokens","discovery"])await provider.invalidateCredentials?.(kind)}else await provider.invalidateCredentials?.("all");return runFlow(provider,options)}if(error instanceof OAuthError&&error.code==="invalid_grant")return await provider.invalidateCredentials?.("tokens"),runFlow(provider,options);throw error}}var REFRESH_SKEW_MS=3e4;function createMcpAuthProvider(options){let{serverUrl,store,redirectUrl}=options,baseUrl=options.clientMetadataBaseUrl===void 0?void 0:parseClientMetadataBaseUrl(options.clientMetadataBaseUrl);if(options.clientMetadataBaseUrl!==void 0&&!baseUrl)throw new Error("oauth.clientMetadataBaseUrl must be an absolute HTTPS URL without userinfo, query, or fragment");let owns=state=>matchesClient(state,serverUrl,baseUrl),refreshing,refresh=(staleToken,fetch=globalThis.fetch,challenge)=>(refreshing??=store.withRefreshLock(async()=>{let state=await store.load();if(!owns(state))throw new McpOAuthAuthorizationRequiredError;if(state?.tokens?.access_token!==staleToken)return;if(!state?.tokens?.refresh_token)throw new McpOAuthAuthorizationRequiredError;let client={...options,settings:options.settings()};if(await refreshStoredTokens(client,state,{fetch,challenge,redirectUrl})==="REDIRECT")throw new McpOAuthAuthorizationRequiredError}).finally(()=>{refreshing=void 0}),refreshing);return{token:async()=>{await refreshing?.catch(()=>{});let state=await store.load();if(!owns(state))return;let token=state?.tokens?.access_token;if(!(state?.tokensExpireAt!==void 0&&state.tokensExpireAt-REFRESH_SKEW_MS<=Date.now())||!state?.tokens?.refresh_token)return token;await refresh(token).catch(()=>{});let refreshed=await store.load();return owns(refreshed)?refreshed?.tokens?.access_token:void 0},onUnauthorized:async context=>{let challenge=parseWwwAuthenticate(context.response.headers.get("www-authenticate"));if(options.onChallenge(challenge),challenge.error==="insufficient_scope")throw new McpOAuthAuthorizationRequiredError;await refresh(context.token,context.fetch,challenge)},settled:async()=>{await refreshing?.catch(()=>{})}}}async function refreshStoredTokens(client,state,options={}){if(!matchesClient(state,client.serverUrl,clientMetadataBaseUrl(client.settings)))return"REDIRECT";let redirectUrl=[options.redirectUrl,loopbackSettings(client.settings).fixedRedirectUrl,registeredRedirectUrls(state.clientInformation)[0]].filter(url=>url!==void 0).find(url=>client.clientMetadataDocuments?.listsRedirectUrl(url))??DEFAULT_REDIRECT_URL;return authorizeMcp(createOAuthClientProvider(client,redirectUrl),{serverUrl:client.serverUrl,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:client.settings.authServerMetadataUrl,fetch:timedFetch(options.fetch),refreshOnly:!0})}import{createServer}from"node:http";function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
|
|
3
3
|
|
|
4
4
|
${page.details}`:page.message}var OAuthCallbackServer=class _OAuthCallbackServer{redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(server,redirectUrl,paths,timeoutMs,renderPage2){this.server=server,this.redirectUrl=redirectUrl,this.paths=paths,this.timeoutMs=timeoutMs,this.renderPage=renderPage2}static async listen(options={}){let host=options.host??"127.0.0.1",redirectHost=options.redirectHost??host,path=options.path??"/callback",instance,server=createServer((request,response)=>instance?.handle(request.url??"/",request.headers.host,response));await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port??0,host,()=>{server.off("error",reject),resolve2()})});let address=server.address();if(!address||typeof address=="string")throw new Error("OAuth callback server did not bind to TCP");return instance=new _OAuthCallbackServer(server,`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}:${address.port}${path}`,[path,...options.extraPaths??[]],options.timeoutMs??5*6e4,options.renderPage),instance}waitForCallback(state,path){if(this.pending.has(state))throw new Error("OAuth state is already pending");return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{this.pending.delete(state),reject(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(state,{resolve:resolve2,reject,timer,path})})}async close(){for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(new Error("OAuth callback server closed"));this.pending.clear();let closed=new Promise((resolve2,reject)=>{this.server.close(error=>error?reject(error):resolve2())});this.server.closeAllConnections(),await closed}reply(response,status,page){this.renderPage?(response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(this.renderPage(page))):response.writeHead(status,{"content-type":"text/plain; charset=utf-8"}).end(plainText(page))}handle(rawUrl,host,response){let url=new URL(rawUrl,this.redirectUrl),redirect=new URL(this.redirectUrl);if(host!==redirect.host||url.origin!==redirect.origin){this.reply(response,400,{ok:!1,message:"Unexpected redirect origin"});return}if(!this.paths.includes(url.pathname)){this.reply(response,404,{ok:!1,message:"Not found"});return}let state=url.searchParams.get("state"),pending=state?this.pending.get(state):void 0;if(!state||!pending){this.reply(response,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(pending.timer),this.pending.delete(state),pending.path!==void 0&&url.pathname!==pending.path){pending.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(response,400,{ok:!1,message:"Unexpected redirect URI"});return}let error=url.searchParams.get("error");if(error){let description=url.searchParams.get("error_description")??error;pending.reject(new Error(description)),this.reply(response,200,{ok:!1,message:"Authorization failed. You may close this window.",details:description});return}let code=url.searchParams.get("code");if(!code){pending.reject(new Error("OAuth callback did not include an authorization code")),this.reply(response,400,{ok:!1,message:"Missing authorization code"});return}let iss=url.searchParams.get("iss");pending.resolve({code,state,...iss?{iss}:{}}),this.reply(response,200,{ok:!0})}};var McpSignInCancelledError=class extends Error{constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};async function startMcpSignIn(options){if(options.signal?.aborted)throw new McpSignInCancelledError;clientMetadataBaseUrl(options.settings);let stepUp=options.challenge?.error==="insufficient_scope";return!stepUp&&await refreshBeforeSignIn(options)==="AUTHORIZED"?{kind:"authorized"}:cancellable(options.signal,()=>startBrowserStep(options,stepUp))}async function refreshBeforeSignIn(options){let{store,settings,serverUrl,challenge,redirectUrl,signal}=options,baseUrl=clientMetadataBaseUrl(settings),refreshed=store.withRefreshLock(async()=>{if(signal?.aborted)return"REDIRECT";let state=await store.load();return!state?.tokens?.refresh_token||!matchesClient(state,serverUrl,baseUrl)||baseUrl&&state.clientInformation?"REDIRECT":refreshStoredTokens(options,state,{challenge,redirectUrl})});try{return await untilAborted(signal,refreshed)}catch(error){if(error instanceof McpRefreshLockBusyError)return"REDIRECT";throw error}}function untilAborted(signal,promise){return signal?new Promise((resolve2,reject)=>{let abort=()=>reject(new McpSignInCancelledError);signal.addEventListener("abort",abort,{once:!0}),promise.then(resolve2,reject).finally(()=>signal.removeEventListener("abort",abort))}):promise}async function startBrowserStep(options,stepUp){let{store,settings,serverUrl,redirectUrl,challenge}=options,previous=await store.load(),stored=matchesClient(previous,serverUrl,clientMetadataBaseUrl(settings))?previous:void 0;stored?await store.save(stateForSignIn(stored,options)):previous&&await store.save({serverUrl:new URL(serverUrl).href});let authorizationUrl,provider=createOAuthClientProvider(options,redirectUrl,url=>{authorizationUrl=url}),scope=mergeScopes(settings.scope,stepUp?stepUpScope(stored?.tokens?.scope,challenge?.scope):challenge?.scope);if(await authorizeMcp(provider,{...flowOptions(options),scope,skipRefresh:!0}),!authorizationUrl)throw new Error("OAuth flow did not produce an authorization URL");let requestedScope=(await store.load())?.authorizationRequest?.scope;return{kind:"redirect",authorizationUrl:authorizationUrl.href,redirectUrl:authorizationUrl.searchParams.get("redirect_uri")??redirectUrl,state:await provider.state(),...requestedScope?{scope:requestedScope}:{}}}function stateForSignIn(stored,options){let{settings,redirectUrl}=options,next={...stored};delete next.oauthState,delete next.codeVerifier,delete next.authorizationRequest;let cimd=offersClientMetadataDocument(settings);return settings.clientId||(stored.clientInformation?!cimd&®isteredRedirectUrls(stored.clientInformation).includes(redirectUrl):cimd)||(delete next.clientInformation,delete next.tokens,delete next.tokensExpireAt),next}function mergeScopes(...scopes){let merged=[...new Set(scopes.flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]))];return merged.length>0?merged.join(" "):void 0}async function completeMcpSignIn(options){await cancellable(options.signal,async()=>{let{authorization,response}=options;if(response.state!==authorization.state)throw new Error("The authorization response belongs to a different sign-in");let stored=await options.store.load();if(!stored?.oauthState)throw new Error("No sign-in to this MCP server is pending; sign in again");if(stored.oauthState!==authorization.state)throw new Error("Another sign-in to this MCP server started since; sign in again");let request=stored.authorizationRequest;if(!request||!stored.codeVerifier)throw new Error("The authorization request of this sign-in is not stored; sign in again");await authorizeMcp(createOAuthClientProvider(options,options.redirectUrl),{...flowOptions(options),scope:request.scope,authorizationRequest:request,authorizationRedirectUrl:authorization.redirectUrl,authorizationCode:response.code,iss:response.iss})})}function flowOptions(options){return{serverUrl:options.serverUrl,fetch:timedFetch(),signal:options.signal,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:options.settings.authServerMetadataUrl}}async function cancellable(signal,fn){if(signal?.aborted)throw new McpSignInCancelledError;try{return await fn()}catch(error){throw signal?.aborted?new McpSignInCancelledError:error}}async function listenForLoopbackSignIn(options){let{settings}=options,baseUrl=clientMetadataBaseUrl(settings),loopback2=loopbackSettings(settings),state=await options.store.load(),registered=matchesClient(state,options.serverUrl,baseUrl)?registeredRedirectUrls(state?.clientInformation)[0]:void 0,port=loopback2.port??(registered&&Number(new URL(registered).port)||void 0),listenOptions={host:loopback2.host,redirectHost:loopback2.redirectHost,path:loopback2.path,extraPaths:baseUrl?[serverSpecificPath(loopback2.path,options.serverUrl)]:[],renderPage:options.renderPage},callback;try{callback=await OAuthCallbackServer.listen({...listenOptions,port:port??0})}catch(error){if(loopback2.port!==void 0||port===void 0)throw error;callback=await OAuthCallbackServer.listen(listenOptions)}return{callback,redirectUrl:loopback2.fixedRedirectUrl??callback.redirectUrl}}async function waitForLoopbackSignIn(options){let{authorization}=options,controller=new AbortController,signal=options.signal?AbortSignal.any([controller.signal,options.signal]):controller.signal,fromBrowser=options.callback.waitForCallback(authorization.state,new URL(authorization.redirectUrl).pathname),fromUser=options.promptForRedirectUrl?options.promptForRedirectUrl(signal).then(input=>{if(!input?.trim())throw new McpSignInCancelledError;return responseFromRedirectUrl(input,authorization)}):new Promise((_,reject)=>{signal.addEventListener("abort",()=>reject(new McpSignInCancelledError),{once:!0})});try{return await cancellable(options.signal,()=>Promise.race([fromBrowser,fromUser]))}finally{controller.abort(),fromBrowser.catch(()=>{}),fromUser.catch(()=>{})}}function responseFromRedirectUrl(input,authorization){let url;try{url=new URL(input.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}let redirectUrl=new URL(authorization.redirectUrl);if(url.origin!==redirectUrl.origin||url.pathname!==redirectUrl.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let error=url.searchParams.get("error");if(error)throw new Error(url.searchParams.get("error_description")??error);let state=url.searchParams.get("state");if(state!==authorization.state)throw new Error("The redirect URL belongs to a different sign-in");let code=url.searchParams.get("code");if(!code)throw new Error("The redirect URL does not contain an authorization code");let iss=url.searchParams.get("iss");return{code,state,...iss?{iss}:{}}}import{createHash as createHash2}from"node:crypto";import{mkdirSync}from"node:fs";import{join}from"node:path";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="120 108 296 296" aria-hidden="true"><g fill="none" stroke="#fff" stroke-width="8" stroke-linejoin="round"><circle cx="157" cy="141" r="10"/><path d="M167 141 H283 A95 115.5 0 0 1 283 372 H219 Q205 372 205 358 V202 Q205 190 217 190 H270 A58 67.5 0 0 1 270 325 H171 Q157 325 157 311 V151"/></g></svg>';function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
|
|
5
5
|
<html lang="en">
|