@stdiobus/workers-registry 1.4.14 → 1.5.0-beta.2

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 (129) hide show
  1. package/README.md +181 -21
  2. package/out/dist/workers-registry/acp-registry/index.js +128 -2
  3. package/out/dist/workers-registry/acp-registry/index.js.map +4 -4
  4. package/out/dist/workers-registry/acp-worker/index.js +1 -3
  5. package/out/dist/workers-registry/acp-worker/index.js.map +4 -4
  6. package/out/dist/workers-registry/index.d.ts +1 -0
  7. package/out/dist/workers-registry/index.js +6 -0
  8. package/out/dist/workers-registry/openai-agent/index.js +1 -1
  9. package/out/dist/workers-registry/openai-agent/index.js.map +2 -2
  10. package/out/dist/workers-registry/registry-launcher/index.js +131 -0
  11. package/out/dist/workers-registry/registry-launcher/index.js.map +7 -0
  12. package/out/tsc/workers-registry/acp-worker/src/index.d.ts +0 -10
  13. package/out/tsc/workers-registry/registry-launcher/src/auth/auth-manager.d.ts +392 -0
  14. package/out/tsc/workers-registry/registry-launcher/src/auth/cli/cli.property.test.d.ts +22 -0
  15. package/out/tsc/workers-registry/registry-launcher/src/auth/cli/index.d.ts +9 -0
  16. package/out/tsc/workers-registry/registry-launcher/src/auth/cli/login-command.d.ts +32 -0
  17. package/out/tsc/workers-registry/registry-launcher/src/auth/cli/logout-command.d.ts +25 -0
  18. package/out/tsc/workers-registry/registry-launcher/src/auth/cli/setup-command.d.ts +25 -0
  19. package/out/tsc/workers-registry/registry-launcher/src/auth/cli/status-command.d.ts +21 -0
  20. package/out/tsc/workers-registry/registry-launcher/src/auth/errors.d.ts +190 -0
  21. package/out/tsc/workers-registry/registry-launcher/src/auth/flows/agent-auth-flow.d.ts +146 -0
  22. package/out/tsc/workers-registry/registry-launcher/src/auth/flows/callback-server.d.ts +131 -0
  23. package/out/tsc/workers-registry/registry-launcher/src/auth/flows/callback-server.test.d.ts +1 -0
  24. package/out/tsc/workers-registry/registry-launcher/src/auth/flows/index.d.ts +11 -0
  25. package/out/tsc/workers-registry/registry-launcher/src/auth/flows/terminal-auth-flow.d.ts +252 -0
  26. package/out/tsc/workers-registry/registry-launcher/src/auth/flows/terminal-auth-flow.test.d.ts +1 -0
  27. package/out/tsc/workers-registry/registry-launcher/src/auth/index.d.ts +33 -0
  28. package/out/tsc/workers-registry/registry-launcher/src/auth/integration.test.d.ts +1 -0
  29. package/out/tsc/workers-registry/registry-launcher/src/auth/model-credentials/anthropic-api-key.d.ts +154 -0
  30. package/out/tsc/workers-registry/registry-launcher/src/auth/model-credentials/index.d.ts +20 -0
  31. package/out/tsc/workers-registry/registry-launcher/src/auth/model-credentials/model-credentials.test.d.ts +1 -0
  32. package/out/tsc/workers-registry/registry-launcher/src/auth/model-credentials/openai-api-key.d.ts +182 -0
  33. package/out/tsc/workers-registry/registry-launcher/src/auth/model-credentials/types.d.ts +186 -0
  34. package/out/tsc/workers-registry/registry-launcher/src/auth/pkce.d.ts +61 -0
  35. package/out/tsc/workers-registry/registry-launcher/src/auth/pkce.property.test.d.ts +1 -0
  36. package/out/tsc/workers-registry/registry-launcher/src/auth/pkce.test.d.ts +1 -0
  37. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/base-provider.d.ts +138 -0
  38. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/base-provider.test.d.ts +1 -0
  39. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/cognito-provider.d.ts +44 -0
  40. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/concrete-providers.test.d.ts +1 -0
  41. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/entra-provider.d.ts +54 -0
  42. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/github-provider.d.ts +19 -0
  43. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/google-provider.d.ts +19 -0
  44. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/index.d.ts +107 -0
  45. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/index.test.d.ts +1 -0
  46. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/oidc-provider.d.ts +413 -0
  47. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/oidc-provider.property.test.d.ts +1 -0
  48. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/oidc-provider.test.d.ts +1 -0
  49. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/providers.property.test.d.ts +1 -0
  50. package/out/tsc/workers-registry/registry-launcher/src/auth/providers/types.d.ts +28 -0
  51. package/out/tsc/workers-registry/registry-launcher/src/auth/session.d.ts +251 -0
  52. package/out/tsc/workers-registry/registry-launcher/src/auth/session.property.test.d.ts +1 -0
  53. package/out/tsc/workers-registry/registry-launcher/src/auth/session.test.d.ts +1 -0
  54. package/out/tsc/workers-registry/registry-launcher/src/auth/state.d.ts +26 -0
  55. package/out/tsc/workers-registry/registry-launcher/src/auth/state.property.test.d.ts +1 -0
  56. package/out/tsc/workers-registry/registry-launcher/src/auth/state.test.d.ts +1 -0
  57. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/credential-store.d.ts +98 -0
  58. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/credential-store.test.d.ts +1 -0
  59. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/encrypted-file-backend.d.ts +101 -0
  60. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/encrypted-file-backend.test.d.ts +1 -0
  61. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/index.d.ts +12 -0
  62. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/keychain-backend.d.ts +80 -0
  63. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/keychain-backend.test.d.ts +1 -0
  64. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/memory-backend.d.ts +54 -0
  65. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/storage.property.test.d.ts +1 -0
  66. package/out/tsc/workers-registry/registry-launcher/src/auth/storage/types.d.ts +44 -0
  67. package/out/tsc/workers-registry/registry-launcher/src/auth/token-manager.d.ts +171 -0
  68. package/out/tsc/workers-registry/registry-launcher/src/auth/token-manager.property.test.d.ts +1 -0
  69. package/out/tsc/workers-registry/registry-launcher/src/auth/token-manager.test.d.ts +1 -0
  70. package/out/tsc/workers-registry/registry-launcher/src/auth/types.d.ts +369 -0
  71. package/out/tsc/workers-registry/registry-launcher/src/auth/types.test.d.ts +1 -0
  72. package/out/tsc/workers-registry/registry-launcher/src/config/config.property.test.d.ts +1 -0
  73. package/out/tsc/workers-registry/registry-launcher/src/config/config.test.d.ts +1 -0
  74. package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/registry/index.d.ts +51 -2
  75. package/out/tsc/workers-registry/registry-launcher/src/registry/index.property.test.d.ts +1 -0
  76. package/out/tsc/workers-registry/registry-launcher/src/registry/index.test.d.ts +1 -0
  77. package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/registry/types.d.ts +24 -0
  78. package/out/tsc/workers-registry/registry-launcher/src/router/message-router.d.ts +770 -0
  79. package/out/tsc/workers-registry/registry-launcher/src/router/message-router.property.test.d.ts +1 -0
  80. package/out/tsc/workers-registry/registry-launcher/src/router/message-router.test.d.ts +1 -0
  81. package/out/tsc/workers-registry/registry-launcher/src/runtime/manager.property.test.d.ts +1 -0
  82. package/out/tsc/workers-registry/registry-launcher/src/runtime/manager.test.d.ts +1 -0
  83. package/out/tsc/workers-registry/registry-launcher/src/stream/ndjson-handler.property.test.d.ts +1 -0
  84. package/out/tsc/workers-registry/registry-launcher/src/stream/ndjson-handler.test.d.ts +1 -0
  85. package/out/tsc/workers-registry/registry-launcher/tests/e2e/auth-flow.e2e.test.d.ts +1 -0
  86. package/out/tsc/workers-registry/registry-launcher/tests/e2e/auth-required-flow.e2e.test.d.ts +1 -0
  87. package/out/tsc/workers-registry/registry-launcher/tests/e2e/helpers/api-keys.d.ts +32 -0
  88. package/out/tsc/workers-registry/registry-launcher/tests/e2e/helpers/index.d.ts +17 -0
  89. package/out/tsc/workers-registry/registry-launcher/tests/e2e/helpers/launcher-harness.d.ts +101 -0
  90. package/out/tsc/workers-registry/registry-launcher/tests/e2e/helpers/registry-server.d.ts +46 -0
  91. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-agent-auth.e2e.test.d.ts +1 -0
  92. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-api-keys.e2e.test.d.ts +1 -0
  93. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-auth-required.e2e.test.d.ts +1 -0
  94. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-cli.e2e.test.d.ts +1 -0
  95. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-concurrent.e2e.test.d.ts +1 -0
  96. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-lifecycle.e2e.test.d.ts +1 -0
  97. package/out/tsc/workers-registry/registry-launcher/tests/e2e/production-terminal-auth.e2e.test.d.ts +1 -0
  98. package/out/tsc/workers-registry/registry-launcher/tests/integration/agent-auth.integration.test.d.ts +9 -0
  99. package/out/tsc/workers-registry/registry-launcher/tests/integration/registry-launcher.test.d.ts +1 -0
  100. package/out/tsc/workers-registry/registry-launcher/tests/integration/terminal-auth.integration.test.d.ts +12 -0
  101. package/package.json +16 -11
  102. package/out/tsc/workers-registry/acp-worker/src/registry-launcher/router/message-router.d.ts +0 -199
  103. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/config/config.property.test.d.ts → registry-launcher/src/auth/auth-manager.property.test.d.ts} +0 -0
  104. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/config/config.test.d.ts → registry-launcher/src/auth/auth-manager.test.d.ts} +0 -0
  105. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/registry/index.property.test.d.ts → registry-launcher/src/auth/cli/cli.test.d.ts} +0 -0
  106. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/registry/index.test.d.ts → registry-launcher/src/auth/cli/login-command.test.d.ts} +0 -0
  107. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/router/message-router.property.test.d.ts → registry-launcher/src/auth/cli/provider-config.test.d.ts} +0 -0
  108. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/router/message-router.test.d.ts → registry-launcher/src/auth/cli/setup-command.test.d.ts} +0 -0
  109. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/runtime/manager.property.test.d.ts → registry-launcher/src/auth/cli/status-command.test.d.ts} +0 -0
  110. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/runtime/manager.test.d.ts → registry-launcher/src/auth/errors.property.test.d.ts} +0 -0
  111. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/stream/ndjson-handler.property.test.d.ts → registry-launcher/src/auth/errors.test.d.ts} +0 -0
  112. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher/stream/ndjson-handler.test.d.ts → registry-launcher/src/auth/flows/agent-auth-flow.test.d.ts} +0 -0
  113. /package/out/tsc/workers-registry/{acp-worker/tests/integration/registry-launcher.test.d.ts → registry-launcher/src/auth/flows/callback-server.property.test.d.ts} +0 -0
  114. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/config/api-keys.d.ts +0 -0
  115. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/config/config.d.ts +0 -0
  116. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/config/index.d.ts +0 -0
  117. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/config/types.d.ts +0 -0
  118. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/index.d.ts +0 -0
  119. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/log.d.ts +0 -0
  120. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/log.test.d.ts +0 -0
  121. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/registry/resolver.d.ts +0 -0
  122. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/router/index.d.ts +0 -0
  123. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/runtime/agent-runtime.d.ts +0 -0
  124. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/runtime/index.d.ts +0 -0
  125. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/runtime/manager.d.ts +0 -0
  126. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/runtime/types.d.ts +0 -0
  127. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/stream/index.d.ts +0 -0
  128. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/stream/ndjson-handler.d.ts +0 -0
  129. /package/out/tsc/workers-registry/{acp-worker/src/registry-launcher → registry-launcher/src}/test-utils/index.d.ts +0 -0
