@easbot/acp 0.3.36 → 0.3.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +1 -1
- package/README.md +55 -5
- package/dist/chunks/{bootstrap-67LTURXQ.cjs → bootstrap-PMTU6E7V.cjs} +1 -1
- package/dist/chunks/bootstrap-QDEKTZBM.mjs +1 -0
- package/dist/chunks/{chunk-SWK2ITXO.mjs → chunk-233AKRGW.mjs} +10 -10
- package/dist/chunks/chunk-6LGQ6YHX.cjs +8 -0
- package/dist/chunks/chunk-KAXUGIGH.mjs +8 -0
- package/dist/chunks/{chunk-PCEPFPJO.cjs → chunk-LBGDEQBN.cjs} +11 -11
- package/dist/chunks/{chunk-DX35VSAT.cjs → chunk-RGGMCKYA.cjs} +1 -1
- package/dist/chunks/{chunk-33M2R2US.mjs → chunk-WFIRDYOS.mjs} +1 -1
- package/dist/chunks/cli-handler-MSHURK4A.mjs +1 -0
- package/dist/chunks/cli-handler-QMVTXDVB.cjs +1 -0
- package/dist/chunks/{types-BZWPIPG6.mjs → types-GMPQJ4DC.mjs} +1 -1
- package/dist/chunks/types-MQMNYZEY.cjs +1 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +29 -60
- package/dist/index.d.ts +29 -60
- package/dist/index.mjs +1 -1
- package/package.json +6 -6
- package/dist/chunks/bootstrap-DHON75MT.mjs +0 -1
- package/dist/chunks/chunk-FDMRPUSH.mjs +0 -8
- package/dist/chunks/chunk-IOEQ7YHD.cjs +0 -8
- package/dist/chunks/cli-handler-IU5ATLSM.cjs +0 -1
- package/dist/chunks/cli-handler-VKJJ4B6G.mjs +0 -1
- package/dist/chunks/types-NFMF7IZL.cjs +0 -1
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkSNWAB3QJ_cjs=require('./chunk-SNWAB3QJ.cjs'),chunkOQH5ALTQ_cjs=require('./chunk-OQH5ALTQ.cjs'),chunk6VF3MZ6H_cjs=require('./chunk-6VF3MZ6H.cjs'),chunk663BEBE4_cjs=require('./chunk-663BEBE4.cjs'),chunkDX35VSAT_cjs=require('./chunk-DX35VSAT.cjs'),chunkISDIC2R6_cjs=require('./chunk-ISDIC2R6.cjs'),utils=require('@easbot/utils'),fs=require('fs'),ut=require('path'),url=require('url'),diff=require('diff'),types=require('@easbot/types'),crypto=require('crypto'),sdk=require('@agentclientprotocol/sdk'),ws=require('ws');require('@easbot/sdk');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ut__default=/*#__PURE__*/_interopDefault(ut);var E=utils.Log.create({service:"acp.event.bridge"}),j=class{constructor(e,t){chunkISDIC2R6_cjs.a(this,"sdk");chunkISDIC2R6_cjs.a(this,"connection");chunkISDIC2R6_cjs.a(this,"abortController",null);chunkISDIC2R6_cjs.a(this,"started",false);chunkISDIC2R6_cjs.a(this,"permissionQueues",new Map);chunkISDIC2R6_cjs.a(this,"_messageMetaCache",new Map);chunkISDIC2R6_cjs.a(this,"permissionOptions",[{optionId:"once",kind:"allow_once",name:"Allow once"},{optionId:"always",kind:"allow_always",name:"Always allow"},{optionId:"reject",kind:"reject_once",name:"Reject"}]);chunkISDIC2R6_cjs.a(this,"acpService");chunkISDIC2R6_cjs.a(this,"_cachedPrimaryAgents",null);this.sdk=e,this.connection=t;}setService(e){this.acpService=e;}async start(){if(this.started){E.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,E.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||E.error("event subscription failed",{error:utils.errorMeta(e)});});}async stop(){this.started&&(E.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.permissionQueues.clear(),this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,E.info("ACP event bridge stopped"));}async runEventSubscription(){let e=this.abortController;if(e)for(;;){if(e.signal.aborted)return;let t=await this.sdk.global.event({signal:e.signal});for await(let n of t.stream){if(e.signal.aborted)return;let r=n?.payload;r&&await this.handleEvent(r).catch(o=>{E.error("failed to handle event",{error:utils.errorMeta(o),type:r.type});});}if(e.signal.aborted)return}}async handleEvent(e){switch(e.type){case "permission.asked":await this.handlePermissionAsked(e.properties);break;case "question.asked":await this.handleQuestionAsked(e.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(e.properties);break;case "session.status":await this.handleSessionStatus(e.properties);break;case "session.deleted":{let n=e.properties.info?.id??"";await this.handleSessionDeleted({sessionId:n});break}}}async handleSessionStatus(e){let{sessionId:t,status:n}=e;if(!this.connection){E.warn("No connection available to publish session status");return}try{await this.connection.extNotification("session_status_update",{sessionId:t,status:n});}catch(r){E.error("Failed to publish session status via extNotification",{sessionId:t,status:n,error:utils.errorMeta(r)});}n.type==="idle"&&(this.permissionQueues.delete(t),this.clearMessageMetaCache(t));}async handleSessionDeleted(e){let{sessionId:t}=e;if(!this.connection){E.warn("No connection available to notify session deletion");return}if(typeof t!="string"||t.length===0){E.debug("handleSessionDeleted: skipping, sessionId is missing or invalid",{sessionId:t});return}this.permissionQueues.delete(t),this.clearMessageMetaCache(t);try{await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"[System] Session has been deleted by the backend. This session is no longer available."}}});}catch(n){E.error("Failed to notify session deletion to client",{sessionId:t,error:utils.errorMeta(n)});}}async handlePermissionAsked(e){let{id:t,sessionId:n,permission:r,tool:o,metadata:d}=e,l=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let h=r==="external_directory"&&d?.tool?ve(d.tool):ve(r),b=r==="external_directory"&&d?.tool?Ce(d.tool,d):Ce(r,d),I=await this.connection.requestPermission({sessionId:n,toolCall:{callId:o?.callId??t,status:"pending",title:r,rawInput:d,kind:h,locations:(b??[]).map(C=>C.path)},options:this.permissionOptions}).catch(async C=>{E.error("failed to request permission from ACP",{error:utils.errorMeta(C),permissionId:t,sessionId:n}),await this.sdk.permission.reply({requestId:t,reply:"reject"});});if(I){if(I.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestId:t,reply:"reject"});return}if(I.outcome.optionId!=="reject"&&r==="edit"){let C=d?.filepath??d?.filePath??"",x=d?.diff??"";if(C&&x){let y=utils.PKG.file(C),c=await y.exists()?await y.text():"",i=gt(c,x);i&&await this.connection.extMethod("client.writeTextFile",{sessionId:n,path:C,content:i});}}await this.sdk.permission.reply({requestId:t,reply:I.outcome.optionId});}}).catch(h=>{E.error("failed to handle permission",{error:utils.errorMeta(h),permissionId:t});}).finally(()=>{this.permissionQueues.get(n)===l&&this.permissionQueues.delete(n);});this.permissionQueues.set(n,l);}async handleQuestionAsked(e){let{id:t,sessionId:n,questions:r}=e;E.debug("Handling question asked in ACP bridge",{requestId:t,sessionId:n,questionCount:r.length});try{let o=await this.connection.extMethod("client.requestQuestion",{sessionId:n,requestId:t,questions:r});if(!o){E.warn("Question request returned no result"),await this.sdk.question.reject({requestId:t});return}o.outcome==="selected"&&o.answers&&o.answers.length>0?await this.sdk.question.reply({requestId:t,answers:o.answers.map(d=>[d.answer])}):await this.sdk.question.reject({requestId:t});}catch(o){E.error("Failed to handle question via extMethod",{error:utils.errorMeta(o),requestId:t,sessionId:n}),await this.sdk.question.reject({requestId:t});}}async handleMessagePartUpdated(e){let{part:t}=e,n=await this.getMessageMeta(t.sessionId,t.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(t.type==="tool"?await this.handleToolPart(t):t.type==="text"?await this.handleTextPart(t,e.delta):t.type==="reasoning"?await this.handleReasoningPart(t,e.delta):t.type==="step-finish"&&await this.handleStepFinishPart(t)));}async handleToolPart(e){let{sessionId:t,callId:n,tool:r,state:o,messageId:d}=e;if(!t){E.debug("AcpEventBridge: skipping tool part without sessionId",{callId:n,tool:r,messageId:d});return}let p=ve(r);switch(o.status){case "pending":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:r,kind:p,status:"pending",locations:[],rawInput:{},_meta:{messageId:d}}}).catch(l=>{E.error("failed to send tool pending to ACP",{error:utils.errorMeta(l)});});return;case "in_progress":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"in_progress",kind:p,title:r,locations:Ce(r,o.input),rawInput:o.input,_meta:{messageId:d}}}).catch(l=>{E.error("failed to send tool in_progress to ACP",{error:utils.errorMeta(l)});});return;case "completed":{let l=[{type:"content",content:{type:"text",text:o.output}}];if(p==="edit"){let h=o.input,b=h.filePath??h.filepath??"",I=h.oldString??"",C=h.newString??h.content??"";l.push({type:"diff",path:b,oldText:I,newText:C});}if(r==="todo"){let h=types.TodoListSchema.safeParse(JSON.parse(o.output));h.success&&o.input.operation==="write"&&await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:h.data.map(b=>{let I=b.status==="cancelled"?"completed":b.status;return {priority:b.priority,status:I,content:b.content}})}}).catch(b=>{E.error("failed to send session update for todo",{error:utils.errorMeta(b)});});}await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:p,content:l,title:o.title??r,rawInput:o.input,rawOutput:{output:o.output,metadata:o.metadata},_meta:{messageId:d}}}).catch(h=>{E.error("failed to send tool completed to ACP",{error:utils.errorMeta(h)});});return}case "failed":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:p,title:r,rawInput:o.input,content:[{type:"content",content:{type:"text",text:o.error}}],rawOutput:{error:o.error},_meta:{messageId:d}}}).catch(l=>{E.error("failed to send tool error to ACP",{error:utils.errorMeta(l)});});return}}async handleTextPart(e,t){if(e.ignored===true)return;if(!e.sessionId){E.debug("AcpEventBridge: skipping text part without sessionId",{messageId:e.messageId});return}if(!("time"in e&&e.time&&typeof e.time=="object"&&"end"in e.time&&!!e.time.end))return;let r=e.text;r&&await this.connection.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_message_chunk",messageId:e.messageId,content:{type:"text",text:r}}}).catch(o=>{E.error("failed to send text to ACP",{error:utils.errorMeta(o)});});}async handleReasoningPart(e,t){if(!e.sessionId){E.debug("AcpEventBridge: skipping reasoning part without sessionId",{messageId:e.messageId});return}if(!("time"in e&&e.time&&typeof e.time=="object"&&"end"in e.time&&!!e.time.end))return;let r=e.text;r&&await this.connection.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_thought_chunk",messageId:e.messageId,content:{type:"text",text:r}}}).catch(o=>{E.error("failed to send reasoning to ACP",{error:utils.errorMeta(o)});});}async handleStepFinishPart(e){let{sessionId:t,messageId:n,tokens:r}=e;if(!this.connection)return;if(!t){E.debug("AcpEventBridge: skipping step-finish part without sessionId",{messageId:n});return}let o=(r?.input??0)+(r?.reasoning??0),d=await this.getContextLimit(t,n);await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:o,size:d,_meta:{messageId:n}}}).catch(p=>{E.error("failed to send usage_update for step-finish",{error:utils.errorMeta(p)});});}async getContextLimit(e,t){try{let r=(await this.sdk.session.messages({sessionId:e}).then(o=>o.data).catch(()=>{}))?.find(o=>o.info.id===t);if(r){let o=r.info;if(o.providerId&&o.modelId)return (await this.sdk.config.providers({}).then(h=>h.data?.providers??[]).catch(()=>[])).find(h=>h.id===o.providerId)?.models[o.modelId]?.limit?.context??2e5}}catch(n){E.errorDegradable("failed to get context limit",{error:utils.errorMeta(n)});}return 2e5}async getMessageMeta(e,t){let n=`${e}:${t}`,r=this._messageMetaCache.get(n);if(r)return r;let o=await this.sdk.session.message({sessionId:e,messageId:t},{throwOnError:true}).then(p=>p.data).catch(p=>{p instanceof Error&&p.name!=="NotFoundError"&&E.error("unexpected error when fetching message",{error:utils.errorMeta(p),sessionId:e,messageId:t});});if(!o)return;let d={role:o.info.role,agent:o.info.agent};return this._messageMetaCache.set(n,d),d}clearMessageMetaCache(e){let t=`${e}:`;for(let n of this._messageMetaCache.keys())n.startsWith(t)&&this._messageMetaCache.delete(n);}async shouldFilterAgent(e){if(!this._cachedPrimaryAgents)try{let n=(await this.sdk.agent.list({})).data||[];this._cachedPrimaryAgents=new Set(n.filter(r=>r.mode==="primary"&&r.hidden!==!0).map(r=>r.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(e)}};function ve(s){switch(s.toLowerCase()){case "bash":return "execute";case "webfetch":return "fetch";case "edit":case "patch":case "write":return "edit";case "grep":case "glob":case "lsp":case "context7_resolve_library_id":case "context7_get_library_docs":return "search";case "list":case "read":return "read";default:return "other"}}function Ce(s,e){if(!e)return [];switch(s.toLowerCase()){case "read":case "edit":case "write":case "patch":case "lsp":{let n=e.filePath??e.filepath??"";return n?[{path:n}]:[]}case "glob":case "grep":return e.path?[{path:e.path}]:[];case "list":return e.path?[{path:e.path}]:[];case "bash":case "shell":{let n=e.cwd??"";return n?[{path:n}]:[]}case "external_directory":{let n=e.tool?.toLowerCase(),r=e.filepath??"",o=e.realPath??"",d=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return o?[{path:o}]:r?[{path:r}]:[];if(n==="list"||n==="glob"||n==="grep"){let l=o??r,h=l?ut__default.default.posix.dirname(l):d;return h?[{path:h}]:[]}let p=o??r;return p?[{path:p}]:d?[{path:d}]:[]}default:return []}}function gt(s,e){try{let t=diff.applyPatch(s,e);return t===!1?null:t}catch{return null}}var J=utils.Log.create({service:"acp.connection.registry"});exports.b=void 0;(i=>{let s=null;async function e(){return s||(s=await c.create()),s}async function t(g){return s||(s=await c.create(g),J.info("ServerConnectionRegistry initialized")),s}i.init=t;async function n(g){return (await e()).connect(g.baseUrl,g.localAgentId,g.remoteAgentId,g.remoteSessionId,g.localSessionId)}i.connect=n;async function r(g){return (await e()).resolve(g)}i.resolve=r;function o(g){if(s)return s.resolve(g)}i.resolveSync=o;async function d(g){(await e()).closeConnection(g);}i.close=d;async function p(g,a){(await e()).markDegraded(g,a);}i.markDegraded=p;async function l(g){return (await e()).getConnectionsByAgent(g)}i.getConnectionsByLocalAgent=l;async function h(g){return (await e()).getConnectionsByService(g)}i.getConnectionsByService=h;async function b(){return (await e()).getAllActiveConnections()}i.getAllActiveConnections=b;async function I(g,a){(await e()).updateLastSeenMessageId(g,a);}i.updateLastSeenMessageId=I;async function C(g,a){(await e()).updateSessionUpdates(g,a);}i.updateSessionUpdates=C;async function x(g,a){let u=await e(),m=u.resolve(g);m&&u.updateSessionUpdates(m.connectionId,a);}i.updateSessionUpdatesBySessionId=x;function y(g){if(s)return s.findConnectionIdBySubscriber(g)}i.findConnectionIdBySubscriber=y;class c{constructor(a){chunkISDIC2R6_cjs.a(this,"defaultHistoryScope");chunkISDIC2R6_cjs.a(this,"defaultHistoryWindowSize");chunkISDIC2R6_cjs.a(this,"defaultDegradePolicy");chunkISDIC2R6_cjs.a(this,"agentIndex",new Map);chunkISDIC2R6_cjs.a(this,"serviceIndex",new Map);chunkISDIC2R6_cjs.a(this,"connections",new Map);this.defaultHistoryScope=a?.defaultHistoryScope??"session",this.defaultHistoryWindowSize=a?.defaultHistoryWindowSize??10,this.defaultDegradePolicy=a?.defaultDegradePolicy??"streaming_first",J.debug("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(a){return new c(a)}connect(a,u,m,P,f){let v=this.agentIndex.get(u);if(v)for(let M of v){let R=this.connections.get(M);if(R&&R.baseUrl===a&&R.status!=="closed")return P&&R.sessionId!==P&&(R.sessionId=P,R.sessionSequence=R.sessionSequence??[],R.sessionSequence.includes(P)||R.sessionSequence.push(P),R.remoteSessionStatus="idle"),f&&(R.localSessionId=f),R.updatedAt=Date.now(),{connectionId:R.connectionId,sessionId:R.sessionId,localAgentId:R.localAgentId,remoteAgentId:R.remoteAgentId,baseUrl:R.baseUrl}}let S=this.generateConnectionId(),_=P??`session-${this.generateShortId()}`,k={localAgentId:u,remoteAgentId:m,connectionId:S,sessionId:_,...f?{localSessionId:f}:{},baseUrl:a,historyScope:this.defaultHistoryScope,historyWindowSize:this.defaultHistoryWindowSize,degradePolicy:this.defaultDegradePolicy,updatedAt:Date.now(),status:"active",remoteSessionStatus:"idle"};return this.connections.set(S,k),this.agentIndex.has(u)||this.agentIndex.set(u,new Set),this.agentIndex.get(u).add(S),this.serviceIndex.has(a)||this.serviceIndex.set(a,new Set),this.serviceIndex.get(a).add(S),{connectionId:S,sessionId:_,localAgentId:u,remoteAgentId:m,baseUrl:a}}resolve(a,u=false){let m=this.connections.get(a);if(m)return m;let P=this.agentIndex.get(a);if(P&&P.size>0)for(let f of P){let v=this.connections.get(f);if(v&&v.status!=="closed")return v}for(let f of this.connections.values())if(f.status!=="closed"&&(f.sessionId===a||f.localSessionId===a))return f;if(u){let S=this.connect("http://localhost","system-local","system-remote",a);return this.connections.get(S.connectionId)}}closeConnection(a){let u=this.connections.get(a);if(!u)return;this.connections.delete(a);let m=this.agentIndex.get(u.localAgentId);m&&(m.delete(a),m.size===0&&this.agentIndex.delete(u.localAgentId));let P=this.serviceIndex.get(u.baseUrl);P&&(P.delete(a),P.size===0&&this.serviceIndex.delete(u.baseUrl)),J.debug("connection closed and removed",{connectionId:a,localAgentId:u.localAgentId,remoteAgentId:u.remoteAgentId});}markDegraded(a,u){let m=this.connections.get(a);m&&(m.status="degraded",m.updatedAt=Date.now(),J.debug("connection marked degraded",{connectionId:a,reason:u}));}getConnectionsByAgent(a){let u=this.agentIndex.get(a);return u?Array.from(u).map(m=>this.connections.get(m)).filter(m=>m!==void 0&&m.status!=="closed"):[]}getConnectionsByService(a){let u=this.serviceIndex.get(a);return u?Array.from(u).map(m=>this.connections.get(m)).filter(m=>m!==void 0&&m.status!=="closed"):[]}getAllActiveConnections(){return Array.from(this.connections.values()).filter(a=>a.status!=="closed")}updateLastSeenMessageId(a,u){let m=this.connections.get(a);m&&(m.lastSeenMessageId=u,m.updatedAt=Date.now());}updateSessionUpdates(a,u){let m=this.connections.get(a);m&&(u.availableCommands!==void 0&&(m.availableCommands=u.availableCommands),u.configOptions!==void 0&&(m.configOptions=u.configOptions),u.currentModeId!==void 0&&(m.currentModeId=u.currentModeId),u.remoteSessionStatus!==void 0&&(m.remoteSessionStatus=u.remoteSessionStatus),m.updatedAt=Date.now(),J.debug("connection session updates",{connectionId:a,hasCommands:!!u.availableCommands,hasConfig:!!u.configOptions,hasMode:!!u.currentModeId}));}findConnectionIdBySubscriber(a){for(let[u,m]of this.connections)if(m.subscriber===a)return u}generateConnectionId(){return `conn-${this.generateShortId()}`}generateShortId(){return crypto.createHash("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").substring(0,8)}async close(){this.connections.clear(),this.agentIndex.clear(),this.serviceIndex.clear(),s=null,J.info("connection registry closed");}}i.ConnectionRegistry=c;})(exports.b||(exports.b={}));var W=utils.Log.create({service:"acp.connection.router"}),St=(o=>(o.EMPTY_CONTEXT="EMPTY_CONTEXT",o.AMBIGUOUS_ROUTE="AMBIGUOUS_ROUTE",o.NOT_FOUND="NOT_FOUND",o.CONNECTION_CLOSED="CONNECTION_CLOSED",o.MISSING_REQUIRED_PARAMS="MISSING_REQUIRED_PARAMS",o))(St||{});function le(s,e,t){return new chunkSNWAB3QJ_cjs.c.RoutingError({message:e,code:s,context:t})}var ye=class s{static create(){return new s}constructor(){W.info("session router created");}route(e){if(!this.isValidContext(e))return {success:false,error:"routing context is empty or invalid"};try{return e.connectionId?this.routeByConnectionId(e.connectionId):e.localAgentId&&e.baseUrl?this.routeByPeerAndBaseUrl(e.localAgentId,e.baseUrl):e.baseUrl&&e.sessionId?this.routeByBaseUrlAndSessionId(e.baseUrl,e.sessionId):{success:!1,error:"insufficient routing parameters: need connectionId, or localAgentId+baseUrl, or baseUrl+sessionId"}}catch(t){let n=utils.errorMeta(t).message;return W.error("routing failed",{context:e,error:utils.errorMeta(t)}),{success:false,error:n}}}routeOrThrow(e){let t=this.route(e);if(!t.success)throw le(this.getErrorCode(t.error),t.error??"routing failed",e);if(!t.connectionId)throw le("NOT_FOUND","connection not found",e);let n=this.getConnectionState(t.connectionId);if(!n)throw le("NOT_FOUND","connection state not found",e);if(n.status==="closed")throw le("CONNECTION_CLOSED","connection is closed",e);return n}registerConnection(e){return !e.connectionId||!e.localAgentId||!e.remoteAgentId||!e.baseUrl||!e.sessionId?{success:false,error:"invalid connection state: missing required fields"}:(W.debug("connection registered",{connectionId:e.connectionId,localAgentId:e.localAgentId,remoteAgentId:e.remoteAgentId,baseUrl:e.baseUrl}),{success:true,connectionId:e.connectionId,sessionId:e.sessionId,localAgentId:e.localAgentId,remoteAgentId:e.remoteAgentId,baseUrl:e.baseUrl})}unregisterConnection(e){let t=this.getConnectionState(e);return t?(W.debug("connection unregistered",{connectionId:e,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}),true):(W.debug("connection not found for unregister",{connectionId:e}),false)}isValidContext(e){return !!(e.connectionId||e.remoteAgentId||e.baseUrl||e.sessionId)}routeByConnectionId(e){let t=this.getConnectionState(e);return t?t.status==="closed"?{success:false,error:`connection is closed: ${e}`}:{success:true,connectionId:t.connectionId,sessionId:t.sessionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}:{success:false,error:`connection not found: ${e}`}}routeByPeerAndBaseUrl(e,t){let r=this.getConnectionsByPeer(e).filter(d=>d.baseUrl===t&&d.status!=="closed");if(r.length===0)return {success:false,error:`no connection found for localAgentId=${e}, baseUrl=${t}`};if(r.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${e}, baseUrl=${t}`};let o=r[0];return {success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}}routeByBaseUrlAndSessionId(e,t){let r=this.getConnectionsByService(e).filter(d=>d.sessionId===t&&d.status!=="closed");if(r.length===0)return {success:false,error:`no connection found for baseUrl=${e}, sessionId=${t}`};if(r.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${e}, sessionId=${t}`};let o=r[0];return {success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}}getConnectionState(e){W.warn("getConnectionState not implemented, returning undefined",{connectionId:e});}getConnectionsByPeer(e){return W.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:e}),[]}getConnectionsByService(e){return W.warn("getConnectionsByService not implemented, returning empty array",{baseUrl:e}),[]}getErrorCode(e){return e?e.includes("empty")||e.includes("invalid")?"EMPTY_CONTEXT":e.includes("ambiguous")?"AMBIGUOUS_ROUTE":e.includes("not found")?"NOT_FOUND":e.includes("closed")?"CONNECTION_CLOSED":e.includes("insufficient")||e.includes("missing")?"MISSING_REQUIRED_PARAMS":"NOT_FOUND":"NOT_FOUND"}},ue=class s extends ye{constructor(t){super();chunkISDIC2R6_cjs.a(this,"registry");this.registry=t,W.info("registry session router created");}static fromRegistry(t){return new s(t)}getConnectionState(t){return this.registry.resolve(t)}getConnectionsByPeer(t){return this.registry.getConnectionsByPeer(t)}getConnectionsByService(t){return this.registry.getConnectionsByService(t)}};var Ae=["general","coder"],Ue="general";var pe=utils.Log.create({service:"acp.session"}),te=class{constructor(e){chunkISDIC2R6_cjs.a(this,"sessions",new Map);chunkISDIC2R6_cjs.a(this,"sdk");this.sdk=e;}tryGet(e){return this.sessions.get(e)}async create(e,t,n,r){let d={id:e,cwd:t,mcpServers:n,createdAt:new Date,model:r};return pe.info("creating_session",{state:d}),this.sessions.set(e,d),d}async load(e,t,n,r){let o=await this.sdk.session.get({sessionId:e},{throwOnError:true}).then(l=>l.data),d=r,p={id:e,cwd:t,mcpServers:n,createdAt:new Date(o.time.created),model:d};return pe.debug("loading_session",{state:p}),this.sessions.set(e,p),p}get(e){let t=this.sessions.get(e);if(!t)throw pe.error("session not found",{sessionId:e}),sdk.RequestError.invalidParams(JSON.stringify({error:`Session not found: ${e}`}));return t}getModel(e){return this.get(e).model}setModel(e,t){let n=this.get(e);return n.model=t,this.sessions.set(e,n),n}getVariant(e){return this.get(e).variant}setVariant(e,t){let n=this.get(e);return n.variant=t,this.sessions.set(e,n),n}setMode(e,t){let n=this.get(e);return n.modeId=t,this.sessions.set(e,n),n}setContextMode(e,t){let n=this.get(e);return n.contextMode=t,this.sessions.set(e,n),n}setAgent(e,t){let n=this.get(e);return n.agent=t,this.sessions.set(e,n),n}close(e){return this.sessions.delete(e)}dispose(){this.sessions.clear(),pe.debug("all sessions cleared");}resolveConnectionState(e){}};var A=utils.Log.create({service:"acp.acp.service"}),ne=class{constructor(e,t){chunkISDIC2R6_cjs.a(this,"config");chunkISDIC2R6_cjs.a(this,"serviceMode");chunkISDIC2R6_cjs.a(this,"connection");chunkISDIC2R6_cjs.a(this,"sdk");chunkISDIC2R6_cjs.a(this,"connectionRegistry",null);chunkISDIC2R6_cjs.a(this,"sessionRouter",null);chunkISDIC2R6_cjs.a(this,"sessionManager");chunkISDIC2R6_cjs.a(this,"executorInitialized",false);chunkISDIC2R6_cjs.a(this,"status","initializing");this.connection=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.sessionManager=new te(this.sdk),t.connectionRegistry&&(this.connectionRegistry=t.connectionRegistry),t.sessionRouter&&(this.sessionRouter=t.sessionRouter),A.info("ACPService instance created",{channel:t.channel.type,hasConnection:!!e,hasProvidedRegistry:!!t.connectionRegistry,hasProvidedRouter:!!t.sessionRouter});}async initializeExecutor(){if(this.executorInitialized){A.warn("Executor components already initialized");return}this.connectionRegistry||(this.connectionRegistry=await exports.b.init(),A.debug("ServerConnectionRegistry initialized")),this.sessionRouter||(this.sessionRouter=ue.fromRegistry({resolve:e=>this.connectionRegistry.resolve(e),getConnectionsByPeer:e=>this.connectionRegistry.getConnectionsByAgent(e),getConnectionsByService:e=>this.connectionRegistry.getConnectionsByService(e)}),A.debug("SessionRouter created")),this.executorInitialized=true,A.info("Executor components initialized");}setStatus(e,t="agent"){let n=this.status;if(n===e)return;this.status=e,A.debug("Agent status changed",{oldStatus:n,newStatus:e,agentId:t});}getStatus(){return this.status}authenticate(e){return Promise.resolve(void 0)}async newSession(e){A.debug("ACP newSession requested",{cwd:e.cwd});let t=e.cwd,r=(await this.sdk.model.default())?.data,d=(await this.sdk.session.create({directory:t})).data?.id;if(!d)throw new utils.NameErrors.OperationFailedError({message:"Failed to create session: no session ID returned",operation:"acp-session-create"});let p=await this.sessionManager.create(d,t,e.mcpServers,r),l=await this.buildSessionStateResponse(p.id,t);return {sessionId:p.id,...l,_meta:{}}}async loadSession(e){A.debug("ACP loadSession requested",{sessionId:e.sessionId});let t=e.cwd,r=(await this.sdk.model.default())?.data;return await this.sessionManager.load(e.sessionId,t,e.mcpServers,r),{...await this.buildSessionStateResponse(e.sessionId,t),_meta:{}}}async prompt(e){let t=e.sessionId,n=this.sessionManager.get(t),r=n.cwd,o=e._meta??{},d=typeof o.agent=="string"&&o.agent?o.agent:void 0,p=typeof o.model=="string"&&o.model?utils.parseModelId(o.model):void 0,l=n.model,h=p?.providerId?{providerId:p.providerId,modelId:p.modelId}:p?.modelId?{providerId:l?.providerId??"",modelId:p.modelId}:l??(await this.sdk.model.default())?.data,b=d??n.agent??(await this.sdk.agent.default())?.data?.name??"build";this.sendAvailableCommandsUpdate(t).catch(y=>{A.warn("Failed to send initial available commands update",{sessionId:t,directory:r,error:utils.errorMeta(y)});});let I=[];for(let y of e.prompt)switch(y.type){case "text":{let c=y.annotations?.audience,i=c?.length===1&&c[0]==="assistant",g=c?.length===1&&c[0]==="user";I.push({type:"text",text:y.text,...i&&{synthetic:true},...g&&{ignored:true}});break}case "image":{let c=this.parseUri(y.uri??""),i=c.type==="file"?c.filename:"image";y.data?I.push({type:"file",url:`data:${y.mimeType};base64,${y.data}`,filename:i,mime:y.mimeType}):y.uri?.startsWith("http:")&&I.push({type:"file",url:y.uri,filename:i,mime:y.mimeType});break}case "resource_link":{let c=this.parseUri(y.uri);y.name&&c.type==="file"&&(c.filename=y.name),I.push(c);break}case "resource":{let c=y.resource;if("text"in c&&c.text)I.push({type:"text",text:c.text});else if("blob"in c&&c.blob&&c.mimeType){let i=this.parseUri(c.uri??""),g=i.type==="file"?i.filename:"file";I.push({type:"file",url:`data:${c.mimeType};base64,${c.blob}`,filename:g,mime:c.mimeType});}break}}A.debug("prompt parts",{sessionId:t,parts:I});let C=(()=>{let y=I.filter(u=>u.type==="text").map(u=>u.text).join("").trim();if(!y.startsWith("/"))return;let c=utils.ParseCommand.tokenize(y.slice(1));if(c.length===0)return;let[i,...g]=c,a=g.join(" ").trim();return A.debug("command",{name:i,args:a}),{name:i,args:a}})();if(!C)return this.sdk.session.prompt({sessionId:t,model:{providerId:h.providerId,modelId:h.modelId},parts:I,agent:b,variant:n.variant,contextMode:n.contextMode}).catch(y=>{A.error("prompt execution failed",{sessionId:t,error:utils.errorMeta(y)});}),{stopReason:"end_turn",_meta:{}};let x=await this.sdk.command.get({name:C.name},{throwOnError:true}).then(y=>y.data);if(x)return x.commandType==="local"&&this.connection?(this.sdk.session.command({sessionId:t,command:x.name,arguments:C.args??"",agent:b,model:utils.formatModelId(h),variant:n.variant,contextMode:n.contextMode,parts:I}).then(async y=>{let c=y.data?.success?y.data.output:`[Error] ${y.data?.error??"Command execution failed"}`;this.connection?.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}});let i=await this.getContextLimit(h.providerId,h.modelId,r);i&&this.connection?.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:0,size:i}});}).catch(y=>{A.error("local command execution failed",{command:x.name,error:utils.errorMeta(y)});}),{stopReason:"end_turn",_meta:{}}):(this.sdk.session.command({sessionId:t,command:x.name,arguments:C.args??"",agent:b,model:utils.formatModelId(h),variant:n.variant,contextMode:n.contextMode,parts:I}).catch(y=>{A.error("prompt command execution failed",{command:x.name,error:utils.errorMeta(y)});}),{stopReason:"end_turn",_meta:{}});switch(C.name){case "compact":if(!h.providerId||!h.modelId)throw new utils.NameErrors.MissingFieldError({message:"Model providerId and modelId are required for compact command",field:"model"});await this.sdk.session.summarize({sessionId:t,providerId:h.providerId,modelId:h.modelId},{throwOnError:true});break}return await this.sendUsageUpdate(t,r),{stopReason:"end_turn",_meta:{}}}async cancel(e){this.sessionManager.tryGet(e.sessionId)?.cwd??"";try{this.sdk&&await this.sdk.session.abort({sessionId:e.sessionId}).catch(r=>{A.warn("SDK abort failed",{sessionId:e.sessionId,error:utils.errorMeta(r)});}),A.debug("Session cancelled",{sessionId:e.sessionId});}catch(r){throw A.error("Failed to cancel session",{sessionId:e.sessionId,error:utils.errorMeta(r)}),r}}parseUri(e){try{if(e.startsWith("file://")){let t=e.slice(7),n=t.split("/").pop()||t;return {type:"file",url:e,filename:n,mime:"text/plain"}}if(e.startsWith("zed://")){let n=new URL(e).searchParams.get("path");if(n){let r=n.split("/").pop()||n;return {type:"file",url:url.pathToFileURL(n).href,filename:r,mime:"text/plain"}}}return {type:"text",text:e}}catch{return {type:"text",text:e}}}async sendUsageUpdate(e,t){if(!this.sdk||!this.connection)return;if(!e){A.debug("sendUsageUpdate: skipping, sessionId is empty");return}let n=await this.sdk.session.messages({sessionId:e},{throwOnError:true}).then(h=>h.data).catch(h=>{A.error("failed to fetch messages for usage update",{error:utils.errorMeta(h)});});if(!n)return;let r=n.filter(h=>h.info.role==="assistant"),o=r[r.length-1];if(!o)return;let d=o.info,p=await this.getContextLimit(d.providerId,d.modelId,t);if(!p)return;let l=d.tokens.input+(d.tokens.cache?.read??0);await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:l,size:p}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.connection){if(!e){A.debug("sendAvailableCommandsUpdate: skipping, sessionId is empty");return}try{let r=this.sessionManager.get(e)?.contextMode,d=(await this.sdk.command.list({contextMode:r},{throwOnError:!0})).data?.filter(p=>!p.hidden).map(p=>({name:p.name,description:p.description??""}))??[];await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:d}});}catch(n){A.error("failed to send available commands update",{error:utils.errorMeta(n)});}}}async sendConfigOptionUpdate(e,t,n){if(this.connection){if(!e){A.debug("sendConfigOptionUpdate: skipping, sessionId is empty");return}try{let o=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!o||o.length===0)return;await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:o}});}catch(r){A.error("failed to send config_option_update to ACP client",{sessionId:e,error:utils.errorMeta(r)});}}}async sendCurrentModeUpdate(e,t){if(this.connection){if(!e){A.debug("sendCurrentModeUpdate: skipping, sessionId is empty");return}try{await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"current_mode_update",currentModeId:t}});}catch(n){A.error("failed to send current_mode_update to ACP client",{sessionId:e,modeId:t,error:utils.errorMeta(n)});}}}async getContextLimit(e,t,n){return this.sdk?(await this.sdk.config.providers({}).then(p=>p.data?.providers??[]).catch(p=>(A.error("failed to get providers for context limit",{error:utils.errorMeta(p)}),[]))).find(p=>p.id===e)?.models[t]?.limit.context??2e5:null}async unstable_forkSession(e){A.debug("ACP forkSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.mcpServers??[],o=(await this.sdk.model.default())?.data,d=await this.sdk.session.fork({sessionId:e.sessionId,directory:t},{throwOnError:true}).then(b=>b.data);if(!d)throw new utils.NameErrors.OperationFailedError({message:"Fork session returned no data",operation:"acp-session-fork"});let p=d.id;await this.sessionManager.load(p,t,n,o);let h=await this.buildSessionStateResponse(p,t);return A.debug("fork_session",{sessionId:p,mcpServers:n.length}),{sessionId:p,...h,_meta:{}}}async resumeSession(e){A.debug("ACP resumeSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.sessionId,r=e.mcpServers??[],d=(await this.sdk.model.default())?.data;await this.sessionManager.load(n,t,r,d);let l=await this.buildSessionStateResponse(n,t);return A.debug("resume_session",{sessionId:n,mcpServers:r.length}),{...l,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,o=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(I=>I.data??[])).toSorted((I,C)=>C.time.updated-I.time.updated),p=(t?o.filter(I=>I.time.updated<t):o).slice(0,n),l=p.map(I=>({sessionId:I.id,cwd:I.directory,title:I.title??`Session ${I.id}`,updatedAt:new Date(I.time.updated).toISOString()})),h=p[p.length-1],b=p.length===n&&h?String(h.time.updated):void 0;return {sessions:l,nextCursor:b}}async setSessionMode(e){A.debug("ACP setSessionMode requested",{sessionId:e.sessionId,modeId:e.modeId}),this.sessionManager.setMode(e.sessionId,e.modeId);let t=this.sessionManager.get(e.sessionId);return await this.sendCurrentModeUpdate(e.sessionId,e.modeId),await this.sendConfigOptionUpdate(e.sessionId,t.cwd),{_meta:{}}}async setSessionConfigOption(e){if(A.debug("ACP setSessionConfigOption requested",{sessionId:e.sessionId,configId:e.configId,value:e.value}),e.configId==="model"){let r=typeof e.value=="string"?e.value:void 0;if(r){let o=this.parseModelSelection(r);this.sessionManager.setModel(e.sessionId,o.model);}}else if(e.configId==="agent"){let r=typeof e.value=="string"?e.value:void 0;this.sessionManager.setAgent(e.sessionId,r);}else if(e.configId==="thought_level"){let r=typeof e.value=="string"?e.value:void 0;this.sessionManager.setVariant(e.sessionId,r);}else if(e.configId==="context_mode"){let r=typeof e.value=="string"&&Ae.includes(e.value)?e.value:void 0;this.sessionManager.setContextMode(e.sessionId,r);}let t=this.sessionManager.get(e.sessionId),n=await this.buildSessionStateResponse(e.sessionId,t.cwd);return await this.sendConfigOptionUpdate(e.sessionId,t.cwd,n),{_meta:{},configOptions:n.configOptions??[]}}async closeSession(e){return A.debug("ACP closeSession requested",{sessionId:e.sessionId}),await this.cancel({sessionId:e.sessionId}),this.sessionManager.close(e.sessionId),{_meta:{}}}async buildSessionStateResponse(e,t){let n=this.sessionManager.tryGet(e),r=n?.model??(await this.sdk.model.default())?.data,o=r?.providerId&&r?.modelId?utils.formatModelId(r):void 0,d=[];try{d=(await this.sdk.config.providers({}).then(x=>x.data?.providers??[])).flatMap(x=>{let y=x.models??{};return Object.keys(y).map(c=>({modelId:`${x.id}/${c}`,name:`${x.id}/${c}`}))});}catch(C){A.warn("failed to build available models for session state",{sessionId:e,error:utils.errorMeta(C)});}o&&!d.some(C=>C.modelId===o)&&(d=[{modelId:o,name:o},...d]);let p=[];try{p=((await this.sdk.agent.list({})).data??[]).filter(y=>y.hidden!==!0&&y.mode!=="subagent").map(y=>({id:y.name,name:y.name,description:y.description}));}catch(C){A.warn("failed to build available agents for session state",{sessionId:e,error:utils.errorMeta(C)});}let l=n?.modeId,h=n?.variant??"low",b=n?.contextMode??Ue,I=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e,t),{models:o?{currentModelId:o,availableModels:d}:void 0,modes:l?{currentModeId:l,availableModes:[{id:l,name:l}]}:void 0,configOptions:[{id:"model",name:"Model",category:"model",type:"select",currentValue:o??"",options:d.map(C=>({value:C.modelId,name:C.name,description:C.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:I,options:p.map(C=>({value:C.id,name:C.name,description:C.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:h,options:[{value:"off",name:"Off"},{value:"low",name:"Low"},{value:"medium",name:"Medium"},{value:"high",name:"High"}]},{id:"context_mode",name:"Context Mode",category:"context_mode",type:"select",currentValue:b,options:Ae.map(C=>({value:C,name:C.charAt(0).toUpperCase()+C.slice(1)}))}]}}parseModelSelection(e){let t=utils.parseModelId(e);if(t.providerId&&t.modelId)return {model:{providerId:t.providerId,modelId:t.modelId}};throw new utils.NameErrors.InvalidArgumentError({message:`Invalid model id: "${e}" (expected format: <providerId>/<modelId>)`,param:"modelId"})}setConnection(e){this.connection=e,A.debug("ACPService connection updated");}getConnection(){return this.connection}setServerConnection(e){this.connection=e,A.debug("ACPService serverConnection updated");}abortConnection(){this.connection&&A.debug("Connection aborted");}closeConnection(){this.connection&&A.debug("Connection closed");}getServerConnectionRegistry(){return this.connectionRegistry}getSessionRouter(){return this.sessionRouter}createConnection(e,t,n,r){if(!this.connectionRegistry)throw new utils.NameErrors.OperationFailedError({message:"ServerConnectionRegistry not initialized. Call initializeExecutor() first.",operation:"acp-connect"});if(!t||!n)throw new utils.NameErrors.MissingFieldError({message:"localAgentId and remoteAgentId are required",field:"agentIds"});return this.connectionRegistry.connect(e,t,n,r)}async routeToConnection(e){if(!this.sessionRouter)throw new utils.NameErrors.OperationFailedError({message:"SessionRouter not initialized. Call initializeExecutor() first.",operation:"acp-route"});return this.sessionRouter.route(e)}async dispose(){A.info("Disposing ACPService"),this.sessionManager&&(this.sessionManager.dispose?.(),A.debug("SessionManager disposed")),this.connectionRegistry&&(await this.connectionRegistry.close(),this.connectionRegistry=null,A.debug("ServerConnectionRegistry closed")),this.sessionRouter=null,this.executorInitialized=false,A.info("ACPService disposed");}};var L={HTTP:chunkDX35VSAT_cjs.b.HTTP,STDIO:chunkDX35VSAT_cjs.b.STDIO,WEBSOCKET:chunkDX35VSAT_cjs.b.WS};function qe(s,e=[]){return new chunkSNWAB3QJ_cjs.c.ServiceModeConflictError({message:s,conflictingModes:e})}function bt(s){let e=[];return s.channel&&e.push(s.channel),e}function Be(s){let e=bt(s);if(e.length===0)throw qe("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw qe(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var we={channel:L.WEBSOCKET,port:3e3,hostname:"localhost",timeout:3e4,historyScope:"session",historyWindowSize:10,degradePolicy:"streaming_first",sessionExpireMs:300*1e3};var B=utils.Log.create({service:"acp.server.config"}),V="EAS_";function De(s){return !(!s||s.trim()===""||s.startsWith("-")||s.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(s))}function He(s){return Number.isInteger(s)&&s>=1&&s<=65535}function ze(s){return Number.isFinite(s)&&s>0}function xt(s){let e={...we,...s};try{Be(e);}catch(t){throw chunkSNWAB3QJ_cjs.f(t)&&B.error("Invalid service mode configuration",{message:utils.errorMeta(t).message,conflictingModes:t.data.conflictingModes}),t}if(e.port!==void 0&&!He(e.port))throw B.error("Invalid port configuration",{port:e.port}),new utils.NameErrors.InvalidArgumentError({message:`Invalid port number: ${e.port}. Must be between 1 and 65535`,param:"port"});if(e.hostname!==void 0&&!De(e.hostname))throw B.error("Invalid hostname configuration",{hostname:e.hostname}),new utils.NameErrors.InvalidArgumentError({message:`Invalid hostname: ${e.hostname}`,param:"hostname"});if(e.timeout!==void 0&&!ze(e.timeout))throw B.error("Invalid timeout configuration",{timeout:e.timeout}),new utils.NameErrors.InvalidArgumentError({message:`Invalid timeout: ${e.timeout}. Must be a positive number`,param:"timeout"});if(e.channel===L.STDIO&&e.stdio&&(!e.stdio.command||e.stdio.command.trim()===""))throw B.error("Invalid stdio configuration",{command:e.stdio.command}),new utils.NameErrors.MissingFieldError({message:"STDIO command is required",field:"command"});return B.debug("ACPServer config loaded",{channel:e.channel,port:e.port,hostname:e.hostname}),e}function Le(){let s={},e=process.env[`${V}ACP_CHANNEL`];if(e){let l=e.toLowerCase();Object.values(L).includes(l)?s.channel=l:B.warn("Invalid EAS_ACP_CHANNEL environment variable",{value:e});}let t=process.env[`${V}ACP_PORT`];if(t){let l=parseInt(t,10);He(l)?s.port=l:B.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${V}ACP_HOSTNAME`];n&&(De(n)?s.hostname=n:B.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let r=process.env[`${V}ACP_TIMEOUT`];if(r){let l=parseInt(r,10);ze(l)?s.timeout=l:B.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:r});}let o=process.env[`${V}ACP_HISTORY_SCOPE`];o&&(["session","peer","global"].includes(o)?s.historyScope=o:B.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:o}));let d=process.env[`${V}ACP_HISTORY_WINDOW_SIZE`];if(d){let l=parseInt(d,10);Number.isInteger(l)&&l>0?s.historyWindowSize=l:B.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:d});}let p=process.env[`${V}ACP_DEGRADE_POLICY`];return p&&(["polling_only","streaming_first"].includes(p)?s.degradePolicy=p:B.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:p})),B.debug("Config loaded from environment",{config:s}),s}function as(s){let e=Le(),t={...e,...s};return B.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:s,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}function Fe(s){let e=Le(),t={...we,...e,...s},n=xt(t);return B.info("ACPServer config resolved (default < env < explicit)",{env:{channel:e.channel,port:e.port,hostname:e.hostname},explicit:{channel:s.channel,port:s.port,hostname:s.hostname},final:{channel:n.channel,port:n.port,hostname:n.hostname}}),n}var Pe=utils.Log.create({service:"acp.server.rpc-handler"}),Q={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,INTERNAL_ERROR:-32603},Z=class{constructor(e){chunkISDIC2R6_cjs.a(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:r}=e;Pe.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:r});try{let o;switch(t){case "initialize":o=await this.handleInitialize(n);break;case "authenticate":o=await this.handleAuthenticate(n);break;case "session.new":case "newSession":o=await this.handleNewSession(n);break;case "session.load":case "loadSession":o=await this.handleLoadSession(n);break;case "session.close":case "closeSession":o=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":o=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),o={success:!0};break;case "session.list":case "listSessions":o=await this.handleListSessions(n);break;case "session.fork":case "forkSession":o=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":o=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":o=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":o=await this.handleSetSessionConfigOption(n);break;case "status":o=this.handleStatus();break;case "subscriptions":o=this.handleSubscriptions();break;default:throw Pe.warn("Unknown method",{method:t}),new utils.NameErrors.NotFoundError({message:`Method not found: ${t}`,location:"rpc-method"})}return {jsonrpc:"2.0",id:r,result:o}}catch(o){return Pe.error("AcpRpcHandler error",{method:t,error:utils.errorMeta(o)}),{jsonrpc:"2.0",id:r,error:{code:Q.INTERNAL_ERROR,message:utils.errorMeta(o).message}}}}async handleInitialize(e){return this.agent.initialize(e)}async handleAuthenticate(e){return this.agent.authenticate(e)}async handleNewSession(e){return this.agent.newSession(e)}async handleLoadSession(e){return this.agent.loadSession(e)}async handleCloseSession(e){return this.agent.closeSession(e)}async handlePrompt(e){return this.agent.prompt(e)}async handleCancel(e){return this.agent.cancel(e)}async handleListSessions(e){return this.agent.listSessions(e)}async handleForkSession(e){return this.agent.unstable_forkSession(e)}async handleResumeSession(e){return this.agent.resumeSession(e)}async handleSetSessionMode(e){return this.agent.setSessionMode(e)}async handleSetSessionConfigOption(e){return this.agent.setSessionConfigOption(e)}handleStatus(){return {status:"running",channel:"http",timestamp:Date.now(),uptime:process.uptime()}}handleSubscriptions(){return {sessions:[]}}};var me=utils.Log.create({service:"acp.server.agent-side-connection"}),X=class{constructor(){chunkISDIC2R6_cjs.a(this,"broadcaster",null);chunkISDIC2R6_cjs.a(this,"sessionIds",new Set);chunkISDIC2R6_cjs.a(this,"sessionRefCounts",new Map);}setBroadcaster(e){this.broadcaster=e;}addSession(e){this.sessionIds.add(e),this.sessionRefCounts.set(e,(this.sessionRefCounts.get(e)??0)+1);}removeSession(e){let t=this.sessionRefCounts.get(e)??0;if(t<=1){this.sessionRefCounts.delete(e),this.sessionIds.delete(e);return}this.sessionRefCounts.set(e,t-1);}clearSessions(){this.sessionIds.clear(),this.sessionRefCounts.clear();}getSessions(){return Array.from(this.sessionIds)}async sessionUpdate(e){let{sessionId:t,update:n}=e;me.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return me.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async extMethod(e,t){return me.debug("ServerAgentSideConnection.extMethod",{method:e}),{}}async extNotification(e,t){if(me.debug("ServerAgentSideConnection.extNotification",{method:e,params:t}),this.broadcaster&&t){let n=t.sessionId||t.sessionId;if(n&&this.sessionIds.has(n)){let r={sessionId:n,update:{sessionUpdate:e,...t}};this.broadcaster.broadcast(n,r);}}}};var z=utils.Log.create({service:"acp.server.http"});async function je(s,e){if(z.info("Starting HTTP server",{port:e.port,hostname:e.hostname}),e.channel!==L.HTTP)throw new utils.NameErrors.InvalidArgumentError({message:`Invalid channel type for HTTP server: ${e.channel}`,param:"channel"});let t=new Map,n=new Map,r=new X,o={broadcast:(i,g)=>{b(i,g);}};r.setBroadcaster(o);let d=new Z(s),p=s.getSDK();if(!p)throw new utils.NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let l=new j(p,r);l.setService(s);let h=(i,g)=>{let a=t.get(i);if(!a)return false;try{return a.controller.enqueue(new TextEncoder().encode(g)),a.lastHeartbeat=Date.now(),!0}catch(u){return z.warn("Failed to push to SSE connection",{connectionId:i,error:utils.errorMeta(u)}),false}},b=(i,g)=>{let a=n.get(i);if(!a||a.size===0)return;let m={jsonrpc:"2.0",method:g.update.sessionUpdate,params:{sessionId:i,...g.update,timestamp:Date.now()}},P=`data: ${JSON.stringify(m)}
|
|
2
|
-
|
|
3
|
-
`;for(let f of a)h(f,P)||(t.delete(f),a.delete(f),r.removeSession(i));},I=(i,g)=>(r.addSession(i),new ReadableStream({start:async a=>{let u={id:g,controller:a,sessionId:i,createdAt:Date.now(),lastHeartbeat:Date.now()};t.set(g,u),n.has(i)||n.set(i,new Set),n.get(i).add(g),z.debug("SSE client connected",{connectionId:g,sessionId:i});let m=`data: ${JSON.stringify({type:"connected",connectionId:g,sessionId:i})}
|
|
4
|
-
|
|
5
|
-
`;a.enqueue(new TextEncoder().encode(m)),s.sendAvailableCommandsUpdate(i).catch(P=>{z.warn("Failed to send initial available commands update",{sessionId:i,connectionId:g,error:utils.errorMeta(P)});});},cancel:()=>{let a=t.get(g);if(a){t.delete(g);let u=n.get(a.sessionId);u&&(u.delete(g),u.size===0&&n.delete(a.sessionId)),r.removeSession(a.sessionId),z.debug("SSE client disconnected",{connectionId:g,sessionId:a.sessionId});}}})),C=null,x=()=>{C||(C=setInterval(()=>{let i=Date.now(),g=3e5;for(let[a,u]of t.entries())if(i-u.lastHeartbeat>g){z.warn("SSE connection timeout, closing",{connectionId:a});try{u.controller.close();}catch{}t.delete(a);let m=n.get(u.sessionId);m&&(m.delete(a),m.size===0&&n.delete(u.sessionId)),r.removeSession(u.sessionId);}else try{u.controller.enqueue(new TextEncoder().encode(`: heartbeat
|
|
6
|
-
|
|
7
|
-
`)),u.lastHeartbeat=i;}catch{}},1e4));},y=[{method:"post",path:"/acp",handler:async i=>{let g=await i.req.json().catch(()=>null);if(!g||typeof g!="object")return i.json({jsonrpc:"2.0",error:{code:Q.PARSE_ERROR,message:"Parse error"}},400);let a=g;if(!a.method||a.jsonrpc!=="2.0")return i.json({jsonrpc:"2.0",error:{code:Q.INVALID_REQUEST,message:"Invalid Request"}},400);if(a.method==="session.prompt")return d.handle(a).catch(m=>{z.error("HTTP server: session.prompt error",{error:utils.errorMeta(m)});}),i.json({jsonrpc:"2.0",id:a.id,result:{accepted:true}},202);let u=await d.handle(a);if(a.method==="initialize"){let m=`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;return i.json(u,200,{"Acp-Connection-Id":m})}return i.json(u)}},{method:"get",path:"/acp",handler:i=>{let g=i.req.header("Acp-Connection-Id"),a=i.req.header("Acp-Session-Id");if(!i.req.header("Accept")?.includes("text/event-stream"))return i.json({error:"Not Acceptable"},406);let m=g||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(a){let v=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,S=I(a,v);return new Response(S,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":m,"Acp-Session-Id":a}})}let P=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,f=I("__connection__",P);return new Response(f,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":m}})}},{method:"delete",path:"/acp",handler:async i=>{let g=i.req.header("Acp-Connection-Id");return z.debug("HTTP server: connection terminated",{connectionId:g}),i.json({success:true})}}],c=utils.createServer({port:e.port,hostname:e.hostname,routes:y,timeout:e.timeout,cors:true});try{await l.start(),s.setServerConnection(r),x();}catch(i){throw z.error("HTTP server: failed to start background resources, cleaning up",{error:utils.errorMeta(i)}),await l.stop().catch(()=>{}),C&&(clearInterval(C),C=null),await c.stop().catch(()=>{}),i}return z.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:c,stop:async()=>{z.info("Stopping HTTP server"),C&&(clearInterval(C),C=null),await l.stop();for(let i of t.values())try{i.controller.close();}catch{}t.clear(),n.clear(),r.clearSessions(),await c.stop(),z.info("HTTP server stopped");}}}var H=utils.Log.create({service:"acp.server.websocket"});function Bt(s){try{let e=new URL(s),t=e.hostname,n=parseInt(e.port,10);if(t&&!Number.isNaN(n)&&n>0&&n<=65535)return {port:n,hostname:t}}catch{}}async function Ve(s,e){let t=e.ws?Bt(e.ws.url):void 0,n=t?.port??e.port??3e3,r=t?.hostname??e.hostname??"localhost",o="/acp";if(H.info("Starting WebSocket server",{port:n,hostname:r,wsUrl:e.ws?.url}),e.channel!==L.WEBSOCKET)throw new utils.NameErrors.InvalidArgumentError({message:`Invalid channel type for WebSocket server: ${e.channel}`,param:"channel"});let d=new Map,p=new Map,l=new X,h={broadcast:(f,v)=>{x(f,v);}};l.setBroadcaster(h);let b=new Z(s),I=s.getSDK();if(!I)throw new utils.NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let C=new j(I,l);C.setService(s);let x=(f,v)=>{let _={jsonrpc:"2.0",method:v.update.sessionUpdate,params:{sessionId:f,...v.update,timestamp:Date.now()}},k=JSON.stringify(_);for(let[M,R]of p.entries())if(R.subscribedSessions.has(f)){let O=d.get(M);O&&O.ws.readyState===O.ws.OPEN&&O.ws.send(k);}},y=f=>{for(let[v,S]of d.entries())if(S.ws===f)return v},c=(f,v)=>{let S=p.get(f);S&&(S.subscribedSessions.has(v)||(S.subscribedSessions.add(v),l.addSession(v)));},i=(f,v)=>{let S=p.get(f);S&&S.subscribedSessions.has(v)&&(S.subscribedSessions.delete(v),l.removeSession(v));},g={onOpen:(f,v)=>{let S=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;d.set(S,{id:S,ws:v,createdAt:Date.now()}),p.set(S,{clientId:S,subscribedSessions:new Set}),H.debug("WebSocket client connected",{clientId:S}),v.send(JSON.stringify({type:"connected",clientId:S}));},onMessage:async(f,v)=>{try{let S=JSON.parse(f.data.toString());if(S.type==="ping"){v.send(JSON.stringify({type:"pong"}));return}let _=y(v);if(!_)return;let k,M;if(S.type==="message"||S.type==="request")k={jsonrpc:"2.0",id:S.id,method:S.method,params:S.params},M=S.sessionId;else if(S.jsonrpc==="2.0"&&S.method)k={jsonrpc:"2.0",id:S.id,method:S.method,params:S.params},M=S.params?.sessionId;else {H.warn("WebSocket server: unknown message format",{data:S});return}if(k.method==="session.subscribe"){M&&(c(_,M),s.sendAvailableCommandsUpdate(M).catch(O=>{H.warn("Failed to send initial available commands update",{sessionId:M,error:utils.errorMeta(O)});})),v.send(JSON.stringify({type:"response",id:k.id,result:{subscribed:!0,sessionId:M}}));return}if(k.method==="session.unsubscribe"){M&&i(_,M),v.send(JSON.stringify({type:"response",id:k.id,result:{unsubscribed:!0,sessionId:M}}));return}if(k.method==="session.interrupt"){let O={jsonrpc:"2.0",method:"session.cancel",params:{sessionId:M}},ce=await b.handle(O);v.send(JSON.stringify({type:"response",id:k.id,result:ce.result,error:ce.error}));return}if(k.method==="session.prompt"){if(v.send(JSON.stringify({jsonrpc:"2.0",id:k.id,result:{accepted:!0}})),M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}b.handle(k).catch(O=>{H.error("WebSocket server: session.prompt error",{error:utils.errorMeta(O)});});return}if(M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}let R=await b.handle(k);v.send(JSON.stringify({type:"response",id:R.id,result:R.result,error:R.error}));}catch(S){H.error("WebSocket server: error handling message",{error:utils.errorMeta(S)});}},onClose:(f,v)=>{let S=y(v);if(S){d.delete(S);let _=p.get(S);if(_){for(let k of _.subscribedSessions)l.removeSession(k);p.delete(S);}H.debug("WebSocket client disconnected",{clientId:S});}},onError:(f,v)=>{H.error("WebSocket error",{error:f.type});}},a=utils.createServer({port:n,hostname:r,routes:[{method:"post",path:"/acp",handler:async f=>{let v=await f.req.json().catch(()=>null);if(!v||typeof v!="object")return f.json({jsonrpc:"2.0",error:{code:Q.PARSE_ERROR,message:"Parse error"}},400);let S=v;if(!S.method||S.jsonrpc!=="2.0")return f.json({jsonrpc:"2.0",error:{code:Q.INVALID_REQUEST,message:"Invalid Request"}},400);let _=await b.handle(S);return f.json(_)}},{method:"delete",path:"/acp",handler:async f=>{let v=f.req.header("Acp-Connection-Id");return H.debug("WebSocket server: connection terminated",{connectionId:v}),f.json({success:true})}}],timeout:e.timeout,cors:true}),u=a.raw,m=null,P=null;u&&(m=new ws.WebSocketServer({noServer:true}),P=(f,v,S)=>{try{let k=new URL(f.url||"/",`http://${f.headers.host}`).pathname,M=f.headers.upgrade?.toLowerCase();k===o&&M==="websocket"&&m.handleUpgrade(f,v,S,R=>{g.onOpen?.({type:"open"},R),R.on("message",O=>{g.onMessage?.({data:O},R);}),R.on("close",(O,ce)=>{g.onClose?.({code:O,reason:ce},R);}),R.on("error",O=>{g.onError?.({type:"error",message:utils.errorMeta(O).message},R);});});}catch{}},u.on("upgrade",P));try{await C.start(),s.setServerConnection(l);}catch(f){if(H.error("WebSocket server: failed to start background resources, cleaning up",{error:utils.errorMeta(f)}),await C.stop().catch(()=>{}),u&&P&&(u.off("upgrade",P),P=null),m){try{await new Promise(v=>m.close(()=>v()));}catch{}m=null;}throw await a.stop().catch(()=>{}),f}return H.info("WebSocket server started",{url:e.ws?.url||`ws://${r}:${n}`,path:o}),{server:a,stop:async()=>{H.info("Stopping WebSocket server"),await C.stop(),u&&P&&(u.off("upgrade",P),P=null);for(let f of d.values())try{f.ws.close();}catch{}if(d.clear(),p.clear(),l.clearSessions(),m){try{await new Promise(f=>m.close(()=>f()));}catch{}m=null;}await a.stop(),H.info("WebSocket server stopped");}}}var oe=utils.Log.create({service:"acp.server.core"});async function Qe(s,e){let t=Fe(e||{});oe.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,r;switch(t.channel){case L.HTTP:({server:n,stop:r}=await je(s,t));break;case L.WEBSOCKET:({server:n,stop:r}=await Ve(s,t));break;default:throw new utils.NameErrors.InvalidArgumentError({message:`Unsupported service mode: ${t.channel}`,param:"channel"})}let o={type:t.channel,server:n,agent:s,stop:async()=>{oe.info("Stopping ACPServer",{type:t.channel}),await r();},healthCheck:async()=>{if(typeof n=="object"&&n!==null&&"healthCheck"in n){let d=n.healthCheck;if(typeof d=="function")return d()}return true}};return oe.info("ACPServer started successfully",{type:o.type,url:Lt(t)}),o}function Lt(s){return chunkSNWAB3QJ_cjs.t({channel:s.channel,hostname:s.hostname,port:s.port})??"unknown://"}async function Ft(s){await Promise.all(s.map(async e=>{try{await e.stop();}catch(t){oe.error("Error stopping server",{type:e.type,error:utils.errorMeta(t)});}}));}async function Ke(s){await Ft([s]);}function Ls(s){return {type:s.channel,server:null,agent:null,stop:async()=>{oe.warn("Server not started, nothing to stop");},healthCheck:async()=>false}}var Kt=url.fileURLToPath(chunkISDIC2R6_cjs.b),Yt=ut.dirname(Kt),Ze="0.0.0";try{let s=ut.join(Yt,"..","package.json");Ze=JSON.parse(fs.readFileSync(s,"utf-8")).version??"0.0.0";}catch{}var N=utils.Log.create({service:"acp.easbot-agent"}),re=class s extends ne{constructor(t,n){super(t,n);chunkISDIC2R6_cjs.a(this,"acpEventBridge",null);chunkISDIC2R6_cjs.a(this,"server",null);chunkISDIC2R6_cjs.a(this,"isAgentInitialized",false);N.info("EasBotAgent instance created",{serviceMode:this.serviceMode});}static async create(t){N.info("creating EasBotAgent",{serviceMode:t.serviceMode});let n=t.serviceMode==="stdio",r=new s(void 0,t);if(n&&t.stdioStream){let{stream:o}=t.stdioStream,d={initialize:async l=>r.initialize(l),newSession:async l=>r.newSession(l),loadSession:async l=>r.loadSession(l),prompt:async l=>r.prompt(l),cancel:async l=>r.cancel(l),authenticate:async l=>r.authenticate(l),setSessionMode:async l=>r.setSessionMode(l),setSessionConfigOption:async l=>r.setSessionConfigOption(l),listSessions:async l=>r.listSessions(l),unstable_forkSession:async l=>r.unstable_forkSession(l),resumeSession:async l=>r.resumeSession(l),closeSession:async l=>r.closeSession(l)},p=new sdk.AgentSideConnection(()=>d,o);r.setConnection(p);}return N.info("EasBotAgent created successfully",{serviceMode:t.serviceMode,hasConnection:n&&!!t.stdioStream}),r}async initialize(t){return N.info("ACP initialize requested",{protocolVersion:t.protocolVersion}),this.isAgentInitialized||await this.initializeAgent(),{protocolVersion:t.protocolVersion,agentCapabilities:{loadSession:true,positionEncoding:"utf-8",mcpCapabilities:{http:true,sse:true},promptCapabilities:{image:true,embeddedContext:true,audio:false},sessionCapabilities:{close:{},fork:{},list:{},resume:{}},_meta:{history_scope:true,session_management:true}},agentInfo:{name:"EasBot Agent",version:Ze,title:"Multi-Agent Collaboration Ecosystem Agent"},authMethods:[{id:"easbot-token",name:"EasBot Token Authentication",description:"Authenticate using EasBot API token"}]}}async initializeAgent(){if(this.isAgentInitialized){N.warn("EasBotAgent already initialized");return}N.info("initializing EasBotAgent internals");try{await this.initializeExecutor(),this.config.acpServerConfig||await this.initializeAcpEventBridge(),this.isAgentInitialized=!0,this.setStatus("ready"),N.info("EasBotAgent internals initialized successfully");}catch(t){throw this.setStatus("error"),N.error("failed to initialize EasBotAgent",{error:utils.errorMeta(t)}),t}}async start(){if(this.status==="running"){N.warn("EasBotAgent already running");return}this.isAgentInitialized||await this.initializeAgent();let t=this.config;t.acpServerConfig&&!this.server&&(this.server=await Qe(this,t.acpServerConfig)),this.setStatus("running"),N.info("EasBotAgent started");}async stop(){if(this.status==="stopped"){N.warn("EasBotAgent already stopped");return}N.info("stopping EasBotAgent");try{this.server&&(await Ke(this.server),this.server=null),this.acpEventBridge&&(await this.acpEventBridge.stop(),this.acpEventBridge=null),await this.dispose(),this.setStatus("stopped"),this.isAgentInitialized=!1,N.info("EasBotAgent stopped successfully");}catch(t){throw this.setStatus("error"),N.error("error stopping EasBotAgent",{error:utils.errorMeta(t)}),t}}async initializeAcpEventBridge(){if(this.acpEventBridge){N.warn("ACP event bridge already initialized");return}let n=this.config.acp?.sdk,r=this.getConnection();if(!n)throw N.error("Cannot initialize ACP event bridge: missing SDK client"),new utils.NameErrors.MissingFieldError({message:"SDK client is required for ACP event bridge",field:"sdk"});if(!r)throw N.error("Cannot initialize ACP event bridge: missing ACP connection"),new utils.NameErrors.MissingFieldError({message:"ACP connection is required for ACP event bridge",field:"acpConnection"});this.acpEventBridge=new j(n,r),this.acpEventBridge.setService(this),await this.acpEventBridge.start(),N.info("ACP event bridge initialized");}getServiceMode(){return this.serviceMode}getServerInstance(){return this.server}getSDK(){return this.sdk}};var F=utils.Log.create({service:"acp.bootstrap.gateway"}),et=6e4;function en(s){if(s.channel===chunkDX35VSAT_cjs.b.WS){let t=s.ws?.url??chunkSNWAB3QJ_cjs.t({channel:"websocket",hostname:s.hostname,port:s.port});return t?t.includes("/acp")?t:`${t.replace(/\/$/,"")}/acp`:`unknown://${s.hostname}:${s.port}`}return s.channel===chunkDX35VSAT_cjs.b.HTTP&&s.http?.baseUrl?s.http.baseUrl:chunkSNWAB3QJ_cjs.t({channel:s.channel,hostname:s.hostname,port:s.port})??`unknown://${s.hostname}:${s.port}`}var ie=null;async function tt(s){if(s.channel===chunkDX35VSAT_cjs.b.STDIO)return F.debug("Skipping gateway registration for stdio mode"),false;let e=chunk663BEBE4_cjs.l();if(!e)return F.debug("No gateway URL configured, skipping registration"),false;if(!e.autoRegister)return F.debug("Gateway auto-registration disabled, skipping registration"),false;if(ie)return F.debug("Gateway registration already active, skipping"),false;let t=s.agentId||utils.Identifier.ascending("agent"),n=s.name||"ACP Agent",r=en(s),o={client:null,agentId:t,cycleTimer:null,registered:false,epoch:0,registerChain:Promise.resolve(),attemptRegister:async()=>{},active:true};ie=o;let d=async()=>{if(!o.active)throw new utils.NameErrors.OperationFailedError({operation:"acp-gateway-register",message:"Registration session is no longer active"});if(o.client.getState()!=="connected")throw new utils.NameErrors.OperationFailedError({operation:"acp-gateway-register",message:"Gateway not connected"});await o.client.registerAgent({agentId:t,name:n,address:r,capabilities:[s.channel],metadata:{hostname:s.hostname,port:s.port,channel:s.channel}});},p=async()=>{!o.active||o.registered||o.client.getState()==="connected"&&(o.registerChain=o.registerChain.then(async()=>{if(!o.active||o.registered||o.client.getState()!=="connected")return;let h=o.epoch;try{if(await d(),h!==o.epoch){F.debug("Discarding stale registration result",{agentId:t,epochAtStart:h,epoch:o.epoch});return}o.registered=!0,F.info("Registered to gateway",{agentId:t,agentName:n,address:r});}catch(b){o.registered=false,F.errorDegradable("Agent registration failed, will retry on next cycle",{error:utils.errorMeta(b),agentId:t});}}),await o.registerChain);};o.attemptRegister=p;let l=h=>{o.active&&(h==="connected"?(o.epoch+=1,o.registered=false,p(),tn(o)):h==="disconnected"&&(o.registered=false));};return o.client=new utils.GatewayClient({baseUrl:e.url,type:"acp",id:`acp-${t}`,heartbeat:{enabled:true,interval:et},onStateChange:h=>{l(h);}}),true}function tn(s){s.cycleTimer||(s.cycleTimer=setInterval(()=>{nn(s);},et));}async function nn(s){if(s.active&&s.client.getState()==="connected"){if(!s.registered){await s.attemptRegister();return}try{await s.client.agentHeartbeat(s.agentId);}catch(e){F.errorDegradable("Agent heartbeat failed",{error:utils.errorMeta(e)});}}}function sn(s){s.cycleTimer&&(clearInterval(s.cycleTimer),s.cycleTimer=null);}async function nt(){let s=ie;if(s){s.active=false,ie=null,sn(s);try{await s.client.deregisterAgent(s.agentId),F.debug("Agent deregistered from gateway",{agentId:s.agentId});}catch(e){F.errorDegradable("Failed to deregister agent",{error:utils.errorMeta(e)});}try{await s.client.disconnect();}catch(e){F.errorDegradable("Failed to disconnect from gateway",{error:utils.errorMeta(e)});}}}function So(){return ie!==null}function st(s,e,t){return new chunkSNWAB3QJ_cjs.c.AdapterEnvironmentInitializationError({message:s,stage:e},t?{cause:t}:void 0)}var K=utils.Log.create({service:"acp.bootstrap"}),rt=utils.State.holder(()=>{try{let s=chunk663BEBE4_cjs.f().directory;return s?utils.Filesystem.normalize(s):"__acp_bootstrap_global__"}catch{return "__acp_bootstrap_global__"}},async()=>({initialized:false,initPromise:null,instancePromise:null,handlersInstalled:false,unhandledRejectionHandler:null,uncaughtExceptionHandler:null,stdinDataHandler:null,stdinEndHandler:null,stdinErrorHandler:null,directory:".easbot",sdk:null,activeChannel:null,agent:null,acpConnection:null}),async s=>{let e=s.agent;e&&await e.stop().catch(()=>{}),it(s),at(s),s.agent=null,s.sdk=null,s.acpConnection=null;});async function $(){return rt.get()}function ot(s){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=s.code;return e.includes(t??"")}function ln(s){if(s.handlersInstalled)return;let e=n=>{let r=n instanceof Error?n:new Error(utils.errorMeta(n).message);ot(r)||K.error("unhandled promise rejection",{error:utils.errorMeta(r)});},t=n=>{ot(n)||(K.error("uncaught exception",{error:utils.errorMeta(n)}),process.exit(1));};process.on("unhandledRejection",e),process.on("uncaughtException",t),s.unhandledRejectionHandler=e,s.uncaughtExceptionHandler=t,s.handlersInstalled=true;}function it(s){s.handlersInstalled&&(s.unhandledRejectionHandler&&(process.off("unhandledRejection",s.unhandledRejectionHandler),s.unhandledRejectionHandler=null),s.uncaughtExceptionHandler&&(process.off("uncaughtException",s.uncaughtExceptionHandler),s.uncaughtExceptionHandler=null),s.handlersInstalled=false);}function at(s){s.stdinDataHandler&&(process.stdin.off("data",s.stdinDataHandler),s.stdinDataHandler=null),s.stdinEndHandler&&(process.stdin.off("end",s.stdinEndHandler),s.stdinEndHandler=null),s.stdinErrorHandler&&(process.stdin.off("error",s.stdinErrorHandler),s.stdinErrorHandler=null);try{process.stdin.pause();}catch{}}async function un(s){return s.instancePromise||(s.instancePromise=(async()=>{let e=chunk663BEBE4_cjs.f();(!e.directory||e.directory===process.cwd())&&chunk663BEBE4_cjs.d({directory:s.directory,worktree:s.directory}),K.debug("instance bootstrap completed",{directory:s.directory});})()),s.instancePromise}async function pn(){try{chunk663BEBE4_cjs.e(),K.debug("instance adapter reset");}catch(s){K.debug("instance dispose skipped",{error:utils.errorMeta(s)});}}exports.w=void 0;(y=>{async function s(c,i){if(c.sdk)return c.sdk;let{getSdk:g}=await import('./interfaces-CGLEY6OS.cjs');return c.sdk=await g(),c.sdk}function e(c){switch(c){case chunkDX35VSAT_cjs.b.STDIO:return "stdio";case chunkDX35VSAT_cjs.b.HTTP:return "http";case chunkDX35VSAT_cjs.b.WS:return "websocket";default:return "stdio"}}function t(){rt.clear();}y.resetState=t;async function n(c){let i=await $();if(i.initialized)return;if(i.initPromise)return i.initPromise;let g={directory:c?.directory??".easbot",initModels:c?.initModels??true,printLogs:c?.printLogs??false,logLevel:c?.logLevel??"INFO",channel:c?.channel??chunkDX35VSAT_cjs.b.STDIO};if(i.directory=g.directory,await s(i,i.directory),i.activeChannel&&i.activeChannel!==g.channel)throw new utils.NameErrors.OperationFailedError({message:`Adapter already initialized with channel ${i.activeChannel}, cannot re-init with ${g.channel}`,operation:"adapter-init"});return i.activeChannel=g.channel,i.initPromise=(async()=>{try{ln(i);}catch(a){throw st("Failed to install unhandled exception handlers","handlers",a instanceof Error?a:void 0)}try{await un(i);}catch(a){throw st("Failed to initialize instance","instance",a instanceof Error?a:void 0)}try{await chunk6VF3MZ6H_cjs.r.init();}catch(a){K.warn("AcpCache init failed, falling back to lazy load",{error:utils.errorMeta(a)});}utils.ConfigFileWatcher.init(),chunkOQH5ALTQ_cjs.a.init(),i.initialized=true;})(),i.initPromise}y.init=n;async function r(){let c=await $();c.initialized&&(c.agent&&(await c.agent.stop().catch(()=>{}),c.agent=null),await nt(),it(c),at(c),await pn(),c.initialized=false,c.initPromise=null,c.instancePromise=null,c.activeChannel=null,c.sdk=null,c.agent=null,c.acpConnection=null);}y.destroy=r;async function o(){return (await $()).initialized}y.isInitialized=o;async function d(c){let i=await $();i.agent=c;}y.setAgent=d;async function p(){return (await $()).agent}y.getAgent=p;async function l(){let i=(await $()).agent?.getServerInstance();return i||null}y.getServer=l;async function h(){return (await $()).sdk}y.getSDK=h;async function b(){return (await $()).acpConnection}y.getACPConnection=b;async function I(){let c=await $(),i=!!c.agent?.getServerInstance();return {initialized:c.initialized,directory:c.directory,activeChannel:c.activeChannel,hasSDK:!!c.sdk,hasAgent:!!c.agent,hasACPConnection:!!c.acpConnection,hasServer:i}}y.getState=I;async function C(c){await n({channel:c.channel,directory:c.directory});let i=await $(),g=await s(i,i.directory);if(c.channel===chunkDX35VSAT_cjs.b.STDIO)return x({directory:c.directory});if(i.agent?.getServerInstance()&&i.activeChannel&&i.activeChannel!==c.channel)throw new utils.NameErrors.OperationFailedError({message:`ACP service already started with channel ${i.activeChannel}, cannot switch to ${c.channel}`,operation:"adapter-switch-channel"});if(i.agent){let P=i.agent.getServerInstance();if(P)return {sdk:g,agent:i.agent,server:P}}let u=await re.create({serviceMode:e(c.channel),acp:{sdk:g},acpServerConfig:c,channel:{type:c.channel,timeout:c.timeout}});await u.start();let m=u.getServerInstance();if(!m)throw new utils.NameErrors.OperationFailedError({message:"ACP server failed to start",operation:"acp-server-start"});return i.agent=u,i.activeChannel=c.channel,await tt(c),{sdk:g,agent:u,server:m}}y.ensureACPService=C;async function x(c){await n({channel:chunkDX35VSAT_cjs.b.STDIO,directory:c.directory});let i=await $(),g=await s(i,i.directory);if(i.agent)return {sdk:g,agent:i.agent};let a=new WritableStream({write(f){return new Promise((v,S)=>{try{process.stdout.write(f)?v():process.stdout.once("drain",v);}catch(_){let k=_;k.code==="EPIPE"||k.code==="EIO"?S(new Error("stdout pipe broken")):S(_);}})}}),u=new ReadableStream({start(f){i.stdinDataHandler=v=>{try{f.enqueue(new Uint8Array(v));}catch{}},i.stdinEndHandler=()=>{try{f.close();}catch{}},i.stdinErrorHandler=v=>{try{f.error(v);}catch{}},process.stdin.on("data",i.stdinDataHandler),process.stdin.on("end",i.stdinEndHandler),process.stdin.on("error",i.stdinErrorHandler);}}),m=sdk.ndJsonStream(a,u),P=await re.create({serviceMode:chunkDX35VSAT_cjs.b.STDIO,acp:{sdk:g},channel:{type:chunkDX35VSAT_cjs.b.STDIO,timeout:3e5},stdioStream:{stream:m}});return i.acpConnection=P.getConnection()??null,await P.start(),i.agent=P,i.activeChannel=chunkDX35VSAT_cjs.b.STDIO,K.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:g,agent:P}}y.ensureACPServiceStdio=x;})(exports.w||(exports.w={}));var Oo=exports.w;
|
|
8
|
-
exports.a=j;exports.c=St;exports.d=le;exports.e=ye;exports.f=ue;exports.g=L;exports.h=qe;exports.i=xt;exports.j=Le;exports.k=as;exports.l=X;exports.m=je;exports.n=Ve;exports.o=Qe;exports.p=Ls;exports.q=re;exports.r=en;exports.s=tt;exports.t=nt;exports.u=So;exports.v=st;exports.x=Oo;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkPCEPFPJO_cjs=require('./chunk-PCEPFPJO.cjs');require('./chunk-SNWAB3QJ.cjs'),require('./chunk-DX35VSAT.cjs'),require('./chunk-ISDIC2R6.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkPCEPFPJO_cjs.k}});Object.defineProperty(exports,"handleAcpCli",{enumerable:true,get:function(){return chunkPCEPFPJO_cjs.o}});Object.defineProperty(exports,"mergeStartServerConfig",{enumerable:true,get:function(){return chunkPCEPFPJO_cjs.n}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkPCEPFPJO_cjs.l}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkPCEPFPJO_cjs.m}});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{k as COMMANDS_HELP,o as handleAcpCli,n as mergeStartServerConfig,l as renderBanner,m as renderHelp}from'./chunk-SWK2ITXO.mjs';import'./chunk-B3ANZALB.mjs';import'./chunk-33M2R2US.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkDX35VSAT_cjs=require('./chunk-DX35VSAT.cjs');require('./chunk-ISDIC2R6.cjs');Object.defineProperty(exports,"AgentErrorSchema",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.f}});Object.defineProperty(exports,"AgentEventType",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.h}});Object.defineProperty(exports,"AgentMessageSchema",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.e}});Object.defineProperty(exports,"AgentStartedSchema",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.c}});Object.defineProperty(exports,"AgentStatus",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.a}});Object.defineProperty(exports,"AgentStatusSchema",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.g}});Object.defineProperty(exports,"AgentStoppedSchema",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.d}});Object.defineProperty(exports,"ChannelType",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.b}});
|