@dev-crowagent/pigeon-coding-agent 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/bundle/chunks/{anthropic-messages-S7OHKPOC.js → anthropic-messages-QJJLDZHE.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-C4HXCGKY.js → azure-openai-responses-DYWZCA5X.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-5YSISOFY.js → chunk-3FMXCUWP.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-6BV2MVXK.js → chunk-3PBWJQ66.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-VY3Y7KDL.js → chunk-3U6YJAQP.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-T52L5B3T.js → chunk-5CCI6VJX.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-PGJVGVSP.js → chunk-5USCOSGN.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-OUFDCV7C.js → chunk-BEK6TYMV.js} +1 -1
  11. package/dist/bundle/chunks/chunk-BMDT5BON.js +17 -0
  12. package/dist/bundle/chunks/chunk-GSHWAOXD.js +2 -0
  13. package/dist/bundle/chunks/chunk-IDIZ4UTE.js +84 -0
  14. package/dist/bundle/chunks/{chunk-BOCI5WGU.js → chunk-JHKMQXNB.js} +1 -1
  15. package/dist/bundle/chunks/chunk-QISAGK35.js +15 -0
  16. package/dist/bundle/chunks/{chunk-WTT6ACRW.js → chunk-QRGBEJWY.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-RMQSLH4P.js → chunk-THQI7SZG.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-3BW64VNB.js → chunk-UKXS2KMU.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-QIM6CXAU.js → chunk-VPWKWGGZ.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-CENTGHH3.js → chunk-VQAGYOJU.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-VKY2XKRH.js → chunk-VRQXNNU2.js} +2 -2
  22. package/dist/bundle/chunks/{chunk-GQHEZCKG.js → chunk-WBYK5EUB.js} +148 -208
  23. package/dist/bundle/chunks/{chunk-ONH666LT.js → chunk-Z66WXIFH.js} +1 -1
  24. package/dist/bundle/chunks/{cli-FNCZKMKM.js → cli-USNOWZD3.js} +1 -1
  25. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-R2JVPCDL.js → cloudflare-workers-ai-system-one-3X2SUJJS.js} +1 -1
  26. package/dist/bundle/chunks/{execute-XNTKW56B.js → execute-GDKXFYVG.js} +1 -1
  27. package/dist/bundle/chunks/{google-generative-ai-5VXURRH2.js → google-generative-ai-GI6YYRFV.js} +1 -1
  28. package/dist/bundle/chunks/{google-vertex-WHGUHG5B.js → google-vertex-6SBDJ6E6.js} +1 -1
  29. package/dist/bundle/chunks/{llama-cpp-classify-LNRMBUDA.js → llama-cpp-classify-A6IS64ZW.js} +1 -1
  30. package/dist/bundle/chunks/{mistral-conversations-FZ4P7VNF.js → mistral-conversations-7RT7TO7K.js} +1 -1
  31. package/dist/bundle/chunks/{openai-codex-responses-OIMJK5WE.js → openai-codex-responses-P5OBIMST.js} +1 -1
  32. package/dist/bundle/chunks/{openai-completions-FHCUS6R5.js → openai-completions-Z6RGAWT5.js} +1 -1
  33. package/dist/bundle/chunks/{openai-decisions-LABKHEXJ.js → openai-decisions-TMZR73QU.js} +1 -1
  34. package/dist/bundle/chunks/{openai-responses-3WC62NWH.js → openai-responses-MFC5X2SY.js} +1 -1
  35. package/dist/bundle/chunks/{openrouter-chat-images-FFVJXZTY.js → openrouter-chat-images-FMPGOOZW.js} +1 -1
  36. package/dist/bundle/chunks/{openrouter-images-SPX5Z3O3.js → openrouter-images-KM7MMBZV.js} +1 -1
  37. package/dist/bundle/chunks/{pigeon-decision-PKYQMZCD.js → pigeon-decision-USGSVSUH.js} +1 -1
  38. package/dist/bundle/chunks/{pigeon-image-4OX3LN22.js → pigeon-image-XCBEUVPA.js} +1 -1
  39. package/dist/bundle/chunks/{pigeon-messages-BDEFLADM.js → pigeon-messages-SJ3XBCLJ.js} +1 -1
  40. package/dist/bundle/chunks/{runtime-5YBC2DMM.js → runtime-BOCII6AA.js} +1 -1
  41. package/dist/bundle/chunks/serve-command-NLBMAD3H.js +41 -0
  42. package/dist/bundle/chunks/{typesafe-system-one-LBP2VTNM.js → typesafe-system-one-X243G3TP.js} +1 -1
  43. package/dist/bundle/chunks/virtual-modules-MKFBVGCK.js +2 -0
  44. package/dist/bundle/cli-runtime.js +1 -1
  45. package/dist/bundle/index.js +1 -1
  46. package/dist/bundle/rpc-entry.js +1 -1
  47. package/dist/cli/args.d.ts.map +1 -1
  48. package/dist/cli/args.js +2 -1
  49. package/dist/cli/args.js.map +1 -1
  50. package/dist/cli/serve-command.d.ts +3 -0
  51. package/dist/cli/serve-command.d.ts.map +1 -0
  52. package/dist/cli/serve-command.js +163 -0
  53. package/dist/cli/serve-command.js.map +1 -0
  54. package/dist/cli/serve-command.lazy.d.ts +2 -0
  55. package/dist/cli/serve-command.lazy.d.ts.map +1 -0
  56. package/dist/cli/serve-command.lazy.js +2 -0
  57. package/dist/cli/serve-command.lazy.js.map +1 -0
  58. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  59. package/dist/extensions/mcp/runtime.js +3 -0
  60. package/dist/extensions/mcp/runtime.js.map +1 -1
  61. package/dist/main.d.ts.map +1 -1
  62. package/dist/main.js +6 -0
  63. package/dist/main.js.map +1 -1
  64. package/package.json +9 -8
  65. package/dist/bundle/chunks/chunk-KQBUYSHV.js +0 -30
  66. package/dist/bundle/chunks/virtual-modules-RXYO7SWA.js +0 -2