@@ -1,7 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import{Readable,Writable,Transform}from"node:stream";import{AgentSideConnection,ndJsonStream}from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION}from"@agentclientprotocol/sdk";import{Client}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport}from"@modelcontextprotocol/sdk/client/stdio.js";var defaultFactories={createClient:options=>new Client(options),createTransport:options=>new StdioClientTransport(options)};var MCPManager=class{connections=new Map;toolToServer=new Map;onServerCrash;factories;constructor(factories){this.factories={...defaultFactories,...factories}}setOnServerCrash(callback){this.onServerCrash=callback}async connect(servers){for(const serverConfig of servers){try{const transport=this.factories.createTransport({command:serverConfig.command,args:serverConfig.args,env:serverConfig.env});const client=this.factories.createClient({name:"stdio-bus-worker",version:"1.0.0"});await client.connect(transport);const capabilities=client.getServerCapabilities();const connection2={client,transport,config:serverConfig,connected:true,capabilities};this.connections.set(serverConfig.id,connection2);this.setupCrashDetection(serverConfig.id,client);console.error(`[MCP] Connected to server: ${serverConfig.id}`)}catch(error){console.error(`[MCP] Failed to connect to server ${serverConfig.id}:`,error)}}}setupCrashDetection(serverId,client){client.onclose=()=>{const connection2=this.connections.get(serverId);if(connection2&&connection2.connected){connection2.connected=false;connection2.crashError="Server process exited unexpectedly";for(const[toolName,toolServerId]of this.toolToServer.entries()){if(toolServerId===serverId){this.toolToServer.delete(toolName)}}console.error(`[MCP] Server ${serverId} crashed: ${connection2.crashError}`);if(this.onServerCrash){this.onServerCrash(serverId,connection2.crashError)}}}}async listTools(){const allTools=[];this.toolToServer.clear();for(const[serverId,connection2]of this.connections){if(!connection2.connected){continue}try{let cursor;do{const result=await connection2.client.listTools(cursor?{cursor}:void 0);for(const tool of result.tools){allTools.push({name:tool.name,description:tool.description,inputSchema:tool.inputSchema,serverId});this.toolToServer.set(tool.name,serverId)}cursor=result.nextCursor}while(cursor)}catch(error){console.error(`[MCP] Failed to list tools from server ${serverId}:`,error)}}return allTools}async callTool(name,args,serverId){const targetServerId=serverId??this.toolToServer.get(name);if(!targetServerId){throw new Error(`Tool "${name}" not found. Call listTools() first to discover available tools.`)}const connection2=this.connections.get(targetServerId);if(!connection2){throw new Error(`Server "${targetServerId}" not found.`)}if(!connection2.connected){const crashMessage=connection2.crashError||"Server is not connected";throw new Error(`Server "${targetServerId}" is unavailable: ${crashMessage}`)}try{const result=await connection2.client.callTool({name,arguments:args});const content=result.content.map(item=>{if(item.type==="text"){return{type:"text",text:item.text}}else if(item.type==="image"){return{type:"image",data:item.data,mimeType:item.mimeType}}else if(item.type==="resource"){const resource=item.resource;return{type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:resource.text,blob:resource.blob}}}return{type:"text",text:JSON.stringify(item)}});return{content,isError:result.isError===true}}catch(error){console.error(`[MCP] Failed to call tool "${name}" on server ${targetServerId}:`,error);throw error}}async listResources(){const allResources=[];for(const[serverId,connection2]of this.connections){if(!connection2.connected){continue}try{let cursor;do{const result=await connection2.client.listResources(cursor?{cursor}:void 0);for(const resource of result.resources){allResources.push({uri:resource.uri,name:resource.name,description:resource.description,mimeType:resource.mimeType,serverId})}cursor=result.nextCursor}while(cursor)}catch(error){console.error(`[MCP] Failed to list resources from server ${serverId}:`,error)}}return allResources}async readResource(uri,serverId){let targetServerId=serverId;if(!targetServerId){for(const[,connection3]of this.connections){if(!connection3.connected){continue}try{const result=await connection3.client.readResource({uri});const contents=result.contents.map(item=>{const resourceItem=item;if("text"in resourceItem&&resourceItem.text!==void 0){return{uri:resourceItem.uri,mimeType:resourceItem.mimeType,text:resourceItem.text}}else if("blob"in resourceItem&&resourceItem.blob!==void 0){return{uri:resourceItem.uri,mimeType:resourceItem.mimeType,blob:resourceItem.blob}}return{uri:resourceItem.uri,mimeType:resourceItem.mimeType,text:""}});return{contents}}catch{continue}}throw new Error(`Resource "${uri}" not found on any connected server.`)}const connection2=this.connections.get(targetServerId);if(!connection2){throw new Error(`Server "${targetServerId}" not found.`)}if(!connection2.connected){throw new Error(`Server "${targetServerId}" is not connected.`)}try{const result=await connection2.client.readResource({uri});const contents=result.contents.map(item=>{const resourceItem=item;if("text"in resourceItem&&resourceItem.text!==void 0){return{uri:resourceItem.uri,mimeType:resourceItem.mimeType,text:resourceItem.text}}else if("blob"in resourceItem&&resourceItem.blob!==void 0){return{uri:resourceItem.uri,mimeType:resourceItem.mimeType,blob:resourceItem.blob}}return{uri:resourceItem.uri,mimeType:resourceItem.mimeType,text:""}});return{contents}}catch(error){console.error(`[MCP] Failed to read resource "${uri}" from server ${targetServerId}:`,error);throw error}}getConnection(serverId){return this.connections.get(serverId)}getAllConnections(){return Array.from(this.connections.values()).filter(conn=>conn.connected)}getServerCapabilities(serverId){const connection2=this.connections.get(serverId);return connection2?.connected?connection2.capabilities:void 0}async close(){for(const connection2 of this.connections.values()){try{await connection2.client.close();connection2.connected=false}catch(error){console.error(`[MCP] Error closing connection ${connection2.config.id}:`,error)}}this.connections.clear();this.toolToServer.clear()}abortPendingOperations(){for(const connection2 of this.connections.values()){connection2.connected=false}}isServerCrashed(serverId){const connection2=this.connections.get(serverId);return connection2!==void 0&&!connection2.connected&&connection2.crashError!==void 0}getServerCrashError(serverId){const connection2=this.connections.get(serverId);return connection2?.crashError}getCrashedServers(){const crashed=[];for(const[serverId,connection2]of this.connections){if(!connection2.connected&&connection2.crashError){crashed.push({serverId,error:connection2.crashError})}}return crashed}};var defaultMcpManagerFactory=()=>new MCPManager;var Session=class{id;cwd;mcpManager;cancelled=false;createdAt;history=[];constructor(id,cwd,mcpManagerFactory){this.id=id;this.cwd=cwd;this.mcpManager=(mcpManagerFactory??defaultMcpManagerFactory)();this.createdAt=new Date}isCancelled(){return this.cancelled}cancel(){this.cancelled=true;this.mcpManager.abortPendingOperations()}addHistoryEntry(role,content){this.history.push({role,content,timestamp:new Date})}getHistory(){return[...this.history]}clearHistory(){this.history=[]}getState(){return{id:this.id,cwd:this.cwd,cancelled:this.cancelled,createdAt:this.createdAt,history:[...this.history]}}async close(){await this.mcpManager.close()}};var SessionManager=class{sessions=new Map;mcpManagerFactory;constructor(mcpManagerFactory){this.mcpManagerFactory=mcpManagerFactory}async createSession(cwd,mcpServers){const id=this.generateSessionId();const session=new Session(id,cwd,this.mcpManagerFactory);if(mcpServers&&mcpServers.length>0){await session.mcpManager.connect(mcpServers)}this.sessions.set(id,session);return session}getSession(id){return this.sessions.get(id)}cancelSession(id){const session=this.sessions.get(id);if(session){session.cancel();return true}return false}async closeSession(id){const session=this.sessions.get(id);if(session){await session.close();this.sessions.delete(id);return true}return false}async closeAll(){for(const session of this.sessions.values()){await session.close()}this.sessions.clear()}getAllSessions(){return Array.from(this.sessions.values())}removeSession(id){return this.sessions.delete(id)}generateSessionId(){return crypto.randomUUID()}};var ACPAgent=class{_connection;_sessionManager;_clientCapabilities=null;constructor(connection2){this._connection=connection2;this._sessionManager=new SessionManager}get connection(){return this._connection}get sessionManager(){return this._sessionManager}get clientCapabilities(){return this._clientCapabilities}async initialize(params){this._clientCapabilities=params.clientCapabilities??null;return{protocolVersion:PROTOCOL_VERSION,agentInfo:{name:"stdio-bus-worker",version:"1.0.0"},agentCapabilities:{promptCapabilities:{embeddedContext:true}},authMethods:[]}}async newSession(params){const mcpServers=params.mcpServers?.map(server=>{if("command"in server){return{id:server.name,command:server.command,args:server.args,env:server.env?.reduce((acc,envVar)=>{acc[envVar.name]=envVar.value;return acc},{})}}return null}).filter(s=>s!==null);const session=await this._sessionManager.createSession(params.cwd,mcpServers);return{sessionId:session.id}}async loadSession(_params){return{}}async authenticate(_params){}async prompt(params){const session=this._sessionManager.getSession(params.sessionId);if(!session){throw new Error(`Session not found: ${params.sessionId}`)}if(session.isCancelled()){return{stopReason:"cancelled"}}for(const block of params.prompt){if(session.isCancelled()){return{stopReason:"cancelled"}}if(block.type==="text"){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:block.text}}})}else if(block.type==="resource_link"){const resourceLink=block;try{const result=await session.mcpManager.readResource(resourceLink.uri);if(result.contents.length>0){const content=result.contents[0];if("text"in content){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resource: ${resourceLink.name}]
3
3
  ${content.text}`}}})}else if("blob"in content){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resource: ${resourceLink.name}] (binary data, ${content.blob.length} bytes)`}}})}}}catch{await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resource link: ${resourceLink.name} (${resourceLink.uri})]`}}})}}else if(block.type==="resource"){const resource=block;if(resource.resource.text!==void 0){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Embedded resource: ${resource.resource.uri}]
4
- ${resource.resource.text}`}}})}else if(resource.resource.blob!==void 0){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Embedded resource: ${resource.resource.uri}] (binary data)`}}})}}else if(block.type==="image"){const image=block;await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Image: ${image.mimeType}]`}}})}}if(session.isCancelled()){return{stopReason:"cancelled"}}return{stopReason:"end_turn"}}async cancel(params){this._sessionManager.cancelSession(params.sessionId)}};var SessionIdRouter=class{requestSessionIdMap=new Map;acpSessionIdMap=new Map;processIncomingLine(line){if(!line.trim()){return line}try{const msg=JSON.parse(line);const routingSessionId=this.readSessionId(msg.sessionId);const hasId=msg.id!==void 0&&msg.id!==null;if(hasId&&routingSessionId){this.requestSessionIdMap.set(msg.id,routingSessionId);console.error(`[worker] Saved sessionId="${routingSessionId}" for request id=${msg.id}`)}const paramsSessionId=this.readSessionId(msg.params?.sessionId);if(routingSessionId&&paramsSessionId){this.setAcpSessionMapping(paramsSessionId,routingSessionId,"request")}if(hasId&&routingSessionId){const{sessionId,...msgWithoutSession}=msg;return JSON.stringify(msgWithoutSession)}return line}catch{return line}}processOutgoingLine(line){if(!line.trim()){return line}try{const msg=JSON.parse(line);const hasId=msg.id!==void 0&&msg.id!==null;if(hasId&&this.requestSessionIdMap.has(msg.id)){const routingSessionId=this.requestSessionIdMap.get(msg.id);this.requestSessionIdMap.delete(msg.id);if(routingSessionId){const resultSessionId=this.readSessionId(msg.result?.sessionId);if(resultSessionId){this.setAcpSessionMapping(resultSessionId,routingSessionId,"response")}const msgWithSession={...msg,sessionId:routingSessionId};console.error(`[worker] Restored sessionId="${routingSessionId}" for response id=${msg.id}`);return JSON.stringify(msgWithSession)}}if(!hasId&&!this.readSessionId(msg.sessionId)){const paramsSessionId=this.readSessionId(msg.params?.sessionId);if(paramsSessionId){const routingSessionId=this.acpSessionIdMap.get(paramsSessionId);if(routingSessionId){const msgWithSession={...msg,sessionId:routingSessionId};return JSON.stringify(msgWithSession)}}}return line}catch{return line}}readSessionId(value){return typeof value==="string"&&value.length>0?value:null}setAcpSessionMapping(acpSessionId,routingSessionId,source){const existing=this.acpSessionIdMap.get(acpSessionId);if(existing===routingSessionId){return}this.acpSessionIdMap.set(acpSessionId,routingSessionId);console.error(`[worker] Mapped ACP sessionId="${acpSessionId}" to routing sessionId="${routingSessionId}" (${source})`)}};var PlatformNotSupportedError=class extends Error{constructor(agentId,platform){super(`Platform not supported: ${platform} for agent ${agentId}`);this.agentId=agentId;this.platform=platform;this.name="PlatformNotSupportedError"}};var NoDistributionError=class extends Error{constructor(agentId){super(`No supported distribution type for agent ${agentId}`);this.agentId=agentId;this.name="NoDistributionError"}};function getCurrentPlatform(){const platform=process.platform;const arch=process.arch;if(platform==="darwin"&&arch==="arm64")return"darwin-aarch64";if(platform==="darwin"&&arch==="x64")return"darwin-x86_64";if(platform==="linux"&&arch==="arm64")return"linux-aarch64";if(platform==="linux"&&arch==="x64")return"linux-x86_64";if(platform==="win32"&&arch==="arm64")return"windows-aarch64";if(platform==="win32"&&arch==="x64")return"windows-x86_64";return"linux-x86_64"}function resolveBinary(distribution,agentId){const currentPlatform=getCurrentPlatform();const target=distribution[currentPlatform];if(!target){throw new PlatformNotSupportedError(agentId,currentPlatform)}return{command:target.cmd,args:target.args??[],env:target.env}}function resolveNpx(distribution){return{command:"npx",args:[distribution.package,...distribution.args??[]],env:distribution.env}}function resolveUvx(distribution){return{command:"uvx",args:[distribution.package,...distribution.args??[]],env:distribution.env}}function resolve(distribution,agentId){if(distribution.npx){return resolveNpx(distribution.npx)}if(distribution.uvx){return resolveUvx(distribution.uvx)}if(distribution.binary){return resolveBinary(distribution.binary,agentId)}throw new NoDistributionError(agentId)}import{spawn}from"child_process";var DEFAULT_TERMINATE_TIMEOUT_MS=5e3;var AgentRuntimeImpl=class _AgentRuntimeImpl{agentId;state;process;onExitCallback;constructor(agentId,process2,onExit){this.agentId=agentId;this.process=process2;this.state="starting";this.onExitCallback=onExit;this.setupProcessHandlers()}static spawn(agentId,spawnCommand,onExit){const childProcess=spawn(spawnCommand.command,spawnCommand.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...spawnCommand.env},detached:false});if(childProcess.stdout){childProcess.stdout.setEncoding("utf8")}if(childProcess.stderr){childProcess.stderr.setEncoding("utf8")}return new _AgentRuntimeImpl(agentId,childProcess,onExit)}setupProcessHandlers(){this.process.on("spawn",()=>{if(this.state==="starting"){this.state="running"}});this.process.on("error",error=>{this.state="stopped";process.stderr.write(`[${new Date().toISOString()}] ERROR: Agent ${this.agentId} process error: ${error.message}
5
- `)});this.process.on("exit",(code,signal)=>{this.state="stopped";if(this.onExitCallback){this.onExitCallback(code,signal)}});if(this.process.stdin){this.process.stdin.on("error",error=>{process.stderr.write(`[${new Date().toISOString()}] WARN: Agent ${this.agentId} stdin error: ${error.message}
6
- `)})}}write(message){if(this.state!=="running"&&this.state!=="starting"){return false}if(!this.process.stdin||this.process.stdin.destroyed){return false}try{const ndjsonLine=JSON.stringify(message)+"\n";return this.process.stdin.write(ndjsonLine)}catch{return false}}async terminate(timeout=DEFAULT_TERMINATE_TIMEOUT_MS){if(this.state==="stopped"){return}if(this.state==="stopping"){return this.waitForExit()}this.state="stopping";if(this.process.stdin&&!this.process.stdin.destroyed){this.process.stdin.end()}this.process.kill("SIGTERM");const exitPromise=this.waitForExit();const timeoutPromise=new Promise(resolve2=>{setTimeout(()=>resolve2("timeout"),timeout)});const result=await Promise.race([exitPromise,timeoutPromise]);if(result==="timeout"&&!this.process.killed&&this.process.exitCode===null){this.process.kill("SIGKILL");await this.waitForExit()}}waitForExit(){if(this.state==="stopped"){return Promise.resolve()}return new Promise(resolve2=>{this.process.once("exit",()=>{resolve2()})})}};var DEFAULT_SHUTDOWN_TIMEOUT_MS=5e3;var AgentRuntimeManager=class{runtimes=new Map;exitCallbacks=[];async getOrSpawn(agentId,spawnCommand){const existing=this.runtimes.get(agentId);if(existing&&existing.state!=="stopped"){return existing}const runtime=AgentRuntimeImpl.spawn(agentId,spawnCommand,(code,_signal)=>{this.handleAgentExit(agentId,code)});this.runtimes.set(agentId,runtime);return runtime}get(agentId){return this.runtimes.get(agentId)}async terminate(agentId,timeout=DEFAULT_SHUTDOWN_TIMEOUT_MS){const runtime=this.runtimes.get(agentId);if(!runtime){return}await runtime.terminate(timeout);this.runtimes.delete(agentId)}async terminateAll(timeout=DEFAULT_SHUTDOWN_TIMEOUT_MS){const terminatePromises=[];for(const[agentId,runtime]of this.runtimes){if(runtime.state!=="stopped"){terminatePromises.push(runtime.terminate(timeout).then(()=>{this.runtimes.delete(agentId)}))}}await Promise.all(terminatePromises)}onAgentExit(callback){this.exitCallbacks.push(callback)}handleAgentExit(agentId,code){this.runtimes.delete(agentId);for(const callback of this.exitCallbacks){try{callback(agentId,code)}catch{}}}get size(){return this.runtimes.size}has(agentId){return this.runtimes.has(agentId)}};function logError(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [ERROR] [ndjson] ${message}`)}var NDJSONHandler=class{buffer="";output;messageCallback=null;errorCallback=null;constructor(output){this.output=output}onMessage(callback){this.messageCallback=callback}onError(callback){this.errorCallback=callback}write(message){if(!this.output.writable){return false}try{const json=JSON.stringify(message);this.output.write(json+"\n");return true}catch{return false}}processChunk(chunk){this.buffer+=chunk.toString("utf-8");this.processBuffer()}processBuffer(){let newlineIndex;while((newlineIndex=this.buffer.indexOf("\n"))!==-1){const line=this.buffer.slice(0,newlineIndex);this.buffer=this.buffer.slice(newlineIndex+1);if(line.trim().length===0){continue}this.parseLine(line)}}parseLine(line){try{const message=JSON.parse(line);if(message===null||typeof message!=="object"){const error=new Error("Parsed JSON is not an object");logError(`Malformed NDJSON line (not an object): ${this.truncateLine(line)}`);this.errorCallback?.(error,line);return}this.messageCallback?.(message)}catch(error){logError(`Failed to parse NDJSON line: ${this.truncateLine(line)}`);this.errorCallback?.(error,line)}}truncateLine(line,maxLength=100){if(line.length<=maxLength){return line}return line.slice(0,maxLength)+"..."}};var AgentNotFoundError=class extends Error{constructor(agentId){super(`Agent not found: ${agentId}`);this.agentId=agentId;this.name="AgentNotFoundError"}};function getAgentApiKey(apiKeys,agentId){const keys=apiKeys[agentId];if(!keys||!keys.apiKey||keys.apiKey.length===0){return void 0}return keys.apiKey}var RoutingErrorCodes={MISSING_AGENT_ID:-32600,AGENT_NOT_FOUND:-32001,PLATFORM_NOT_SUPPORTED:-32002,SPAWN_FAILED:-32003};function logError2(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [ERROR] [router] ${message}`)}function logInfo(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [INFO] [router] ${message}`)}function createErrorResponse(id,code,message,data){const response={jsonrpc:"2.0",id,error:{code,message}};if(data!==void 0){response.error.data=data}return response}function extractAgentId(message){const msg=message;const agentId=msg.agentId;if(typeof agentId==="string"&&agentId.length>0){return agentId}return void 0}function extractId(message){const msg=message;const id=msg.id;if(typeof id==="string"||typeof id==="number"){return id}return null}function transformMessage(message){const{agentId:_,...rest}=message;return rest}var MessageRouter=class{registry;runtimeManager;writeCallback;apiKeys;pendingRequests=new Map;authState=new Map;sessionIdMap=new Map;constructor(registry,runtimeManager,writeCallback,apiKeys={}){this.registry=registry;this.runtimeManager=runtimeManager;this.writeCallback=writeCallback;this.apiKeys=apiKeys}injectMcpServers(message,agentId){const agent=this.registry.lookup(agentId);if(!agent?.mcpServers||agent.mcpServers.length===0){return message}const msg=message;const params=msg.params||{};const existingServers=Array.isArray(params.mcpServers)?params.mcpServers:[];const registryServers=agent.mcpServers.map(server=>({name:server.name,command:server.command,args:server.args,env:server.env?Object.entries(server.env).map(([name,value])=>({name,value})):void 0}));const existingNames=new Set(existingServers.filter(s=>s!==null&&typeof s==="object").map(s=>s.name).filter(n=>typeof n==="string"));const mergedServers=[...registryServers.filter(s=>!existingNames.has(s.name)),...existingServers];logInfo(`Injecting ${registryServers.length} MCP servers from registry for agent ${agentId}`);return{...msg,params:{...params,mcpServers:mergedServers}}}async route(message){const id=extractId(message);const agentId=extractAgentId(message);if(agentId===void 0){logError2("Missing agentId in request");return createErrorResponse(id,RoutingErrorCodes.MISSING_AGENT_ID,"Missing agentId")}let spawnCommand;try{spawnCommand=this.registry.resolve(agentId)}catch(error){if(error instanceof AgentNotFoundError){logError2(`Agent not found: ${agentId}`);return createErrorResponse(id,RoutingErrorCodes.AGENT_NOT_FOUND,"Agent not found",{agentId})}if(error instanceof PlatformNotSupportedError){logError2(`Platform not supported for agent: ${agentId}`);return createErrorResponse(id,RoutingErrorCodes.PLATFORM_NOT_SUPPORTED,"Platform not supported",{agentId,platform:error.platform})}throw error}let runtime;try{runtime=await this.runtimeManager.getOrSpawn(agentId,spawnCommand)}catch(error){logError2(`Failed to spawn agent ${agentId}: ${error.message}`);return createErrorResponse(id,RoutingErrorCodes.SPAWN_FAILED,"Agent spawn failed",{agentId,error:error.message})}if(id!==null){const msg2=message;const clientSessionId=typeof msg2.sessionId==="string"?msg2.sessionId:void 0;this.pendingRequests.set(id,{id,agentId,timestamp:Date.now(),clientSessionId})}let transformedMessage=transformMessage(message);const msg=message;if(msg.method==="session/new"){transformedMessage=this.injectMcpServers(transformedMessage,agentId)}const success=runtime.write(transformedMessage);if(!success){logError2(`Failed to write to agent ${agentId}`);if(id!==null){this.pendingRequests.delete(id)}}else{logInfo(`Routed message to agent ${agentId}`)}return void 0}handleAgentResponse(agentId,response){const id=extractId(response);const msg=response;const method=typeof msg.method==="string"?msg.method:void 0;if(id!==null&&method){this.handleAgentRequest(agentId,id,method,msg);return}if(id!==null){const pending=this.pendingRequests.get(id);if(pending&&pending.agentId===agentId){const result=msg.result;if(result&&Array.isArray(result.authMethods)&&result.authMethods.length>0){logInfo(`Agent ${agentId} requires authentication, attempting auto-auth`);this.authState.set(agentId,"pending");void this.attemptAuthentication(agentId,result.authMethods)}if(result&&typeof result.sessionId==="string"){const agentSessionId=result.sessionId;const clientSessionId=pending.clientSessionId;if(clientSessionId){this.sessionIdMap.set(agentSessionId,clientSessionId);logInfo(`Mapped agent sessionId ${agentSessionId} to client sessionId ${clientSessionId}`)}}this.pendingRequests.delete(id)}}if(id===null&&method){logInfo(`Received notification: ${method}`);const params=msg.params;if(params&&typeof params.sessionId==="string"){const agentSessionId=params.sessionId;const clientSessionId=this.sessionIdMap.get(agentSessionId);if(clientSessionId){const enriched={...msg,sessionId:clientSessionId,params:{...params,sessionId:agentSessionId}};logInfo(`Forwarding notification with mapped sessionId: ${clientSessionId}`);this.writeCallback(enriched);return}else{logError2(`Notification with unmapped agentSessionId: ${agentSessionId}, using default sessionId`);const enriched={...msg,sessionId:"global-notifications",params:{...params,sessionId:agentSessionId}};this.writeCallback(enriched);return}}else{const topLevelSessionId=msg.sessionId;if(topLevelSessionId){this.writeCallback(response);return}else{logError2(`Notification without sessionId: ${method}, adding default sessionId for routing`);const enriched={...msg,sessionId:"global-notifications"};this.writeCallback(enriched);return}}}this.writeCallback(response)}handleAgentRequest(agentId,id,method,msg){logInfo(`Agent ${agentId} sent request: ${method} (id=${id}), auto-responding`);let result;if(method==="session/request_permission"){result=this.buildPermissionResponse(msg)}else{logInfo(`Unknown agent request method: ${method}, sending generic success`);result={}}const response={jsonrpc:"2.0",id,result};this.sendToAgent(agentId,response)}buildPermissionResponse(msg){const params=msg.params;const options=params?.options;if(!options||options.length===0){return{optionId:"approved"}}const allowAlways=options.find(o=>o.kind==="allow_always");if(allowAlways&&typeof allowAlways.optionId==="string"){logInfo(`Auto-approving permission with option: ${allowAlways.optionId} (allow_always)`);return{optionId:allowAlways.optionId}}const allowOnce=options.find(o=>o.kind==="allow_once");if(allowOnce&&typeof allowOnce.optionId==="string"){logInfo(`Auto-approving permission with option: ${allowOnce.optionId} (allow_once)`);return{optionId:allowOnce.optionId}}const firstOption=options[0];const optionId=typeof firstOption.optionId==="string"?firstOption.optionId:"approved";logInfo(`Auto-approving permission with fallback option: ${optionId}`);return{optionId}}sendToAgent(agentId,message){let runtime;try{runtime=this.runtimeManager.get(agentId)}catch{logError2(`Failed to get runtime for agent ${agentId} to send response`);return}if(!runtime){logError2(`No runtime found for agent ${agentId}, cannot send response`);return}const success=runtime.write(message);if(!success){logError2(`Failed to write response to agent ${agentId}`)}else{logInfo(`Sent auto-response to agent ${agentId}`)}}async attemptAuthentication(agentId,authMethods){const apiKey=getAgentApiKey(this.apiKeys,agentId);if(!apiKey){logError2(`No API key found for agent ${agentId}, authentication will fail`);this.authState.set(agentId,"none");return}let selectedMethod=authMethods.find(m=>m.id==="openai-api-key");if(!selectedMethod){selectedMethod=authMethods.find(m=>m.id.includes("api-key")||m.id.includes("apikey"))}if(!selectedMethod){selectedMethod=authMethods[0]}logInfo(`Authenticating agent ${agentId} with method: ${selectedMethod.id}`);let runtime;try{const spawnCommand=this.registry.resolve(agentId);runtime=await this.runtimeManager.getOrSpawn(agentId,spawnCommand)}catch(error){logError2(`Failed to get runtime for authentication: ${error.message}`);this.authState.set(agentId,"none");return}const authRequest={jsonrpc:"2.0",id:`auth-${agentId}-${Date.now()}`,method:"authenticate",params:{methodId:selectedMethod.id,credentials:{apiKey}}};const transformed=transformMessage(authRequest);const serialized=JSON.stringify(transformed)+"\n";if(runtime.process.stdin){runtime.process.stdin.write(serialized,error=>{if(error){logError2(`Failed to send authenticate request to ${agentId}: ${error.message}`);this.authState.set(agentId,"none")}else{logInfo(`Sent authenticate request to agent ${agentId}`);this.authState.set(agentId,"authenticated")}})}}get pendingCount(){return this.pendingRequests.size}isPending(id){return this.pendingRequests.has(id)}clearPending(){this.pendingRequests.clear()}};import{readFileSync}from"node:fs";var DEFAULT_CONFIG={registryUrl:"https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",apiKeysPath:"./api-keys.json",shutdownTimeoutSec:5};var ENV_REGISTRY_URL="ACP_REGISTRY_URL";var ENV_API_KEYS_PATH="ACP_API_KEYS_PATH";var ENV_CUSTOM_AGENTS_PATH="ACP_CUSTOM_AGENTS_PATH";function logWarning(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [WARN] [config] ${message}`)}function isNonEmptyString(value){return typeof value==="string"&&value.length>0}function isPositiveNumber(value){return typeof value==="number"&&value>0&&Number.isFinite(value)}function parseConfigObject(obj){const config={...DEFAULT_CONFIG};if(obj===null||typeof obj!=="object"){logWarning("Config file does not contain a valid object, using defaults");return config}const rawConfig=obj;if("registryUrl"in rawConfig){if(isNonEmptyString(rawConfig.registryUrl)){config.registryUrl=rawConfig.registryUrl}else{logWarning('Config field "registryUrl" is not a valid string, using default')}}if("apiKeysPath"in rawConfig){if(isNonEmptyString(rawConfig.apiKeysPath)){config.apiKeysPath=rawConfig.apiKeysPath}else{logWarning('Config field "apiKeysPath" is not a valid string, using default')}}if("shutdownTimeoutSec"in rawConfig){if(isPositiveNumber(rawConfig.shutdownTimeoutSec)){config.shutdownTimeoutSec=rawConfig.shutdownTimeoutSec}else{logWarning('Config field "shutdownTimeoutSec" is not a valid positive number, using default')}}if("customAgentsPath"in rawConfig){if(isNonEmptyString(rawConfig.customAgentsPath)){config.customAgentsPath=rawConfig.customAgentsPath}else{logWarning('Config field "customAgentsPath" is not a valid string, ignoring')}}return config}function applyEnvironmentOverrides(config){const envRegistryUrl=process.env[ENV_REGISTRY_URL];const envApiKeysPath=process.env[ENV_API_KEYS_PATH];const envCustomAgentsPath=process.env[ENV_CUSTOM_AGENTS_PATH];const overrides={};if(isNonEmptyString(envRegistryUrl)){overrides.registryUrl=envRegistryUrl}if(isNonEmptyString(envApiKeysPath)){overrides.apiKeysPath=envApiKeysPath}if(isNonEmptyString(envCustomAgentsPath)){overrides.customAgentsPath=envCustomAgentsPath}return{...config,...overrides}}function loadConfig(configPath){let config={...DEFAULT_CONFIG};if(configPath){try{const fileContent=readFileSync(configPath,"utf-8");const parsed=JSON.parse(fileContent);config=parseConfigObject(parsed)}catch(error){if(error instanceof SyntaxError){logWarning(`Config file "${configPath}" contains malformed JSON, using defaults`)}else if(error.code==="ENOENT"){logWarning(`Config file "${configPath}" not found, using defaults`)}else if(error.code==="EACCES"){logWarning(`Config file "${configPath}" is not readable, using defaults`)}else{logWarning(`Failed to read config file "${configPath}": ${error.message}, using defaults`)}}}config=applyEnvironmentOverrides(config);return config}function canReadFile(capabilities){return capabilities?.fs?.readTextFile===true}function canWriteFile(capabilities){return capabilities?.fs?.writeTextFile===true}function canUseTerminal(capabilities){return capabilities?.terminal===true}async function readFile(connection2,sessionId,path,options){try{const response=await connection2.readTextFile({sessionId,path,line:options?.line,limit:options?.limit});return{content:response.content,success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to read file "${path}":`,error);return{content:"",success:false,error:errorMessage}}}async function writeFile(connection2,sessionId,path,content){try{await connection2.writeTextFile({sessionId,path,content});return{success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to write file "${path}":`,error);return{success:false,error:errorMessage}}}async function executeCommand(connection2,sessionId,command,options){let terminal=null;try{terminal=await connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit});let timeoutId=null;let timedOut=false;if(options?.timeout&&options.timeout>0){timeoutId=setTimeout(async()=>{timedOut=true;if(terminal){try{await terminal.kill()}catch{}}},options.timeout)}try{const exitResult=await terminal.waitForExit();if(timeoutId){clearTimeout(timeoutId)}const outputResult=await terminal.currentOutput();return{output:outputResult.output,exitCode:timedOut?null:exitResult.exitCode??null,signal:timedOut?"SIGTERM":exitResult.signal??null,truncated:outputResult.truncated,success:!timedOut&&exitResult.exitCode===0,error:timedOut?"Command timed out":void 0}}finally{if(timeoutId){clearTimeout(timeoutId)}}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to execute command "${command}":`,error);return{output:"",exitCode:null,signal:null,truncated:false,success:false,error:errorMessage}}finally{if(terminal){try{await terminal.release()}catch{}}}}async function startCommand(connection2,sessionId,command,options){return connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit})}function mapMCPContentToACPContentBlock(mcpContent){switch(mcpContent.type){case"text":return mapTextContent(mcpContent);case"image":return mapImageContent(mcpContent);case"resource":return mapEmbeddedResource(mcpContent);default:return{type:"text",text:JSON.stringify(mcpContent)}}}function mapTextContent(mcpText){const result={type:"text",text:mcpText.text};return result}function mapImageContent(mcpImage){const result={type:"image",data:mcpImage.data,mimeType:mcpImage.mimeType};return result}function mapEmbeddedResource(mcpResource){const{resource}=mcpResource;if(resource.text!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:resource.text}};return result}else if(resource.blob!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,blob:resource.blob}};return result}else{const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:""}};return result}}function mapMCPResultToACPToolCallContent(mcpContents){return mcpContents.map(mcpContent=>{const contentBlock=mapMCPContentToACPContentBlock(mcpContent);return{type:"content",content:contentBlock}})}function createErrorToolCallContent(errorMessage){return[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}]}function mapToolResultToACPContent(content,isError=false){if(isError&&content.length>0){const errorText=content.filter(c=>c.type==="text").map(c=>c.text).join("\n");if(errorText){return createErrorToolCallContent(errorText)}}return mapMCPResultToACPToolCallContent(content)}function isResourceLink(block){return block.type==="resource_link"&&"uri"in block}function mapMCPResourceContentsToACPContentBlock(contents){if("text"in contents){const result2={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,text:contents.text}};return result2}const result={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,blob:contents.blob}};return result}function extractResourceLinkUri(block){if(isResourceLink(block)){return block.uri}return null}var toolCallCounter=0;function generateToolCallId(){toolCallCounter++;return`tool-${Date.now()}-${toolCallCounter}`}function determineToolKind(toolName,description){const name=toolName.toLowerCase();const desc=(description||"").toLowerCase();if(desc.includes("external")||desc.includes("api")||desc.includes("http")){return"fetch"}if(name.includes("read")||name.includes("get")||name.includes("list")||name.includes("fetch")){return"read"}if(name.includes("write")||name.includes("edit")||name.includes("update")||name.includes("modify")){return"edit"}if(name.includes("delete")||name.includes("remove")){return"delete"}if(name.includes("move")||name.includes("rename")){return"move"}if(name.includes("search")||name.includes("find")||name.includes("query")){return"search"}if(name.includes("exec")||name.includes("run")||name.includes("shell")||name.includes("command")){return"execute"}if(name.includes("http")||name.includes("api")||name.includes("request")){return"fetch"}return"other"}async function sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind="other",status="pending"){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call",toolCallId,title,kind,status}})}async function sendToolCallUpdate(connection2,sessionId,toolCallId,status,content,title){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call_update",toolCallId,status,content,title}})}async function requestToolPermission(connection2,sessionId,toolCallId,title,kind="other",options){const permissionOptions=options??[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Allow always",kind:"allow_always"},{optionId:"reject_once",name:"Reject",kind:"reject_once"}];const toolCall={toolCallId,title,kind,status:"pending"};try{const response=await connection2.requestPermission({sessionId,toolCall,options:permissionOptions});if(response.outcome.outcome==="cancelled"){return{granted:false,cancelled:true}}if(response.outcome.outcome==="selected"){const selectedOption=response.outcome.optionId;const isAllowed=selectedOption.startsWith("allow");return{granted:isAllowed,optionId:selectedOption,cancelled:false}}return{granted:false,cancelled:false}}catch(error){console.error("[ACP] Permission request failed:",error);return{granted:false,cancelled:true}}}async function executeToolCall(connection2,sessionId,mcpManager,toolName,args,description){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return content}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return errorContent}}async function executeToolCallWithPermission(connection2,sessionId,mcpManager,toolName,args,description,requirePermission=true){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");if(requirePermission){const permissionResult=await requestToolPermission(connection2,sessionId,toolCallId,title,kind);if(!permissionResult.granted){const status=permissionResult.cancelled?"failed":"failed";const message=permissionResult.cancelled?"Permission request cancelled":"Permission denied";const errorContent=[{type:"content",content:{type:"text",text:message}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,status,errorContent);return{content:errorContent,permissionResult}}}await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return{content}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return{content:errorContent}}}console.error("[worker] Starting ACP/MCP Protocol Worker...");var sessionIdRouter=new SessionIdRouter;var stdinTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processIncomingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});var stdoutTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processOutgoingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});process.stdin.pipe(stdinTransform);var inputStream=Readable.toWeb(stdinTransform);var outputStream=Writable.toWeb(stdoutTransform);stdoutTransform.pipe(process.stdout);var stream=ndJsonStream(outputStream,inputStream);var connection=new AgentSideConnection(conn=>new ACPAgent(conn),stream);console.error("[worker] AgentSideConnection established, ready for messages");process.on("SIGTERM",async()=>{console.error("[worker] Received SIGTERM, shutting down...");await connection.closed;process.exit(0)});process.on("SIGINT",async()=>{console.error("[worker] Received SIGINT, shutting down...");await connection.closed;process.exit(0)});process.on("uncaughtException",error=>{console.error("[worker] Uncaught exception:",error);process.exit(1)});process.on("unhandledRejection",(reason,promise)=>{console.error("[worker] Unhandled rejection at:",promise,"reason:",reason)});connection.closed.then(()=>{console.error("[worker] Connection closed");process.exit(0)}).catch(error=>{console.error("[worker] Connection error:",error);process.exit(1)});export{ACPAgent,AgentRuntimeImpl,AgentRuntimeManager,MCPManager,MessageRouter,NDJSONHandler,NoDistributionError,PlatformNotSupportedError,RoutingErrorCodes,canReadFile,canUseTerminal,canWriteFile,createErrorResponse,createErrorToolCallContent,determineToolKind,executeCommand,executeToolCall,executeToolCallWithPermission,extractAgentId,extractId,extractResourceLinkUri,generateToolCallId,getCurrentPlatform,isResourceLink,loadConfig,mapMCPContentToACPContentBlock,mapMCPResourceContentsToACPContentBlock,mapMCPResultToACPToolCallContent,mapToolResultToACPContent,readFile,requestToolPermission,resolve,resolveBinary,resolveNpx,resolveUvx,sendToolCallInitiation,sendToolCallUpdate,startCommand,transformMessage,writeFile};
4
+ ${resource.resource.text}`}}})}else if(resource.resource.blob!==void 0){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Embedded resource: ${resource.resource.uri}] (binary data)`}}})}}else if(block.type==="image"){const image=block;await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Image: ${image.mimeType}]`}}})}}if(session.isCancelled()){return{stopReason:"cancelled"}}return{stopReason:"end_turn"}}async cancel(params){this._sessionManager.cancelSession(params.sessionId)}};var SessionIdRouter=class{requestSessionIdMap=new Map;acpSessionIdMap=new Map;processIncomingLine(line){if(!line.trim()){return line}try{const msg=JSON.parse(line);const routingSessionId=this.readSessionId(msg.sessionId);const hasId=msg.id!==void 0&&msg.id!==null;if(hasId&&routingSessionId){this.requestSessionIdMap.set(msg.id,routingSessionId);console.error(`[worker] Saved sessionId="${routingSessionId}" for request id=${msg.id}`)}const paramsSessionId=this.readSessionId(msg.params?.sessionId);if(routingSessionId&&paramsSessionId){this.setAcpSessionMapping(paramsSessionId,routingSessionId,"request")}if(hasId&&routingSessionId){const{sessionId,...msgWithoutSession}=msg;return JSON.stringify(msgWithoutSession)}return line}catch{return line}}processOutgoingLine(line){if(!line.trim()){return line}try{const msg=JSON.parse(line);const hasId=msg.id!==void 0&&msg.id!==null;if(hasId&&this.requestSessionIdMap.has(msg.id)){const routingSessionId=this.requestSessionIdMap.get(msg.id);this.requestSessionIdMap.delete(msg.id);if(routingSessionId){const resultSessionId=this.readSessionId(msg.result?.sessionId);if(resultSessionId){this.setAcpSessionMapping(resultSessionId,routingSessionId,"response")}const msgWithSession={...msg,sessionId:routingSessionId};console.error(`[worker] Restored sessionId="${routingSessionId}" for response id=${msg.id}`);return JSON.stringify(msgWithSession)}}if(!hasId&&!this.readSessionId(msg.sessionId)){const paramsSessionId=this.readSessionId(msg.params?.sessionId);if(paramsSessionId){const routingSessionId=this.acpSessionIdMap.get(paramsSessionId);if(routingSessionId){const msgWithSession={...msg,sessionId:routingSessionId};return JSON.stringify(msgWithSession)}}}return line}catch{return line}}readSessionId(value){return typeof value==="string"&&value.length>0?value:null}setAcpSessionMapping(acpSessionId,routingSessionId,source){const existing=this.acpSessionIdMap.get(acpSessionId);if(existing===routingSessionId){return}this.acpSessionIdMap.set(acpSessionId,routingSessionId);console.error(`[worker] Mapped ACP sessionId="${acpSessionId}" to routing sessionId="${routingSessionId}" (${source})`)}};function canReadFile(capabilities){return capabilities?.fs?.readTextFile===true}function canWriteFile(capabilities){return capabilities?.fs?.writeTextFile===true}function canUseTerminal(capabilities){return capabilities?.terminal===true}async function readFile(connection2,sessionId,path,options){try{const response=await connection2.readTextFile({sessionId,path,line:options?.line,limit:options?.limit});return{content:response.content,success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to read file "${path}":`,error);return{content:"",success:false,error:errorMessage}}}async function writeFile(connection2,sessionId,path,content){try{await connection2.writeTextFile({sessionId,path,content});return{success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to write file "${path}":`,error);return{success:false,error:errorMessage}}}async function executeCommand(connection2,sessionId,command,options){let terminal=null;try{terminal=await connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit});let timeoutId=null;let timedOut=false;if(options?.timeout&&options.timeout>0){timeoutId=setTimeout(async()=>{timedOut=true;if(terminal){try{await terminal.kill()}catch{}}},options.timeout)}try{const exitResult=await terminal.waitForExit();if(timeoutId){clearTimeout(timeoutId)}const outputResult=await terminal.currentOutput();return{output:outputResult.output,exitCode:timedOut?null:exitResult.exitCode??null,signal:timedOut?"SIGTERM":exitResult.signal??null,truncated:outputResult.truncated,success:!timedOut&&exitResult.exitCode===0,error:timedOut?"Command timed out":void 0}}finally{if(timeoutId){clearTimeout(timeoutId)}}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to execute command "${command}":`,error);return{output:"",exitCode:null,signal:null,truncated:false,success:false,error:errorMessage}}finally{if(terminal){try{await terminal.release()}catch{}}}}async function startCommand(connection2,sessionId,command,options){return connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit})}function mapMCPContentToACPContentBlock(mcpContent){switch(mcpContent.type){case"text":return mapTextContent(mcpContent);case"image":return mapImageContent(mcpContent);case"resource":return mapEmbeddedResource(mcpContent);default:return{type:"text",text:JSON.stringify(mcpContent)}}}function mapTextContent(mcpText){const result={type:"text",text:mcpText.text};return result}function mapImageContent(mcpImage){const result={type:"image",data:mcpImage.data,mimeType:mcpImage.mimeType};return result}function mapEmbeddedResource(mcpResource){const{resource}=mcpResource;if(resource.text!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:resource.text}};return result}else if(resource.blob!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,blob:resource.blob}};return result}else{const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:""}};return result}}function mapMCPResultToACPToolCallContent(mcpContents){return mcpContents.map(mcpContent=>{const contentBlock=mapMCPContentToACPContentBlock(mcpContent);return{type:"content",content:contentBlock}})}function createErrorToolCallContent(errorMessage){return[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}]}function mapToolResultToACPContent(content,isError=false){if(isError&&content.length>0){const errorText=content.filter(c=>c.type==="text").map(c=>c.text).join("\n");if(errorText){return createErrorToolCallContent(errorText)}}return mapMCPResultToACPToolCallContent(content)}function isResourceLink(block){return block.type==="resource_link"&&"uri"in block}function mapMCPResourceContentsToACPContentBlock(contents){if("text"in contents){const result2={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,text:contents.text}};return result2}const result={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,blob:contents.blob}};return result}function extractResourceLinkUri(block){if(isResourceLink(block)){return block.uri}return null}var toolCallCounter=0;function generateToolCallId(){toolCallCounter++;return`tool-${Date.now()}-${toolCallCounter}`}function determineToolKind(toolName,description){const name=toolName.toLowerCase();const desc=(description||"").toLowerCase();if(desc.includes("external")||desc.includes("api")||desc.includes("http")){return"fetch"}if(name.includes("read")||name.includes("get")||name.includes("list")||name.includes("fetch")){return"read"}if(name.includes("write")||name.includes("edit")||name.includes("update")||name.includes("modify")){return"edit"}if(name.includes("delete")||name.includes("remove")){return"delete"}if(name.includes("move")||name.includes("rename")){return"move"}if(name.includes("search")||name.includes("find")||name.includes("query")){return"search"}if(name.includes("exec")||name.includes("run")||name.includes("shell")||name.includes("command")){return"execute"}if(name.includes("http")||name.includes("api")||name.includes("request")){return"fetch"}return"other"}async function sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind="other",status="pending"){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call",toolCallId,title,kind,status}})}async function sendToolCallUpdate(connection2,sessionId,toolCallId,status,content,title){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call_update",toolCallId,status,content,title}})}async function requestToolPermission(connection2,sessionId,toolCallId,title,kind="other",options){const permissionOptions=options??[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Allow always",kind:"allow_always"},{optionId:"reject_once",name:"Reject",kind:"reject_once"}];const toolCall={toolCallId,title,kind,status:"pending"};try{const response=await connection2.requestPermission({sessionId,toolCall,options:permissionOptions});if(response.outcome.outcome==="cancelled"){return{granted:false,cancelled:true}}if(response.outcome.outcome==="selected"){const selectedOption=response.outcome.optionId;const isAllowed=selectedOption.startsWith("allow");return{granted:isAllowed,optionId:selectedOption,cancelled:false}}return{granted:false,cancelled:false}}catch(error){console.error("[ACP] Permission request failed:",error);return{granted:false,cancelled:true}}}async function executeToolCall(connection2,sessionId,mcpManager,toolName,args,description){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return content}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return errorContent}}async function executeToolCallWithPermission(connection2,sessionId,mcpManager,toolName,args,description,requirePermission=true){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");if(requirePermission){const permissionResult=await requestToolPermission(connection2,sessionId,toolCallId,title,kind);if(!permissionResult.granted){const status=permissionResult.cancelled?"failed":"failed";const message=permissionResult.cancelled?"Permission request cancelled":"Permission denied";const errorContent=[{type:"content",content:{type:"text",text:message}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,status,errorContent);return{content:errorContent,permissionResult}}}await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return{content}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return{content:errorContent}}}console.error("[worker] Starting ACP/MCP Protocol Worker...");var sessionIdRouter=new SessionIdRouter;var stdinTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processIncomingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});var stdoutTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processOutgoingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});process.stdin.pipe(stdinTransform);var inputStream=Readable.toWeb(stdinTransform);var outputStream=Writable.toWeb(stdoutTransform);stdoutTransform.pipe(process.stdout);var stream=ndJsonStream(outputStream,inputStream);var connection=new AgentSideConnection(conn=>new ACPAgent(conn),stream);console.error("[worker] AgentSideConnection established, ready for messages");process.on("SIGTERM",async()=>{console.error("[worker] Received SIGTERM, shutting down...");await connection.closed;process.exit(0)});process.on("SIGINT",async()=>{console.error("[worker] Received SIGINT, shutting down...");await connection.closed;process.exit(0)});process.on("uncaughtException",error=>{console.error("[worker] Uncaught exception:",error);process.exit(1)});process.on("unhandledRejection",(reason,promise)=>{console.error("[worker] Unhandled rejection at:",promise,"reason:",reason)});connection.closed.then(()=>{console.error("[worker] Connection closed");process.exit(0)}).catch(error=>{console.error("[worker] Connection error:",error);process.exit(1)});export{ACPAgent,MCPManager,canReadFile,canUseTerminal,canWriteFile,createErrorToolCallContent,determineToolKind,executeCommand,executeToolCall,executeToolCallWithPermission,extractResourceLinkUri,generateToolCallId,isResourceLink,mapMCPContentToACPContentBlock,mapMCPResourceContentsToACPContentBlock,mapMCPResultToACPToolCallContent,mapToolResultToACPContent,readFile,requestToolPermission,sendToolCallInitiation,sendToolCallUpdate,startCommand,writeFile};
7
5
  //# sourceMappingURL=index.js.map