UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

12 lines (11 loc) • 19.9 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{UnauthorizedError,auth,extractWWWAuthenticateParams}from"./chunk-REMY6HQK.js";import{createFetchWithInit,fetchLeavingRedirects,fetchWithinOrigin,followWithinOrigin,normalizeHeaders,unfollowedRedirect}from"./chunk-YP72RYUP.js";import{JSONRPCMessageSchema,isInitializedNotification,isJSONRPCRequest,isJSONRPCResultResponse}from"./chunk-PM3CCDYH.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import{__commonJS,__toESM}from"./chunk-IKOFCODM.js";var require_content_type=__commonJS({"node_modules/content-type/index.js"(exports){"use strict";var PARAM_REGEXP=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,TEXT_REGEXP=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,TOKEN_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,QESC_REGEXP=/\\([\u000b\u0020-\u00ff])/g,QUOTE_REGEXP=/([\\"])/g,TYPE_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;exports.format=format;exports.parse=parse;function format(obj){if(!obj||typeof obj!="object")throw new TypeError("argument obj is required");var parameters=obj.parameters,type=obj.type;if(!type||!TYPE_REGEXP.test(type))throw new TypeError("invalid type");var string=type;if(parameters&&typeof parameters=="object")for(var param,params=Object.keys(parameters).sort(),i=0;i<params.length;i++){if(param=params[i],!TOKEN_REGEXP.test(param))throw new TypeError("invalid parameter name");string+="; "+param+"="+qstring(parameters[param])}return string}function parse(string){if(!string)throw new TypeError("argument string is required");var header=typeof string=="object"?getcontenttype(string):string;if(typeof header!="string")throw new TypeError("argument string is required to be a string");var index=header.indexOf(";"),type=index!==-1?header.slice(0,index).trim():header.trim();if(!TYPE_REGEXP.test(type))throw new TypeError("invalid media type");var obj=new ContentType(type.toLowerCase());if(index!==-1){var key,match,value;for(PARAM_REGEXP.lastIndex=index;match=PARAM_REGEXP.exec(header);){if(match.index!==index)throw new TypeError("invalid parameter format");index+=match[0].length,key=match[1].toLowerCase(),value=match[2],value.charCodeAt(0)===34&&(value=value.slice(1,-1),value.indexOf("\\")!==-1&&(value=value.replace(QESC_REGEXP,"$1"))),obj.parameters[key]=value}if(index!==header.length)throw new TypeError("invalid parameter format")}return obj}function getcontenttype(obj){var header;if(typeof obj.getHeader=="function"?header=obj.getHeader("content-type"):typeof obj.headers=="object"&&(header=obj.headers&&obj.headers["content-type"]),typeof header!="string")throw new TypeError("content-type header is missing from object");return header}function qstring(val){var str=String(val);if(TOKEN_REGEXP.test(str))return str;if(str.length>0&&!TEXT_REGEXP.test(str))throw new TypeError("invalid parameter value");return'"'+str.replace(QUOTE_REGEXP,"\\$1")+'"'}function ContentType(type){this.parameters=Object.create(null),this.type=type}}});var import_content_type=__toESM(require_content_type(),1);function mediaTypeEssence(header){if(header)try{return import_content_type.default.parse(header).type}catch{let essence=(header.split(";",1)[0]??"").trim().toLowerCase();return essence===""||header.slice(essence.length).includes(",")?void 0:essence}}var ParseError=class extends Error{constructor(message,options){super(message),this.name="ParseError",this.type=options.type,this.field=options.field,this.value=options.value,this.line=options.line}},LF=10,CR=13,SPACE=32;function noop(_arg){}function createParser(config){if(typeof config=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent=noop,onError=noop,onRetry=noop,onComment,maxBufferSize}=config,pendingFragments=[],pendingFragmentsLength=0,isFirstChunk=!0,id,data="",dataLines=0,eventType,terminated=!1;function feed(chunk){if(terminated)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(isFirstChunk&&(isFirstChunk=!1,chunk.charCodeAt(0)===239&&chunk.charCodeAt(1)===187&&chunk.charCodeAt(2)===191&&(chunk=chunk.slice(3))),pendingFragments.length===0){let trailing2=processLines(chunk);trailing2!==""&&(pendingFragments.push(trailing2),pendingFragmentsLength=trailing2.length),checkBufferSize();return}if(chunk.indexOf(` `)===-1&&chunk.indexOf("\r")===-1){pendingFragments.push(chunk),pendingFragmentsLength+=chunk.length,checkBufferSize();return}pendingFragments.push(chunk);let input=pendingFragments.join("");pendingFragments.length=0,pendingFragmentsLength=0;let trailing=processLines(input);trailing!==""&&(pendingFragments.push(trailing),pendingFragmentsLength=trailing.length),checkBufferSize()}function checkBufferSize(){maxBufferSize!==void 0&&(pendingFragmentsLength+data.length<=maxBufferSize||(terminated=!0,pendingFragments.length=0,pendingFragmentsLength=0,id=void 0,data="",dataLines=0,eventType=void 0,onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`,{type:"max-buffer-size-exceeded"}))))}function processLines(chunk){let searchIndex=0;if(chunk.indexOf("\r")===-1){let lfIndex=chunk.indexOf(` `,searchIndex);for(;lfIndex!==-1;){if(searchIndex===lfIndex){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data="",dataLines=0,eventType=void 0,searchIndex=lfIndex+1,lfIndex=chunk.indexOf(` `,searchIndex);continue}let firstCharCode=chunk.charCodeAt(searchIndex);if(isDataPrefix(chunk,searchIndex,firstCharCode)){let valueStart=chunk.charCodeAt(searchIndex+5)===SPACE?searchIndex+6:searchIndex+5,value=chunk.slice(valueStart,lfIndex);if(dataLines===0&&chunk.charCodeAt(lfIndex+1)===LF){onEvent({id,event:eventType,data:value}),id=void 0,data="",eventType=void 0,searchIndex=lfIndex+2,lfIndex=chunk.indexOf(` `,searchIndex);continue}data=dataLines===0?value:`${data} ${value}`,dataLines++}else isEventPrefix(chunk,searchIndex,firstCharCode)?eventType=chunk.slice(chunk.charCodeAt(searchIndex+6)===SPACE?searchIndex+7:searchIndex+6,lfIndex)||void 0:parseLine(chunk,searchIndex,lfIndex);searchIndex=lfIndex+1,lfIndex=chunk.indexOf(` `,searchIndex)}return chunk.slice(searchIndex)}for(;searchIndex<chunk.length;){let crIndex=chunk.indexOf("\r",searchIndex),lfIndex=chunk.indexOf(` `,searchIndex),lineEnd=-1;if(crIndex!==-1&&lfIndex!==-1?lineEnd=crIndex<lfIndex?crIndex:lfIndex:crIndex!==-1?crIndex===chunk.length-1?lineEnd=-1:lineEnd=crIndex:lfIndex!==-1&&(lineEnd=lfIndex),lineEnd===-1)break;parseLine(chunk,searchIndex,lineEnd),searchIndex=lineEnd+1,chunk.charCodeAt(searchIndex-1)===CR&&chunk.charCodeAt(searchIndex)===LF&&searchIndex++}return chunk.slice(searchIndex)}function parseLine(chunk,start,end){if(start===end){dispatchEvent();return}let firstCharCode=chunk.charCodeAt(start);if(isDataPrefix(chunk,start,firstCharCode)){let valueStart=chunk.charCodeAt(start+5)===SPACE?start+6:start+5,value2=chunk.slice(valueStart,end);data=dataLines===0?value2:`${data} ${value2}`,dataLines++;return}if(isEventPrefix(chunk,start,firstCharCode)){eventType=chunk.slice(chunk.charCodeAt(start+6)===SPACE?start+7:start+6,end)||void 0;return}if(firstCharCode===105&&chunk.charCodeAt(start+1)===100&&chunk.charCodeAt(start+2)===58){let value2=chunk.slice(chunk.charCodeAt(start+3)===SPACE?start+4:start+3,end);id=value2.includes("\0")?void 0:value2;return}if(firstCharCode===58){if(onComment){let line2=chunk.slice(start,end);onComment(line2.slice(chunk.charCodeAt(start+1)===SPACE?2:1))}return}let line=chunk.slice(start,end),fieldSeparatorIndex=line.indexOf(":");if(fieldSeparatorIndex===-1){processField(line,"",line);return}let field=line.slice(0,fieldSeparatorIndex),offset=line.charCodeAt(fieldSeparatorIndex+1)===SPACE?2:1,value=line.slice(fieldSeparatorIndex+offset);processField(field,value,line)}function processField(field,value,line){switch(field){case"event":eventType=value||void 0;break;case"data":data=dataLines===0?value:`${data} ${value}`,dataLines++;break;case"id":id=value.includes("\0")?void 0:value;break;case"retry":/^\d+$/.test(value)?onRetry(parseInt(value,10)):onError(new ParseError(`Invalid \`retry\` value: "${value}"`,{type:"invalid-retry",value,line}));break;default:onError(new ParseError(`Unknown field "${field.length>20?`${field.slice(0,20)}\u2026`:field}"`,{type:"unknown-field",field,value,line}));break}}function dispatchEvent(){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data="",dataLines=0,eventType=void 0}function reset(options={}){if(options.consume&&pendingFragments.length>0){let incompleteLine=pendingFragments.join("");parseLine(incompleteLine,0,incompleteLine.length)}isFirstChunk=!0,id=void 0,data="",dataLines=0,eventType=void 0,pendingFragments.length=0,pendingFragmentsLength=0,terminated=!1}return{feed,reset}}function isDataPrefix(chunk,i,firstCharCode){return firstCharCode===100&&chunk.charCodeAt(i+1)===97&&chunk.charCodeAt(i+2)===116&&chunk.charCodeAt(i+3)===97&&chunk.charCodeAt(i+4)===58}function isEventPrefix(chunk,i,firstCharCode){return firstCharCode===101&&chunk.charCodeAt(i+1)===118&&chunk.charCodeAt(i+2)===101&&chunk.charCodeAt(i+3)===110&&chunk.charCodeAt(i+4)===116&&chunk.charCodeAt(i+5)===58}var EventSourceParserStream=class extends TransformStream{constructor({onError,onRetry,onComment,maxBufferSize}={}){let parser;super({start(controller){parser=createParser({onEvent:event=>{controller.enqueue(event)},onError(error){typeof onError=="function"&&onError(error),(onError==="terminate"||error.type==="max-buffer-size-exceeded")&&controller.error(error)},onRetry,onComment,maxBufferSize})},transform(chunk){parser.feed(chunk)}})}};var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},StreamableHTTPError=class extends Error{constructor(code,message){super(`Streamable HTTP error: ${message}`),this.code=code}},StreamableHTTPClientTransport=class{constructor(url,opts){this._hasCompletedAuthFlow=!1,this._url=url,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=opts?.requestInit,this._authProvider=opts?.authProvider,this._fetch=opts?.fetch,this._fetchWithInit=createFetchWithInit(opts?.fetch,opts?.requestInit),this._followRedirects=opts?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=fetchLeavingRedirects(this._fetch),this._fetchWithInit=fetchLeavingRedirects(this._fetchWithInit)),this._sessionId=opts?.sessionId,this._reconnectionOptions=opts?.reconnectionOptions??DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS}_unfollowedRedirect(response,url){let text=unfollowedRedirect(response,url);return text&&!this._followRedirects?`${text} (redirectPolicy: 'same-origin')`:text}async _authThenStart(){if(!this._authProvider)throw new UnauthorizedError("No auth provider");let result;try{result=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(error){throw this.onerror?.(error),error}if(result!=="AUTHORIZED")throw new UnauthorizedError;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let headers={};if(this._authProvider){let tokens=await this._authProvider.tokens();tokens&&(headers.Authorization=`Bearer ${tokens.access_token}`)}this._sessionId&&(headers["mcp-session-id"]=this._sessionId),this._protocolVersion&&(headers["mcp-protocol-version"]=this._protocolVersion);let extraHeaders=normalizeHeaders(this._requestInit?.headers);return new Headers({...headers,...extraHeaders})}async _startOrAuthSse(options){let{resumptionToken}=options;try{let headers=await this._commonHeaders();headers.set("Accept","text/event-stream"),resumptionToken&&headers.set("last-event-id",resumptionToken);let fetchFn=this._fetch??fetch,init={method:"GET",headers,signal:this._abortController?.signal},response=await fetchFn(this._url,this._followRedirects?init:{...init,redirect:"manual"}),followed=this._followRedirects?void 0:followWithinOrigin(fetchFn,this._url,init,response);if(followed&&(response=await followed),!response.ok){if(await response.body?.cancel(),response.status===401&&this._authProvider)return await this._authThenStart();if(response.status===405)return;throw new StreamableHTTPError(response.status,`Failed to open SSE stream: ${this._unfollowedRedirect(response,this._url)??response.statusText}`)}this._handleSseStream(response.body,options,!0)}catch(error){throw this.onerror?.(error),error}}_getNextReconnectionDelay(attempt){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let initialDelay=this._reconnectionOptions.initialReconnectionDelay,growFactor=this._reconnectionOptions.reconnectionDelayGrowFactor,maxDelay=this._reconnectionOptions.maxReconnectionDelay;return Math.min(initialDelay*Math.pow(growFactor,attempt),maxDelay)}_scheduleReconnection(options,attemptCount=0){let maxRetries=this._reconnectionOptions.maxRetries;if(attemptCount>=maxRetries){this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));return}let delay=this._getNextReconnectionDelay(attemptCount);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(options).catch(error=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error?error.message:String(error)}`)),this._scheduleReconnection(options,attemptCount+1)})},delay)}_handleSseStream(stream,options,isReconnectable){if(!stream)return;let{onresumptiontoken,replayMessageId}=options,lastEventId,hasPrimingEvent=!1,receivedResponse=!1;(async()=>{try{let reader=stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream({onRetry:retryMs=>{this._serverRetryMs=retryMs}})).getReader();for(;;){let{value:event,done}=await reader.read();if(done)break;if(event.id&&(lastEventId=event.id,hasPrimingEvent=!0,onresumptiontoken?.(event.id)),!!event.data&&(!event.event||event.event==="message"))try{let message=JSONRPCMessageSchema.parse(JSON.parse(event.data));isJSONRPCResultResponse(message)&&(receivedResponse=!0,replayMessageId!==void 0&&(message.id=replayMessageId)),this.onmessage?.(message)}catch(error){this.onerror?.(error)}}(isReconnectable||hasPrimingEvent)&&!receivedResponse&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:lastEventId,onresumptiontoken,replayMessageId},0)}catch(error){if(this.onerror?.(new Error(`SSE stream disconnected: ${error}`)),(isReconnectable||hasPrimingEvent)&&!receivedResponse&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:lastEventId,onresumptiontoken,replayMessageId},0)}catch(error2){this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error?error2.message:String(error2)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(authorizationCode){if(!this._authProvider)throw new UnauthorizedError("No auth provider");if(await auth(this._authProvider,{serverUrl:this._url,authorizationCode,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(message,options){try{let{resumptionToken,onresumptiontoken}=options||{};if(resumptionToken){this._startOrAuthSse({resumptionToken,replayMessageId:isJSONRPCRequest(message)?message.id:void 0}).catch(err=>this.onerror?.(err));return}let headers=await this._commonHeaders();headers.set("content-type","application/json"),headers.set("accept","application/json, text/event-stream");let init={...this._requestInit,method:"POST",headers,body:JSON.stringify(message),signal:this._abortController?.signal},response=await fetchWithinOrigin(this._fetch??fetch)(this._url,init),sessionId=response.headers.get("mcp-session-id");if(sessionId&&(this._sessionId=sessionId),!response.ok){let text=await response.text().catch(()=>null);if(response.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new StreamableHTTPError(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl,scope}=extractWWWAuthenticateParams(response);if(this._resourceMetadataUrl=resourceMetadataUrl,this._scope=scope,await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError;return this._hasCompletedAuthFlow=!0,this.send(message)}if(response.status===403&&this._authProvider){let{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(error==="insufficient_scope"){let wwwAuthHeader=response.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===wwwAuthHeader)throw new StreamableHTTPError(403,"Server returned 403 after trying upscoping");if(scope&&(this._scope=scope),resourceMetadataUrl&&(this._resourceMetadataUrl=resourceMetadataUrl),this._lastUpscopingHeader=wwwAuthHeader??void 0,await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new UnauthorizedError;return this.send(message)}}throw new StreamableHTTPError(response.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(response,this._url)??text}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,response.status===202){await response.body?.cancel(),isInitializedNotification(message)&&this._startOrAuthSse({resumptionToken:void 0}).catch(err=>this.onerror?.(err));return}let hasRequests=(Array.isArray(message)?message:[message]).filter(msg=>"method"in msg&&"id"in msg&&msg.id!==void 0).length>0,contentType2=response.headers.get("content-type"),responseMediaType=mediaTypeEssence(contentType2);if(hasRequests)if(responseMediaType==="text/event-stream")this._handleSseStream(response.body,{onresumptiontoken},!1);else if(responseMediaType==="application/json"){let data=await response.json(),responseMessages=Array.isArray(data)?data.map(msg=>JSONRPCMessageSchema.parse(msg)):[JSONRPCMessageSchema.parse(data)];for(let msg of responseMessages)this.onmessage?.(msg)}else throw await response.body?.cancel(),new StreamableHTTPError(-1,`Unexpected content type: ${contentType2}`);else await response.body?.cancel()}catch(error){throw this.onerror?.(error),error}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let headers=await this._commonHeaders(),init={...this._requestInit,method:"DELETE",headers,signal:this._abortController?.signal},response=await fetchWithinOrigin(this._fetch??fetch)(this._url,init);if(await response.body?.cancel(),!response.ok&&response.status!==405)throw new StreamableHTTPError(response.status,`Failed to terminate session: ${this._unfollowedRedirect(response,this._url)??response.statusText}`);this._sessionId=void 0}catch(error){throw this.onerror?.(error),error}}setProtocolVersion(version){this._protocolVersion=version}get protocolVersion(){return this._protocolVersion}async resumeStream(lastEventId,options){await this._startOrAuthSse({resumptionToken:lastEventId,onresumptiontoken:options?.onresumptiontoken})}};export{StreamableHTTPClientTransport,StreamableHTTPError};