@easbot/acp 0.0.0-stage → 0.3.32
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/LICENSE +21 -0
- package/README.en.md +522 -0
- package/README.md +667 -2
- package/dist/chunks/bootstrap-GGS3N5CF.cjs +1 -0
- package/dist/chunks/bootstrap-MZQICOGZ.mjs +1 -0
- package/dist/chunks/cache-3R3ORBTY.cjs +1 -0
- package/dist/chunks/cache-76CBF3LU.mjs +1 -0
- package/dist/chunks/chunk-2KOCPHVP.mjs +1 -0
- package/dist/chunks/chunk-33M2R2US.mjs +1 -0
- package/dist/chunks/chunk-3DHMW4DB.mjs +11 -0
- package/dist/chunks/chunk-5HWD3B3N.cjs +11 -0
- package/dist/chunks/chunk-7RWES66A.cjs +2 -0
- package/dist/chunks/chunk-B3ANZALB.mjs +2 -0
- package/dist/chunks/chunk-BNSJ6COS.cjs +1 -0
- package/dist/chunks/chunk-D4TSQ2TT.mjs +0 -0
- package/dist/chunks/chunk-D7S7ARXV.mjs +8 -0
- package/dist/chunks/chunk-DX35VSAT.cjs +1 -0
- package/dist/chunks/chunk-HQBRVVXS.mjs +1 -0
- package/dist/chunks/chunk-ITV7SWGU.cjs +8 -0
- package/dist/chunks/chunk-JLO7UYKQ.cjs +1 -0
- package/dist/chunks/chunk-M2YU5LAI.cjs +1 -0
- package/dist/chunks/chunk-NHXAYBZH.mjs +1 -0
- package/dist/chunks/chunk-PATHHDWE.mjs +1 -0
- package/dist/chunks/chunk-RHW6YR3D.mjs +2 -0
- package/dist/chunks/chunk-SNWAB3QJ.cjs +2 -0
- package/dist/chunks/chunk-VVGGER23.cjs +1 -0
- package/dist/chunks/chunk-Z3YEK7DD.cjs +1 -0
- package/dist/chunks/cli-handler-6XB6B5DV.mjs +1 -0
- package/dist/chunks/cli-handler-IU3YUTOU.cjs +1 -0
- package/dist/chunks/config-FTGKCGYZ.mjs +1 -0
- package/dist/chunks/config-ZVDYJ7TW.cjs +1 -0
- package/dist/chunks/interfaces-6ZCF5T55.cjs +1 -0
- package/dist/chunks/interfaces-TXNKX4HT.mjs +1 -0
- package/dist/chunks/loader-3KX33KJQ.cjs +1 -0
- package/dist/chunks/loader-6HBCWO6Y.mjs +1 -0
- package/dist/chunks/types-BZWPIPG6.mjs +1 -0
- package/dist/chunks/types-R3VOD4XE.cjs +1 -0
- package/dist/cli.cjs +2 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +2 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +2030 -0
- package/dist/index.d.ts +2030 -0
- package/dist/index.mjs +1 -0
- package/package.json +87 -3
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
'use strict';var chunkSNWAB3QJ_cjs=require('./chunk-SNWAB3QJ.cjs'),chunkDX35VSAT_cjs=require('./chunk-DX35VSAT.cjs'),chunkBNSJ6COS_cjs=require('./chunk-BNSJ6COS.cjs'),chunkVVGGER23_cjs=require('./chunk-VVGGER23.cjs'),chunkZ3YEK7DD_cjs=require('./chunk-Z3YEK7DD.cjs'),chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),fs=require('fs'),nt=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 nt__default=/*#__PURE__*/_interopDefault(nt);var R=utils.Log.create({service:"acp.event.bridge"}),j=class{constructor(e,t){chunkM2YU5LAI_cjs.a(this,"sdk");chunkM2YU5LAI_cjs.a(this,"connection");chunkM2YU5LAI_cjs.a(this,"abortController",null);chunkM2YU5LAI_cjs.a(this,"started",false);chunkM2YU5LAI_cjs.a(this,"permissionQueues",new Map);chunkM2YU5LAI_cjs.a(this,"_messageMetaCache",new Map);chunkM2YU5LAI_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"}]);chunkM2YU5LAI_cjs.a(this,"acpService");chunkM2YU5LAI_cjs.a(this,"_cachedPrimaryAgents",null);this.sdk=e,this.connection=t;}setService(e){this.acpService=e;}async start(){if(this.started){R.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,R.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||R.error("event subscription failed",{error:utils.errorMeta(e)});});}async stop(){this.started&&(R.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.permissionQueues.clear(),this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,R.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 s=n?.payload;s&&await this.handleEvent(s).catch(i=>{R.error("failed to handle event",{error:utils.errorMeta(i),type:s.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){R.warn("No connection available to publish session status");return}try{await this.connection.extNotification("session_status_update",{sessionId:t,status:n});}catch(s){R.error("Failed to publish session status via extNotification",{sessionId:t,status:n,error:utils.errorMeta(s)});}n.type==="idle"&&(this.permissionQueues.delete(t),this.clearMessageMetaCache(t));}async handleSessionDeleted(e){let{sessionId:t}=e;if(!this.connection){R.warn("No connection available to notify session deletion");return}if(typeof t!="string"||t.length===0){R.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){R.error("Failed to notify session deletion to client",{sessionId:t,error:utils.errorMeta(n)});}}async handlePermissionAsked(e){let{id:t,sessionId:n,permission:s,tool:i,metadata:d}=e,l=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let C=s==="external_directory"&&d?.tool?ge(d.tool):ge(s),E=s==="external_directory"&&d?.tool?me(d.tool,d):me(s,d),I=await this.connection.requestPermission({sessionId:n,toolCall:{callId:i?.callId??t,status:"pending",title:s,rawInput:d,kind:C,locations:(E??[]).map(v=>v.path)},options:this.permissionOptions}).catch(async v=>{R.error("failed to request permission from ACP",{error:utils.errorMeta(v),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"&&s==="edit"){let v=d?.filepath??d?.filePath??"",x=d?.diff??"";if(v&&x){let y=utils.PKG.file(v),c=await y.exists()?await y.text():"",r=ot(c,x);r&&await this.connection.extMethod("client.writeTextFile",{sessionId:n,path:v,content:r});}}await this.sdk.permission.reply({requestId:t,reply:I.outcome.optionId});}}).catch(C=>{R.error("failed to handle permission",{error:utils.errorMeta(C),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:s}=e;R.debug("Handling question asked in ACP bridge",{requestId:t,sessionId:n,questionCount:s.length});try{let i=await this.connection.extMethod("client.requestQuestion",{sessionId:n,requestId:t,questions:s});if(!i){R.warn("Question request returned no result"),await this.sdk.question.reject({requestId:t});return}i.outcome==="selected"&&i.answers&&i.answers.length>0?await this.sdk.question.reply({requestId:t,answers:i.answers.map(d=>[d.answer])}):await this.sdk.question.reject({requestId:t});}catch(i){R.error("Failed to handle question via extMethod",{error:utils.errorMeta(i),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:s,state:i,messageId:d}=e;if(!t){R.debug("AcpEventBridge: skipping tool part without sessionId",{callId:n,tool:s,messageId:d});return}let g=ge(s);switch(i.status){case "pending":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:s,kind:g,status:"pending",locations:[],rawInput:{},_meta:{messageId:d}}}).catch(l=>{R.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:g,title:s,locations:me(s,i.input),rawInput:i.input,_meta:{messageId:d}}}).catch(l=>{R.error("failed to send tool in_progress to ACP",{error:utils.errorMeta(l)});});return;case "completed":{let l=[{type:"content",content:{type:"text",text:i.output}}];if(g==="edit"){let C=i.input,E=C.filePath??C.filepath??"",I=C.oldString??"",v=C.newString??C.content??"";l.push({type:"diff",path:E,oldText:I,newText:v});}if(s==="todo"){let C=types.TodoListSchema.safeParse(JSON.parse(i.output));C.success&&i.input.operation==="write"&&await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:C.data.map(E=>{let I=E.status==="cancelled"?"completed":E.status;return {priority:E.priority,status:I,content:E.content}})}}).catch(E=>{R.error("failed to send session update for todo",{error:utils.errorMeta(E)});});}await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:g,content:l,title:i.title??s,rawInput:i.input,rawOutput:{output:i.output,metadata:i.metadata},_meta:{messageId:d}}}).catch(C=>{R.error("failed to send tool completed to ACP",{error:utils.errorMeta(C)});});return}case "failed":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:g,title:s,rawInput:i.input,content:[{type:"content",content:{type:"text",text:i.error}}],rawOutput:{error:i.error},_meta:{messageId:d}}}).catch(l=>{R.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){R.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 s=e.text;s&&await this.connection.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_message_chunk",messageId:e.messageId,content:{type:"text",text:s}}}).catch(i=>{R.error("failed to send text to ACP",{error:utils.errorMeta(i)});});}async handleReasoningPart(e,t){if(!e.sessionId){R.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 s=e.text;s&&await this.connection.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_thought_chunk",messageId:e.messageId,content:{type:"text",text:s}}}).catch(i=>{R.error("failed to send reasoning to ACP",{error:utils.errorMeta(i)});});}async handleStepFinishPart(e){let{sessionId:t,messageId:n,tokens:s}=e;if(!this.connection)return;if(!t){R.debug("AcpEventBridge: skipping step-finish part without sessionId",{messageId:n});return}let i=(s?.input??0)+(s?.reasoning??0),d=await this.getContextLimit(t,n);await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:i,size:d,_meta:{messageId:n}}}).catch(g=>{R.error("failed to send usage_update for step-finish",{error:utils.errorMeta(g)});});}async getContextLimit(e,t){try{let s=(await this.sdk.session.messages({sessionId:e}).then(i=>i.data).catch(()=>{}))?.find(i=>i.info.id===t);if(s){let i=s.info;if(i.providerId&&i.modelId)return (await this.sdk.config.providers({}).then(C=>C.data?.providers??[]).catch(()=>[])).find(C=>C.id===i.providerId)?.models[i.modelId]?.limit?.context??2e5}}catch(n){R.errorDegradable("failed to get context limit",{error:utils.errorMeta(n)});}return 2e5}async getMessageMeta(e,t){let n=`${e}:${t}`,s=this._messageMetaCache.get(n);if(s)return s;let i=await this.sdk.session.message({sessionId:e,messageId:t},{throwOnError:true}).then(g=>g.data).catch(g=>{g instanceof Error&&g.name!=="NotFoundError"&&R.error("unexpected error when fetching message",{error:utils.errorMeta(g),sessionId:e,messageId:t});});if(!i)return;let d={role:i.info.role,agent:i.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(s=>s.mode==="primary"&&s.hidden!==!0).map(s=>s.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(e)}};function ge(o){switch(o.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 me(o,e){if(!e)return [];switch(o.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(),s=e.filepath??"",i=e.realPath??"",d=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return i?[{path:i}]:s?[{path:s}]:[];if(n==="list"||n==="glob"||n==="grep"){let l=i??s,C=l?nt__default.default.posix.dirname(l):d;return C?[{path:C}]:[]}let g=i??s;return g?[{path:g}]:d?[{path:d}]:[]}default:return []}}function ot(o,e){try{let t=diff.applyPatch(o,e);return t===!1?null:t}catch{return null}}var K=utils.Log.create({service:"acp.connection.registry"});exports.b=void 0;(r=>{let o=null;async function e(){return o||(o=await c.create()),o}async function t(p){return o||(o=await c.create(p),K.info("ServerConnectionRegistry initialized")),o}r.init=t;async function n(p){return (await e()).connect(p.baseUrl,p.localAgentId,p.remoteAgentId,p.remoteSessionId,p.localSessionId)}r.connect=n;async function s(p){return (await e()).resolve(p)}r.resolve=s;function i(p){if(o)return o.resolve(p)}r.resolveSync=i;async function d(p){(await e()).closeConnection(p);}r.close=d;async function g(p,a){(await e()).markDegraded(p,a);}r.markDegraded=g;async function l(p){return (await e()).getConnectionsByAgent(p)}r.getConnectionsByLocalAgent=l;async function C(p){return (await e()).getConnectionsByService(p)}r.getConnectionsByService=C;async function E(){return (await e()).getAllActiveConnections()}r.getAllActiveConnections=E;async function I(p,a){(await e()).updateLastSeenMessageId(p,a);}r.updateLastSeenMessageId=I;async function v(p,a){(await e()).updateSessionUpdates(p,a);}r.updateSessionUpdates=v;async function x(p,a){let u=await e(),m=u.resolve(p);m&&u.updateSessionUpdates(m.connectionId,a);}r.updateSessionUpdatesBySessionId=x;function y(p){if(o)return o.findConnectionIdBySubscriber(p)}r.findConnectionIdBySubscriber=y;class c{constructor(a){chunkM2YU5LAI_cjs.a(this,"defaultHistoryScope");chunkM2YU5LAI_cjs.a(this,"defaultHistoryWindowSize");chunkM2YU5LAI_cjs.a(this,"defaultDegradePolicy");chunkM2YU5LAI_cjs.a(this,"agentIndex",new Map);chunkM2YU5LAI_cjs.a(this,"serviceIndex",new Map);chunkM2YU5LAI_cjs.a(this,"connections",new Map);this.defaultHistoryScope=a?.defaultHistoryScope??"session",this.defaultHistoryWindowSize=a?.defaultHistoryWindowSize??10,this.defaultDegradePolicy=a?.defaultDegradePolicy??"streaming_first",K.debug("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(a){return new c(a)}connect(a,u,m,w,f){let S=this.agentIndex.get(u);if(S)for(let M of S){let b=this.connections.get(M);if(b&&b.baseUrl===a&&b.status!=="closed")return w&&b.sessionId!==w&&(b.sessionId=w,b.sessionSequence=b.sessionSequence??[],b.sessionSequence.includes(w)||b.sessionSequence.push(w),b.remoteSessionStatus="idle"),f&&(b.localSessionId=f),b.updatedAt=Date.now(),{connectionId:b.connectionId,sessionId:b.sessionId,localAgentId:b.localAgentId,remoteAgentId:b.remoteAgentId,baseUrl:b.baseUrl}}let h=this.generateConnectionId(),_=w??`session-${this.generateShortId()}`,k={localAgentId:u,remoteAgentId:m,connectionId:h,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(h,k),this.agentIndex.has(u)||this.agentIndex.set(u,new Set),this.agentIndex.get(u).add(h),this.serviceIndex.has(a)||this.serviceIndex.set(a,new Set),this.serviceIndex.get(a).add(h),{connectionId:h,sessionId:_,localAgentId:u,remoteAgentId:m,baseUrl:a}}resolve(a,u=false){let m=this.connections.get(a);if(m)return m;let w=this.agentIndex.get(a);if(w&&w.size>0)for(let f of w){let S=this.connections.get(f);if(S&&S.status!=="closed")return S}for(let f of this.connections.values())if(f.status!=="closed"&&(f.sessionId===a||f.localSessionId===a))return f;if(u){let h=this.connect("http://localhost","system-local","system-remote",a);return this.connections.get(h.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 w=this.serviceIndex.get(u.baseUrl);w&&(w.delete(a),w.size===0&&this.serviceIndex.delete(u.baseUrl)),K.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(),K.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(),K.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(),o=null,K.info("connection registry closed");}}r.ConnectionRegistry=c;})(exports.b||(exports.b={}));var $=utils.Log.create({service:"acp.connection.router"}),ct=(i=>(i.EMPTY_CONTEXT="EMPTY_CONTEXT",i.AMBIGUOUS_ROUTE="AMBIGUOUS_ROUTE",i.NOT_FOUND="NOT_FOUND",i.CONNECTION_CLOSED="CONNECTION_CLOSED",i.MISSING_REQUIRED_PARAMS="MISSING_REQUIRED_PARAMS",i))(ct||{});function re(o,e,t){return new chunkSNWAB3QJ_cjs.c.RoutingError({message:e,code:o,context:t})}var fe=class o{static create(){return new o}constructor(){$.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 $.error("routing failed",{context:e,error:utils.errorMeta(t)}),{success:false,error:n}}}routeOrThrow(e){let t=this.route(e);if(!t.success)throw re(this.getErrorCode(t.error),t.error??"routing failed",e);if(!t.connectionId)throw re("NOT_FOUND","connection not found",e);let n=this.getConnectionState(t.connectionId);if(!n)throw re("NOT_FOUND","connection state not found",e);if(n.status==="closed")throw re("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"}:($.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?($.debug("connection unregistered",{connectionId:e,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}),true):($.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 s=this.getConnectionsByPeer(e).filter(d=>d.baseUrl===t&&d.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for localAgentId=${e}, baseUrl=${t}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${e}, baseUrl=${t}`};let i=s[0];return {success:true,connectionId:i.connectionId,sessionId:i.sessionId,localAgentId:i.localAgentId,remoteAgentId:i.remoteAgentId,baseUrl:i.baseUrl}}routeByBaseUrlAndSessionId(e,t){let s=this.getConnectionsByService(e).filter(d=>d.sessionId===t&&d.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for baseUrl=${e}, sessionId=${t}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${e}, sessionId=${t}`};let i=s[0];return {success:true,connectionId:i.connectionId,sessionId:i.sessionId,localAgentId:i.localAgentId,remoteAgentId:i.remoteAgentId,baseUrl:i.baseUrl}}getConnectionState(e){$.warn("getConnectionState not implemented, returning undefined",{connectionId:e});}getConnectionsByPeer(e){return $.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:e}),[]}getConnectionsByService(e){return $.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"}},ae=class o extends fe{constructor(t){super();chunkM2YU5LAI_cjs.a(this,"registry");this.registry=t,$.info("registry session router created");}static fromRegistry(t){return new o(t)}getConnectionState(t){return this.registry.resolve(t)}getConnectionsByPeer(t){return this.registry.getConnectionsByPeer(t)}getConnectionsByService(t){return this.registry.getConnectionsByService(t)}};var he=["general","coder"],xe="general";var ce=utils.Log.create({service:"acp.session"}),Z=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"sessions",new Map);chunkM2YU5LAI_cjs.a(this,"sdk");this.sdk=e;}tryGet(e){return this.sessions.get(e)}async create(e,t,n,s){let d={id:e,cwd:t,mcpServers:n,createdAt:new Date,model:s};return ce.info("creating_session",{state:d}),this.sessions.set(e,d),d}async load(e,t,n,s){let i=await this.sdk.session.get({sessionId:e},{throwOnError:true}).then(l=>l.data),d=s,g={id:e,cwd:t,mcpServers:n,createdAt:new Date(i.time.created),model:d};return ce.debug("loading_session",{state:g}),this.sessions.set(e,g),g}get(e){let t=this.sessions.get(e);if(!t)throw ce.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(),ce.debug("all sessions cleared");}resolveConnectionState(e){}};var A=utils.Log.create({service:"acp.acp.service"}),X=class{constructor(e,t){chunkM2YU5LAI_cjs.a(this,"config");chunkM2YU5LAI_cjs.a(this,"serviceMode");chunkM2YU5LAI_cjs.a(this,"connection");chunkM2YU5LAI_cjs.a(this,"sdk");chunkM2YU5LAI_cjs.a(this,"connectionRegistry",null);chunkM2YU5LAI_cjs.a(this,"sessionRouter",null);chunkM2YU5LAI_cjs.a(this,"sessionManager");chunkM2YU5LAI_cjs.a(this,"executorInitialized",false);chunkM2YU5LAI_cjs.a(this,"status","initializing");this.connection=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.sessionManager=new Z(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=ae.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,s=(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 g=await this.sessionManager.create(d,t,e.mcpServers,s),l=await this.buildSessionStateResponse(g.id,t);return {sessionId:g.id,...l,_meta:{}}}async loadSession(e){A.debug("ACP loadSession requested",{sessionId:e.sessionId});let t=e.cwd,s=(await this.sdk.model.default())?.data;return await this.sessionManager.load(e.sessionId,t,e.mcpServers,s),{...await this.buildSessionStateResponse(e.sessionId,t),_meta:{}}}async prompt(e){let t=e.sessionId,n=this.sessionManager.get(t),s=n.cwd,i=e._meta??{},d=typeof i.agent=="string"&&i.agent?i.agent:void 0,g=typeof i.model=="string"&&i.model?utils.parseModelId(i.model):void 0,l=n.model,C=g?.providerId?{providerId:g.providerId,modelId:g.modelId}:g?.modelId?{providerId:l?.providerId??"",modelId:g.modelId}:l??(await this.sdk.model.default())?.data,E=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:s,error:utils.errorMeta(y)});});let I=[];for(let y of e.prompt)switch(y.type){case "text":{let c=y.annotations?.audience,r=c?.length===1&&c[0]==="assistant",p=c?.length===1&&c[0]==="user";I.push({type:"text",text:y.text,...r&&{synthetic:true},...p&&{ignored:true}});break}case "image":{let c=this.parseUri(y.uri??""),r=c.type==="file"?c.filename:"image";y.data?I.push({type:"file",url:`data:${y.mimeType};base64,${y.data}`,filename:r,mime:y.mimeType}):y.uri?.startsWith("http:")&&I.push({type:"file",url:y.uri,filename:r,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 r=this.parseUri(c.uri??""),p=r.type==="file"?r.filename:"file";I.push({type:"file",url:`data:${c.mimeType};base64,${c.blob}`,filename:p,mime:c.mimeType});}break}}A.debug("prompt parts",{sessionId:t,parts:I});let v=(()=>{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[r,...p]=c,a=p.join(" ").trim();return A.debug("command",{name:r,args:a}),{name:r,args:a}})();if(!v)return this.sdk.session.prompt({sessionId:t,model:{providerId:C.providerId,modelId:C.modelId},parts:I,agent:E,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:v.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:v.args??"",agent:E,model:utils.formatModelId(C),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 r=await this.getContextLimit(C.providerId,C.modelId,s);r&&this.connection?.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:0,size:r}});}).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:v.args??"",agent:E,model:utils.formatModelId(C),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(v.name){case "compact":if(!C.providerId||!C.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:C.providerId,modelId:C.modelId},{throwOnError:true});break}return await this.sendUsageUpdate(t,s),{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(s=>{A.warn("SDK abort failed",{sessionId:e.sessionId,error:utils.errorMeta(s)});}),A.debug("Session cancelled",{sessionId:e.sessionId});}catch(s){throw A.error("Failed to cancel session",{sessionId:e.sessionId,error:utils.errorMeta(s)}),s}}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 s=n.split("/").pop()||n;return {type:"file",url:url.pathToFileURL(n).href,filename:s,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(C=>C.data).catch(C=>{A.error("failed to fetch messages for usage update",{error:utils.errorMeta(C)});});if(!n)return;let s=n.filter(C=>C.info.role==="assistant"),i=s[s.length-1];if(!i)return;let d=i.info,g=await this.getContextLimit(d.providerId,d.modelId,t);if(!g)return;let l=d.tokens.input+(d.tokens.cache?.read??0);await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:l,size:g}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.connection){if(!e){A.debug("sendAvailableCommandsUpdate: skipping, sessionId is empty");return}try{let s=this.sessionManager.get(e)?.contextMode,d=(await this.sdk.command.list({contextMode:s},{throwOnError:!0})).data?.filter(g=>!g.hidden).map(g=>({name:g.name,description:g.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 i=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!i||i.length===0)return;await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:i}});}catch(s){A.error("failed to send config_option_update to ACP client",{sessionId:e,error:utils.errorMeta(s)});}}}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(g=>g.data?.providers??[]).catch(g=>(A.error("failed to get providers for context limit",{error:utils.errorMeta(g)}),[]))).find(g=>g.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??[],i=(await this.sdk.model.default())?.data,d=await this.sdk.session.fork({sessionId:e.sessionId,directory:t},{throwOnError:true}).then(E=>E.data);if(!d)throw new utils.NameErrors.OperationFailedError({message:"Fork session returned no data",operation:"acp-session-fork"});let g=d.id;await this.sessionManager.load(g,t,n,i);let C=await this.buildSessionStateResponse(g,t);return A.debug("fork_session",{sessionId:g,mcpServers:n.length}),{sessionId:g,...C,_meta:{}}}async resumeSession(e){A.debug("ACP resumeSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.sessionId,s=e.mcpServers??[],d=(await this.sdk.model.default())?.data;await this.sessionManager.load(n,t,s,d);let l=await this.buildSessionStateResponse(n,t);return A.debug("resume_session",{sessionId:n,mcpServers:s.length}),{...l,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,i=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(I=>I.data??[])).toSorted((I,v)=>v.time.updated-I.time.updated),g=(t?i.filter(I=>I.time.updated<t):i).slice(0,n),l=g.map(I=>({sessionId:I.id,cwd:I.directory,title:I.title??`Session ${I.id}`,updatedAt:new Date(I.time.updated).toISOString()})),C=g[g.length-1],E=g.length===n&&C?String(C.time.updated):void 0;return {sessions:l,nextCursor:E}}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 s=typeof e.value=="string"?e.value:void 0;if(s){let i=this.parseModelSelection(s);this.sessionManager.setModel(e.sessionId,i.model);}}else if(e.configId==="agent"){let s=typeof e.value=="string"?e.value:void 0;this.sessionManager.setAgent(e.sessionId,s);}else if(e.configId==="thought_level"){let s=typeof e.value=="string"?e.value:void 0;this.sessionManager.setVariant(e.sessionId,s);}else if(e.configId==="context_mode"){let s=typeof e.value=="string"&&he.includes(e.value)?e.value:void 0;this.sessionManager.setContextMode(e.sessionId,s);}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),s=n?.model??(await this.sdk.model.default())?.data,i=s?.providerId&&s?.modelId?utils.formatModelId(s):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(v){A.warn("failed to build available models for session state",{sessionId:e,error:utils.errorMeta(v)});}i&&!d.some(v=>v.modelId===i)&&(d=[{modelId:i,name:i},...d]);let g=[];try{g=((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(v){A.warn("failed to build available agents for session state",{sessionId:e,error:utils.errorMeta(v)});}let l=n?.modeId,C=n?.variant??"low",E=n?.contextMode??xe,I=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e,t),{models:i?{currentModelId:i,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:i??"",options:d.map(v=>({value:v.modelId,name:v.name,description:v.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:I,options:g.map(v=>({value:v.id,name:v.name,description:v.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:C,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:E,options:he.map(v=>({value:v,name:v.charAt(0).toUpperCase()+v.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,s){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,s)}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 Me(o,e=[]){return new chunkSNWAB3QJ_cjs.c.ServiceModeConflictError({message:o,conflictingModes:e})}function ht(o){let e=[];return o.channel&&e.push(o.channel),e}function _e(o){let e=ht(o);if(e.length===0)throw Me("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw Me(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var Oe={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 Te(o){return !(!o||o.trim()===""||o.startsWith("-")||o.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(o))}function Ne(o){return Number.isInteger(o)&&o>=1&&o<=65535}function Ue(o){return Number.isFinite(o)&&o>0}function qe(o){let e={...Oe,...o};try{_e(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&&!Ne(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&&!Te(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&&!Ue(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 Ct(){let o={},e=process.env[`${V}ACP_CHANNEL`];if(e){let l=e.toLowerCase();Object.values(L).includes(l)?o.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);Ne(l)?o.port=l:B.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${V}ACP_HOSTNAME`];n&&(Te(n)?o.hostname=n:B.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let s=process.env[`${V}ACP_TIMEOUT`];if(s){let l=parseInt(s,10);Ue(l)?o.timeout=l:B.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:s});}let i=process.env[`${V}ACP_HISTORY_SCOPE`];i&&(["session","peer","global"].includes(i)?o.historyScope=i:B.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:i}));let d=process.env[`${V}ACP_HISTORY_WINDOW_SIZE`];if(d){let l=parseInt(d,10);Number.isInteger(l)&&l>0?o.historyWindowSize=l:B.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:d});}let g=process.env[`${V}ACP_DEGRADE_POLICY`];return g&&(["polling_only","streaming_first"].includes(g)?o.degradePolicy=g:B.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:g})),B.debug("Config loaded from environment",{config:o}),o}function Be(o){let e=Ct(),t={...e,...o};return B.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:o,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}var ve=utils.Log.create({service:"acp.server.rpc-handler"}),It={INTERNAL_ERROR:-32603},Y=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:s}=e;ve.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:s});try{let i;switch(t){case "initialize":i=await this.handleInitialize(n);break;case "authenticate":i=await this.handleAuthenticate(n);break;case "session.new":case "newSession":i=await this.handleNewSession(n);break;case "session.load":case "loadSession":i=await this.handleLoadSession(n);break;case "session.close":case "closeSession":i=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":i=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),i={success:!0};break;case "session.list":case "listSessions":i=await this.handleListSessions(n);break;case "session.fork":case "forkSession":i=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":i=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":i=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":i=await this.handleSetSessionConfigOption(n);break;case "status":i=this.handleStatus();break;case "subscriptions":i=this.handleSubscriptions();break;default:throw ve.warn("Unknown method",{method:t}),new utils.NameErrors.NotFoundError({message:`Method not found: ${t}`,location:"rpc-method"})}return {jsonrpc:"2.0",id:s,result:i}}catch(i){return ve.error("AcpRpcHandler error",{method:t,error:utils.errorMeta(i)}),{jsonrpc:"2.0",id:s,error:{code:It.INTERNAL_ERROR,message:utils.errorMeta(i).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 le=utils.Log.create({service:"acp.server.agent-side-connection"}),J=class{constructor(){chunkM2YU5LAI_cjs.a(this,"broadcaster",null);chunkM2YU5LAI_cjs.a(this,"sessionIds",new Set);chunkM2YU5LAI_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;le.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return le.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async extMethod(e,t){return le.debug("ServerAgentSideConnection.extMethod",{method:e}),{}}async extNotification(e,t){if(le.debug("ServerAgentSideConnection.extNotification",{method:e,params:t}),this.broadcaster&&t){let n=t.sessionId||t.sessionId;if(n&&this.sessionIds.has(n)){let s={sessionId:n,update:{sessionUpdate:e,...t}};this.broadcaster.broadcast(n,s);}}}};var z=utils.Log.create({service:"acp.server.http"});async function ze(o,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,s=new J,i={broadcast:(r,p)=>{E(r,p);}};s.setBroadcaster(i);let d=new Y(o),g=o.getSDK();if(!g)throw new utils.NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let l=new j(g,s);l.setService(o);let C=(r,p)=>{let a=t.get(r);if(!a)return false;try{return a.controller.enqueue(new TextEncoder().encode(p)),a.lastHeartbeat=Date.now(),!0}catch(u){return z.warn("Failed to push to SSE connection",{connectionId:r,error:utils.errorMeta(u)}),false}},E=(r,p)=>{let a=n.get(r);if(!a||a.size===0)return;let m={jsonrpc:"2.0",method:p.update.sessionUpdate,params:{sessionId:r,...p.update,timestamp:Date.now()}},w=`data: ${JSON.stringify(m)}
|
|
2
|
+
|
|
3
|
+
`;for(let f of a)C(f,w)||(t.delete(f),a.delete(f),s.removeSession(r));},I=(r,p)=>(s.addSession(r),new ReadableStream({start:async a=>{let u={id:p,controller:a,sessionId:r,createdAt:Date.now(),lastHeartbeat:Date.now()};t.set(p,u),n.has(r)||n.set(r,new Set),n.get(r).add(p),z.debug("SSE client connected",{connectionId:p,sessionId:r});let m=`data: ${JSON.stringify({type:"connected",connectionId:p,sessionId:r})}
|
|
4
|
+
|
|
5
|
+
`;a.enqueue(new TextEncoder().encode(m)),o.sendAvailableCommandsUpdate(r).catch(w=>{z.warn("Failed to send initial available commands update",{sessionId:r,connectionId:p,error:utils.errorMeta(w)});});},cancel:()=>{let a=t.get(p);if(a){t.delete(p);let u=n.get(a.sessionId);u&&(u.delete(p),u.size===0&&n.delete(a.sessionId)),s.removeSession(a.sessionId),z.debug("SSE client disconnected",{connectionId:p,sessionId:a.sessionId});}}})),v=null,x=()=>{v||(v=setInterval(()=>{let r=Date.now(),p=3e5;for(let[a,u]of t.entries())if(r-u.lastHeartbeat>p){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)),s.removeSession(u.sessionId);}else try{u.controller.enqueue(new TextEncoder().encode(`: heartbeat
|
|
6
|
+
|
|
7
|
+
`)),u.lastHeartbeat=r;}catch{}},1e4));},y=[{method:"post",path:"/acp",handler:async r=>{let p=await r.req.json().catch(()=>null);if(!p||typeof p!="object")return r.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}},400);let a=p;if(!a.method||a.jsonrpc!=="2.0")return r.json({jsonrpc:"2.0",error:{code:-32600,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)});}),r.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 r.json(u,200,{"Acp-Connection-Id":m})}return r.json(u)}},{method:"get",path:"/acp",handler:r=>{let p=r.req.header("Acp-Connection-Id"),a=r.req.header("Acp-Session-Id");if(!r.req.header("Accept")?.includes("text/event-stream"))return r.json({error:"Not Acceptable"},406);let m=p||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(a){let S=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,h=I(a,S);return new Response(h,{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 w=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,f=I("__connection__",w);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 r=>{let p=r.req.header("Acp-Connection-Id");return z.debug("HTTP server: connection terminated",{connectionId:p}),r.json({success:true})}}],c=utils.createServer({port:e.port,hostname:e.hostname,routes:y,timeout:e.timeout,cors:true});try{await l.start(),o.setServerConnection(s),x();}catch(r){throw z.error("HTTP server: failed to start background resources, cleaning up",{error:utils.errorMeta(r)}),await l.stop().catch(()=>{}),v&&(clearInterval(v),v=null),await c.stop().catch(()=>{}),r}return z.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:c,stop:async()=>{z.info("Stopping HTTP server"),v&&(clearInterval(v),v=null),await l.stop();for(let r of t.values())try{r.controller.close();}catch{}t.clear(),n.clear(),s.clearSessions(),await c.stop(),z.info("HTTP server stopped");}}}var H=utils.Log.create({service:"acp.server.websocket"});function kt(o){try{let e=new URL(o),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 Fe(o,e){let t=e.ws?kt(e.ws.url):void 0,n=t?.port??e.port??3e3,s=t?.hostname??e.hostname??"localhost",i="/acp";if(H.info("Starting WebSocket server",{port:n,hostname:s,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,g=new Map,l=new J,C={broadcast:(f,S)=>{x(f,S);}};l.setBroadcaster(C);let E=new Y(o),I=o.getSDK();if(!I)throw new utils.NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let v=new j(I,l);v.setService(o);let x=(f,S)=>{let _={jsonrpc:"2.0",method:S.update.sessionUpdate,params:{sessionId:f,...S.update,timestamp:Date.now()}},k=JSON.stringify(_);for(let[M,b]of g.entries())if(b.subscribedSessions.has(f)){let O=d.get(M);O&&O.ws.readyState===O.ws.OPEN&&O.ws.send(k);}},y=f=>{for(let[S,h]of d.entries())if(h.ws===f)return S},c=(f,S)=>{let h=g.get(f);h&&(h.subscribedSessions.has(S)||(h.subscribedSessions.add(S),l.addSession(S)));},r=(f,S)=>{let h=g.get(f);h&&h.subscribedSessions.has(S)&&(h.subscribedSessions.delete(S),l.removeSession(S));},p={onOpen:(f,S)=>{let h=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;d.set(h,{id:h,ws:S,createdAt:Date.now()}),g.set(h,{clientId:h,subscribedSessions:new Set}),H.debug("WebSocket client connected",{clientId:h}),S.send(JSON.stringify({type:"connected",clientId:h}));},onMessage:async(f,S)=>{try{let h=JSON.parse(f.data.toString());if(h.type==="ping"){S.send(JSON.stringify({type:"pong"}));return}let _=y(S);if(!_)return;let k,M;if(h.type==="message"||h.type==="request")k={jsonrpc:"2.0",id:h.id,method:h.method,params:h.params},M=h.sessionId;else if(h.jsonrpc==="2.0"&&h.method)k={jsonrpc:"2.0",id:h.id,method:h.method,params:h.params},M=h.params?.sessionId;else {H.warn("WebSocket server: unknown message format",{data:h});return}if(k.method==="session.subscribe"){M&&(c(_,M),o.sendAvailableCommandsUpdate(M).catch(O=>{H.warn("Failed to send initial available commands update",{sessionId:M,error:utils.errorMeta(O)});})),S.send(JSON.stringify({type:"response",id:k.id,result:{subscribed:!0,sessionId:M}}));return}if(k.method==="session.unsubscribe"){M&&r(_,M),S.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}},oe=await E.handle(O);S.send(JSON.stringify({type:"response",id:k.id,result:oe.result,error:oe.error}));return}if(k.method==="session.prompt"){if(S.send(JSON.stringify({jsonrpc:"2.0",id:k.id,result:{accepted:!0}})),M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}E.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 b=await E.handle(k);S.send(JSON.stringify({type:"response",id:b.id,result:b.result,error:b.error}));}catch(h){H.error("WebSocket server: error handling message",{error:utils.errorMeta(h)});}},onClose:(f,S)=>{let h=y(S);if(h){d.delete(h);let _=g.get(h);if(_){for(let k of _.subscribedSessions)l.removeSession(k);g.delete(h);}H.debug("WebSocket client disconnected",{clientId:h});}},onError:(f,S)=>{H.error("WebSocket error",{error:f.type});}},a=utils.createServer({port:n,hostname:s,routes:[{method:"post",path:"/acp",handler:async f=>{let S=await f.req.json().catch(()=>null);if(!S||typeof S!="object")return f.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}});let h=S;if(!h.method||h.jsonrpc!=="2.0")return f.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request"}});let _=await E.handle(h);return f.json(_)}},{method:"delete",path:"/acp",handler:async f=>{let S=f.req.header("Acp-Connection-Id");return H.debug("WebSocket server: connection terminated",{connectionId:S}),f.json({success:true})}}],timeout:e.timeout,cors:true}),u=a.raw,m=null,w=null;u&&(m=new ws.WebSocketServer({noServer:true}),w=(f,S,h)=>{try{let k=new URL(f.url||"/",`http://${f.headers.host}`).pathname,M=f.headers.upgrade?.toLowerCase();k===i&&M==="websocket"&&m.handleUpgrade(f,S,h,b=>{p.onOpen?.({type:"open"},b),b.on("message",O=>{p.onMessage?.({data:O},b);}),b.on("close",(O,oe)=>{p.onClose?.({code:O,reason:oe},b);}),b.on("error",O=>{p.onError?.({type:"error",message:utils.errorMeta(O).message},b);});});}catch{}},u.on("upgrade",w));try{await v.start(),o.setServerConnection(l);}catch(f){if(H.error("WebSocket server: failed to start background resources, cleaning up",{error:utils.errorMeta(f)}),await v.stop().catch(()=>{}),u&&w&&(u.off("upgrade",w),w=null),m){try{await new Promise(S=>m.close(()=>S()));}catch{}m=null;}throw await a.stop().catch(()=>{}),f}return H.info("WebSocket server started",{url:e.ws?.url||`ws://${s}:${n}`,path:i}),{server:a,stop:async()=>{H.info("Stopping WebSocket server"),await v.stop(),u&&w&&(u.off("upgrade",w),w=null);for(let f of d.values())try{f.ws.close();}catch{}if(d.clear(),g.clear(),l.clearSessions(),m){try{await new Promise(f=>m.close(()=>f()));}catch{}m=null;}await a.stop(),H.info("WebSocket server stopped");}}}var te=utils.Log.create({service:"acp.server.core"});async function $e(o,e){let t=Be(qe(e||{}));te.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,s;switch(t.channel){case L.HTTP:({server:n,stop:s}=await ze(o,t));break;case L.WEBSOCKET:({server:n,stop:s}=await Fe(o,t));break;default:throw new utils.NameErrors.InvalidArgumentError({message:`Unsupported service mode: ${t.channel}`,param:"channel"})}let i={type:t.channel,server:n,agent:o,stop:async()=>{te.info("Stopping ACPServer",{type:t.channel}),await s();},healthCheck:async()=>{if(typeof n=="object"&&n!==null&&"healthCheck"in n){let d=n.healthCheck;if(typeof d=="function")return d()}return true}};return te.info("ACPServer started successfully",{type:i.type,url:Tt(t)}),i}function Tt(o){return chunkSNWAB3QJ_cjs.t({channel:o.channel,hostname:o.hostname,port:o.port})??"unknown://"}async function Nt(o){await Promise.all(o.map(async e=>{try{await e.stop();}catch(t){te.error("Error stopping server",{type:e.type,error:utils.errorMeta(t)});}}));}async function je(o){await Nt([o]);}function bs(o){return {type:o.channel,server:null,agent:null,stop:async()=>{te.warn("Server not started, nothing to stop");},healthCheck:async()=>false}}var Lt=url.fileURLToPath(chunkM2YU5LAI_cjs.b),Ft=nt.dirname(Lt),Qe="0.0.0";try{let o=nt.join(Ft,"..","package.json");Qe=JSON.parse(fs.readFileSync(o,"utf-8")).version??"0.0.0";}catch{}var N=utils.Log.create({service:"acp.easbot-agent"}),ne=class o extends X{constructor(t,n){super(t,n);chunkM2YU5LAI_cjs.a(this,"acpEventBridge",null);chunkM2YU5LAI_cjs.a(this,"server",null);chunkM2YU5LAI_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",s=new o(void 0,t);if(n&&t.stdioStream){let{stream:i}=t.stdioStream,d={initialize:async l=>s.initialize(l),newSession:async l=>s.newSession(l),loadSession:async l=>s.loadSession(l),prompt:async l=>s.prompt(l),cancel:async l=>s.cancel(l),authenticate:async l=>s.authenticate(l),setSessionMode:async l=>s.setSessionMode(l),setSessionConfigOption:async l=>s.setSessionConfigOption(l),listSessions:async l=>s.listSessions(l),unstable_forkSession:async l=>s.unstable_forkSession(l),resumeSession:async l=>s.resumeSession(l),closeSession:async l=>s.closeSession(l)},g=new sdk.AgentSideConnection(()=>d,i);s.setConnection(g);}return N.info("EasBotAgent created successfully",{serviceMode:t.serviceMode,hasConnection:n&&!!t.stdioStream}),s}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:Qe,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 $e(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 je(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,s=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(!s)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,s),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}};function Ge(o,e,t){return new chunkSNWAB3QJ_cjs.c.AdapterEnvironmentInitializationError({message:o,stage:e},t?{cause:t}:void 0)}var Q=utils.Log.create({service:"acp.bootstrap"}),Ye=utils.State.holder(()=>{try{let o=chunkZ3YEK7DD_cjs.f().directory;return o?utils.Filesystem.normalize(o):"__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 o=>{let e=o.agent;e&&await e.stop().catch(()=>{}),Je(o),Ze(o),o.agent=null,o.sdk=null,o.acpConnection=null;});async function F(){return Ye.get()}function Ke(o){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=o.code;return e.includes(t??"")}function Gt(o){if(o.handlersInstalled)return;let e=n=>{let s=n instanceof Error?n:new Error(utils.errorMeta(n).message);Ke(s)||Q.error("unhandled promise rejection",{error:utils.errorMeta(s)});},t=n=>{Ke(n)||(Q.error("uncaught exception",{error:utils.errorMeta(n)}),process.exit(1));};process.on("unhandledRejection",e),process.on("uncaughtException",t),o.unhandledRejectionHandler=e,o.uncaughtExceptionHandler=t,o.handlersInstalled=true;}function Je(o){o.handlersInstalled&&(o.unhandledRejectionHandler&&(process.off("unhandledRejection",o.unhandledRejectionHandler),o.unhandledRejectionHandler=null),o.uncaughtExceptionHandler&&(process.off("uncaughtException",o.uncaughtExceptionHandler),o.uncaughtExceptionHandler=null),o.handlersInstalled=false);}function Ze(o){o.stdinDataHandler&&(process.stdin.off("data",o.stdinDataHandler),o.stdinDataHandler=null),o.stdinEndHandler&&(process.stdin.off("end",o.stdinEndHandler),o.stdinEndHandler=null),o.stdinErrorHandler&&(process.stdin.off("error",o.stdinErrorHandler),o.stdinErrorHandler=null);try{process.stdin.pause();}catch{}}async function Kt(o){return o.instancePromise||(o.instancePromise=(async()=>{let e=chunkZ3YEK7DD_cjs.f();(!e.directory||e.directory===process.cwd())&&chunkZ3YEK7DD_cjs.d({directory:o.directory,worktree:o.directory}),Q.debug("instance bootstrap completed",{directory:o.directory});})()),o.instancePromise}async function Yt(){try{chunkZ3YEK7DD_cjs.e(),Q.debug("instance adapter reset");}catch(o){Q.debug("instance dispose skipped",{error:utils.errorMeta(o)});}}exports.s=void 0;(y=>{async function o(c,r){if(c.sdk)return c.sdk;let{getSdk:p}=await import('./interfaces-6ZCF5T55.cjs');return c.sdk=await p(),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(){Ye.clear();}y.resetState=t;async function n(c){let r=await F();if(r.initialized)return;if(r.initPromise)return r.initPromise;let p={directory:c?.directory??".easbot",initModels:c?.initModels??true,printLogs:c?.printLogs??false,logLevel:c?.logLevel??"INFO",channel:c?.channel??chunkDX35VSAT_cjs.b.STDIO};if(r.directory=p.directory,await o(r,r.directory),r.activeChannel&&r.activeChannel!==p.channel)throw new utils.NameErrors.OperationFailedError({message:`Adapter already initialized with channel ${r.activeChannel}, cannot re-init with ${p.channel}`,operation:"adapter-init"});return r.activeChannel=p.channel,r.initPromise=(async()=>{try{Gt(r);}catch(a){throw Ge("Failed to install unhandled exception handlers","handlers",a instanceof Error?a:void 0)}try{await Kt(r);}catch(a){throw Ge("Failed to initialize instance","instance",a instanceof Error?a:void 0)}try{await chunkVVGGER23_cjs.r.init();}catch(a){Q.warn("AcpCache init failed, falling back to lazy load",{error:utils.errorMeta(a)});}utils.ConfigFileWatcher.init(),chunkBNSJ6COS_cjs.a.init(),r.initialized=true;})(),r.initPromise}y.init=n;async function s(){let c=await F();c.initialized&&(c.agent&&(await c.agent.stop().catch(()=>{}),c.agent=null),Je(c),Ze(c),await Yt(),c.initialized=false,c.initPromise=null,c.instancePromise=null,c.activeChannel=null,c.sdk=null,c.agent=null,c.acpConnection=null);}y.destroy=s;async function i(){return (await F()).initialized}y.isInitialized=i;async function d(c){let r=await F();r.agent=c;}y.setAgent=d;async function g(){return (await F()).agent}y.getAgent=g;async function l(){let r=(await F()).agent?.getServerInstance();return r||null}y.getServer=l;async function C(){return (await F()).sdk}y.getSDK=C;async function E(){return (await F()).acpConnection}y.getACPConnection=E;async function I(){let c=await F(),r=!!c.agent?.getServerInstance();return {initialized:c.initialized,directory:c.directory,activeChannel:c.activeChannel,hasSDK:!!c.sdk,hasAgent:!!c.agent,hasACPConnection:!!c.acpConnection,hasServer:r}}y.getState=I;async function v(c){await n({channel:c.channel,directory:c.directory});let r=await F(),p=await o(r,r.directory);if(c.channel===chunkDX35VSAT_cjs.b.STDIO)return x({directory:c.directory});if(r.agent?.getServerInstance()&&r.activeChannel&&r.activeChannel!==c.channel)throw new utils.NameErrors.OperationFailedError({message:`ACP service already started with channel ${r.activeChannel}, cannot switch to ${c.channel}`,operation:"adapter-switch-channel"});if(r.agent){let w=r.agent.getServerInstance();if(w)return {sdk:p,agent:r.agent,server:w}}let u=await ne.create({serviceMode:e(c.channel),acp:{sdk:p},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 r.agent=u,r.activeChannel=c.channel,{sdk:p,agent:u,server:m}}y.ensureACPService=v;async function x(c){await n({channel:chunkDX35VSAT_cjs.b.STDIO,directory:c.directory});let r=await F(),p=await o(r,r.directory);if(r.agent)return {sdk:p,agent:r.agent};let a=new WritableStream({write(f){return new Promise((S,h)=>{try{process.stdout.write(f)?S():process.stdout.once("drain",S);}catch(_){let k=_;k.code==="EPIPE"||k.code==="EIO"?h(new Error("stdout pipe broken")):h(_);}})}}),u=new ReadableStream({start(f){r.stdinDataHandler=S=>{try{f.enqueue(new Uint8Array(S));}catch{}},r.stdinEndHandler=()=>{try{f.close();}catch{}},r.stdinErrorHandler=S=>{try{f.error(S);}catch{}},process.stdin.on("data",r.stdinDataHandler),process.stdin.on("end",r.stdinEndHandler),process.stdin.on("error",r.stdinErrorHandler);}}),m=sdk.ndJsonStream(a,u),w=await ne.create({serviceMode:chunkDX35VSAT_cjs.b.STDIO,acp:{sdk:p},channel:{type:chunkDX35VSAT_cjs.b.STDIO,timeout:3e5},stdioStream:{stream:m}});return r.acpConnection=w.getConnection()??null,await w.start(),r.agent=w,r.activeChannel=chunkDX35VSAT_cjs.b.STDIO,Q.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:p,agent:w}}y.ensureACPServiceStdio=x;})(exports.s||(exports.s={}));var ao=exports.s;
|
|
8
|
+
exports.a=j;exports.c=ct;exports.d=re;exports.e=fe;exports.f=ae;exports.g=L;exports.h=Me;exports.i=qe;exports.j=Ct;exports.k=Be;exports.l=J;exports.m=ze;exports.n=Fe;exports.o=$e;exports.p=bs;exports.q=ne;exports.r=Ge;exports.t=ao;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var n=Object.defineProperty;var c=(t,e,r)=>e in t?n(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var m=(t,e,r)=>c(t,typeof e!="symbol"?e+"":e,r);var o=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,u=o();exports.a=m;exports.b=u;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {State,Filesystem,Global}from'@easbot/utils';var e=null,r=null;function b(t){e=t;}function f(){e=null;}function s(){return e||{Path:Global.get()}}function y(t){r=t;}function g(){r=null;}function a(){if(r)return r;let t=Filesystem.normalize(process.cwd());return {directory:t,worktree:t}}var i=State.holder(()=>{try{return a().directory||"__acp_sdk_global__"}catch{return "__acp_sdk_global__"}},async()=>({override:null,fallback:null}));async function m(t){let n=await i.get();n.override=t;}async function I(){let t=await i.get();t.override=null,t.fallback=null;}async function k(){let t=await i.get();if(t.override)return t.override;if(!t.fallback){let{createEasbotClient:n}=await import('@easbot/sdk');t.fallback=n();}return t.fallback}function _(){return s().Path.home||Global.home()}function v(){return s().Path.data||Global.data()}function x(){return Filesystem.normalize(a().worktree||process.cwd())}function E(){return Filesystem.normalize(a().directory||process.cwd())}export{b as a,f as b,s as c,y as d,g as e,a as f,m as g,I as h,k as i,_ as j,v as k,x as l,E as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {Log,createConfigChangeSubscriber}from'@easbot/utils';var c=Log.create({service:"acp.config.loader"}),i=createConfigChangeSubscriber({service:"acp.config.loader",onChanged:()=>{import('./loader-6HBCWO6Y.mjs').then(({AcpConfig:e})=>{e.resetState();}).catch(e=>{c.error("failed to reset acp config loader on external config change",{error:e instanceof Error?e:new Error(String(e))});});}});export{i as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-PATHHDWE.mjs';import {r,d,a as a$1,o}from'./chunk-2KOCPHVP.mjs';import {c,f as f$1}from'./chunk-NHXAYBZH.mjs';import {Log,State,Instance,Filesystem,ConfigFileParse,errorMeta}from'@easbot/utils';var g=Log.create({service:"acp.config.loader"}),f=null;async function w(e){a.track(e);try{let n=await ConfigFileParse.loadFile(e);return !n||typeof n!="object"||Array.isArray(n)?null:n}catch(n){return g.errorDegradable("Failed to load acp config file, skipping partial",{file:e,error:errorMeta(n)}),null}}async function m(e){let t=(await w(Filesystem.join(e,"easbot.json")))?.acp;return t&&typeof t=="object"&&!Array.isArray(t)?(g.debug("Loaded acp config from easbot.json acp field",{dir:e}),t):null}async function j(){let e=c().Path.config,n=f$1().directory,t=[],s=await m(e);s&&t.push(s);let r$1=await w(Filesystem.join(e,"acp.json"));r$1&&t.push(r$1);let c$1=await m(Filesystem.join(n,".easbot"));c$1&&t.push(c$1);let o=await r.getAcpJson();o&&Object.keys(o).length>0&&t.push(o),a.track(await r.getConfigPath());let a$1=ConfigFileParse.merge(t,d);return f=a$1,g.debug("ACP config loaded (multi-layer merged)",{partials:t.length,hasGlobal:r$1!==null,hasCache:o!==void 0&&Object.keys(o).length>0,serverEnabled:a$1.server?.enabled,channel:a$1.server?.channel,clientCount:a$1.clients?.clients?.length??0}),{config:a$1,cachedConfig:a$1,directories:[await r.getConfigPath()]}}var i;(c=>{let e=false,n=State.holder(()=>{try{return Instance.directory}catch{return "__acp_loader_global__"}},j);async function t(){let o=await n.get();return f=o.cachedConfig,o}c.state=t;function s(){n.clear(),f=null,e=false;}c.resetState=s;async function r(){e||(e=true,g.info("ACP config loader init"),await t());}c.init=r;})(i||(i={}));async function R(){return (await i.state()).config}function U(){return f}function J(){return f!==null}function O(){i.resetState();}async function $(){return r.resetState(),i.resetState(),R()}function z(){return f$1().directory}async function B(){let{config:e}=await i.state();return a$1.parse(ConfigFileParse.merge([o,e.server??{}]))}async function b(){let{config:e}=await i.state(),n=e.clients?.clients??[],t=e.clients?.defaultClientId;return {clients:n,defaultClientId:t}}async function M(e){return (await b()).clients.find(t=>t.id===e)}async function N(){let e=await b();if(e.clients.length!==0){if(e.defaultClientId){let n=e.clients.find(t=>t.id===e.defaultClientId);if(n)return n}return e.clients[0]}}async function T(){let{config:e}=await i.state();if(!(e.client?.autoRegister??true))return;if(e.client?.gatewayUrl)return e.client.gatewayUrl;let t=e.server,s=t?.hostname??"localhost",r=t?.port??3e3,c=t?.path||"/acp";return `ws://${s}:${r}${c}`}
|
|
2
|
+
export{i as a,R as b,U as c,J as d,O as e,$ as f,z as g,B as h,b as i,M as j,N as k,T as l};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var r=require('zod'),utils=require('@easbot/utils');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);var h=utils.NameErrors;exports.c=void 0;(i=>(i.ConfigNotFoundError=utils.NamedError.create("AcpConfigNotFoundError",r__default.default.object({message:r__default.default.string(),path:r__default.default.string()})),i.ConfigValidationError=utils.NamedError.create("AcpConfigValidationError",r__default.default.object({message:r__default.default.string(),path:r__default.default.string().optional()})),i.ServerStartFailedError=utils.NamedError.create("AcpServerStartFailedError",r__default.default.object({message:r__default.default.string(),channel:r__default.default.string().optional(),port:r__default.default.number().optional(),code:r__default.default.string().optional()})),i.ClientConnectionFailedError=utils.NamedError.create("AcpClientConnectionFailedError",r__default.default.object({message:r__default.default.string(),clientId:r__default.default.string().optional(),channel:r__default.default.string().optional(),code:r__default.default.string().optional()})),i.RpcParseFailedError=utils.NamedError.create("AcpRpcParseFailedError",r__default.default.object({message:r__default.default.string(),frame:r__default.default.string().optional(),method:r__default.default.string().optional()})),i.ServiceModeConflictError=utils.NamedError.create("AcpServiceModeConflictError",r__default.default.object({message:r__default.default.string(),conflictingModes:r__default.default.array(r__default.default.string())})),i.RoutingError=utils.NamedError.create("AcpRoutingError",r__default.default.object({message:r__default.default.string(),code:r__default.default.string(),context:r__default.default.record(r__default.default.string(),r__default.default.unknown()).optional()})),i.AdapterEnvironmentInitializationError=utils.NamedError.create("AcpAdapterEnvironmentInitializationError",r__default.default.object({message:r__default.default.string(),stage:r__default.default.enum(["global","log","models","handlers","instance"])})),i.AdapterError=utils.NamedError.create("AcpAdapterError",r__default.default.object({message:r__default.default.string(),type:r__default.default.string(),context:r__default.default.record(r__default.default.string(),r__default.default.unknown()).optional()}))))(exports.c||(exports.c={}));var u=(t=>(t.CHANNEL_ERROR="channel_error",t.CHANNEL_TIMEOUT="channel_timeout",t.CHANNEL_UNAVAILABLE="channel_unavailable",t.NETWORK_ERROR="network_error",t.CONNECTION_FAILED="connection_failed",t.CONNECTION_TIMEOUT="connection_timeout",t.ACP_ERROR="acp_error",t.ACP_AUTH_FAILED="acp_auth_failed",t.ACP_SESSION_NOT_FOUND="acp_session_not_found",t.CONFIG_ERROR="config_error",t.CONFIG_INVALID="config_invalid",t.SYSTEM_ERROR="system_error",t.INITIALIZATION_FAILED="initialization_failed",t))(u||{});function y(e){return exports.c.AdapterError.isInstance(e)}function v(e){return exports.c.ServiceModeConflictError.isInstance(e)}function F(e){return exports.c.RoutingError.isInstance(e)}function b(e){return exports.c.AdapterEnvironmentInitializationError.isInstance(e)}var g=new Set(["network_error","connection_failed","connection_timeout","channel_timeout"]),R=new Set(["config_error","config_invalid","initialization_failed"]);function L(e){return g.has(e)}function w(e){return R.has(e)}function p(e,n,o,s){return new exports.c.AdapterError({message:n,type:e,context:o},s?{cause:s}:void 0)}function D(e,n,o){return p("channel_error",e,n,o)}function k(e,n,o){return p("network_error",e,n,o)}function M(e,n){return p("config_error",e,n)}function U(e,n,o){return p("channel_timeout",e,{...o,timeout:n})}var I=new Set(["NOT_FOUND","AMBIGUOUS","INTERNAL","CONNECTION_FAILED","SERVER_START_FAILED"]),N={NOT_FOUND:"acp config not found; run acp init first to create .easbot/acp.json",INTERNAL:"acp service internal invariant broken; check acp.json schema + workspaceDir are non-empty",CONNECTION_FAILED:"remote ACP agent unreachable; verify channel (stdio/http/ws) + hostname/port + auth",SERVER_START_FAILED:"port may be in use; check --port and EADDRINUSE; verify --channel matches server capability"};async function P(){await utils.ServiceErrorBus.register("acp",I,N);}var _="easbot";function H(e){let{channel:n,hostname:o="localhost",port:s=3e3,command:E=_}=e;switch(n){case "stdio":return `stdio://${E}`;case "http":return `http://${o}:${s}`;case "websocket":return `ws://${o}:${s}`;default:return null}}
|
|
2
|
+
Object.defineProperty(exports,"a",{enumerable:true,get:function(){return utils.ServiceError}});exports.b=h;exports.d=u;exports.e=y;exports.f=v;exports.g=F;exports.h=b;exports.i=L;exports.j=w;exports.k=p;exports.l=D;exports.m=k;exports.n=M;exports.o=U;exports.p=I;exports.q=N;exports.r=P;exports.s=_;exports.t=H;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkZ3YEK7DD_cjs=require('./chunk-Z3YEK7DD.cjs'),fs=require('fs'),utils=require('@easbot/utils'),types=require('@easbot/types'),zod=require('zod');var b=e=>e==="local"?types.ChannelType.STDIO:e,S=zod.z.object({directory:zod.z.string().default(process.cwd()),enabled:zod.z.boolean().default(true),channel:zod.z.preprocess(b,zod.z.enum(["stdio","http","websocket"])).default("websocket"),port:zod.z.number().int().min(1).max(65535).default(3e3),hostname:zod.z.hostname().default("localhost"),timeout:zod.z.number().positive().default(3e4),name:zod.z.string().optional(),agentId:zod.z.string().optional(),stdio:zod.z.object({command:zod.z.string(),args:zod.z.array(zod.z.string())}).optional(),http:zod.z.object({baseUrl:zod.z.string().url(),timeout:zod.z.number().positive().default(6e4)}).optional(),ws:zod.z.object({url:zod.z.string().url(),timeout:zod.z.number().positive().default(3e4),batchSize:zod.z.number().positive().default(10),batchInterval:zod.z.number().positive().default(50),heartbeatInterval:zod.z.number().positive().default(3e4)}).optional(),agent:zod.z.object({agent:zod.z.string().optional(),model:zod.z.object({id:zod.z.string().min(1),options:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}).optional()}).optional()}).transform(e=>({...e,channel:e.channel})),w=zod.z.object({id:zod.z.string().min(1),type:zod.z.enum(["easbot","custom"]),name:zod.z.string().optional(),agentId:zod.z.string().optional(),channel:zod.z.preprocess(b,zod.z.enum(["stdio","http","websocket"])).optional(),connection:zod.z.object({stdio:zod.z.object({command:zod.z.string(),args:zod.z.array(zod.z.string())}).optional(),http:zod.z.object({baseUrl:zod.z.string().url(),timeout:zod.z.number().positive().default(6e4)}).optional(),ws:zod.z.object({url:zod.z.string().url(),timeout:zod.z.number().positive().default(3e4),batchSize:zod.z.number().positive().default(10),batchInterval:zod.z.number().positive().default(50),heartbeatInterval:zod.z.number().positive().default(3e4)}).optional()}),autoConnect:zod.z.boolean().default(false),priority:zod.z.number().int().nonnegative().default(0)}).transform(e=>{let t=e.channel;return t||(e.connection.ws?t="websocket":e.connection.http?t="http":e.connection.stdio?t="stdio":t="websocket"),{...e,channel:t}}),y=zod.z.object({clients:zod.z.array(w).min(1),defaultClientId:zod.z.string().optional()}),r=zod.z.object({server:S.optional(),clients:y.optional(),client:zod.z.object({autoRegister:zod.z.boolean().default(true),gatewayUrl:zod.z.url().optional()}).optional()});function E(e){let t=r.safeParse(e);if(t.success)return t.data;let s=r.safeParse({});return s.success?s.data:{}}function J(e){return r.parse(e)}var a=utils.Log.create({service:"acp.cache"}),L=[".easbot","acp.json"],j=new Set;function k(){try{let t=chunkZ3YEK7DD_cjs.f().directory;if(t&&t.length>0)return t}catch{}return process.cwd()}function l(e){return utils.Filesystem.join(e,...L)}async function O(e){let t=l(e);if(j.add(utils.Filesystem.normalize(t)),!fs.existsSync(t))return {acpJson:{},exists:false,rootDir:e};try{return {acpJson:await utils.ConfigFileParse.loadFile(t),exists:!0,rootDir:e}}catch(c){return a.warn("acp.json parse failed",{configPath:t,error:utils.errorMeta(c)}),{acpJson:void 0,exists:true,rootDir:e}}}var x=utils.State.holder(()=>{try{let t=chunkZ3YEK7DD_cjs.f().directory;return t?utils.Filesystem.normalize(t):"__acp_cache_global__"}catch{return "__acp_cache_global__"}},async()=>O(k()));exports.r=void 0;($=>{let e=false;async function t(){return x.get()}$.state=t;function s(o){x.clear(),e=false,utils.ConfigFileParse.invalidate(o??l(k()),"acp.resetState");}$.resetState=s;function c(){P||(P=utils.ConfigFileParse.onChange(o=>{j.has(o)&&(a.info("acp.json changed externally, reloading",{configPath:o}),utils.ConfigFileParse.invalidateNormalized(o,"acp.externalChange"),s(o));}));}let P;async function U(){e||(e=true,c(),a.info("AcpCache init"),await t());}$.init=U;async function V(){return (await t()).acpJson}$.getAcpJson=V;async function H(){return (await t()).exists}$.exists=H;async function M(){return (await t()).rootDir}$.getRootDir=M;async function G(o){let d=await t(),i=l(d.rootDir),g={...d.acpJson??{},...o},f=r.safeParse(g);if(!f.success)throw a.error("acp.json validation failed on write",{configPath:i,issues:f.error.issues}),new utils.NameErrors.ValidationError({message:`acp.json validation failed: ${f.error.message}`,location:i,issues:f.error.issues});let A=utils.Filesystem.dirname(i);fs.existsSync(A)||fs.mkdirSync(A,{recursive:true});try{fs.writeFileSync(i,JSON.stringify(g,null,2),"utf-8");}catch(h){throw a.error("acp.json write failed",{configPath:i,error:utils.errorMeta(h)}),h}return s(i),a.debug("acp.json written",{configPath:i}),g}$.writeAcpJson=G;async function W(){let o=await t();return l(o.rootDir)}$.getConfigPath=W;})(exports.r||(exports.r={}));Object.defineProperty(exports,"g",{enumerable:true,get:function(){return types.ACPStdioConnectionConfigSchema}});Object.defineProperty(exports,"h",{enumerable:true,get:function(){return types.ACPHttpConnectionConfigSchema}});Object.defineProperty(exports,"i",{enumerable:true,get:function(){return types.ACPWebSocketConnectionConfigSchema}});Object.defineProperty(exports,"j",{enumerable:true,get:function(){return types.ACPConnectionConfigSchema}});Object.defineProperty(exports,"k",{enumerable:true,get:function(){return types.ACPModelConfigSchema}});Object.defineProperty(exports,"l",{enumerable:true,get:function(){return types.ACPAgentRuntimeConfigSchema}});Object.defineProperty(exports,"m",{enumerable:true,get:function(){return types.ACPInfoACPServerConfigSchema}});Object.defineProperty(exports,"n",{enumerable:true,get:function(){return types.ACPInfoACPClientsConfigSchema}});Object.defineProperty(exports,"o",{enumerable:true,get:function(){return types.ACP_DEFAULT_SERVER_CONFIG}});Object.defineProperty(exports,"p",{enumerable:true,get:function(){return types.ACP_DEFAULT_CLIENT_CONFIG}});exports.a=S;exports.b=w;exports.c=y;exports.d=r;exports.e=E;exports.f=J;exports.q=L;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var utils=require('@easbot/utils');var e=null,r=null;function p(t){e=t;}function b(){e=null;}function s(){return e||{Path:utils.Global.get()}}function f(t){r=t;}function y(){r=null;}function a(){if(r)return r;let t=utils.Filesystem.normalize(process.cwd());return {directory:t,worktree:t}}var i=utils.State.holder(()=>{try{return a().directory||"__acp_sdk_global__"}catch{return "__acp_sdk_global__"}},async()=>({override:null,fallback:null}));async function g(t){let n=await i.get();n.override=t;}async function m(){let t=await i.get();t.override=null,t.fallback=null;}async function I(){let t=await i.get();if(t.override)return t.override;if(!t.fallback){let{createEasbotClient:n}=await import('@easbot/sdk');t.fallback=n();}return t.fallback}function k(){return s().Path.home||utils.Global.home()}function _(){return s().Path.data||utils.Global.data()}function v(){return utils.Filesystem.normalize(a().worktree||process.cwd())}function x(){return utils.Filesystem.normalize(a().directory||process.cwd())}exports.a=p;exports.b=b;exports.c=s;exports.d=f;exports.e=y;exports.f=a;exports.g=g;exports.h=m;exports.i=I;exports.j=k;exports.k=_;exports.l=v;exports.m=x;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{k as COMMANDS_HELP,n as handleAcpCli,l as renderBanner,m as renderHelp}from'./chunk-3DHMW4DB.mjs';import'./chunk-B3ANZALB.mjs';import'./chunk-33M2R2US.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk5HWD3B3N_cjs=require('./chunk-5HWD3B3N.cjs');require('./chunk-SNWAB3QJ.cjs'),require('./chunk-DX35VSAT.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.k}});Object.defineProperty(exports,"handleAcpCli",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.n}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.l}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.m}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import'./chunk-D4TSQ2TT.mjs';export{e as clearConfigCache,j as getClientById,i as getClientsConfig,c as getConfig,g as getConfigDirectory,k as getDefaultClient,l as getGatewayClientUrl,h as getServerConfig,d as isConfigLoaded,b as loadConfig,f as reloadConfig}from'./chunk-RHW6YR3D.mjs';import'./chunk-PATHHDWE.mjs';export{l as ACPAgentRuntimeConfigSchema,b as ACPClientConfigSchema,c as ACPClientsConfigSchema,j as ACPConnectionConfigSchema,h as ACPHttpConnectionConfigSchema,n as ACPInfoACPClientsConfigSchema,d as ACPInfoACPConfigSchema,m as ACPInfoACPServerConfigSchema,k as ACPModelConfigSchema,f as ACPParsePartialConfig,a as ACPServerConfigSchema,g as ACPStdioConnectionConfigSchema,e as ACPValidateConfig,i as ACPWebSocketConnectionConfigSchema,p as ACP_DEFAULT_CLIENT_CONFIG,o as ACP_DEFAULT_SERVER_CONFIG}from'./chunk-2KOCPHVP.mjs';import'./chunk-NHXAYBZH.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';require('./chunk-JLO7UYKQ.cjs');var chunk7RWES66A_cjs=require('./chunk-7RWES66A.cjs');require('./chunk-BNSJ6COS.cjs');var chunkVVGGER23_cjs=require('./chunk-VVGGER23.cjs');require('./chunk-Z3YEK7DD.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunk7RWES66A_cjs.e}});Object.defineProperty(exports,"getClientById",{enumerable:true,get:function(){return chunk7RWES66A_cjs.j}});Object.defineProperty(exports,"getClientsConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.i}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.c}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunk7RWES66A_cjs.g}});Object.defineProperty(exports,"getDefaultClient",{enumerable:true,get:function(){return chunk7RWES66A_cjs.k}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunk7RWES66A_cjs.l}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.h}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunk7RWES66A_cjs.d}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.b}});Object.defineProperty(exports,"reloadConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.f}});Object.defineProperty(exports,"ACPAgentRuntimeConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.l}});Object.defineProperty(exports,"ACPClientConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.b}});Object.defineProperty(exports,"ACPClientsConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.c}});Object.defineProperty(exports,"ACPConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.j}});Object.defineProperty(exports,"ACPHttpConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.h}});Object.defineProperty(exports,"ACPInfoACPClientsConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.n}});Object.defineProperty(exports,"ACPInfoACPConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.d}});Object.defineProperty(exports,"ACPInfoACPServerConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.m}});Object.defineProperty(exports,"ACPModelConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.k}});Object.defineProperty(exports,"ACPParsePartialConfig",{enumerable:true,get:function(){return chunkVVGGER23_cjs.f}});Object.defineProperty(exports,"ACPServerConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.a}});Object.defineProperty(exports,"ACPStdioConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.g}});Object.defineProperty(exports,"ACPValidateConfig",{enumerable:true,get:function(){return chunkVVGGER23_cjs.e}});Object.defineProperty(exports,"ACPWebSocketConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.i}});Object.defineProperty(exports,"ACP_DEFAULT_CLIENT_CONFIG",{enumerable:true,get:function(){return chunkVVGGER23_cjs.p}});Object.defineProperty(exports,"ACP_DEFAULT_SERVER_CONFIG",{enumerable:true,get:function(){return chunkVVGGER23_cjs.o}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkZ3YEK7DD_cjs=require('./chunk-Z3YEK7DD.cjs');require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.j}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.f}});Object.defineProperty(exports,"getProjectDirectory",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.m}});Object.defineProperty(exports,"getSdk",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.i}});Object.defineProperty(exports,"getWorktree",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.l}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.k}});Object.defineProperty(exports,"resetEasbotClientAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.e}});Object.defineProperty(exports,"setEasbotClientAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.g}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.d}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{c as getGlobal,j as getHomeDir,f as getInstance,m as getProjectDirectory,i as getSdk,l as getWorktree,k as getXdgData,h as resetEasbotClientAdapter,b as resetGlobalAdapter,e as resetInstanceAdapter,g as setEasbotClientAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunk-NHXAYBZH.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk7RWES66A_cjs=require('./chunk-7RWES66A.cjs');require('./chunk-BNSJ6COS.cjs');var chunkVVGGER23_cjs=require('./chunk-VVGGER23.cjs');require('./chunk-Z3YEK7DD.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"AcpConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.a}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunk7RWES66A_cjs.e}});Object.defineProperty(exports,"getClientById",{enumerable:true,get:function(){return chunk7RWES66A_cjs.j}});Object.defineProperty(exports,"getClientsConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.i}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.c}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunk7RWES66A_cjs.g}});Object.defineProperty(exports,"getDefaultClient",{enumerable:true,get:function(){return chunk7RWES66A_cjs.k}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunk7RWES66A_cjs.l}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.h}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunk7RWES66A_cjs.d}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.b}});Object.defineProperty(exports,"reloadConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.f}});Object.defineProperty(exports,"ACPInfoACPConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.d}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as AcpConfig,e as clearConfigCache,j as getClientById,i as getClientsConfig,c as getConfig,g as getConfigDirectory,k as getDefaultClient,l as getGatewayClientUrl,h as getServerConfig,d as isConfigLoaded,b as loadConfig,f as reloadConfig}from'./chunk-RHW6YR3D.mjs';import'./chunk-PATHHDWE.mjs';export{d as ACPInfoACPConfigSchema}from'./chunk-2KOCPHVP.mjs';import'./chunk-NHXAYBZH.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{f as AgentErrorSchema,h as AgentEventType,e as AgentMessageSchema,c as AgentStartedSchema,a as AgentStatus,g as AgentStatusSchema,d as AgentStoppedSchema,b as ChannelType}from'./chunk-33M2R2US.mjs';import'./chunk-HQBRVVXS.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkDX35VSAT_cjs=require('./chunk-DX35VSAT.cjs');require('./chunk-M2YU5LAI.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}});
|
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');var E=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function y(){try{let e=path.join(E,"..","package.json");return JSON.parse(fs.readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var p=new Set(["DEBUG","INFO","WARN","ERROR"]);function A(e){let s=[];for(let o=0;o<e.length;o++){let t=e[o];if(t){if(t==="--cwd"||t==="--config"||t==="--log-level"||t==="--print-logs"||t==="--debug"){if(t!=="--print-logs"&&t!=="--debug"){let n=e[o+1];n&&!n.startsWith("-")&&o++;}continue}t.startsWith("--cwd=")||t.startsWith("--config=")||t.startsWith("--log-level=")||s.push(t);}}return s}function G(e){let s={logLevel:"INFO",printLogs:false,debug:false};for(let o=0;o<e.length;o++){let t=e[o];if(t)if(t==="--cwd"&&o+1<e.length){let n=e[o+1];n&&!n.startsWith("-")&&(s.cwd=n,o++);}else if(t.startsWith("--cwd="))s.cwd=t.slice(6);else if(t==="--config"&&o+1<e.length){let n=e[o+1];n&&!n.startsWith("-")&&(s.configPath=n,o++);}else if(t.startsWith("--config="))s.configPath=t.slice(9);else if(t==="--log-level"&&o+1<e.length){let n=e[o+1];if(n&&!n.startsWith("-")){let i=n.toUpperCase();p.has(i)&&(s.logLevel=i,o++);}}else if(t.startsWith("--log-level=")){let n=t.slice(12).toUpperCase();p.has(n)&&(s.logLevel=n);}else t==="--print-logs"?s.printLogs=true:t==="--debug"&&(s.debug=true);}return s}async function N(){let e=process.argv.slice(2),s=y(),{loadEnv:o}=await import('@easbot/utils');o(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US"),process.env.EASBOT_CLIENT||(process.env.EASBOT_CLIENT="acp");let t=G(e),{Log:n}=await import('@easbot/utils'),{getXdgData:i}=await import('./chunks/interfaces-6ZCF5T55.cjs'),f=path.join(i(),"acp","log");if(await n.init({logDir:f,print:t.printLogs,dev:t.debug||false,level:t.logLevel}),e.length===0){let{renderBanner:c}=await import('./chunks/cli-handler-IU3YUTOU.cjs');c();return}if(e[0]==="--help"||e[0]==="-h"){let{renderHelp:c}=await import('./chunks/cli-handler-IU3YUTOU.cjs');c();return}if(e[0]==="--version"||e[0]==="-v"){terminal.printHuman([terminal.formatInfo(s)]);return}let r=t.cwd??process.cwd(),{setInstanceAdapter:d}=await import('./chunks/interfaces-6ZCF5T55.cjs');d({directory:r,worktree:r});let h=A(e),{handleAcpCli:u}=await import('./chunks/cli-handler-IU3YUTOU.cjs'),{Instance:L}=await import('@easbot/utils'),l=await L.provide({directory:r,fn:()=>u(h,{version:s,cwd:r})});l.code!==0&&(process.exitCode=l.code);}N().catch(async e=>{try{let{Log:s,errorMeta:o}=await import('@easbot/utils');s.create({service:"acp.cli.standalone"}).error("acp CLI crashed",{error:o(e)});}catch{console.error(e);}process.exitCode=1;}).finally(async()=>{try{let{Log:e}=await import('@easbot/utils');await e.close();}catch{}process.exit(process.exitCode??0);});
|
package/dist/cli.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';import {printHuman,formatInfo}from'@easbot/terminal';var b=dirname(fileURLToPath(import.meta.url));function E(){try{let e=join(b,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var a=new Set(["DEBUG","INFO","WARN","ERROR"]);function y(e){let s=[];for(let o=0;o<e.length;o++){let t=e[o];if(t){if(t==="--cwd"||t==="--config"||t==="--log-level"||t==="--print-logs"||t==="--debug"){if(t!=="--print-logs"&&t!=="--debug"){let n=e[o+1];n&&!n.startsWith("-")&&o++;}continue}t.startsWith("--cwd=")||t.startsWith("--config=")||t.startsWith("--log-level=")||s.push(t);}}return s}function A(e){let s={logLevel:"INFO",printLogs:false,debug:false};for(let o=0;o<e.length;o++){let t=e[o];if(t)if(t==="--cwd"&&o+1<e.length){let n=e[o+1];n&&!n.startsWith("-")&&(s.cwd=n,o++);}else if(t.startsWith("--cwd="))s.cwd=t.slice(6);else if(t==="--config"&&o+1<e.length){let n=e[o+1];n&&!n.startsWith("-")&&(s.configPath=n,o++);}else if(t.startsWith("--config="))s.configPath=t.slice(9);else if(t==="--log-level"&&o+1<e.length){let n=e[o+1];if(n&&!n.startsWith("-")){let i=n.toUpperCase();a.has(i)&&(s.logLevel=i,o++);}}else if(t.startsWith("--log-level=")){let n=t.slice(12).toUpperCase();a.has(n)&&(s.logLevel=n);}else t==="--print-logs"?s.printLogs=true:t==="--debug"&&(s.debug=true);}return s}async function G(){let e=process.argv.slice(2),s=E(),{loadEnv:o}=await import('@easbot/utils');o(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US"),process.env.EASBOT_CLIENT||(process.env.EASBOT_CLIENT="acp");let t=A(e),{Log:n}=await import('@easbot/utils'),{getXdgData:i}=await import('./chunks/interfaces-TXNKX4HT.mjs'),g=join(i(),"acp","log");if(await n.init({logDir:g,print:t.printLogs,dev:t.debug||false,level:t.logLevel}),e.length===0){let{renderBanner:c}=await import('./chunks/cli-handler-6XB6B5DV.mjs');c();return}if(e[0]==="--help"||e[0]==="-h"){let{renderHelp:c}=await import('./chunks/cli-handler-6XB6B5DV.mjs');c();return}if(e[0]==="--version"||e[0]==="-v"){printHuman([formatInfo(s)]);return}let r=t.cwd??process.cwd(),{setInstanceAdapter:f}=await import('./chunks/interfaces-TXNKX4HT.mjs');f({directory:r,worktree:r});let d=y(e),{handleAcpCli:h}=await import('./chunks/cli-handler-6XB6B5DV.mjs'),{Instance:u}=await import('@easbot/utils'),l=await u.provide({directory:r,fn:()=>h(d,{version:s,cwd:r})});l.code!==0&&(process.exitCode=l.code);}G().catch(async e=>{try{let{Log:s,errorMeta:o}=await import('@easbot/utils');s.create({service:"acp.cli.standalone"}).error("acp CLI crashed",{error:o(e)});}catch{console.error(e);}process.exitCode=1;}).finally(async()=>{try{let{Log:e}=await import('@easbot/utils');await e.close();}catch{}process.exit(process.exitCode??0);});
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk5HWD3B3N_cjs=require('./chunks/chunk-5HWD3B3N.cjs');require('./chunks/chunk-JLO7UYKQ.cjs');var chunk7RWES66A_cjs=require('./chunks/chunk-7RWES66A.cjs'),chunkITV7SWGU_cjs=require('./chunks/chunk-ITV7SWGU.cjs'),chunkSNWAB3QJ_cjs=require('./chunks/chunk-SNWAB3QJ.cjs'),chunkDX35VSAT_cjs=require('./chunks/chunk-DX35VSAT.cjs');require('./chunks/chunk-BNSJ6COS.cjs');var chunkVVGGER23_cjs=require('./chunks/chunk-VVGGER23.cjs'),chunkZ3YEK7DD_cjs=require('./chunks/chunk-Z3YEK7DD.cjs');require('./chunks/chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.k}});Object.defineProperty(exports,"I18n",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.c}});Object.defineProperty(exports,"LanguagesSupported",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.b}});Object.defineProperty(exports,"changeI18nLanguage",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.f}});Object.defineProperty(exports,"formatLog",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.j}});Object.defineProperty(exports,"getRegisteredResources",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.g}});Object.defineProperty(exports,"handleAcpCli",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.n}});Object.defineProperty(exports,"initI18n",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.e}});Object.defineProperty(exports,"languages",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.a}});Object.defineProperty(exports,"registerI18nResources",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.l}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.m}});Object.defineProperty(exports,"t",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.i}});Object.defineProperty(exports,"translate",{enumerable:true,get:function(){return chunk5HWD3B3N_cjs.h}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunk7RWES66A_cjs.e}});Object.defineProperty(exports,"getClientById",{enumerable:true,get:function(){return chunk7RWES66A_cjs.j}});Object.defineProperty(exports,"getClientsConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.i}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.c}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunk7RWES66A_cjs.g}});Object.defineProperty(exports,"getDefaultClient",{enumerable:true,get:function(){return chunk7RWES66A_cjs.k}});Object.defineProperty(exports,"getGatewayClientUrl",{enumerable:true,get:function(){return chunk7RWES66A_cjs.l}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.h}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunk7RWES66A_cjs.d}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.b}});Object.defineProperty(exports,"reloadConfig",{enumerable:true,get:function(){return chunk7RWES66A_cjs.f}});Object.defineProperty(exports,"AcpEventBridge",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.a}});Object.defineProperty(exports,"AdapterBootstrap",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.t}});Object.defineProperty(exports,"EasBotAgent",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.q}});Object.defineProperty(exports,"EasbotAdapter",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.s}});Object.defineProperty(exports,"RegistrySessionRouter",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.f}});Object.defineProperty(exports,"RoutingErrorCode",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.c}});Object.defineProperty(exports,"ServerAgentSideConnection",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.l}});Object.defineProperty(exports,"ServerConnectionRegistry",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.b}});Object.defineProperty(exports,"ServiceMode",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.g}});Object.defineProperty(exports,"SessionRouter",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.e}});Object.defineProperty(exports,"applyEnvironmentOverrides",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.k}});Object.defineProperty(exports,"createACPServerInstance",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.p}});Object.defineProperty(exports,"createAdapterEnvironmentInitializationError",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.r}});Object.defineProperty(exports,"createRoutingError",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.d}});Object.defineProperty(exports,"createServiceModeConflictError",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.h}});Object.defineProperty(exports,"loadACPServerConfig",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.i}});Object.defineProperty(exports,"loadConfigFromEnv",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.j}});Object.defineProperty(exports,"startACPServer",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.o}});Object.defineProperty(exports,"startHttpServer",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.m}});Object.defineProperty(exports,"startWebSocketServer",{enumerable:true,get:function(){return chunkITV7SWGU_cjs.n}});Object.defineProperty(exports,"ACP_BUSINESS_CODES",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.p}});Object.defineProperty(exports,"ACP_BUSINESS_HINTS",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.q}});Object.defineProperty(exports,"ACP_STDIO_COMMAND",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.s}});Object.defineProperty(exports,"AcpError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.c}});Object.defineProperty(exports,"ErrorType",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.d}});Object.defineProperty(exports,"NameErrors",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.b}});Object.defineProperty(exports,"ServiceError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.a}});Object.defineProperty(exports,"createAdapterError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.k}});Object.defineProperty(exports,"createChannelError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.l}});Object.defineProperty(exports,"createConfigError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.n}});Object.defineProperty(exports,"createNetworkError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.m}});Object.defineProperty(exports,"createTimeoutError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.o}});Object.defineProperty(exports,"getAcpEndpointUrl",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.t}});Object.defineProperty(exports,"isAdapterEnvironmentInitializationError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.h}});Object.defineProperty(exports,"isAdapterError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.e}});Object.defineProperty(exports,"isAdapterErrorFatal",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.j}});Object.defineProperty(exports,"isAdapterErrorRetryable",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.i}});Object.defineProperty(exports,"isRoutingError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.g}});Object.defineProperty(exports,"isServiceModeConflictError",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.f}});Object.defineProperty(exports,"registerBusinessErrors",{enumerable:true,get:function(){return chunkSNWAB3QJ_cjs.r}});Object.defineProperty(exports,"AgentStatus",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.a}});Object.defineProperty(exports,"ChannelType",{enumerable:true,get:function(){return chunkDX35VSAT_cjs.b}});Object.defineProperty(exports,"ACPAgentRuntimeConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.l}});Object.defineProperty(exports,"ACPClientConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.b}});Object.defineProperty(exports,"ACPClientsConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.c}});Object.defineProperty(exports,"ACPConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.j}});Object.defineProperty(exports,"ACPHttpConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.h}});Object.defineProperty(exports,"ACPInfoACPClientsConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.n}});Object.defineProperty(exports,"ACPInfoACPConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.d}});Object.defineProperty(exports,"ACPInfoACPServerConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.m}});Object.defineProperty(exports,"ACPModelConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.k}});Object.defineProperty(exports,"ACPParsePartialConfig",{enumerable:true,get:function(){return chunkVVGGER23_cjs.f}});Object.defineProperty(exports,"ACPServerConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.a}});Object.defineProperty(exports,"ACPStdioConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.g}});Object.defineProperty(exports,"ACPValidateConfig",{enumerable:true,get:function(){return chunkVVGGER23_cjs.e}});Object.defineProperty(exports,"ACPWebSocketConnectionConfigSchema",{enumerable:true,get:function(){return chunkVVGGER23_cjs.i}});Object.defineProperty(exports,"ACP_DEFAULT_CLIENT_CONFIG",{enumerable:true,get:function(){return chunkVVGGER23_cjs.p}});Object.defineProperty(exports,"ACP_DEFAULT_SERVER_CONFIG",{enumerable:true,get:function(){return chunkVVGGER23_cjs.o}});Object.defineProperty(exports,"ACP_JSON_REL_PATH",{enumerable:true,get:function(){return chunkVVGGER23_cjs.q}});Object.defineProperty(exports,"AcpCache",{enumerable:true,get:function(){return chunkVVGGER23_cjs.r}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.j}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.f}});Object.defineProperty(exports,"getProjectDirectory",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.m}});Object.defineProperty(exports,"getSdk",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.i}});Object.defineProperty(exports,"getWorktree",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.l}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.k}});Object.defineProperty(exports,"resetEasbotClientAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.e}});Object.defineProperty(exports,"setEasbotClientAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.g}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkZ3YEK7DD_cjs.d}});
|