@draht/coding-agent 2026.11.14-1 → 2026.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/chunks/{anthropic-messages-C5ZJVCKX.js → anthropic-messages-FKSSTO6N.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-TNRID5YC.js → azure-openai-responses-AHIW4IRP.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +21 -21
- package/dist/bundle/chunks/{chunk-SXHVGWCU.js → chunk-46NQOOTO.js} +1 -1
- package/dist/bundle/chunks/{chunk-2IQVBLH6.js → chunk-4ALYWMDD.js} +1 -1
- package/dist/bundle/chunks/{chunk-GAABJAG4.js → chunk-5K3TBDND.js} +3 -3
- package/dist/bundle/chunks/chunk-6MSE6LZ3.js +6 -0
- package/dist/bundle/chunks/chunk-736QBNUZ.js +12 -0
- package/dist/bundle/chunks/chunk-BIBUE2PO.js +2 -0
- package/dist/bundle/chunks/{chunk-LCTFXH4P.js → chunk-DFFQ5ETM.js} +1 -1
- package/dist/bundle/chunks/{chunk-4FPBO5KP.js → chunk-G7DJ6PIU.js} +1 -1
- package/dist/bundle/chunks/{chunk-5C4MAPF6.js → chunk-GR3JEDCL.js} +1 -1
- package/dist/bundle/chunks/{chunk-YSE3VKKB.js → chunk-HIL6BIBX.js} +1 -1
- package/dist/bundle/chunks/{chunk-GQXRTK54.js → chunk-ITP6IDBA.js} +2 -2
- package/dist/bundle/chunks/{chunk-6WESOD4H.js → chunk-KVH4HR57.js} +1 -1
- package/dist/bundle/chunks/{chunk-5WEOWREV.js → chunk-NJDELBDB.js} +1 -1
- package/dist/bundle/chunks/{chunk-OUXJRC2W.js → chunk-NLVN7RG3.js} +1 -1
- package/dist/bundle/chunks/chunk-NLYBRJ3F.js +9 -0
- package/dist/bundle/chunks/{chunk-JHKMYVPC.js → chunk-PPJRJAR3.js} +28 -28
- package/dist/bundle/chunks/{chunk-KFREX3FS.js → chunk-QVGSXIKT.js} +1 -1
- package/dist/bundle/chunks/{chunk-RVXTPNXQ.js → chunk-RIPTEKPX.js} +8 -8
- package/dist/bundle/chunks/{chunk-O2XYFH2E.js → chunk-ROB5AWV5.js} +3 -3
- package/dist/bundle/chunks/chunk-TIA2T6EO.js +3 -0
- package/dist/bundle/chunks/{chunk-MPJIXESS.js → chunk-XEVRP72T.js} +1 -1
- package/dist/bundle/chunks/{chunk-RI7HJ6AF.js → chunk-XY64T2H6.js} +10 -10
- package/dist/bundle/chunks/{chunk-B6S2UR4T.js → chunk-ZZAOELWU.js} +1 -1
- package/dist/bundle/chunks/{cli-2QKCAPPD.js → cli-JDGPEN7N.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-UCG6T3XP.js → cloudflare-workers-ai-system-one-ZPDQKK4H.js} +1 -1
- package/dist/bundle/chunks/{execute-KGJOWTPG.js → execute-YOMYOVUT.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-GPBKPOXA.js → google-generative-ai-EEDLVZAQ.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-USZY53NF.js → google-vertex-YQDP6U25.js} +1 -1
- package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +13 -0
- package/dist/bundle/chunks/lib-XOG5PI3Y.js +9 -0
- package/dist/bundle/chunks/{llama-cpp-classify-7DEQ4ZUF.js → llama-cpp-classify-SRUYBPZS.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-UOGXPDZ3.js → mistral-conversations-QKVAIF57.js} +1 -1
- package/dist/bundle/chunks/{multipart-parser-HMCXZ4BD.js → multipart-parser-AZP5BX2W.js} +1 -1
- package/dist/bundle/chunks/{node-DXZFQBEO.js → node-BZAVEWJ3.js} +1 -1
- package/dist/bundle/chunks/{node-LBZLUIBE.js → node-C2JGH2OB.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-VUDXQ3EU.js → openai-codex-responses-2FIT2Z3L.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-UQOOS7NM.js → openai-completions-42OND4EW.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-24WNXO2R.js → openai-decisions-FAP6LRGH.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-5AF6MZ5L.js → openai-responses-BGC7WCIQ.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-OUXVVTYQ.js → openrouter-images-EAWW57ZG.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-DRMOEO6B.js → pi-messages-JM6JDMH5.js} +1 -1
- package/dist/bundle/chunks/{runtime-L23MZBKL.js → runtime-F63NCS5Y.js} +1 -1
- package/dist/bundle/chunks/{runtime-FZKS2BWI.js → runtime-S5WBSLTE.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-CWRQW6PZ.js → settings-manager-H3QEOPQ3.js} +1 -1
- package/dist/bundle/chunks/src-TIBHS42X.js +4 -0
- package/dist/bundle/chunks/{typesafe-system-one-K63EBJDD.js → typesafe-system-one-QOA2PTJR.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-JZV35VDE.js → virtual-modules-2BURZRW7.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/package.json +9 -9
- package/dist/bundle/chunks/chunk-2JZLKNZ4.js +0 -3
- package/dist/bundle/chunks/chunk-6M3D4XVD.js +0 -2
- package/dist/bundle/chunks/chunk-GBFVS2SF.js +0 -12
- package/dist/bundle/chunks/chunk-LO6CVU2L.js +0 -6
- package/dist/bundle/chunks/chunk-XWZLYE4L.js +0 -9
- package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +0 -13
- package/dist/bundle/chunks/lib-ULKZYRGD.js +0 -9
- package/dist/bundle/chunks/src-KDGO7EGF.js +0 -4
- /package/dist/bundle/chunks/{chunk-ATYP3OSV.js → chunk-OPLOTJXH.js} +0 -0
- /package/dist/bundle/chunks/{chunk-ITKDPD4D.js → chunk-PX3CDFUB.js} +0 -0
- /package/dist/bundle/chunks/{chunk-MOOADNVS.js → chunk-ZZD35WKM.js} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
-
import{__commonJS,__export,__toESM}from"./chunk-HZ2UHMBT.js";var require_x509_transport_state=__commonJS({"node_modules/.bun/openai@7.19.0+16827b643d36304c/node_modules/openai/internal/auth/x509-transport-state.js"(exports,module){"use strict";if(typeof module<"u"&&module!==globalThis.module&&typeof exports<"u"&&module.exports===exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.findX509Credential=exports.rememberX509Credential=exports.findX509OAuthError=exports.rememberX509OAuthError=exports.isApprovedX509Client=exports.markApprovedX509Client=exports.isRetryableX509IssuerError=exports.markRetryableX509IssuerError=exports.isTransientX509ConnectionError=exports.markTransientX509ConnectionError=exports.rememberRegisteredX509Transport=exports.findRegisteredX509Transport=void 0;let registeredX509Transports2=new WeakMap,transientX509ConnectionErrors2=new WeakSet,retryableX509IssuerErrors2=new WeakSet,approvedX509Clients2=new WeakSet,approvedX509OAuthErrors2=new WeakMap,approvedX509Credentials2=new WeakMap;exports.findRegisteredX509Transport=WeakMap.prototype.get.bind(registeredX509Transports2),exports.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(registeredX509Transports2),exports.markTransientX509ConnectionError=WeakSet.prototype.add.bind(transientX509ConnectionErrors2),exports.isTransientX509ConnectionError=WeakSet.prototype.has.bind(transientX509ConnectionErrors2),exports.markRetryableX509IssuerError=WeakSet.prototype.add.bind(retryableX509IssuerErrors2),exports.isRetryableX509IssuerError=WeakSet.prototype.has.bind(retryableX509IssuerErrors2),exports.markApprovedX509Client=WeakSet.prototype.add.bind(approvedX509Clients2),exports.isApprovedX509Client=WeakSet.prototype.has.bind(approvedX509Clients2),exports.rememberX509OAuthError=WeakMap.prototype.set.bind(approvedX509OAuthErrors2),exports.findX509OAuthError=WeakMap.prototype.get.bind(approvedX509OAuthErrors2),exports.rememberX509Credential=WeakMap.prototype.set.bind(approvedX509Credentials2),exports.findX509Credential=WeakMap.prototype.get.bind(approvedX509Credentials2)}}});function __classPrivateFieldSet(receiver,state2,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state2.set(receiver,value),value}function __classPrivateFieldGet(receiver,state2,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state2.get(receiver)}var uuid4=function(){let{crypto:crypto2}=globalThis;if(crypto2?.randomUUID)return uuid4=crypto2.randomUUID.bind(crypto2),crypto2.randomUUID();let u8=new Uint8Array(1),randomByte=crypto2?()=>crypto2.getRandomValues(u8)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,c=>(+c^randomByte()&15>>+c/4).toString(16))};function isAbortError(err){return typeof err=="object"&&err!==null&&("name"in err&&err.name==="AbortError"||"message"in err&&String(err.message).includes("FetchRequestCanceledException"))}var castToError=err=>{if(err instanceof Error)return err;if(typeof err=="object"&&err!==null){try{if(Object.prototype.toString.call(err)==="[object Error]"){let hasCause="cause"in err,error=new Error(err.message,hasCause?{cause:err.cause}:{});return err.stack&&(error.stack=err.stack),hasCause&&!Object.prototype.hasOwnProperty.call(error,"cause")&&(error.cause=err.cause),err.name&&(error.name=err.name),error}}catch{}try{return new Error(JSON.stringify(err))}catch{}}return new Error(err)};var OpenAIError=class extends Error{},APIError=class _APIError extends OpenAIError{constructor(status,error,message,headers){super(`${_APIError.makeMessage(status,error,message)}`),this.status=status,this.headers=headers,this.requestID=headers?.get("x-request-id"),this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message=="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;return status&&msg?`${status} ${msg}`:status?`${status} status code (no body)`:msg||"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;return status===400?new BadRequestError(status,error,message,headers):status===401?new AuthenticationError(status,error,message,headers):status===403?new PermissionDeniedError(status,error,message,headers):status===404?new NotFoundError(status,error,message,headers):status===409?new ConflictError(status,error,message,headers):status===422?new UnprocessableEntityError(status,error,message,headers):status===429?new RateLimitError(status,error,message,headers):status>=500?new InternalServerError(status,error,message,headers):new _APIError(status,error,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),cause&&(this.cause=cause)}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{},LengthFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}},ContentFilterFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},InvalidWebhookSignatureError=class extends Error{constructor(message){super(message)}},OAuthError=class extends APIError{constructor(status,error,headers){let finalMessage="OAuth2 authentication error",error_code;if(error&&typeof error=="object"){let errorData=error;error_code=errorData.error;let description=errorData.error_description;description&&typeof description=="string"?finalMessage=description:error_code&&(finalMessage=error_code)}super(status,error,finalMessage,headers),this.error_code=error_code}},SubjectTokenProviderError=class extends OpenAIError{constructor(message,provider,cause){super(message),this.provider=provider,this.cause=cause}};var startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isAbsoluteURL=url=>startsWithSchemeRegexp.test(url),isArray=val=>(isArray=Array.isArray,isArray(val)),isReadonlyArray=isArray;function maybeObj(x){return typeof x!="object"?{}:x??{}}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function isObj(obj){return obj!=null&&typeof obj=="object"&&!Array.isArray(obj)}var validatePositiveInteger=(name,n)=>{if(typeof n!="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n};var safeJSON=text=>{try{return JSON.parse(text)}catch{return}};var sleep=(ms,...signals)=>new Promise((resolve,reject)=>{let activeSignals=[...new Set(signals.filter(signal=>signal!=null))],timeout,settled=!1,cleanup=()=>{for(let signal of activeSignals)try{signal.removeEventListener("abort",abort)}catch{}},settle=callback=>{settled||(settled=!0,timeout!==void 0&&(clearTimeout(timeout),timeout=void 0),cleanup(),callback())},abort=()=>{settle(()=>reject())};if(activeSignals.some(signal=>signal.aborted)){abort();return}timeout=setTimeout(()=>{settle(resolve)},ms);for(let signal of activeSignals){if(settled)break;try{signal.addEventListener("abort",abort,{once:!0})}catch(error){settle(()=>reject(error))}}activeSignals.some(signal=>signal.aborted)&&abort()});var weakGlobals=globalThis,finalizer=typeof weakGlobals.FinalizationRegistry=="function"?new weakGlobals.FinalizationRegistry(cleanup=>{try{cleanup()}catch{}}):void 0,callbackOwners=new WeakMap,subscriptions=new WeakMap;function subscribeWeakly(signal,reference,registry){let subscription=subscriptions.get(signal);if(!subscription){let callbacks=new Set,abort=()=>{subscriptions.delete(signal);for(let callback of callbacks)registry.unregister(callback),callback.deref()?.();callbacks.clear()};subscription={callbacks,abort},signal.addEventListener("abort",abort,{once:!0}),subscriptions.set(signal,subscription)}let owner=subscription;return owner.callbacks.add(reference),()=>{owner.callbacks.delete(reference),registry.unregister(reference),owner.callbacks.size===0&&(subscriptions.get(signal)===owner&&subscriptions.delete(signal),signal.removeEventListener("abort",owner.abort))}}function releaseOnAbort(signal,callbacks,abort){signal.addEventListener("abort",()=>callbacks.deref()?.delete(abort),{once:!0})}function retainRequestAbortCallback(owner,abort,requestSignal){if(typeof weakGlobals.WeakRef=="function"&&finalizer&&!requestSignal.aborted){let callbacks=callbackOwners.get(owner);callbacks||(callbacks=new Set,callbackOwners.set(owner,callbacks)),callbacks.add(abort),releaseOnAbort(requestSignal,new weakGlobals.WeakRef(callbacks),abort)}}function addRequestAbortListener(signal,abort,requestSignal){if(signal.aborted)return abort(),()=>{};if(typeof weakGlobals.WeakRef!="function"||!finalizer)return signal.addEventListener("abort",abort,{once:!0}),()=>signal.removeEventListener("abort",abort);let reference=new weakGlobals.WeakRef(abort),cleanup=subscribeWeakly(signal,reference,finalizer);return finalizer.register(abort,cleanup,reference),retainRequestAbortCallback(requestSignal,abort,requestSignal),cleanup}function getDefaultFetch(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function makeReadableStream(...args){let ReadableStream2=globalThis.ReadableStream;if(typeof ReadableStream2>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new ReadableStream2(...args)}function ReadableStreamFrom(iterable){let iter=Symbol.asyncIterator in iterable?iterable[Symbol.asyncIterator]():iterable[Symbol.iterator]();return makeReadableStream({start(){},async pull(controller){let{done,value}=await iter.next();done?controller.close():controller.enqueue(value)},async cancel(){await iter.return?.()}})}function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();return result?.done&&reader.releaseLock(),result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CancelReadableStream(stream){if(stream===null||typeof stream!="object")return;if(stream[Symbol.asyncIterator]){await stream[Symbol.asyncIterator]().return?.();return}let reader=stream.getReader(),cancelPromise=reader.cancel();reader.releaseLock(),await cancelPromise}var encodeUTF8_;function encodeUTF8(str){let encoder;return(encodeUTF8_??(encoder=new globalThis.TextEncoder,encodeUTF8_=encoder.encode.bind(encoder)))(str)}var decodeUTF8_;function decodeUTF8(bytes){let decoder;return(decodeUTF8_??(decoder=new globalThis.TextDecoder,decodeUTF8_=decoder.decode.bind(decoder)))(bytes)}var _LineDecoder_instances,_LineDecoder_buffer,_LineDecoder_start,_LineDecoder_end,_LineDecoder_searchIndex,_LineDecoder_skipLeadingLF,_LineDecoder_append,MAX_RETAINED_BUFFER_BYTES=64*1024,LineDecoder=class{constructor(){_LineDecoder_instances.add(this),_LineDecoder_buffer.set(this,void 0),_LineDecoder_start.set(this,void 0),_LineDecoder_end.set(this,void 0),_LineDecoder_searchIndex.set(this,void 0),_LineDecoder_skipLeadingLF.set(this,void 0),__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk;if(chunk instanceof ArrayBuffer?binaryChunk=new Uint8Array(chunk):typeof chunk=="string"?binaryChunk=encodeUTF8(chunk):binaryChunk=chunk,binaryChunk.length===0)return[];if(__classPrivateFieldGet(this,_LineDecoder_skipLeadingLF,"f")&&(__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),binaryChunk[0]===10&&(binaryChunk=binaryChunk.subarray(1)),binaryChunk.length===0))return[];__classPrivateFieldGet(this,_LineDecoder_instances,"m",_LineDecoder_append).call(this,binaryChunk);let lines=[],patternIndex;for(;(patternIndex=findNewlineIndex(__classPrivateFieldGet(this,_LineDecoder_buffer,"f"),__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f")))!=null;){let line=decodeUTF8(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),patternIndex.preceding));lines.push(line),__classPrivateFieldSet(this,_LineDecoder_start,patternIndex.index,"f"),patternIndex.carriage&&(__classPrivateFieldGet(this,_LineDecoder_start,"f")<__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f")[__classPrivateFieldGet(this,_LineDecoder_start,"f")]===10?__classPrivateFieldSet(this,_LineDecoder_start,__classPrivateFieldGet(this,_LineDecoder_start,"f")+1,"f"):__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!0,"f")),__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f")}if(__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_end,"f"),"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f"))__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES&&__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f");else if(lines.length>0&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(length<=MAX_RETAINED_BUFFER_BYTES||__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>length*4){let capacity=length<=MAX_RETAINED_BUFFER_BYTES?Math.min(Math.max(length*2,256),MAX_RETAINED_BUFFER_BYTES):length*2,buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,length,"f")}}return lines}flush(){return __classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")?[]:this.decode(`
|
|
2
|
+
import{__commonJS,__export,__toESM}from"./chunk-HZ2UHMBT.js";var require_x509_transport_state=__commonJS({"node_modules/openai/internal/auth/x509-transport-state.js"(exports,module){"use strict";if(typeof module<"u"&&module!==globalThis.module&&typeof exports<"u"&&module.exports===exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.findX509Credential=exports.rememberX509Credential=exports.findX509OAuthError=exports.rememberX509OAuthError=exports.isApprovedX509Client=exports.markApprovedX509Client=exports.isRetryableX509IssuerError=exports.markRetryableX509IssuerError=exports.isTransientX509ConnectionError=exports.markTransientX509ConnectionError=exports.rememberRegisteredX509Transport=exports.findRegisteredX509Transport=void 0;let registeredX509Transports2=new WeakMap,transientX509ConnectionErrors2=new WeakSet,retryableX509IssuerErrors2=new WeakSet,approvedX509Clients2=new WeakSet,approvedX509OAuthErrors2=new WeakMap,approvedX509Credentials2=new WeakMap;exports.findRegisteredX509Transport=WeakMap.prototype.get.bind(registeredX509Transports2),exports.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(registeredX509Transports2),exports.markTransientX509ConnectionError=WeakSet.prototype.add.bind(transientX509ConnectionErrors2),exports.isTransientX509ConnectionError=WeakSet.prototype.has.bind(transientX509ConnectionErrors2),exports.markRetryableX509IssuerError=WeakSet.prototype.add.bind(retryableX509IssuerErrors2),exports.isRetryableX509IssuerError=WeakSet.prototype.has.bind(retryableX509IssuerErrors2),exports.markApprovedX509Client=WeakSet.prototype.add.bind(approvedX509Clients2),exports.isApprovedX509Client=WeakSet.prototype.has.bind(approvedX509Clients2),exports.rememberX509OAuthError=WeakMap.prototype.set.bind(approvedX509OAuthErrors2),exports.findX509OAuthError=WeakMap.prototype.get.bind(approvedX509OAuthErrors2),exports.rememberX509Credential=WeakMap.prototype.set.bind(approvedX509Credentials2),exports.findX509Credential=WeakMap.prototype.get.bind(approvedX509Credentials2)}}});function __classPrivateFieldSet(receiver,state2,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state2.set(receiver,value),value}function __classPrivateFieldGet(receiver,state2,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state2.get(receiver)}var uuid4=function(){let{crypto:crypto2}=globalThis;if(crypto2?.randomUUID)return uuid4=crypto2.randomUUID.bind(crypto2),crypto2.randomUUID();let u8=new Uint8Array(1),randomByte=crypto2?()=>crypto2.getRandomValues(u8)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,c=>(+c^randomByte()&15>>+c/4).toString(16))};function isAbortError(err){return typeof err=="object"&&err!==null&&("name"in err&&err.name==="AbortError"||"message"in err&&String(err.message).includes("FetchRequestCanceledException"))}var castToError=err=>{if(err instanceof Error)return err;if(typeof err=="object"&&err!==null){try{if(Object.prototype.toString.call(err)==="[object Error]"){let hasCause="cause"in err,error=new Error(err.message,hasCause?{cause:err.cause}:{});return err.stack&&(error.stack=err.stack),hasCause&&!Object.prototype.hasOwnProperty.call(error,"cause")&&(error.cause=err.cause),err.name&&(error.name=err.name),error}}catch{}try{return new Error(JSON.stringify(err))}catch{}}return new Error(err)};var OpenAIError=class extends Error{},APIError=class _APIError extends OpenAIError{constructor(status,error,message,headers){super(`${_APIError.makeMessage(status,error,message)}`),this.status=status,this.headers=headers,this.requestID=headers?.get("x-request-id"),this.error=error;let data=error;this.code=data?.code,this.param=data?.param,this.type=data?.type}static makeMessage(status,error,message){let msg=error?.message?typeof error.message=="string"?error.message:JSON.stringify(error.message):error?JSON.stringify(error):message;return status&&msg?`${status} ${msg}`:status?`${status} status code (no body)`:msg||"(no status code or body)"}static generate(status,errorResponse,message,headers){if(!status||!headers)return new APIConnectionError({message,cause:castToError(errorResponse)});let error=errorResponse?.error;return status===400?new BadRequestError(status,error,message,headers):status===401?new AuthenticationError(status,error,message,headers):status===403?new PermissionDeniedError(status,error,message,headers):status===404?new NotFoundError(status,error,message,headers):status===409?new ConflictError(status,error,message,headers):status===422?new UnprocessableEntityError(status,error,message,headers):status===429?new RateLimitError(status,error,message,headers):status>=500?new InternalServerError(status,error,message,headers):new _APIError(status,error,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),cause&&(this.cause=cause)}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message??"Request timed out."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{},LengthFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}},ContentFilterFinishReasonError=class extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},InvalidWebhookSignatureError=class extends Error{constructor(message){super(message)}},OAuthError=class extends APIError{constructor(status,error,headers){let finalMessage="OAuth2 authentication error",error_code;if(error&&typeof error=="object"){let errorData=error;error_code=errorData.error;let description=errorData.error_description;description&&typeof description=="string"?finalMessage=description:error_code&&(finalMessage=error_code)}super(status,error,finalMessage,headers),this.error_code=error_code}},SubjectTokenProviderError=class extends OpenAIError{constructor(message,provider,cause){super(message),this.provider=provider,this.cause=cause}};var startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isAbsoluteURL=url=>startsWithSchemeRegexp.test(url),isArray=val=>(isArray=Array.isArray,isArray(val)),isReadonlyArray=isArray;function maybeObj(x){return typeof x!="object"?{}:x??{}}function isEmptyObj(obj){if(!obj)return!0;for(let _k in obj)return!1;return!0}function hasOwn(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function isObj(obj){return obj!=null&&typeof obj=="object"&&!Array.isArray(obj)}var validatePositiveInteger=(name,n)=>{if(typeof n!="number"||!Number.isInteger(n))throw new OpenAIError(`${name} must be an integer`);if(n<0)throw new OpenAIError(`${name} must be a positive integer`);return n};var safeJSON=text=>{try{return JSON.parse(text)}catch{return}};var sleep=(ms,...signals)=>new Promise((resolve,reject)=>{let activeSignals=[...new Set(signals.filter(signal=>signal!=null))],timeout,settled=!1,cleanup=()=>{for(let signal of activeSignals)try{signal.removeEventListener("abort",abort)}catch{}},settle=callback=>{settled||(settled=!0,timeout!==void 0&&(clearTimeout(timeout),timeout=void 0),cleanup(),callback())},abort=()=>{settle(()=>reject())};if(activeSignals.some(signal=>signal.aborted)){abort();return}timeout=setTimeout(()=>{settle(resolve)},ms);for(let signal of activeSignals){if(settled)break;try{signal.addEventListener("abort",abort,{once:!0})}catch(error){settle(()=>reject(error))}}activeSignals.some(signal=>signal.aborted)&&abort()});var weakGlobals=globalThis,finalizer=typeof weakGlobals.FinalizationRegistry=="function"?new weakGlobals.FinalizationRegistry(cleanup=>{try{cleanup()}catch{}}):void 0,callbackOwners=new WeakMap,subscriptions=new WeakMap;function subscribeWeakly(signal,reference,registry){let subscription=subscriptions.get(signal);if(!subscription){let callbacks=new Set,abort=()=>{subscriptions.delete(signal);for(let callback of callbacks)registry.unregister(callback),callback.deref()?.();callbacks.clear()};subscription={callbacks,abort},signal.addEventListener("abort",abort,{once:!0}),subscriptions.set(signal,subscription)}let owner=subscription;return owner.callbacks.add(reference),()=>{owner.callbacks.delete(reference),registry.unregister(reference),owner.callbacks.size===0&&(subscriptions.get(signal)===owner&&subscriptions.delete(signal),signal.removeEventListener("abort",owner.abort))}}function releaseOnAbort(signal,callbacks,abort){signal.addEventListener("abort",()=>callbacks.deref()?.delete(abort),{once:!0})}function retainRequestAbortCallback(owner,abort,requestSignal){if(typeof weakGlobals.WeakRef=="function"&&finalizer&&!requestSignal.aborted){let callbacks=callbackOwners.get(owner);callbacks||(callbacks=new Set,callbackOwners.set(owner,callbacks)),callbacks.add(abort),releaseOnAbort(requestSignal,new weakGlobals.WeakRef(callbacks),abort)}}function addRequestAbortListener(signal,abort,requestSignal){if(signal.aborted)return abort(),()=>{};if(typeof weakGlobals.WeakRef!="function"||!finalizer)return signal.addEventListener("abort",abort,{once:!0}),()=>signal.removeEventListener("abort",abort);let reference=new weakGlobals.WeakRef(abort),cleanup=subscribeWeakly(signal,reference,finalizer);return finalizer.register(abort,cleanup,reference),retainRequestAbortCallback(requestSignal,abort,requestSignal),cleanup}function getDefaultFetch(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function makeReadableStream(...args){let ReadableStream2=globalThis.ReadableStream;if(typeof ReadableStream2>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new ReadableStream2(...args)}function ReadableStreamFrom(iterable){let iter=Symbol.asyncIterator in iterable?iterable[Symbol.asyncIterator]():iterable[Symbol.iterator]();return makeReadableStream({start(){},async pull(controller){let{done,value}=await iter.next();done?controller.close():controller.enqueue(value)},async cancel(){await iter.return?.()}})}function ReadableStreamToAsyncIterable(stream){if(stream[Symbol.asyncIterator])return stream;let reader=stream.getReader();return{async next(){try{let result=await reader.read();return result?.done&&reader.releaseLock(),result}catch(e){throw reader.releaseLock(),e}},async return(){let cancelPromise=reader.cancel();return reader.releaseLock(),await cancelPromise,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CancelReadableStream(stream){if(stream===null||typeof stream!="object")return;if(stream[Symbol.asyncIterator]){await stream[Symbol.asyncIterator]().return?.();return}let reader=stream.getReader(),cancelPromise=reader.cancel();reader.releaseLock(),await cancelPromise}var encodeUTF8_;function encodeUTF8(str){let encoder;return(encodeUTF8_??(encoder=new globalThis.TextEncoder,encodeUTF8_=encoder.encode.bind(encoder)))(str)}var decodeUTF8_;function decodeUTF8(bytes){let decoder;return(decodeUTF8_??(decoder=new globalThis.TextDecoder,decodeUTF8_=decoder.decode.bind(decoder)))(bytes)}var _LineDecoder_instances,_LineDecoder_buffer,_LineDecoder_start,_LineDecoder_end,_LineDecoder_searchIndex,_LineDecoder_skipLeadingLF,_LineDecoder_append,MAX_RETAINED_BUFFER_BYTES=64*1024,LineDecoder=class{constructor(){_LineDecoder_instances.add(this),_LineDecoder_buffer.set(this,void 0),_LineDecoder_start.set(this,void 0),_LineDecoder_end.set(this,void 0),_LineDecoder_searchIndex.set(this,void 0),_LineDecoder_skipLeadingLF.set(this,void 0),__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f")}decode(chunk){if(chunk==null)return[];let binaryChunk;if(chunk instanceof ArrayBuffer?binaryChunk=new Uint8Array(chunk):typeof chunk=="string"?binaryChunk=encodeUTF8(chunk):binaryChunk=chunk,binaryChunk.length===0)return[];if(__classPrivateFieldGet(this,_LineDecoder_skipLeadingLF,"f")&&(__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),binaryChunk[0]===10&&(binaryChunk=binaryChunk.subarray(1)),binaryChunk.length===0))return[];__classPrivateFieldGet(this,_LineDecoder_instances,"m",_LineDecoder_append).call(this,binaryChunk);let lines=[],patternIndex;for(;(patternIndex=findNewlineIndex(__classPrivateFieldGet(this,_LineDecoder_buffer,"f"),__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f")))!=null;){let line=decodeUTF8(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),patternIndex.preceding));lines.push(line),__classPrivateFieldSet(this,_LineDecoder_start,patternIndex.index,"f"),patternIndex.carriage&&(__classPrivateFieldGet(this,_LineDecoder_start,"f")<__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f")[__classPrivateFieldGet(this,_LineDecoder_start,"f")]===10?__classPrivateFieldSet(this,_LineDecoder_start,__classPrivateFieldGet(this,_LineDecoder_start,"f")+1,"f"):__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")&&__classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!0,"f")),__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f")}if(__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_end,"f"),"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f"))__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,0,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,0,"f"),__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES&&__classPrivateFieldSet(this,_LineDecoder_buffer,new Uint8Array,"f");else if(lines.length>0&&__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>MAX_RETAINED_BUFFER_BYTES){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(length<=MAX_RETAINED_BUFFER_BYTES||__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length>length*4){let capacity=length<=MAX_RETAINED_BUFFER_BYTES?Math.min(Math.max(length*2,256),MAX_RETAINED_BUFFER_BYTES):length*2,buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_searchIndex,length,"f")}}return lines}flush(){return __classPrivateFieldSet(this,_LineDecoder_skipLeadingLF,!1,"f"),__classPrivateFieldGet(this,_LineDecoder_start,"f")===__classPrivateFieldGet(this,_LineDecoder_end,"f")?[]:this.decode(`
|
|
3
3
|
`)}};_LineDecoder_buffer=new WeakMap,_LineDecoder_start=new WeakMap,_LineDecoder_end=new WeakMap,_LineDecoder_searchIndex=new WeakMap,_LineDecoder_skipLeadingLF=new WeakMap,_LineDecoder_instances=new WeakSet,_LineDecoder_append=function(chunk){if(__classPrivateFieldGet(this,_LineDecoder_end,"f")+chunk.length>__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length){let length=__classPrivateFieldGet(this,_LineDecoder_end,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f");if(__classPrivateFieldGet(this,_LineDecoder_start,"f")>=__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length/2&&length+chunk.length<=__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length)__classPrivateFieldGet(this,_LineDecoder_buffer,"f").copyWithin(0,__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"));else{let capacity=Math.max(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").length*2,length+chunk.length,256),buffer=new Uint8Array(capacity);buffer.set(__classPrivateFieldGet(this,_LineDecoder_buffer,"f").subarray(__classPrivateFieldGet(this,_LineDecoder_start,"f"),__classPrivateFieldGet(this,_LineDecoder_end,"f"))),__classPrivateFieldSet(this,_LineDecoder_buffer,buffer,"f")}__classPrivateFieldSet(this,_LineDecoder_searchIndex,__classPrivateFieldGet(this,_LineDecoder_searchIndex,"f")-__classPrivateFieldGet(this,_LineDecoder_start,"f"),"f"),__classPrivateFieldSet(this,_LineDecoder_end,length,"f"),__classPrivateFieldSet(this,_LineDecoder_start,0,"f")}__classPrivateFieldGet(this,_LineDecoder_buffer,"f").set(chunk,__classPrivateFieldGet(this,_LineDecoder_end,"f")),__classPrivateFieldSet(this,_LineDecoder_end,__classPrivateFieldGet(this,_LineDecoder_end,"f")+chunk.length,"f")};LineDecoder.NEWLINE_CHARS=new Set([`
|
|
4
4
|
`,"\r"]);LineDecoder.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function findNewlineIndex(buffer,start,end){for(let i=start;i<end;i++){if(buffer[i]===10)return{preceding:i,index:i+1,carriage:!1};if(buffer[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function findDoubleNewlineIndex(buffer){for(let i=0;i<buffer.length-1;i++){let firstEndingLength=lineEndingLength(buffer,i);if(firstEndingLength>0){let secondEndingIndex=i+firstEndingLength,secondEndingLength=lineEndingLength(buffer,secondEndingIndex);if(secondEndingLength>0)return secondEndingIndex+secondEndingLength}}return-1}function lineEndingLength(buffer,index){return buffer[index]===10?1:buffer[index]===13?buffer[index+1]===10?2:1:0}var levelNumbers={off:0,error:200,warn:300,info:400,debug:500},parseLogLevel=(maybeLevel,sourceName,client)=>{if(maybeLevel){if(hasOwn(levelNumbers,maybeLevel))return maybeLevel;loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`)}};function noop(){}function makeLogFn(fnLevel,logger,logLevel){return!logger||levelNumbers[fnLevel]>levelNumbers[logLevel]?noop:logger[fnLevel].bind(logger)}var noopLogger={error:noop,warn:noop,info:noop,debug:noop},cachedLoggers=new WeakMap;function loggerFor(client){let logger=client.logger,logLevel=client.logLevel??"off";if(!logger)return noopLogger;let cachedLogger=cachedLoggers.get(logger);if(cachedLogger&&cachedLogger[0]===logLevel)return cachedLogger[1];let levelLogger={error:makeLogFn("error",logger,logLevel),warn:makeLogFn("warn",logger,logLevel),info:makeLogFn("info",logger,logLevel),debug:makeLogFn("debug",logger,logLevel)};return cachedLoggers.set(logger,[logLevel,levelLogger]),levelLogger}var sensitiveQueryNames=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","signingsecret","xamzsecuritytoken","xamzsignature","xamzcredential"]);function isSensitiveQueryParameter(name){let normalized=name.toLowerCase().replace(/[-_]/gu,"");return sensitiveQueryNames.has(normalized)||sensitiveQueryNames.has(normalized.replace(/^x/u,""))}var sensitiveHeaderNames=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"]);function isSensitiveHeader(name){return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu,"-"))||isSensitiveQueryParameter(name)}function redactURL(value){let url=new URL(value);url.username="",url.password="",url.hash="";for(let name of url.searchParams.keys())isSensitiveQueryParameter(name)&&url.searchParams.set(name,"***");return url.href}var formatRequestDetails=details=>{if(details.options){if(details.options={...details.options},delete details.options.headers,details.options.path){let path2=details.options.path,redacted=new URL(redactURL(new URL(path2,"https://redacted.invalid").href));details.options.path=redacted.origin==="https://redacted.invalid"?`${path2.startsWith("/")?"/":""}${redacted.pathname.slice(1)}${redacted.search}`:redacted.href}details.options.query&&(details.options.query=Object.fromEntries(Object.entries(details.options.query).map(([name,value])=>[name,isSensitiveQueryParameter(name)?"***":value])))}return details.url&&(details.url=redactURL(details.url)),details.headers&&(details.headers=Object.fromEntries((details.headers instanceof Headers?[...details.headers]:Object.entries(details.headers)).map(([name,value])=>[name,isSensitiveHeader(name)?"***":value]))),"retryOfRequestLogID"in details&&(details.retryOfRequestLogID&&(details.retryOf=details.retryOfRequestLogID),delete details.retryOfRequestLogID),details};var _Stream_instances,_Stream_client,_Stream_isTeeBranch,_Stream_cancelIterator;function isTransportAbortError(error){return!(error instanceof APIError)&&isAbortError(error)}function createStreamTeeQueue(){let entries=[],head=0,canceled=!1;return{get length(){return entries.length-head},get canceled(){return canceled},enqueue(value){canceled||entries.push(value)},dequeue(){if(head===entries.length)return;let value=entries[head];return entries[head]=void 0,head+=1,head===entries.length?(entries=[],head=0):head>=1024&&head*2>=entries.length&&(entries=entries.slice(head),head=0),value},cancel(){canceled=!0,entries.length=0,head=0}}}var Stream=class _Stream{constructor(iterator,controller,client){_Stream_instances.add(this),_Stream_client.set(this,void 0),_Stream_isTeeBranch.set(this,!1),this.iterator=iterator,this.controller=controller,__classPrivateFieldSet(this,_Stream_client,client,"f")}static fromSSEResponse(response,controller,client,synthesizeEventData){let consumed=!1,logger=client?loggerFor(client):console;async function*iterator(){if(consumed)throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1,receivedCompletionSentinel=!1,messages=_iterSSEMessages(response,controller),closeMessages=messages.return.bind(messages);messages.return=value=>(receivedCompletionSentinel||controller.abort(),closeMessages(value));try{for await(let sse of messages){if(sse.data==="[DONE]"){receivedCompletionSentinel=!0;break}if(sse.event===null||!sse.event.startsWith("thread.")){let data;try{data=JSON.parse(sse.data)}catch{throw logger.error("Could not parse message into JSON:"),logger.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(sse.event==="error")throw new APIError(void 0,data?.error??data,void 0,response.headers);if(data&&data.error)throw new APIError(void 0,data.error,void 0,response.headers);yield synthesizeEventData?{event:sse.event,data}:data}else{let data;try{data=JSON.parse(sse.data)}catch{throw logger.error("Could not parse message into JSON:"),logger.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:sse.event,data}}}done=!0}catch(e){if(receivedCompletionSentinel||isTransportAbortError(e)||controller.signal.aborted&&e===controller.signal.reason)return;throw e}finally{done||controller.abort()}}return new _Stream(iterator,controller,client)}static fromReadableStream(readableStream,controller,client){let consumed=!1;async function*iterLines(){let lineDecoder=new LineDecoder,reader=readableStream.getReader(),closed=!1,cancelPromise,cancel=()=>{cancelPromise??(cancelPromise=reader.cancel()),cancelPromise.catch(()=>{})};controller.signal.addEventListener("abort",cancel,{once:!0});try{if(controller.signal.aborted){cancel();return}for(;;){let{value:chunk,done}=await reader.read();if(done){closed=!0;break}if(controller.signal.aborted)return;for(let line of lineDecoder.decode(chunk)){if(controller.signal.aborted)return;yield line}}if(controller.signal.aborted)return;for(let line of lineDecoder.flush()){if(controller.signal.aborted)return;yield line}}finally{controller.signal.removeEventListener("abort",cancel),closed||cancel(),reader.releaseLock()}}async function*iterator(){if(consumed)throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");consumed=!0;let done=!1;try{for await(let line of iterLines())if(line){let data;try{data=JSON.parse(line)}catch(error){throw error instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):error}yield data}done=!0}catch(e){if(controller.signal.aborted||isAbortError(e))return;throw e}finally{done||controller.abort()}}return new _Stream(iterator,controller,client)}[(_Stream_client=new WeakMap,_Stream_isTeeBranch=new WeakMap,_Stream_instances=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller}=this,left=createStreamTeeQueue(),right=createStreamTeeQueue(),iterator=this.iterator(),teeIterator=queue=>({next:()=>{if(queue.canceled)return Promise.resolve({value:void 0,done:!0});if(queue.length===0){let result=iterator.next();left.enqueue(result),right.enqueue(result)}return queue.dequeue()},return:async()=>(queue.canceled||(queue.cancel(),left.canceled&&right.canceled&&await __classPrivateFieldGet(this,_Stream_instances,"m",_Stream_cancelIterator).call(this,iterator,controller)),{value:void 0,done:!0})}),branch=queue=>{let stream=new _Stream(()=>teeIterator(queue),controller,__classPrivateFieldGet(this,_Stream_client,"f"));return __classPrivateFieldSet(stream,_Stream_isTeeBranch,!0,"f"),stream};return[branch(left),branch(right)]}toReadableStream(){let{controller}=this,iter,cancellation,cancel=()=>cancellation??(cancellation=__classPrivateFieldGet(this,_Stream_instances,"m",_Stream_cancelIterator).call(this,iter,controller));return makeReadableStream({start:async()=>{iter=this[Symbol.asyncIterator]()},async pull(ctrl){try{let{value,done}=await iter.next();if(done)return ctrl.close();let bytes=encodeUTF8(JSON.stringify(value)+`
|
|
5
5
|
`);ctrl.enqueue(bytes)}catch(err){ctrl.error(err),cancel().catch(()=>{})}},cancel})}};_Stream_cancelIterator=async function(iterator,controller){let returnMethod=iterator.return;returnMethod&&(__classPrivateFieldGet(this,_Stream_isTeeBranch,"f")||controller.abort(),await Reflect.apply(returnMethod,iterator,[]))};function createAbortableSSESource(body,signal){let reader=typeof body.getReader=="function"?body.getReader():void 0,source=reader?{next:()=>reader.read(),return:()=>reader.cancel()}:ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator](),ended={value:void 0,done:!0},closed=!1,canceled=!1,cancellation,interrupt,waitForAbort=()=>new Promise(resolve=>{interrupt=resolve}),cancel=()=>{if(canceled||closed)return cancellation;canceled=!0;try{cancellation=Promise.resolve(source.return?.())}catch(error){cancellation=Promise.reject(error)}return cancellation.catch(()=>{}),cancellation},abort=()=>{queueMicrotask(()=>{interrupt?.(),cancel()})};return{iterator:{async next(){if(signal.aborted)return ended;let aborted=waitForAbort().then(()=>ended);try{let result=await Promise.race([source.next(),aborted]);return signal.aborted?ended:result.done?(closed=!0,ended):{value:result.value,done:!1}}catch(error){if(signal.aborted&&(isAbortError(error)||error===signal.reason))return ended;throw error}finally{interrupt=void 0}},async return(){let pending=cancel();if(pending&&!signal.aborted){let aborted=waitForAbort();try{signal.aborted||await Promise.race([pending,aborted])}finally{interrupt=void 0}}return ended},[Symbol.asyncIterator](){return this}},start(){signal.addEventListener("abort",abort,{once:!0}),signal.aborted&&abort()},async cleanup(failed){let cleanupError;try{signal.removeEventListener("abort",abort)}catch(error){cleanupError=error}if(!closed){let pending=cancel();if(pending&&!failed&&!signal.aborted)try{await pending}catch(error){cleanupError??(cleanupError=error)}}if(reader)try{reader.releaseLock()}catch(error){cleanupError??(cleanupError=error)}if(cleanupError!==void 0&&!failed&&!signal.aborted)throw cleanupError}}}async function*_iterSSEMessages(response,controller){if(!response.body)throw controller.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new OpenAIError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new OpenAIError("Attempted to iterate over a response with no body");let sseDecoder=new SSEDecoder,lineDecoder=new LineDecoder,{signal}=controller,source=createAbortableSSESource(response.body,signal),failed=!1;try{source.start();for await(let sseChunk of iterSSEChunks(source.iterator)){if(signal.aborted)return;for(let line of lineDecoder.decode(sseChunk)){if(signal.aborted)return;let sse=sseDecoder.decode(line);sse&&(yield sse)}}if(signal.aborted)return;for(let line of lineDecoder.flush()){if(signal.aborted)return;let sse=sseDecoder.decode(line);sse&&(yield sse)}if(signal.aborted)return;let pending=sseDecoder.flush();pending&&(yield pending)}catch(error){if(failed=!0,!signal.aborted||!isAbortError(error)&&error!==signal.reason)throw error}finally{await source.cleanup(failed)}}var DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES=3;async function*iterSSEChunks(iterator){let data=new Uint8Array,dataStart=0,dataEnd=0,searchStartIndex=0;for await(let chunk of iterator){if(chunk==null)continue;let binaryChunk;if(chunk instanceof ArrayBuffer?binaryChunk=new Uint8Array(chunk):typeof chunk=="string"?binaryChunk=encodeUTF8(chunk):binaryChunk=chunk,dataEnd+binaryChunk.length>data.length){let bufferedLength=dataEnd-dataStart;if(dataStart>=data.length/2&&bufferedLength+binaryChunk.length<=data.length)data.copyWithin(0,dataStart,dataEnd);else{let newData=new Uint8Array(Math.max(data.length*2,bufferedLength+binaryChunk.length));newData.set(data.subarray(dataStart,dataEnd)),data=newData}searchStartIndex-=dataStart,dataStart=0,dataEnd=bufferedLength}data.set(binaryChunk,dataEnd),dataEnd+=binaryChunk.length;let patternIndex;for(;(patternIndex=findDoubleNewlineIndex(data.subarray(searchStartIndex,dataEnd)))!==-1;)patternIndex+=searchStartIndex,yield data.slice(dataStart,patternIndex),dataStart=patternIndex,searchStartIndex=dataStart;searchStartIndex=Math.max(dataStart,dataEnd-DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES)}dataEnd>dataStart&&(yield data.slice(dataStart,dataEnd))}var SSEDecoder=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(line){if(line.endsWith("\r")&&(line=line.slice(0,-1)),!line){if(!this.event&&!this.data.length)return null;let sse={event:this.event,data:this.data.join(`
|
|
@@ -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-4ALYWMDD.js";import{sliceTail}from"./chunk-G7DJ6PIU.js";import{require_proper_lockfile}from"./chunk-TIA2T6EO.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-BIBUE2PO.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">
|
|
@@ -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-NLYBRJ3F.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};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
+
function contentText(content,separator=`
|
|
3
|
+
`){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(`
|
|
4
|
+
|
|
5
|
+
`)}function renderSystemMessageUpdate(message){let parts=[],text=contentText(message.content);text.length>0&&parts.push(text);for(let[name,value]of Object.entries(message.sections??{}))parts.push(value===null?`Removed system prompt section "${name}".`:`Updated system prompt section "${name}":
|
|
6
|
+
|
|
7
|
+
${value}`);return parts.join(`
|
|
8
|
+
|
|
9
|
+
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}var DRAHT_AI_VERSION="2026.11.14";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};
|