@@ -77,6 +77,6 @@ ${page.details}`:page.message}var OAuthCallbackServer=class _OAuthCallbackServer
77
77
  </html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var REFRESH_LOCK_STALE_MS=2e4,REFRESH_LOCK_WAIT_MS=25e3,REFRESH_LOCK_RETRY_MS=100;function parseStates(content){if(!content?.trim())return{};let parsed=JSON.parse(content);return typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:{}}function serializeStates(states){return`${JSON.stringify(states,null,2)}
78
78
  `}function storeKeys(name,serverUrl){let legacyKey=String(new URL(serverUrl));return{key:`${mcpNamespace(name)}|${legacyKey}`,legacyKey}}var McpOAuthCredentialStore=class{backend;lockDir;constructor(backend,lockDir){this.backend=backend??new FileAuthStorageBackend(join(getAgentDir(),"mcp-auth.json")),this.lockDir=backend?lockDir:getAgentDir()}forServer(name,serverUrl){let{key,legacyKey}=storeKeys(name,serverUrl);return{load:()=>this.backend.withLock(current=>{let states=parseStates(current);return states[key]||!states[legacyKey]?{result:states[key]}:(states[key]=states[legacyKey],delete states[legacyKey],{result:states[key],next:serializeStates(states)})}),save:state=>this.write(states=>{states[key]=state}),withRefreshLock:fn=>this.withRefreshLock(key,fn)}}async withRefreshLock(key,fn){if(!this.lockDir)return fn();mkdirSync(this.lockDir,{recursive:!0,mode:448});let hash=createHash2("sha256").update(key).digest("hex").slice(0,16),release=await import_proper_lockfile.default.lock(join(this.lockDir,`mcp-auth-refresh-${hash}`),{realpath:!1,stale:REFRESH_LOCK_STALE_MS,retries:{retries:REFRESH_LOCK_WAIT_MS/REFRESH_LOCK_RETRY_MS,factor:1,minTimeout:REFRESH_LOCK_RETRY_MS,maxTimeout:REFRESH_LOCK_RETRY_MS},onCompromised:()=>{}}).catch(error=>{throw error instanceof Error&&"code"in error&&error.code==="ELOCKED"?new McpRefreshLockBusyError:error});try{return await fn()}finally{await release().catch(()=>{})}}tokens(name,serverUrl){let{key,legacyKey}=storeKeys(name,serverUrl),states=this.backend.withLock(current=>({result:parseStates(current)}));return(states[key]??states[legacyKey])?.tokens}remove(name,serverUrl){let{key,legacyKey}=storeKeys(name,serverUrl);return this.backend.withLock(current=>{let states=parseStates(current),stored=key in states?key:legacyKey in states?legacyKey:void 0;return stored?(delete states[stored],{result:!0,next:serializeStates(states)}):{result:!1}})}write(update){this.backend.withLock(current=>{let states=parseStates(current);return update(states),{result:void 0,next:serializeStates(states)}})}},PIGEON_CLIENT_METADATA_DOCUMENTS={baseUrl:"https://pi.dev/oauth",listsRedirectUrl:isClientMetadataDocumentCallback},PIGEON_CLIENT={clientName:APP_NAME,clientMetadataDocuments:PIGEON_CLIENT_METADATA_DOCUMENTS};function pigeonSettings(settings){return(settings.clientRegistration??"auto")==="auto"&&APP_NAME!=="pigeon"?{...settings,clientRegistration:"dcr"}:settings}function createMcpAuthProvider2(options){return createMcpAuthProvider({...options,...PIGEON_CLIENT,settings:()=>pigeonSettings(options.settings())})}function renderCallbackPage(page){return page.ok?oauthSuccessHtml("Signed in to the MCP server. You may now close this page."):oauthErrorHtml(page.message,page.details)}async function signInMcpServer(options){let{serverUrl,store,challenge,prompt,signal}=options,settings=pigeonSettings(options.settings),{callback,redirectUrl}=await listenForLoopbackSignIn({serverUrl,store,settings,clientMetadataDocuments:PIGEON_CLIENT_METADATA_DOCUMENTS,renderPage:renderCallbackPage});try{let signIn={serverUrl,store,settings,redirectUrl,challenge,signal,...PIGEON_CLIENT},authorization=await startMcpSignIn(signIn);if(authorization.kind==="authorized")return;prompt.showAuthorizationUrl(new URL(authorization.authorizationUrl));let response=await waitForLoopbackSignIn({callback,authorization,promptForRedirectUrl:promptSignal=>prompt.promptForRedirectUrl(promptSignal),signal});await completeMcpSignIn({...signIn,authorization,response})}finally{await callback.close()}}import{appendFileSync,mkdirSync as mkdirSync2,renameSync,statSync}from"node:fs";import{dirname}from"node:path";var MAX_LOG_BYTES=5*1024*1024;function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function formatData(data){if(typeof data=="string")return data;try{return JSON.stringify(data)??String(data)}catch{return String(data)}}function formatMcpLogMessage(server,params,now=new Date){let message=isRecord(params)?params:{data:params},level=typeof message.level=="string"?message.level:"info",logger=typeof message.logger=="string"&&message.logger?` ${message.logger}:`:"",text=formatData(message.data).replace(/\r?\n/g,`
79
79
  `);return`${now.toISOString()} [${server}] ${level}${logger} ${text}
80
- `}var McpServerLog=class{path;size;constructor(path){this.path=path}write(server,params){let line=formatMcpLogMessage(server,params);try{this.size===void 0&&(mkdirSync2(dirname(this.path),{recursive:!0}),this.size=this.currentSize()),this.size>MAX_LOG_BYTES&&(this.currentSize()>MAX_LOG_BYTES&&renameSync(this.path,`${this.path}.1`),this.size=this.currentSize()),appendFileSync(this.path,line),this.size+=Buffer.byteLength(line)}catch{}}currentSize(){try{return statSync(this.path).size}catch{return 0}}};var DEFAULT_TIMEOUT_SECONDS=60,STDERR_TAIL_CHARS=2e3,CONNECT_RETRY_DELAYS_MS=[250,1e3],LISTEN_RETRY_DELAYS_MS=[1e3,5e3,3e4],RESTART_CONNECT_TIMEOUT_MS=1e4;function errorMessage(error){return error instanceof Error?error.message:String(error)}function isTransientError(error){return error instanceof McpHttpError?error.status===408||error.status===429||error.status>=500&&error.status!==501:error instanceof TypeError}function signInRequiredMessage(entry){let provider="url"in entry.config?entry.config.auth?.provider:void 0;return`MCP server "${entry.name}" requires sign-in. Run ${provider?`/login ${provider}`:"/mcp"} to sign in.`}function usesOAuth(entry){let{config}=entry;return!("url"in config)||config.auth?!1:!Object.keys(config.headers??{}).some(header=>header.toLowerCase()==="authorization")}function expandHome(value){return value==="~"?homedir():value.startsWith("~/")||process.platform==="win32"&&value.startsWith("~\\")?join2(homedir(),value.slice(2)):value}function createDefaultTransport(entry,cwd,authProvider){let{config,name}=entry;if("url"in config)return new StreamableHttpTransport({url:config.url,headers:resolveHeadersOrThrow(config.headers,`MCP server "${name}"`),authProvider});let env={};for(let[key,value]of Object.entries(config.env??{}))env[key]=resolveConfigValueOrThrow(value,`MCP server "${name}" env "${key}"`);return new StdioTransport({command:expandHome(config.command),args:config.args?.map(expandHome),cwd:resolve(cwd,expandHome(config.cwd??".")),env,stderr:"pipe"})}async function withoutTemplates(list,empty){try{return await list()}catch(error){if(error instanceof McpError&&error.code===JSON_RPC_ERROR_CODES.methodNotFound)return empty;throw error}}function listTemplates(client,options={}){return withoutTemplates(()=>client.listResourceTemplates(options),[])}var McpServerConnection=class{entry;state="connecting";error;tools=[];hasResources=!1;instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(options){this.entry=options.entry,this.cwd=options.cwd,this.createTransport=options.createTransport,this.onTools=options.onTools,this.onChange=options.onChange,this.log=options.log;let url=this.oauthUrl,provider="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=url?createMcpAuthProvider2({serverUrl:url,store:options.credentials.forServer(this.entry.name,url),settings:()=>this.oauthSettings(),onChallenge:challenge=>{this.challenge=challenge}}):provider?{token:async()=>options.providerToken?.(provider),settled:async()=>{}}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??DEFAULT_TIMEOUT_SECONDS)*1e3}get oauthUrl(){return usesOAuth(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let oauth="url"in this.entry.config?this.entry.config.oauth:void 0;return oauth?{clientId:oauth.clientId,clientSecret:oauth.clientSecret===void 0?void 0:resolveConfigValueOrThrow(oauth.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:oauth.callbackPort,callbackUrl:oauth.callbackUrl,scope:oauth.scope,clientName:oauth.clientName,clientRegistration:oauth.clientRegistration,authServerMetadataUrl:oauth.authServerMetadataUrl?new URL(oauth.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(name,args,options){return this.withClient(client=>client.callTool(name,args,options))}readResource(uri,options){return this.withClient(client=>client.readResource(uri,options),!0)}resourcesPage(cursor,options){return this.withClient(client=>client.listResourcesPage(cursor,options),!0)}resourceTemplatesPage(cursor,options){return this.withClient(client=>withoutTemplates(()=>client.listResourceTemplatesPage(cursor,options),{resourceTemplates:[]}),!0)}allResources(options){return this.withClient(client=>client.listResources(options),!0)}allResourceTemplates(options){return this.withClient(client=>listTemplates(client,options),!0)}async withClient(run,readOnly=!1){for(let attempt=1;;attempt++){let client=await this.getClient();try{return await run(client)}catch(error){if(readOnly&&attempt===1&&error instanceof McpHttpError&&isTransientError(error)){await new Promise(resolve2=>setTimeout(resolve2,CONNECT_RETRY_DELAYS_MS[0]));continue}if(error instanceof McpSessionExpiredError&&attempt===1){this.client===client&&(this.client=void 0);continue}throw this.needsSignIn(error)?(await this.dropClient(client),this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):error}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(error){return error instanceof McpOAuthAuthorizationRequiredError||this.authProvider!==void 0&&error instanceof McpAuthRequiredError}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(client){this.client===client&&(this.client=void 0),await client.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let retries="url"in this.entry.config?CONNECT_RETRY_DELAYS_MS:[],configured=this.entry.config.protocol,protocol=configured??"auto",rejected;for(let attempt=0;;){this.stderrTail=void 0;try{return await this.connectOnce(protocol,rejected?RESTART_CONNECT_TIMEOUT_MS:void 0)}catch(error){if(configured===void 0&&!rejected&&!("url"in this.entry.config)&&error instanceof McpInitializeRejectedError&&!(error.discoverError instanceof McpTimeoutError)&&!this.closed){rejected=error,protocol=STATELESS_PROTOCOL_VERSION;continue}let reported=rejected??error,delay=retries[attempt++];if(this.closed||delay===void 0||!isTransientError(error))throw this.connectFailed(reported);if(await sleep(delay,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(reported)}}}async connectOnce(protocol,connectTimeoutMs){let log=this.log,client=new McpClient({name:"pigeon",version:VERSION,protocol,requestTimeoutMs:this.timeoutMs,...connectTimeoutMs===void 0?{}:{connectTimeoutMs:Math.min(connectTimeoutMs,this.timeoutMs)},roots:[{uri:pathToFileURL(this.cwd).href,name:basename(this.cwd)}],...log?{logLevel:"info"}:{}});log&&client.onNotification("notifications/message",params=>log.write(this.entry.name,params));let closing,closeClient=()=>(closing??=client.close().catch(()=>{}),closing);this.shutdown.signal.addEventListener("abort",closeClient,{once:!0});let transport;try{transport=this.createTransport(this.entry,this.cwd,this.authProvider),await client.connect(transport),client.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(client)});let stdio=transport instanceof StdioTransport?transport:void 0;client.onClose(()=>this.handleClientClose(client,stdio));let tools=client.serverCapabilities?.tools?await client.listTools():[];if(this.closed)throw new Error("shut down while connecting");if(client.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=client,this.tools=tools,this.hasResources=client.serverCapabilities?.resources!==void 0,this.instructions=client.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),client.protocolVersion===STATELESS_PROTOCOL_VERSION&&client.serverCapabilities?.tools?.listChanged&&this.watchToolChanges(client),client}catch(error){throw await closeClient(),transport instanceof StdioTransport&&(this.stderrTail=sliceTail(transport.stderr.trim(),STDERR_TAIL_CHARS)||void 0),error}finally{this.shutdown.signal.removeEventListener("abort",closeClient)}}connectFailed(error){return this.needsSignIn(error)&&!this.closed?(this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${errorMessage(error)}
80
+ `}var McpServerLog=class{path;size;constructor(path){this.path=path}write(server,params){let line=formatMcpLogMessage(server,params);try{this.size===void 0&&(mkdirSync2(dirname(this.path),{recursive:!0}),this.size=this.currentSize()),this.size>MAX_LOG_BYTES&&(this.currentSize()>MAX_LOG_BYTES&&renameSync(this.path,`${this.path}.1`),this.size=this.currentSize()),appendFileSync(this.path,line),this.size+=Buffer.byteLength(line)}catch{}}currentSize(){try{return statSync(this.path).size}catch{return 0}}};var DEFAULT_TIMEOUT_SECONDS=60,STDERR_TAIL_CHARS=2e3,CONNECT_RETRY_DELAYS_MS=[250,1e3],LISTEN_RETRY_DELAYS_MS=[1e3,5e3,3e4],RESTART_CONNECT_TIMEOUT_MS=1e4;function errorMessage(error){return error instanceof Error?error.message:String(error)}function isTransientError(error){return error instanceof McpHttpError?error.status===408||error.status===429||error.status>=500&&error.status!==501:error instanceof TypeError}function signInRequiredMessage(entry){let provider="url"in entry.config?entry.config.auth?.provider:void 0;return`MCP server "${entry.name}" requires sign-in. Run ${provider?`/login ${provider}`:"/mcp"} to sign in.`}function usesOAuth(entry){let{config}=entry;return!("url"in config)||config.auth?!1:!Object.keys(config.headers??{}).some(header=>header.toLowerCase()==="authorization")}function expandHome(value){return value==="~"?homedir():value.startsWith("~/")||process.platform==="win32"&&value.startsWith("~\\")?join2(homedir(),value.slice(2)):value}function createDefaultTransport(entry,cwd,authProvider){let{config,name}=entry;if("url"in config)return new StreamableHttpTransport({url:config.url,headers:resolveHeadersOrThrow(config.headers,`MCP server "${name}"`),authProvider});let env={};for(let[key,value]of Object.entries(config.env??{})){if(typeof value!="string")throw new Error(`MCP server "${name}" env "${key}" must be a string.`);env[key]=resolveConfigValueOrThrow(value,`MCP server "${name}" env "${key}"`)}return new StdioTransport({command:expandHome(config.command),args:config.args?.map(expandHome),cwd:resolve(cwd,expandHome(config.cwd??".")),env,stderr:"pipe"})}async function withoutTemplates(list,empty){try{return await list()}catch(error){if(error instanceof McpError&&error.code===JSON_RPC_ERROR_CODES.methodNotFound)return empty;throw error}}function listTemplates(client,options={}){return withoutTemplates(()=>client.listResourceTemplates(options),[])}var McpServerConnection=class{entry;state="connecting";error;tools=[];hasResources=!1;instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(options){this.entry=options.entry,this.cwd=options.cwd,this.createTransport=options.createTransport,this.onTools=options.onTools,this.onChange=options.onChange,this.log=options.log;let url=this.oauthUrl,provider="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=url?createMcpAuthProvider2({serverUrl:url,store:options.credentials.forServer(this.entry.name,url),settings:()=>this.oauthSettings(),onChallenge:challenge=>{this.challenge=challenge}}):provider?{token:async()=>options.providerToken?.(provider),settled:async()=>{}}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??DEFAULT_TIMEOUT_SECONDS)*1e3}get oauthUrl(){return usesOAuth(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let oauth="url"in this.entry.config?this.entry.config.oauth:void 0;return oauth?{clientId:oauth.clientId,clientSecret:oauth.clientSecret===void 0?void 0:resolveConfigValueOrThrow(oauth.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:oauth.callbackPort,callbackUrl:oauth.callbackUrl,scope:oauth.scope,clientName:oauth.clientName,clientRegistration:oauth.clientRegistration,authServerMetadataUrl:oauth.authServerMetadataUrl?new URL(oauth.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(name,args,options){return this.withClient(client=>client.callTool(name,args,options))}readResource(uri,options){return this.withClient(client=>client.readResource(uri,options),!0)}resourcesPage(cursor,options){return this.withClient(client=>client.listResourcesPage(cursor,options),!0)}resourceTemplatesPage(cursor,options){return this.withClient(client=>withoutTemplates(()=>client.listResourceTemplatesPage(cursor,options),{resourceTemplates:[]}),!0)}allResources(options){return this.withClient(client=>client.listResources(options),!0)}allResourceTemplates(options){return this.withClient(client=>listTemplates(client,options),!0)}async withClient(run,readOnly=!1){for(let attempt=1;;attempt++){let client=await this.getClient();try{return await run(client)}catch(error){if(readOnly&&attempt===1&&error instanceof McpHttpError&&isTransientError(error)){await new Promise(resolve2=>setTimeout(resolve2,CONNECT_RETRY_DELAYS_MS[0]));continue}if(error instanceof McpSessionExpiredError&&attempt===1){this.client===client&&(this.client=void 0);continue}throw this.needsSignIn(error)?(await this.dropClient(client),this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):error}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(error){return error instanceof McpOAuthAuthorizationRequiredError||this.authProvider!==void 0&&error instanceof McpAuthRequiredError}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(client){this.client===client&&(this.client=void 0),await client.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let retries="url"in this.entry.config?CONNECT_RETRY_DELAYS_MS:[],configured=this.entry.config.protocol,protocol=configured??"auto",rejected;for(let attempt=0;;){this.stderrTail=void 0;try{return await this.connectOnce(protocol,rejected?RESTART_CONNECT_TIMEOUT_MS:void 0)}catch(error){if(configured===void 0&&!rejected&&!("url"in this.entry.config)&&error instanceof McpInitializeRejectedError&&!(error.discoverError instanceof McpTimeoutError)&&!this.closed){rejected=error,protocol=STATELESS_PROTOCOL_VERSION;continue}let reported=rejected??error,delay=retries[attempt++];if(this.closed||delay===void 0||!isTransientError(error))throw this.connectFailed(reported);if(await sleep(delay,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(reported)}}}async connectOnce(protocol,connectTimeoutMs){let log=this.log,client=new McpClient({name:"pigeon",version:VERSION,protocol,requestTimeoutMs:this.timeoutMs,...connectTimeoutMs===void 0?{}:{connectTimeoutMs:Math.min(connectTimeoutMs,this.timeoutMs)},roots:[{uri:pathToFileURL(this.cwd).href,name:basename(this.cwd)}],...log?{logLevel:"info"}:{}});log&&client.onNotification("notifications/message",params=>log.write(this.entry.name,params));let closing,closeClient=()=>(closing??=client.close().catch(()=>{}),closing);this.shutdown.signal.addEventListener("abort",closeClient,{once:!0});let transport;try{transport=this.createTransport(this.entry,this.cwd,this.authProvider),await client.connect(transport),client.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(client)});let stdio=transport instanceof StdioTransport?transport:void 0;client.onClose(()=>this.handleClientClose(client,stdio));let tools=client.serverCapabilities?.tools?await client.listTools():[];if(this.closed)throw new Error("shut down while connecting");if(client.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=client,this.tools=tools,this.hasResources=client.serverCapabilities?.resources!==void 0,this.instructions=client.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),client.protocolVersion===STATELESS_PROTOCOL_VERSION&&client.serverCapabilities?.tools?.listChanged&&this.watchToolChanges(client),client}catch(error){throw await closeClient(),transport instanceof StdioTransport&&(this.stderrTail=sliceTail(transport.stderr.trim(),STDERR_TAIL_CHARS)||void 0),error}finally{this.shutdown.signal.removeEventListener("abort",closeClient)}}connectFailed(error){return this.needsSignIn(error)&&!this.closed?(this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${errorMessage(error)}
81
81
  ${this.stderrTail}`:errorMessage(error),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(client,stdio){if(this.client!==client||this.closed)return;this.client=void 0,this.state="disconnected";let stderr=stdio?sliceTail(stdio.stderr.trim(),STDERR_TAIL_CHARS):void 0;this.error=stderr?`Connection closed
82
82
  ${stderr}`:"Connection closed",this.changed()}async watchToolChanges(client){let current=()=>this.client===client&&!this.closed&&client.connectionState==="connected",lastDelay=LISTEN_RETRY_DELAYS_MS[LISTEN_RETRY_DELAYS_MS.length-1]??0,ends=0;for(let opened=0;current();opened++){let openedAt=Date.now();try{let subscription=await client.listen({toolsListChanged:!0},{signal:this.shutdown.signal});if(!subscription.notifications.toolsListChanged){subscription.close();return}opened>0&&this.refreshTools(client),await subscription.closed}catch{}ends=Date.now()-openedAt>lastDelay?1:ends+1;let delay=LISTEN_RETRY_DELAYS_MS[ends-1];if(delay===void 0||!current())return;await sleep(delay,void 0,{signal:this.shutdown.signal}).catch(()=>{})}}async refreshTools(client){try{let tools=await client.listTools();if(this.client!==client||this.closed)return;this.tools=tools,this.onTools(this)}catch(error){this.error=`Failed to refresh tools: ${errorMessage(error)}`}this.changed()}async close(){this.shutdown.abort(),this.state="closed",this.changed();let client=this.client;this.client=void 0,await Promise.all([client?.close().catch(()=>{}),this.opening?.catch(()=>{})]),await this.authProvider?.settled()}};export{McpSignInCancelledError,McpOAuthCredentialStore,signInMcpServer,McpServerLog,createDefaultTransport,McpServerConnection};