@easbot/agent 0.2.33 → 0.2.35
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/dist/assets/txt/tool/agent-client.txt +27 -17
- package/dist/chunks/acp-E24MSMFC.mjs +22 -0
- package/dist/chunks/adapter-loader-RB3DHR4L.mjs +1 -0
- package/dist/chunks/{agent-EXH3EXNP.mjs → agent-L27ZE5IW.mjs} +1 -1
- package/dist/chunks/{agent-IKNANWOU.mjs → agent-TZHNEJZL.mjs} +1 -1
- package/dist/chunks/app-YFHCVHLE.mjs +1 -0
- package/dist/chunks/bootstrap-CF7VDTXX.mjs +1 -0
- package/dist/chunks/{build-program-HXXT6DQM.mjs → build-program-C64GX76M.mjs} +1 -1
- package/dist/chunks/bus-KIUMM7BC.mjs +1 -0
- package/dist/chunks/{chunk-R3MXNCX5.mjs → chunk-6AVNQKBM.mjs} +1 -1
- package/dist/chunks/chunk-7HB3V4GJ.mjs +1050 -0
- package/dist/chunks/{chunk-T75GE4R6.mjs → chunk-CK4NOPWT.mjs} +7 -7
- package/dist/chunks/{chunk-W7J4LU42.mjs → chunk-HJNJBNAS.mjs} +1 -1
- package/dist/chunks/{chunk-HACAZH7T.mjs → chunk-JJFETXKH.mjs} +1 -1
- package/dist/chunks/{chunk-3GBVNLVL.mjs → chunk-LNK3TPGD.mjs} +1 -1
- package/dist/chunks/{chunk-WIU6CVKP.mjs → chunk-LVPNJIYT.mjs} +1 -1
- package/dist/chunks/{chunk-YZOAYITQ.mjs → chunk-MKLPO5E6.mjs} +1 -1
- package/dist/chunks/{chunk-4GMKI6FY.mjs → chunk-NGFNJSSC.mjs} +1 -1
- package/dist/chunks/{chunk-OEPPJZFZ.mjs → chunk-UCS2W4UN.mjs} +1 -1
- package/dist/chunks/{chunk-XTHATUY4.mjs → chunk-ZMABUCCZ.mjs} +1 -1
- package/dist/chunks/{command-V7QNKP7O.mjs → command-4JQJZLXN.mjs} +1 -1
- package/dist/chunks/compaction-CUBPPBPC.mjs +1 -0
- package/dist/chunks/config-5A4HFMUH.mjs +1 -0
- package/dist/chunks/{debug-4SGU2Y2Q.mjs → debug-WFVKKNMQ.mjs} +3 -3
- package/dist/chunks/file-3VDVAZTL.mjs +1 -0
- package/dist/chunks/{gateway-SSDLJMXI.mjs → gateway-NX63YLNB.mjs} +2 -2
- package/dist/chunks/{generate-NUX2GBYY.mjs → generate-NGTCWD3T.mjs} +1 -1
- package/dist/chunks/{github-W2LFG2G6.mjs → github-T2BVXCZH.mjs} +2 -2
- package/dist/chunks/global-Q3QO7P6M.mjs +1 -0
- package/dist/chunks/{import-NFHPQNA7.mjs → import-3Q6LMACX.mjs} +1 -1
- package/dist/chunks/installation-MHESQKXT.mjs +1 -0
- package/dist/chunks/instance-H2KYIHLZ.mjs +1 -0
- package/dist/chunks/loader-NR6EJAIR.mjs +1 -0
- package/dist/chunks/loader-ZHMSBZC2.mjs +1 -0
- package/dist/chunks/lsp-L4WU5NEW.mjs +1 -0
- package/dist/chunks/{mcp-BR3CYNJB.mjs → mcp-6F5MHKJC.mjs} +1 -1
- package/dist/chunks/mcp-OZVV2MA6.mjs +1 -0
- package/dist/chunks/models-WKDPYQYF.mjs +1 -0
- package/dist/chunks/{pr-4X42BEJT.mjs → pr-CVTJCVMI.mjs} +1 -1
- package/dist/chunks/preferences-NAD3LBYN.mjs +1 -0
- package/dist/chunks/project-RW7NRQ42.mjs +1 -0
- package/dist/chunks/prompt-FN4CZ6ZA.mjs +1 -0
- package/dist/chunks/provider-YOFLNR7G.mjs +1 -0
- package/dist/chunks/registry-5NHTTRE5.mjs +1 -0
- package/dist/chunks/revert-D3MDFRAF.mjs +1 -0
- package/dist/chunks/ripgrep-Y3BU52A7.mjs +1 -0
- package/dist/chunks/{run-BD36UNJF.mjs → run-ATMTXRAJ.mjs} +2 -2
- package/dist/chunks/scheduler-PMVLXV3Z.mjs +1 -0
- package/dist/chunks/server-YOD742QH.mjs +1 -0
- package/dist/chunks/session-H42OUA2M.mjs +1 -0
- package/dist/chunks/{session-R3U252OC.mjs → session-QSAQNL2Z.mjs} +1 -1
- package/dist/chunks/session-W4QX2MD7.mjs +1 -0
- package/dist/chunks/share-UZGTO5TA.mjs +1 -0
- package/dist/chunks/snapshot-HPOFHBZF.mjs +1 -0
- package/dist/chunks/storage-AATJSH75.mjs +1 -0
- package/dist/chunks/tui-IHXXWMOO.mjs +1 -0
- package/dist/chunks/{tui-SW7BOEMQ.mjs → tui-SVCBKLDD.mjs} +1 -1
- package/dist/chunks/types-KRODLUPF.mjs +1 -0
- package/dist/chunks/{update-424STNM5.mjs → update-DGH5TARR.mjs} +1 -1
- package/dist/cli.mjs +2 -2
- package/package.json +14 -14
- package/dist/chunks/acp-VDKINAWR.mjs +0 -16
- package/dist/chunks/adapter-loader-HTS4EEL4.mjs +0 -1
- package/dist/chunks/app-BZWD4E32.mjs +0 -1
- package/dist/chunks/bootstrap-CB65J4FA.mjs +0 -1
- package/dist/chunks/bus-S6EWJZAJ.mjs +0 -1
- package/dist/chunks/chunk-EXZOV2YR.mjs +0 -1043
- package/dist/chunks/compaction-HKN7HOBD.mjs +0 -1
- package/dist/chunks/config-LSCANUOQ.mjs +0 -1
- package/dist/chunks/file-KHHRKYLJ.mjs +0 -1
- package/dist/chunks/global-ZK2HE4L2.mjs +0 -1
- package/dist/chunks/installation-4XG5GKF2.mjs +0 -1
- package/dist/chunks/instance-6HPNQZR5.mjs +0 -1
- package/dist/chunks/loader-4EPHUIR3.mjs +0 -1
- package/dist/chunks/loader-PVSCRHAG.mjs +0 -1
- package/dist/chunks/lsp-XWC37KPE.mjs +0 -1
- package/dist/chunks/mcp-MMYCROXT.mjs +0 -1
- package/dist/chunks/models-M5BT6WMD.mjs +0 -1
- package/dist/chunks/preferences-XV3DOFFV.mjs +0 -1
- package/dist/chunks/project-VUSYTQRZ.mjs +0 -1
- package/dist/chunks/prompt-TC6ZOCJ7.mjs +0 -1
- package/dist/chunks/provider-RSD6RHBA.mjs +0 -1
- package/dist/chunks/registry-JC6QFFEI.mjs +0 -1
- package/dist/chunks/revert-Q4KBW2OL.mjs +0 -1
- package/dist/chunks/ripgrep-CKVVXX5D.mjs +0 -1
- package/dist/chunks/scheduler-S37CNKWR.mjs +0 -1
- package/dist/chunks/server-PWL7MLW7.mjs +0 -1
- package/dist/chunks/session-27P45HFD.mjs +0 -1
- package/dist/chunks/session-2ECCHYP7.mjs +0 -1
- package/dist/chunks/share-VRVDSUF4.mjs +0 -1
- package/dist/chunks/snapshot-JKLZBDBN.mjs +0 -1
- package/dist/chunks/storage-2SFY3R4G.mjs +0 -1
- package/dist/chunks/tui-P7HR545F.mjs +0 -1
- package/dist/chunks/types-WCQ4KHSB.mjs +0 -1
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
Manage a full-duplex conversation channel with another easbot agent endpoint.
|
|
2
|
-
Use this as the single tool for connect, list, discover, capabilities, send, status, config, interrupt, and close.
|
|
1
|
+
Manage a full-duplex conversation channel with another easbot agent endpoint over HTTP or WebSocket.
|
|
3
2
|
|
|
4
3
|
Inputs (kept minimal):
|
|
5
4
|
- operation: connect | list | discover | capabilities | send | status | config | interrupt | close
|
|
6
|
-
- baseUrl: target easbot service base URL (required for connect, e.g.
|
|
5
|
+
- baseUrl: target easbot service base URL (required for connect, e.g. ws://localhost:3000)
|
|
7
6
|
- connectionId: local connection id (required for remote ops: capabilities/send/interrupt/close/status; auto-resolved from baseUrl if not provided)
|
|
8
7
|
- prompt: message to send (required for send)
|
|
9
8
|
|
|
@@ -12,35 +11,42 @@ Operations:
|
|
|
12
11
|
- Required: baseUrl (connectionId not needed)
|
|
13
12
|
- Returns: connectionId, sessionId, remoteAgentId, channel
|
|
14
13
|
- No service registration required; pure URL connection is supported
|
|
14
|
+
|
|
15
15
|
2. list: List all locally managed connections (active sessions)
|
|
16
|
-
- Returns: array of connection info with connectionId, baseUrl, sessionId,
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
- Returns: array of
|
|
16
|
+
- Returns: array of connection info with connectionId, baseUrl, sessionId, channel
|
|
17
|
+
|
|
18
|
+
3. discover: Discover available agent services
|
|
19
|
+
- Returns: array of { name, status, baseUrl }
|
|
20
|
+
|
|
20
21
|
4. capabilities: Query remote agent capabilities (ACP initialize)
|
|
21
22
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
22
|
-
- Returns: protocolVersion,
|
|
23
|
+
- Returns: protocolVersion, authMethods
|
|
24
|
+
|
|
23
25
|
5. send: Push one message to remote session
|
|
24
26
|
- Required: connectionId, prompt
|
|
25
27
|
- Automatically establishes event subscription on first send
|
|
26
28
|
- Remote responses are injected into local SessionPrompt asynchronously
|
|
27
29
|
- Returns: pending round info (waiting for remote response)
|
|
30
|
+
|
|
28
31
|
6. status: Inspect local managed connection state
|
|
29
32
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
30
|
-
- Returns: connection state including sessionId, baseUrl,
|
|
33
|
+
- Returns: connection state including sessionId, baseUrl, status
|
|
34
|
+
|
|
31
35
|
7. config: Inspect local agent client config and managed connections count
|
|
32
|
-
- Returns:
|
|
36
|
+
- Returns: server config (channel, port, hostname) and managedConnections count
|
|
37
|
+
|
|
33
38
|
8. interrupt: Cancel remote session and cleanup local interaction state
|
|
34
39
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
35
40
|
- Sends interrupt signal to remote server, cancels subscription
|
|
36
41
|
- Use when you need to abort an ongoing interaction
|
|
42
|
+
|
|
37
43
|
9. close: Release local connection state and cleanup all interaction resources
|
|
38
44
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
39
45
|
- Always call close when done to prevent resource leaks
|
|
40
46
|
|
|
41
47
|
Connection Flow:
|
|
42
|
-
1. connect + baseUrl
|
|
43
|
-
2. Other operations use connectionId
|
|
48
|
+
1. connect + baseUrl -> creates connection, returns connectionId
|
|
49
|
+
2. Other operations use connectionId -> auto-resolved from baseUrl if not provided
|
|
44
50
|
3. If baseUrl provided but no connectionId, searches existing connections by baseUrl
|
|
45
51
|
4. If no matching connection found, connect operation is required first
|
|
46
52
|
5. Use discover to find available services before connecting
|
|
@@ -56,11 +62,14 @@ Round Control:
|
|
|
56
62
|
- Use `close` to manually cleanup when interaction is complete
|
|
57
63
|
|
|
58
64
|
Returns:
|
|
59
|
-
- Standard tool result: { title, metadata: { count, ... }, output:
|
|
60
|
-
-
|
|
61
|
-
-
|
|
62
|
-
-
|
|
63
|
-
-
|
|
65
|
+
- Standard tool result: { title, metadata: { count, ... }, output: XML format }
|
|
66
|
+
- Output format is XML-like for easy parsing:
|
|
67
|
+
- <config>: configuration info
|
|
68
|
+
- <connections>: list of active connections
|
|
69
|
+
- <connection>: single connection details
|
|
70
|
+
- <services>: discovered agent services
|
|
71
|
+
- <capabilities>: remote agent capabilities
|
|
72
|
+
- <agent_message>: message sent status, response will be injected automatically
|
|
64
73
|
|
|
65
74
|
Notes:
|
|
66
75
|
- Send without prior connect will fail with explicit error
|
|
@@ -70,3 +79,4 @@ Notes:
|
|
|
70
79
|
- Use `interrupt` to abort an ongoing interaction before completion
|
|
71
80
|
- Pure URL connection: no service registration needed, just provide baseUrl
|
|
72
81
|
- Use discover to find available agent services before connecting
|
|
82
|
+
- Supports HTTP and WebSocket channels only
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-LAHYVX5K.mjs';import {a as a$3}from'./chunk-LNK3TPGD.mjs';import'./chunk-VII7JKGB.mjs';import {g,e as e$1,d,k,i as i$1,b as b$2,h,c,a as a$4}from'./chunk-M3K32WJV.mjs';import {Ha,xa,Oa,qb,la,ma,za,Aa,pb,Q}from'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import {e,f}from'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import {b}from'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-6AVNQKBM.mjs';import {b as b$1}from'./chunk-X6ISXWBN.mjs';import'commander';import {parseModelId,PKG,createServer,getProxyConfig}from'@easbot/utils';import {applyPatch}from'diff';import Je from'path';import {z}from'zod';import {WebSocketServer}from'ws';import {pathToFileURL}from'url';import {ndJsonStream,AgentSideConnection,RequestError}from'@agentclientprotocol/sdk';var w=a.create({service:"acp-event-bridge"}),Ye={Info:z.object({id:z.string(),content:z.string(),status:z.enum(["in_progress","pending","completed","cancelled"]),priority:z.enum(["high","medium","low"])})},H=class{constructor(e,t){b$1(this,"sdk");b$1(this,"connection");b$1(this,"abortController",null);b$1(this,"started",false);b$1(this,"permissionQueues",new Map);b$1(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"}]);b$1(this,"acpService");this.sdk=e,this.connection=t;}setService(e){this.acpService=e;}async start(){if(this.started){w.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,w.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||w.error("event subscription failed",{error:e});});}async stop(){this.started&&(w.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this.permissionQueues.clear(),w.info("ACP event bridge stopped"));}async runEventSubscription(){for(;;){if(this.abortController?.signal.aborted)return;let e=await this.sdk.global.event({signal:this.abortController?.signal??void 0});for await(let t of e.stream){if(this.abortController?.signal.aborted)return;let n=t?.payload;n&&await this.handleEvent(n).catch(s=>{w.error("failed to handle event",{error:s,type:n.type});});}}}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":await this.handleSessionDeleted(e.properties);break}}async handleSessionStatus(e){let{sessionID:t,status:n}=e;if(w.debug("Handling session status event in ACP bridge",{sessionID:t,status:n}),!this.connection){w.warn("No connection available to publish session status");return}try{await this.connection.extNotification("session.status",{sessionId:t,status:n}),w.debug("Session status published via extNotification",{sessionID:t,status:n});}catch(s){w.error("Failed to publish session status via extNotification",{sessionID:t,status:n,error:s});}}async handleSessionDeleted(e){let{sessionID:t}=e;if(w.info("Handling session deleted event in ACP bridge",{sessionID:t}),!this.connection){w.warn("No connection available to notify session deletion");return}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."}}}),w.debug("Session deletion notified to client",{sessionID:t});}catch(n){w.error("Failed to notify session deletion to client",{sessionID:t,error:n});}}async handlePermissionAsked(e){let{id:t,sessionID:n,permission:s,tool:o,metadata:i}=e,a=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let h=i?.directory??"",I=s==="external_directory"&&i?.tool?he(i.tool):he(s),R=s==="external_directory"&&i?.tool?fe(i.tool,i):fe(s,i),u=await this.connection.requestPermission({sessionId:n,toolCall:{callID:o?.callID??t,status:"pending",title:s,rawInput:i,kind:I,locations:(R??[]).map(m=>m.path)},options:this.permissionOptions}).catch(async m=>{w.error("failed to request permission from ACP",{error:m,permissionID:t,sessionID:n}),await this.sdk.permission.reply({requestID:t,reply:"reject",directory:h});});if(u){if(u.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestID:t,reply:"reject",directory:h});return}if(u.outcome.optionId!=="reject"&&s==="edit"){let m=i?.filepath??i?.filePath??"",p=i?.diff??"";if(m&&p){let c=PKG.file(m),S=await c.exists()?await c.text():"",g=Ze(S,p);g&&await this.connection.extMethod("client.writeTextFile",{sessionId:n,path:m,content:g});}}await this.sdk.permission.reply({requestID:t,reply:u.outcome.optionId,directory:h});}}).catch(h=>{w.error("failed to handle permission",{error:h,permissionID:t});}).finally(()=>{this.permissionQueues.get(n)===a&&this.permissionQueues.delete(n);});this.permissionQueues.set(n,a);}async handleQuestionAsked(e){let{id:t,sessionID:n,questions:s}=e,o="";w.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){w.warn("Question request returned no result"),await this.sdk.question.reject({requestID:t,directory:o});return}w.debug("Question request completed",{requestID:t,outcome:i.outcome,answerCount:i.answers?.length??0}),i.outcome==="selected"&&i.answers&&i.answers.length>0?(await this.sdk.question.reply({requestID:t,answers:i.answers.map(l=>[l.answer]),directory:o}),w.debug("Question answers submitted",{requestID:t})):(await this.sdk.question.reject({requestID:t,directory:o}),w.debug("Question rejected",{requestID:t}));}catch(i){w.error("Failed to handle question via extMethod",{error:i instanceof Error?i.message:String(i),requestID:t,sessionID:n}),await this.sdk.question.reject({requestID:t,directory:o});}}async handleMessagePartUpdated(e){let{part:t}=e;w.debug("message part updated",{event:e});let n=await this.sdk.session.message({sessionID:t.sessionID,messageID:t.messageID},{throwOnError:true}).then(s=>s.data).catch(s=>{s instanceof Error&&s.name==="NotFoundError"?w.debug("message not found, skipping",{sessionID:t.sessionID,messageID:t.messageID}):w.error("unexpected error when fetching message",{error:s});});!n||n.info.role!=="assistant"||(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:o,messageID:i}=e,l=he(s);switch(o.status){case "pending":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:s,kind:l,status:"pending",locations:[],rawInput:{},_meta:{messageId:i}}}).catch(a=>{w.error("failed to send tool pending to ACP",{error:a});});return;case "running":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"in_progress",kind:l,title:s,locations:fe(s,o.input),rawInput:o.input,_meta:{messageId:i}}}).catch(a=>{w.error("failed to send tool in_progress to ACP",{error:a});});return;case "completed":{let a=[{type:"content",content:{type:"text",text:o.output}}];if(l==="edit"){let h=o.input,I=h.filePath??h.filepath??"",R=h.oldString??"",u=h.newString??h.content??"";a.push({type:"diff",path:I,oldText:R,newText:u});}if(s==="todo"){let h=Ye.Info.array().safeParse(JSON.parse(o.output));h.success&&o.input.operation==="write"&&await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:h.data.map(I=>{let R=I.status==="cancelled"?"completed":I.status;return {priority:I.priority,status:R,content:I.content}})}}).catch(I=>{w.error("failed to send session update for todo",{error:I});});}await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:l,content:a,title:o.title??s,rawInput:o.input,rawOutput:{output:o.output,metadata:o.metadata},_meta:{messageId:i}}}).catch(h=>{w.error("failed to send tool completed to ACP",{error:h});});return}case "error":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:l,title:s,rawInput:o.input,content:[{type:"content",content:{type:"text",text:o.error}}],rawOutput:{error:o.error},_meta:{messageId:i}}}).catch(a=>{w.error("failed to send tool error to ACP",{error:a});});return}}async handleTextPart(e,t){if(e.ignored===true||!("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(o=>{w.error("failed to send text to ACP",{error:o});});}async handleReasoningPart(e,t){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(o=>{w.error("failed to send reasoning to ACP",{error:o});});}async handleStepFinishPart(e){let{sessionID:t,messageID:n,tokens:s}=e;if(!this.connection)return;let o=(s?.input??0)+(s?.reasoning??0),i=await this.getContextLimit(t,n);await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:o,size:i,_meta:{messageId:n}}}).catch(l=>{w.error("failed to send usage_update for step-finish",{error:l});});}async getContextLimit(e,t){try{let s=(await this.sdk.session.messages({sessionID:e}).then(o=>o.data).catch(()=>{}))?.find(o=>o.info.id===t);if(s){let o=s.info;if(o.providerID&&o.modelID)return (await this.sdk.config.providers({}).then(h=>h.data?.providers??[]).catch(()=>[])).find(h=>h.id===o.providerID)?.models[o.modelID]?.limit?.context??2e5}}catch(n){w.debug("failed to get context limit",{error:n});}return 2e5}};function he(r){switch(r.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 fe(r,e){if(!e)return [];switch(r.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??"",o=e.realPath??"",i=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return o?[{path:o}]:s?[{path:s}]:[];if(n==="list"||n==="glob"||n==="grep"){let a=o??s,h=a?Je.posix.dirname(a):i;return h?[{path:h}]:[]}let l=o??s;return l?[{path:l}]:i?[{path:i}]:[]}default:return []}}function Ze(r,e){try{let t=applyPatch(r,e);return t===!1?null:t}catch{return null}}z.object({agentId:z.string(),agentType:z.string(),directory:z.string(),timestamp:z.number()});z.object({agentId:z.string(),reason:z.enum(["normal","error","timeout"]),timestamp:z.number()});z.object({agentId:z.string(),status:z.enum(["idle","busy","error"]),timestamp:z.number()});z.object({agentId:z.string(),error:z.string(),context:z.record(z.string(),z.any()).optional(),timestamp:z.number()});z.object({sessionId:z.string(),update:z.record(z.string(),z.any()),timestamp:z.number()});z.object({requestId:z.string(),sessionId:z.string(),permission:z.string(),tool:z.object({callID:z.string().optional()}).optional(),metadata:z.record(z.string(),z.any()).optional(),timestamp:z.number()});z.object({sessionId:z.string(),timestamp:z.number()});z.object({sessionId:z.string(),inputTokens:z.number(),outputTokens:z.number(),totalTokens:z.number(),model:z.string(),timestamp:z.number()});z.object({sessionId:z.string(),messageId:z.string(),messageType:z.enum(["text","tool_call","tool_result","system"]),content:z.any(),timestamp:z.number()});z.object({sessionId:z.string(),messageId:z.string(),messageType:z.enum(["text","tool_call","tool_result","system"]),response:z.any(),duration:z.number(),timestamp:z.number()});z.object({sessionId:z.string(),messageId:z.string(),toolName:z.string(),input:z.record(z.string(),z.any()),output:z.any().optional(),status:z.enum(["started","completed","failed"]),error:z.string().optional(),duration:z.number().optional(),timestamp:z.number()});z.object({sessionId:z.string().optional(),errorType:z.enum(["connection","timeout","validation","runtime","unknown"]),code:z.string().optional(),message:z.string(),stack:z.string().optional(),context:z.record(z.string(),z.any()).optional(),timestamp:z.number()});z.object({sessionId:z.string(),previousState:z.enum(["idle","active","paused","terminated"]),newState:z.enum(["idle","active","paused","terminated"]),reason:z.string().optional(),timestamp:z.number()});a.create({service:"event-subscription-manager"});var ie=class{constructor(){b$1(this,"log",a.create({service:"event-subscription-manager"}));b$1(this,"subscriptions",new Map);}subscribe(e,t){return this.subscriptions.has(e)||this.subscriptions.set(e,new Set),this.subscriptions.get(e).add(t),this.log.debug("Event subscription added",{eventType:e}),()=>{this.unsubscribe(e,t);}}unsubscribe(e,t){let n=this.subscriptions.get(e);n&&(n.delete(t),n.size===0&&this.subscriptions.delete(e),this.log.debug("Event subscription removed",{eventType:e}));}unsubscribeAll(){this.subscriptions.clear(),this.log.debug("All event subscriptions removed");}async publish(e,t){this.log.debug("Publishing event",{eventType:e});let n=[],s=this.subscriptions.get(e);s&&n.push(...s);let o=this.subscriptions.get("*");o&&n.push(...o),await Promise.all(n.map(async i=>{try{await i(t);}catch(l){this.log.error("Event callback failed",{error:l instanceof Error?l.message:String(l),eventType:e});}})),this.log.debug("Event published",{eventType:e,callbackCount:n.length});}getSubscriptionCount(e){if(e)return this.subscriptions.get(e)?.size??0;let t=0;for(let n of this.subscriptions.values())t+=n.size;return t}getSubscribedEventTypes(){return Array.from(this.subscriptions.keys())}};a.create({service:"event-subscription-flow"});var B={HTTP:"http",STDIO:"stdio",WEBSOCKET:"websocket"},J=class r extends Error{constructor(t,n=[]){super(t);b$1(this,"conflictingModes");this.name="ServiceModeConflictError",this.conflictingModes=n,Object.setPrototypeOf(this,r.prototype);}getConflictingModesDescription(){return this.conflictingModes.length===0?"No modes specified":this.conflictingModes.join(", ")}};function Xe(r){let e=[];return r.channel&&e.push(r.channel),e}function Oe(r){let e=Xe(r);if(e.length===0)throw new J("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw new J(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var Ne={channel:B.WEBSOCKET,port:3e3,hostname:"localhost",timeout:3e4,historyScope:"session",historyWindowSize:10,degradePolicy:"streaming_first",sessionExpireMs:300*1e3};var q=a.create({service:"acp-server-config"}),G="EAS_";function Ue(r){return !(!r||r.trim()===""||r.startsWith("-")||r.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(r))}function qe(r){return Number.isInteger(r)&&r>=1&&r<=65535}function ze(r){return Number.isFinite(r)&&r>0}function Be(r){let e={...Ne,...r};try{Oe(e);}catch(t){throw t instanceof J&&q.error("Invalid service mode configuration",{message:t.message,conflictingModes:t.conflictingModes}),t}if(e.port!==void 0&&!qe(e.port)){let t=new Error(`Invalid port number: ${e.port}. Must be between 1 and 65535`);throw q.error("Invalid port configuration",{port:e.port}),t}if(e.hostname!==void 0&&!Ue(e.hostname)){let t=new Error(`Invalid hostname: ${e.hostname}`);throw q.error("Invalid hostname configuration",{hostname:e.hostname}),t}if(e.timeout!==void 0&&!ze(e.timeout)){let t=new Error(`Invalid timeout: ${e.timeout}. Must be a positive number`);throw q.error("Invalid timeout configuration",{timeout:e.timeout}),t}if(e.channel===B.STDIO&&e.stdio&&(!e.stdio.command||e.stdio.command.trim()==="")){let t=new Error("STDIO command is required");throw q.error("Invalid stdio configuration",{command:e.stdio.command}),t}return q.debug("ACPServer config loaded",{channel:e.channel,port:e.port,hostname:e.hostname}),e}function et(){let r={},e=process.env[`${G}ACP_CHANNEL`];if(e){let a=e.toLowerCase();Object.values(B).includes(a)?r.channel=a:q.warn("Invalid EAS_ACP_CHANNEL environment variable",{value:e});}let t=process.env[`${G}ACP_PORT`];if(t){let a=parseInt(t,10);qe(a)?r.port=a:q.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${G}ACP_HOSTNAME`];n&&(Ue(n)?r.hostname=n:q.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let s=process.env[`${G}ACP_TIMEOUT`];if(s){let a=parseInt(s,10);ze(a)?r.timeout=a:q.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:s});}let o=process.env[`${G}ACP_HISTORY_SCOPE`];o&&(["session","peer","global"].includes(o)?r.historyScope=o:q.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:o}));let i=process.env[`${G}ACP_HISTORY_WINDOW_SIZE`];if(i){let a=parseInt(i,10);Number.isInteger(a)&&a>0?r.historyWindowSize=a:q.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:i});}let l=process.env[`${G}ACP_DEGRADE_POLICY`];return l&&(["polling_only","streaming_first"].includes(l)?r.degradePolicy=l:q.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:l})),q.debug("Config loaded from environment",{config:r}),r}function Le(r){let e=et(),t={...e,...r};return q.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:r,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}var Se=a.create({service:"acp-rpc-handler"}),tt={INTERNAL_ERROR:-32603},Y=class{constructor(e){b$1(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:s}=e;Se.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:s});try{let o;switch(t){case "initialize":o=await this.handleInitialize(n);break;case "authenticate":o=await this.handleAuthenticate(n);break;case "session.new":case "newSession":o=await this.handleNewSession(n);break;case "session.load":case "loadSession":o=await this.handleLoadSession(n);break;case "session.close":case "closeSession":o=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":o=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),o={success:!0};break;case "session.list":case "listSessions":o=await this.handleListSessions(n);break;case "session.fork":case "forkSession":o=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":o=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":o=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":o=await this.handleSetSessionConfigOption(n);break;case "status":o=this.handleStatus();break;case "subscriptions":o=this.handleSubscriptions();break;default:throw Se.warn("Unknown method",{method:t}),new Error(`Method not found: ${t}`)}return {jsonrpc:"2.0",id:s,result:o}}catch(o){return Se.error("AcpRpcHandler error",{method:t,error:o instanceof Error?o.message:String(o)}),{jsonrpc:"2.0",id:s,error:{code:tt.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)}}}}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 re=a.create({service:"server-agent-side-connection"}),Z=class{constructor(){b$1(this,"broadcaster",null);b$1(this,"sessionIds",new Set);}setBroadcaster(e){this.broadcaster=e;}addSession(e){this.sessionIds.add(e);}removeSession(e){this.sessionIds.delete(e);}clearSessions(){this.sessionIds.clear();}getSessions(){return Array.from(this.sessionIds)}async sessionUpdate(e){let{sessionId:t,update:n}=e;re.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return re.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async extMethod(e,t){return re.debug("ServerAgentSideConnection.extMethod",{method:e}),{}}async extNotification(e,t){if(re.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 W=a.create({service:"http-server"});async function $e(r,e){if(W.info("Starting HTTP server",{port:e.port,hostname:e.hostname}),e.channel!==B.HTTP)throw new Error("Invalid channel type for HTTP server");let t=new Map,n=new Map,s=new Z,o={broadcast:(c,S)=>{I(c,S);}};s.setBroadcaster(o);let i=new Y(r),l=r.getSDK();if(!l)throw new Error("SDK not configured");let a=new H(l,s);a.setService(r),await a.start();let h=(c,S)=>{let g=t.get(c);if(!g)return false;try{return g.controller.enqueue(new TextEncoder().encode(S)),g.lastHeartbeat=Date.now(),!0}catch(f){return W.warn("Failed to push to SSE connection",{connectionId:c,error:f instanceof Error?f.message:String(f)}),false}},I=(c,S)=>{let g=n.get(c);if(!g||g.size===0)return;let v={jsonrpc:"2.0",method:S.update.sessionUpdate,params:{sessionId:c,...S.update,timestamp:Date.now()}},b=`data: ${JSON.stringify(v)}
|
|
2
|
+
|
|
3
|
+
`;for(let k of g)h(k,b)||(t.delete(k),g.delete(k));},R=(c,S)=>(s.addSession(c),new ReadableStream({start:g=>{let f={id:S,controller:g,sessionId:c,createdAt:Date.now(),lastHeartbeat:Date.now()};t.set(S,f),n.has(c)||n.set(c,new Set),n.get(c).add(S),W.info("SSE client connected",{connectionId:S,sessionId:c});let v=`data: ${JSON.stringify({type:"connected",connectionId:S,sessionId:c})}
|
|
4
|
+
|
|
5
|
+
`;g.enqueue(new TextEncoder().encode(v));},cancel:()=>{let g=t.get(S);if(g){t.delete(S);let f=n.get(g.sessionId);f&&(f.delete(S),f.size===0&&(n.delete(g.sessionId),s.removeSession(g.sessionId))),W.info("SSE client disconnected",{connectionId:S,sessionId:g.sessionId});}}})),u=setInterval(()=>{let c=Date.now(),S=3e5;for(let[g,f]of t.entries())if(c-f.lastHeartbeat>S){W.warn("SSE connection timeout, closing",{connectionId:g});try{f.controller.close();}catch{}t.delete(g);let v=n.get(f.sessionId);v&&v.delete(g);}else try{f.controller.enqueue(new TextEncoder().encode(`: heartbeat
|
|
6
|
+
|
|
7
|
+
`)),f.lastHeartbeat=c;}catch{}},1e4),m=[{method:"post",path:"/acp",handler:async c=>{let S=await c.req.json().catch(()=>null);if(!S||typeof S!="object")return c.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}},400);let g=S;if(!g.method||g.jsonrpc!=="2.0")return c.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request"}},400);if(g.method==="session.prompt")return i.handle(g).catch(v=>{W.error("HTTP server: session.prompt error",{error:String(v)});}),c.json({jsonrpc:"2.0",id:g.id,result:{accepted:true}},202);let f=await i.handle(g);if(g.method==="initialize"){let v=`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;return c.json(f,200,{"Acp-Connection-Id":v})}return c.json(f)}},{method:"get",path:"/acp",handler:c=>{let S=c.req.header("Acp-Connection-Id"),g=c.req.header("Acp-Session-Id");if(!c.req.header("Accept")?.includes("text/event-stream"))return c.json({error:"Not Acceptable"},406);let v=S||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(g){let _=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,x=R(g,_);return new Response(x,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":v,"Acp-Session-Id":g}})}let b=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,k=R("__connection__",b);return new Response(k,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":v}})}},{method:"delete",path:"/acp",handler:async c=>{let S=c.req.header("Acp-Connection-Id");return W.debug("HTTP server: connection terminated",{connectionId:S}),c.json({success:true})}}],p=createServer({port:e.port,hostname:e.hostname,routes:m,timeout:e.timeout,cors:true});return W.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:p,stop:async()=>{W.info("Stopping HTTP server"),clearInterval(u),await a.stop();for(let c of t.values())try{c.controller.close();}catch{}t.clear(),n.clear(),s.clearSessions(),await p.stop(),W.info("HTTP server stopped");}}}var $=a.create({service:"websocket-server"});function it(r){try{let e=new URL(r),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 je(r,e){let t=e.ws?it(e.ws.url):void 0,n=t?.port??e.port??3e3,s=t?.hostname??e.hostname??"localhost",o="/acp";if($.info("Starting WebSocket server",{port:n,hostname:s,wsUrl:e.ws?.url}),e.channel!==B.WEBSOCKET)throw new Error("Invalid channel type for WebSocket server");let i=new Map,l=new Map,a=new Z,h={broadcast:(f,v)=>{m(f,v);}};a.setBroadcaster(h);let I=new Y(r),R=r.getSDK();if(!R)throw new Error("SDK not configured");let u=new H(R,a);u.setService(r),await u.start();let m=(f,v)=>{let k={jsonrpc:"2.0",method:v.update.sessionUpdate,params:{sessionId:f,...v.update,timestamp:Date.now()}},_=JSON.stringify(k);for(let[x,L]of l.entries())if(L.subscribedSessions.has(f)){let E=i.get(x);E&&E.ws.readyState===E.ws.OPEN&&E.ws.send(_);}},p=f=>{for(let[v,b]of i.entries())if(b.ws===f)return v},c={onOpen:(f,v)=>{let b=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;i.set(b,{id:b,ws:v,createdAt:Date.now()}),l.set(b,{clientId:b,subscribedSessions:new Set}),$.info("WebSocket client connected",{clientId:b}),v.send(JSON.stringify({type:"connected",clientId:b}));},onMessage:async(f,v)=>{try{let b=JSON.parse(f.data.toString());if(b.type==="ping"){v.send(JSON.stringify({type:"pong"}));return}let k=p(v);if(!k)return;let _,x;if(b.type==="message"||b.type==="request")_={jsonrpc:"2.0",id:b.id,method:b.method,params:b.params},x=b.sessionId;else if(b.jsonrpc==="2.0"&&b.method)_={jsonrpc:"2.0",id:b.id,method:b.method,params:b.params},x=b.params?.sessionId;else {$.warn("WebSocket server: unknown message format",{data:b});return}if(_.method==="session.subscribe"){if(x){let E=l.get(k);E&&(E.subscribedSessions.add(x),a.addSession(x));}v.send(JSON.stringify({type:"response",id:_.id,result:{subscribed:!0,sessionId:x}}));return}if(_.method==="session.unsubscribe"){if(x){let E=l.get(k);E&&(E.subscribedSessions.delete(x),E.subscribedSessions.size===0&&a.removeSession(x));}v.send(JSON.stringify({type:"response",id:_.id,result:{unsubscribed:!0,sessionId:x}}));return}if(_.method==="session.interrupt"){let E={jsonrpc:"2.0",method:"session.cancel",params:{sessionId:x}},z=await I.handle(E);v.send(JSON.stringify({type:"response",id:_.id,result:z.result,error:z.error}));return}if(_.method==="session.prompt"){if(v.send(JSON.stringify({jsonrpc:"2.0",id:_.id,result:{accepted:!0}})),x){let E=i.get(k);E&&(E.sessionId=x);let z=l.get(k);z&&(z.subscribedSessions.add(x),a.addSession(x));}I.handle(_).catch(E=>{$.error("WebSocket server: session.prompt error",{error:String(E)});});return}if(x){let E=i.get(k);E&&(E.sessionId=x);let z=l.get(k);z&&(z.subscribedSessions.add(x),a.addSession(x));}let L=await I.handle(_);v.send(JSON.stringify({type:"response",id:L.id,result:L.result,error:L.error}));}catch(b){$.error("WebSocket server: error handling message",{error:String(b)});}},onClose:(f,v)=>{let b=p(v);if(b){i.delete(b);let k=l.get(b);if(k){for(let _ of k.subscribedSessions)a.removeSession(_);l.delete(b);}$.info("WebSocket client disconnected",{clientId:b});}},onError:(f,v)=>{$.error("WebSocket error",{error:f.type});}},S=createServer({port:n,hostname:s,routes:[{method:"post",path:"/acp",handler:async f=>{let v=await f.req.json().catch(()=>null);if(!v||typeof v!="object")return f.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}});let b=v;if(!b.method||b.jsonrpc!=="2.0")return f.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request"}});let k=await I.handle(b);return f.json(k)}},{method:"delete",path:"/acp",handler:async f=>{let v=f.req.header("Acp-Connection-Id");return $.debug("WebSocket server: connection terminated",{connectionId:v}),f.json({success:true})}}],timeout:e.timeout,cors:true}),g=S.raw;if(g){let f=new WebSocketServer({noServer:true});g.on("upgrade",(v,b,k)=>{try{let x=new URL(v.url||"/",`http://${v.headers.host}`).pathname,L=v.headers.upgrade?.toLowerCase();x===o&&L==="websocket"&&f.handleUpgrade(v,b,k,E=>{c.onOpen?.({type:"open"},E),E.on("message",z=>{c.onMessage?.({data:z},E);}),E.on("close",(z,Ve)=>{c.onClose?.({code:z,reason:Ve},E);}),E.on("error",z=>{c.onError?.({type:"error",message:z.message},E);});});}catch{}});}return $.info("WebSocket server started",{url:e.ws?.url||`ws://${s}:${n}`,path:o}),{server:S,stop:async()=>{$.info("Stopping WebSocket server"),await u.stop();for(let f of i.values())try{f.ws.close();}catch{}i.clear(),l.clear(),a.clearSessions(),await S.stop(),$.info("WebSocket server stopped");}}}var ae=a.create({service:"acp-server"});async function We(r,e){let t=Le(Be(e||{}));ae.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,s;switch(t.channel){case B.HTTP:({server:n,stop:s}=await $e(r,t));break;case B.WEBSOCKET:({server:n,stop:s}=await je(r,t));break;default:throw new Error(`Unsupported service mode: ${t.channel}`)}let o={type:t.channel,server:n,agent:r,stop:async()=>{ae.info("Stopping ACPServer",{type:t.channel}),await s();},healthCheck:async()=>{if(typeof n=="object"&&n!==null&&"healthCheck"in n){let i=n.healthCheck;if(typeof i=="function")return i()}return true}};return ae.info("ACPServer started successfully",{type:o.type,url:rt(t)}),o}function rt(r){switch(r.channel){case B.STDIO:return "stdio://process";case B.HTTP:return `http://${r.hostname}:${r.port}`;case B.WEBSOCKET:return `ws://${r.hostname}:${r.port}`;default:return "unknown://"}}async function at(r){await Promise.all(r.map(async e=>{try{await e.stop();}catch(t){ae.error("Error stopping server",{type:e.type,error:String(t)});}}));}async function He(r){await at([r]);}z.object({agentId:z.string(),agentType:z.string(),directory:z.string(),timestamp:z.number()});z.object({agentId:z.string(),reason:z.enum(["normal","error","timeout"]),timestamp:z.number()});z.object({sessionId:z.string(),messageType:z.enum(["text","tool_call","tool_result"]),content:z.any(),timestamp:z.number()});z.object({agentId:z.string(),error:z.string(),context:z.record(z.string(),z.any()).optional(),timestamp:z.number()});z.object({agentId:z.string(),status:z.enum(["idle","busy","error"]),timestamp:z.number()});var ce=a.create({service:"acp-session-manager"}),se=class{constructor(e){b$1(this,"sessions",new Map);b$1(this,"sdk");this.sdk=e;}tryGet(e){return this.sessions.get(e)}async create(e,t,n,s){let i={id:e,cwd:t,mcpServers:n,createdAt:new Date,model:s};return ce.info("creating_session",{state:i}),this.sessions.set(e,i),i}async load(e,t,n,s){let o=await this.sdk.session.get({sessionID:e,directory:t},{throwOnError:true}).then(a=>a.data),i=s,l={id:e,cwd:t,mcpServers:n,createdAt:new Date(o.time.created),model:i};return ce.info("loading_session",{state:l}),this.sessions.set(e,l),l}get(e){let t=this.sessions.get(e);if(!t)throw ce.error("session not found",{sessionId:e}),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 P=a.create({service:"acp-service"}),oe=class{constructor(e,t){b$1(this,"eventBus");b$1(this,"config");b$1(this,"serviceMode");b$1(this,"connection");b$1(this,"sdk");b$1(this,"connectionRegistry",null);b$1(this,"sessionRouter",null);b$1(this,"sessionManager");b$1(this,"executorInitialized",false);b$1(this,"status","initializing");this.connection=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.eventBus=new ie,this.sessionManager=new se(this.sdk),t.connectionRegistry&&(this.connectionRegistry=t.connectionRegistry),t.sessionRouter&&(this.sessionRouter=t.sessionRouter),P.info("ACPService instance created",{channel:t.channel.type,hasConnection:!!e,hasProvidedRegistry:!!t.connectionRegistry,hasProvidedRouter:!!t.sessionRouter});}async initializeExecutor(){if(this.executorInitialized){P.warn("Executor components already initialized");return}this.connectionRegistry||(this.connectionRegistry=await la.create(),P.debug("ConnectionRegistry created")),this.sessionRouter||(this.sessionRouter=ma.fromRegistry({resolve:e=>this.connectionRegistry.resolve(e),getConnectionsByPeer:e=>this.connectionRegistry.getConnectionsByAgent(e),getConnectionsByService:e=>this.connectionRegistry.getConnectionsByService(e)}),P.debug("SessionRouter created")),this.executorInitialized=true,P.info("Executor components initialized");}setStatus(e,t="agent"){let n=this.status;if(n===e)return;this.status=e,P.info("Agent status changed",{oldStatus:n,newStatus:e,agentId:t});let s=pt(e);this.eventBus.publish("agent.status",{type:"agent.status",properties:{agentId:t,status:s,timestamp:Date.now()}});}getStatus(){return this.status}authenticate(e){return Promise.resolve(void 0)}async newSession(e){P.info("ACP newSession requested",{cwd:e.cwd});let t=e.cwd,s=(await this.sdk.model.default())?.data,i=(await this.sdk.session.create({directory:t})).data?.id;if(!i)throw new Error("Failed to create session: no session ID returned");let l=await this.sessionManager.create(i,t,e.mcpServers,s),a=await this.buildSessionStateResponse(l.id,t);return {sessionId:l.id,...a,_meta:{}}}async loadSession(e){P.info("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=n.model??(await this.sdk.model.default())?.data,l=n.agent??(await this.sdk.agent.default({directory:s}))?.data?.name??"build";await this.sendAvailableCommandsUpdate(t,s);let a=[];for(let u of e.prompt)switch(u.type){case "text":{let m=u.annotations?.audience,p=m?.length===1&&m[0]==="assistant",c=m?.length===1&&m[0]==="user";a.push({type:"text",text:u.text,...p&&{synthetic:true},...c&&{ignored:true}});break}case "image":{let m=this.parseUri(u.uri??""),p=m.type==="file"?m.filename:"image";u.data?a.push({type:"file",url:`data:${u.mimeType};base64,${u.data}`,filename:p,mime:u.mimeType}):u.uri?.startsWith("http:")&&a.push({type:"file",url:u.uri,filename:p,mime:u.mimeType});break}case "resource_link":{let m=this.parseUri(u.uri);u.name&&m.type==="file"&&(m.filename=u.name),a.push(m);break}case "resource":{let m=u.resource;if("text"in m&&m.text)a.push({type:"text",text:m.text});else if("blob"in m&&m.blob&&m.mimeType){let p=this.parseUri(m.uri??""),c=p.type==="file"?p.filename:"file";a.push({type:"file",url:`data:${m.mimeType};base64,${m.blob}`,filename:c,mime:m.mimeType});}break}}P.info("prompt parts",{sessionID:t,parts:a});let h=(()=>{let u=a.filter(c=>c.type==="text").map(c=>c.text).join("").trim();if(!u.startsWith("/"))return;let[m,...p]=u.slice(1).split(/\s+/);return {name:m,args:p.join(" ").trim()}})(),I=u=>({totalTokens:u.tokens.input+u.tokens.output+u.tokens.reasoning+(u.tokens.cache?.read??0)+(u.tokens.cache?.write??0),inputTokens:u.tokens.input,outputTokens:u.tokens.output,thoughtTokens:u.tokens.reasoning||void 0,cachedReadTokens:u.tokens.cache?.read||void 0,cachedWriteTokens:u.tokens.cache?.write||void 0});if(!h){let m=(await this.sdk.session.prompt({sessionID:t,model:{providerID:i.providerID,modelID:i.modelID},parts:a,agent:l,directory:s,variant:n.variant,contextMode:n.contextMode})).data?.info;return {stopReason:"end_turn",usage:m?I(m):void 0,_meta:{}}}let R=await this.sdk.command.list({directory:s},{throwOnError:true}).then(u=>u.data?.find(m=>m.name===h.name));if(R){let u=await za.get(h.name),m=await Aa.command({sessionID:t,agent:l,model:i.providerID+"/"+i.modelID,arguments:h.args,command:R.name});if(await this.sendUsageUpdate(t,s),u?.commandType==="local"&&this.connection){let p=m.success?m.output:`[Error] ${m.error??"Command execution failed"}`;await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});}return {stopReason:"end_turn",usage:m.info?I({tokens:{input:m.info.tokens.input,output:m.info.tokens.output,reasoning:m.info.tokens.reasoning,cache:m.info.tokens.cache}}):void 0,_meta:{}}}switch(h.name){case "compact":if(!i.providerID||!i.modelID)throw new Error("Model providerID and modelID are required for compact command");await this.sdk.session.summarize({sessionID:t,directory:s,providerID:i.providerID,modelID:i.modelID},{throwOnError:true});break}return await this.sendUsageUpdate(t,s),{stopReason:"end_turn",_meta:{}}}async cancel(e){let n=this.sessionManager.tryGet(e.sessionId)?.cwd??"";try{this.sdk&&await this.sdk.session.abort({sessionID:e.sessionId,directory:n}).catch(s=>{P.warn("SDK abort failed",{sessionId:e.sessionId,error:String(s)});}),P.info("Session cancelled",{sessionId:e.sessionId});}catch(s){throw P.error("Failed to cancel session",{sessionId:e.sessionId,error:s instanceof Error?s.message:String(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: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;let n=await this.sdk.session.messages({sessionID:e,directory:t},{throwOnError:true}).then(h=>h.data).catch(h=>{P.error("failed to fetch messages for usage update",{error:h});});if(!n)return;let s=n.filter(h=>h.info.role==="assistant"),o=s[s.length-1];if(!o)return;let i=o.info,l=await this.getContextLimit(i.providerID,i.modelID,t);if(!l)return;let a=i.tokens.input+(i.tokens.cache?.read??0);await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:a,size:l}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.connection)try{let s=(await this.sdk.command.list({directory:t},{throwOnError:!0})).data?.map(o=>({name:o.name,description:o.description??""}))??[];await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:s}});}catch(n){P.error("failed to send available commands update",{error:n});}}async sendConfigOptionUpdate(e,t,n){if(this.connection)try{let o=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!o||o.length===0)return;await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:o}});}catch(s){P.error("failed to send config_option_update to ACP client",{sessionId:e,error:s});}}async sendCurrentModeUpdate(e,t){if(this.connection)try{await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"current_mode_update",currentModeId:t}});}catch(n){P.error("failed to send current_mode_update to ACP client",{sessionId:e,modeId:t,error:n});}}async getContextLimit(e,t,n){return this.sdk?(await this.sdk.config.providers({directory:n}).then(l=>l.data?.providers??[]).catch(l=>(P.error("failed to get providers for context limit",{error:l}),[]))).find(l=>l.id===e)?.models[t]?.limit.context??2e5:null}async unstable_forkSession(e){P.info("ACP forkSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.mcpServers??[],o=(await this.sdk.model.default())?.data,i=await this.sdk.session.fork({sessionID:e.sessionId,directory:t},{throwOnError:true}).then(I=>I.data);if(!i)throw new Error("Fork session returned no data");let l=i.id;await this.sessionManager.load(l,t,n,o);let h=await this.buildSessionStateResponse(l,t);return P.info("fork_session",{sessionId:l,mcpServers:n.length}),{sessionId:l,...h,_meta:{}}}async resumeSession(e){P.info("ACP resumeSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.sessionId,s=e.mcpServers??[],i=(await this.sdk.model.default())?.data;await this.sessionManager.load(n,t,s,i);let a=await this.buildSessionStateResponse(n,t);return P.info("resume_session",{sessionId:n,mcpServers:s.length}),{...a,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,o=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(R=>R.data??[])).toSorted((R,u)=>u.time.updated-R.time.updated),l=(t?o.filter(R=>R.time.updated<t):o).slice(0,n),a=l.map(R=>({sessionId:R.id,cwd:R.directory,title:R.title??`Session ${R.id}`,updatedAt:new Date(R.time.updated).toISOString()})),h=l[l.length-1],I=l.length===n&&h?String(h.time.updated):void 0;return {sessions:a,nextCursor:I}}async setSessionMode(e){P.info("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$1){if(P.info("ACP setSessionConfigOption requested",{sessionId:e$1.sessionId,configId:e$1.configId,value:e$1.value}),e$1.configId==="model"){let s=typeof e$1.value=="string"?e$1.value:void 0;if(s){let o=this.parseModelSelection(s);this.sessionManager.setModel(e$1.sessionId,o.model);}}else if(e$1.configId==="agent"){let s=typeof e$1.value=="string"?e$1.value:void 0;this.sessionManager.setAgent(e$1.sessionId,s);}else if(e$1.configId==="thought_level"){let s=typeof e$1.value=="string"?e$1.value:void 0;this.sessionManager.setVariant(e$1.sessionId,s);}else if(e$1.configId==="context_mode"){let s=typeof e$1.value=="string"&&e.includes(e$1.value)?e$1.value:void 0;this.sessionManager.setContextMode(e$1.sessionId,s);}let t=this.sessionManager.get(e$1.sessionId),n=await this.buildSessionStateResponse(e$1.sessionId,t.cwd);return await this.sendConfigOptionUpdate(e$1.sessionId,t.cwd,n),{_meta:{},configOptions:n.configOptions??[]}}async closeSession(e){return P.info("ACP closeSession requested",{sessionId:e.sessionId}),await this.cancel({sessionId:e.sessionId}),this.sessionManager.close(e.sessionId),{_meta:{}}}async buildSessionStateResponse(e$1,t){let n=this.sessionManager.tryGet(e$1),s=n?.model??(await this.sdk.model.default())?.data,o=s?.providerID&&s?.modelID?`${s.providerID}/${s.modelID}`:void 0,i=[];try{i=(await this.sdk.config.providers({directory:t}).then(m=>m.data?.providers??[])).flatMap(m=>{let p=m.models??{};return Object.keys(p).map(c=>({modelId:`${m.id}/${c}`,name:`${m.id}/${c}`}))});}catch(u){P.warn("failed to build available models for session state",{sessionId:e$1,error:u instanceof Error?u.message:String(u)});}o&&!i.some(u=>u.modelId===o)&&(i=[{modelId:o,name:o},...i]);let l=[];try{l=((await this.sdk.app.agents({directory:t})).data??[]).filter(p=>p.hidden!==!0&&p.mode!=="subagent").map(p=>({id:p.name,name:p.name,description:p.description}));}catch(u){P.warn("failed to build available agents for session state",{sessionId:e$1,error:u instanceof Error?u.message:String(u)});}let a=n?.modeId,h=n?.variant??"low",I=n?.contextMode??f,R=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e$1,t),{models:o?{currentModelId:o,availableModels:i}:void 0,modes:a?{currentModeId:a,availableModes:[{id:a,name:a}]}:void 0,configOptions:[{id:"model",name:"Model",category:"model",type:"select",currentValue:o??"",options:i.map(u=>({value:u.modelId,name:u.name,description:u.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:R,options:l.map(u=>({value:u.id,name:u.name,description:u.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:h,options:[{value:"off",name:"Off"},{value:"low",name:"Low"},{value:"medium",name:"Medium"},{value:"high",name:"High"}]},{id:"context_mode",name:"Context Mode",category:"context_mode",type:"select",currentValue:I,options:e.map(u=>({value:u,name:u.charAt(0).toUpperCase()+u.slice(1)}))}]}}parseModelSelection(e){let{provider:t,model:n}=parseModelId(e);return t&&n?{model:{providerID:t,modelID:n}}:{model:{providerID:"unknown",modelID:e}}}subscribeEvents(e){return this.eventBus.subscribe("*",e)}setConnection(e){this.connection=e,P.info("ACPService connection updated");}getConnection(){return this.connection}abortConnection(){this.connection&&P.debug("Connection aborted");}closeConnection(){this.connection&&P.debug("Connection closed");}getConnectionRegistry(){return this.connectionRegistry}getSessionRouter(){return this.sessionRouter}createConnection(e,t,n,s){if(!this.connectionRegistry)throw new Error("ConnectionRegistry not initialized. Call initializeExecutor() first.");if(!t||!n)throw new Error("localAgentId and remoteAgentId are required");return this.connectionRegistry.connect(e,t,n,s)}async routeToConnection(e){if(!this.sessionRouter)throw new Error("SessionRouter not initialized. Call initializeExecutor() first.");return this.sessionRouter.route(e)}async dispose(){P.info("Disposing ACPService"),this.eventBus.unsubscribeAll(),this.sessionManager&&(this.sessionManager.dispose?.(),P.debug("SessionManager disposed")),this.connectionRegistry&&(await this.connectionRegistry.close(),this.connectionRegistry=null,P.debug("ConnectionRegistry closed")),this.sessionRouter=null,this.executorInitialized=false,P.info("ACPService disposed");}};function pt(r){switch(r){case "initializing":case "ready":case "stopped":return "idle";case "running":return "busy";case "error":return "error"}}var U=a.create({service:"easbot-agent"}),X=class r extends oe{constructor(t,n){super(t,n);b$1(this,"acpEventBridge",null);b$1(this,"server",null);b$1(this,"isAgentInitialized",false);U.info("EasBotAgent instance created",{serviceMode:this.serviceMode});}static async create(t){U.info("creating EasBotAgent",{serviceMode:t.serviceMode});let n=t.serviceMode==="stdio",s=new r(void 0,t);if(n&&t.stdioStream){let{stream:o}=t.stdioStream,i={initialize:async a=>s.initialize(a),newSession:async a=>s.newSession(a),loadSession:async a=>s.loadSession(a),prompt:async a=>s.prompt(a),cancel:async a=>s.cancel(a),authenticate:async a=>s.authenticate(a),setSessionMode:async a=>s.setSessionMode(a),setSessionConfigOption:async a=>s.setSessionConfigOption(a),listSessions:async a=>s.listSessions(a),unstable_forkSession:async a=>s.unstable_forkSession(a),resumeSession:async a=>s.resumeSession(a),closeSession:async a=>s.closeSession(a)},l=new AgentSideConnection(()=>i,o);s.setConnection(l);}return U.info("EasBotAgent created successfully",{serviceMode:t.serviceMode,hasConnection:n&&!!t.stdioStream}),s}async initialize(t){return U.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:a$1.getVersion(),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){U.warn("EasBotAgent already initialized");return}U.info("initializing EasBotAgent internals");try{await this.initializeExecutor(),this.config.acpServerConfig||await this.initializeAcpEventBridge(),this.isAgentInitialized=!0,this.setStatus("ready"),U.info("EasBotAgent internals initialized successfully");}catch(t){throw this.setStatus("error"),U.error("failed to initialize EasBotAgent",{error:String(t)}),t}}async start(){if(this.status==="running"){U.warn("EasBotAgent already running");return}this.isAgentInitialized||await this.initializeAgent();let t=this.config;t.acpServerConfig&&!this.server&&(this.server=await We(this,t.acpServerConfig)),this.setStatus("running"),U.info("EasBotAgent started");}async stop(){if(this.status==="stopped"){U.warn("EasBotAgent already stopped");return}U.info("stopping EasBotAgent");try{this.server&&(await He(this.server),this.server=null),this.acpEventBridge&&(await this.acpEventBridge.stop(),this.acpEventBridge=null),await this.dispose(),this.setStatus("stopped"),this.isAgentInitialized=!1,U.info("EasBotAgent stopped successfully");}catch(t){throw this.setStatus("error"),U.error("error stopping EasBotAgent",{error:String(t)}),t}}async initializeAcpEventBridge(){if(this.acpEventBridge){U.warn("ACP event bridge already initialized");return}let n=this.config.acp?.sdk,s=this.getConnection();if(!n)throw U.error("Cannot initialize ACP event bridge: missing SDK client"),new Error("SDK client is required for ACP event bridge");if(!s)throw U.error("Cannot initialize ACP event bridge: missing ACP connection"),new Error("ACP connection is required for ACP event bridge");this.acpEventBridge=new H(n,s),this.acpEventBridge.setService(this),await this.acpEventBridge.start(),U.info("ACP event bridge initialized");}getServiceMode(){return this.serviceMode}getServerInstance(){return this.server}getSDK(){return this.sdk}};var F=class r extends Error{constructor(t,n,s){super(t);b$1(this,"type");b$1(this,"stage");b$1(this,"cause");this.type="AdapterEnvironmentInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,r);}},ee=a.create({service:"adapter.bootstrap"}),ve;function gt(){return ve||(ve=Oa.state(async()=>({initialized:false,initPromise:null,instancePromise:null,handlersInstalled:false,directory:".easbot",sdk:null,activeChannel:null,agent:null,acpConnection:null}),async r=>{let e=r.agent;e&&await e.stop().catch(()=>{}),r.agent=null,r.sdk=null,r.acpConnection=null;})),ve}async function j(){return gt()()}function Ge(r){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=r.code;return e.includes(t??"")}function ht(r){r.handlersInstalled||(process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));Ge(t)||ee.error("unhandled promise rejection",{error:t.message,stack:t.stack});}),process.on("uncaughtException",e=>{Ge(e)||(ee.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));}),r.handlersInstalled=true);}async function ft(r){return r.instancePromise||(r.instancePromise=Oa.provide({directory:r.directory,init:qb,fn:async()=>{ee.debug("instance bootstrap completed");}}).then(()=>{})),r.instancePromise}async function St(){try{await Oa.dispose(),ee.debug("instance disposed");}catch(r){ee.warn("failed to dispose instance",{error:r instanceof Error?r.message:String(r)});}}var V;(m=>{function r(p,c){return p.sdk||(p.sdk=xa({directory:c})),p.sdk}function e(p){switch(p){case "http":return "http";case "stdio":return "stdio";case "websocket":return "websocket";default:return "stdio"}}async function t(p){let c=await j();if(c.initialized)return;if(c.initPromise)return c.initPromise;let S={directory:p?.directory??".easbot",initModels:p?.initModels??true,printLogs:p?.printLogs??false,logLevel:p?.logLevel??"INFO",channel:p?.channel??"stdio"};if(c.directory=S.directory,r(c,c.directory),c.activeChannel&&c.activeChannel!==S.channel)throw new Error(`Adapter already initialized with channel ${c.activeChannel}, cannot re-init with ${S.channel}`);return c.activeChannel=S.channel,c.initPromise=(async()=>{try{await a$1.init();}catch(g){throw new F("Failed to initialize global directories","global",g instanceof Error?g:void 0)}try{await a.init({logDir:a$1.Path.log,print:S.printLogs??!1,level:S.logLevel??"INFO"});}catch(g){throw new F("Failed to initialize log infrastructure","log",g instanceof Error?g:void 0)}if(S.initModels)try{b();}catch(g){throw new F("Failed to initialize models refresh","models",g instanceof Error?g:void 0)}try{ht(c);}catch(g){throw new F("Failed to install unhandled exception handlers","handlers",g instanceof Error?g:void 0)}try{await ft(c);}catch(g){throw new F("Failed to initialize instance","instance",g instanceof Error?g:void 0)}c.initialized=true;})(),c.initPromise}m.init=t;async function n(){let p=await j();if(p.initialized){await Ha.stop().catch(()=>{});try{let{MCP:c}=await import('./mcp-OZVV2MA6.mjs'),S=await c.clients();for(let[g,f]of Object.entries(S))await f.disconnect().catch(()=>{});}catch{}p.agent&&(await p.agent.stop().catch(()=>{}),p.agent=null),await St(),p.initialized=false,p.initPromise=null,p.instancePromise=null,p.activeChannel=null,p.sdk=null,p.agent=null,p.acpConnection=null;}}m.destroy=n;async function s(){return (await j()).initialized}m.isInitialized=s;async function o(p){let c=await j();c.agent=p;}m.setAgent=o;async function i(){return (await j()).agent}m.getAgent=i;async function l(){let c=(await j()).agent?.getServerInstance();return c||null}m.getServer=l;async function a$2(){return (await j()).sdk}m.getSDK=a$2;async function h(){return (await j()).acpConnection}m.getACPConnection=h;async function I(){let p=await j(),c=!!p.agent?.getServerInstance();return {initialized:p.initialized,directory:p.directory,activeChannel:p.activeChannel,hasSDK:!!p.sdk,hasAgent:!!p.agent,hasACPConnection:!!p.acpConnection,hasServer:c}}m.getState=I;async function R(p){await t({channel:p.channel,directory:p.directory});let c=await j(),S=r(c,c.directory);if(p.channel==="stdio")return u({directory:p.directory});if(c.agent?.getServerInstance()&&c.activeChannel&&c.activeChannel!==p.channel)throw new Error(`ACP service already started with channel ${c.activeChannel}, cannot switch to ${p.channel}`);if(c.agent){let b=c.agent.getServerInstance();if(b)return {sdk:S,agent:c.agent,server:b}}let f=await X.create({serviceMode:e(p.channel),acp:{sdk:S},acpServerConfig:p,channel:{type:p.channel,timeout:p.timeout}});await f.start();let v=f.getServerInstance();if(!v)throw new Error("ACP server failed to start");return c.agent=f,c.activeChannel=p.channel,{sdk:S,agent:f,server:v}}m.ensureACPService=R;async function u(p){await t({channel:"stdio",directory:p.directory});let c=await j(),S=r(c,c.directory);if(c.agent)return {sdk:S,agent:c.agent};let g=new WritableStream({write(k){return new Promise((_,x)=>{try{process.stdout.write(k)?_():process.stdout.once("drain",_);}catch(L){let E=L;E.code==="EPIPE"||E.code==="EIO"?x(new Error("stdout pipe broken")):x(L);}})}}),f=new ReadableStream({start(k){process.stdin.on("data",_=>{k.enqueue(new Uint8Array(_));}),process.stdin.on("end",()=>k.close()),process.stdin.on("error",_=>k.error(_));}}),v=ndJsonStream(g,f),b=await X.create({serviceMode:"stdio",acp:{sdk:S},channel:{type:"stdio",timeout:6e4},stdioStream:{stream:v}});return c.acpConnection=b.getConnection()??null,await b.start(),c.agent=b,c.activeChannel="stdio",ee.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:S,agent:b}}m.ensureACPServiceStdio=u;})(V||(V={}));var T=a.create({service:"cli-command-acp"});async function yt(r,e){let t=await pb.getACPServerConfig();T.debug("Merging ACP configuration",{baseConfig:{channel:t.channel,port:t.port,hostname:t.hostname,timeout:t.timeout},cliOptions:{channel:e.channel,port:e.port,hostname:e.hostname,timeout:e.timeout}});let n={};if(e.channel!==void 0){let o=e.channel.toLowerCase();Object.values(Q).includes(o)?(n.channel=o,T.debug("CLI override: channel",{value:n.channel})):T.warn("Invalid channel type from command line",{value:e.channel});}if(e.port!==void 0&&(e.port>0&&e.port<=65535?(n.port=e.port,T.debug("CLI override: port",{value:n.port})):T.warn("Invalid port from command line",{value:e.port})),e.hostname!==void 0&&(n.hostname=e.hostname,T.debug("CLI override: hostname",{value:n.hostname})),e.timeout!==void 0&&(e.timeout>0?(n.timeout=e.timeout,T.debug("CLI override: timeout",{value:n.timeout})):T.warn("Invalid timeout from command line",{value:e.timeout})),e.hostname!==void 0||e.port!==void 0){let o=e.hostname??t.hostname??"127.0.0.1",i=e.port??t.port??3e3;t.ws&&(n.ws={...t.ws,url:`ws://${o}:${i}`}),t.http&&(n.http={...t.http,baseUrl:`http://${o}:${i}`}),T.debug("CLI override: ws.url and http.baseUrl updated",{hostname:e.hostname,port:e.port,wsUrl:n.ws?.url,httpBaseUrl:n.http?.baseUrl});}e.timeout!==void 0&&(n.ws||n.http)&&(n.ws&&(n.ws.timeout=e.timeout),n.http&&(n.http.timeout=e.timeout),T.debug("CLI override: ws.timeout and http.timeout updated",{timeout:e.timeout}));let s={...t,...n};return T.debug("Merged ACP configuration",{channel:s.channel,port:s.port,hostname:s.hostname,timeout:s.timeout}),s}async function Ct(r,e,t){T.info("Starting ACP service",{channel:e.channel,port:e.port,hostname:e.hostname,debug:t.config.debug}),await V.init({directory:r,printLogs:t.config.print_logs,logLevel:t.config.log_level,channel:e.channel});await V.ensureACPService(e);console.log(""),console.log(d(i("acp.server.started"))),console.log(k(60)),console.log(i$1(i("acp.field.directory"),r,15)),console.log(i$1(i("acp.field.worktree"),Oa.project.worktree||"N/A",15)),console.log(i$1(i("acp.field.channel"),e.channel,15));let s=b$2();switch(e.channel){case "websocket":{let i$2,l="/";if(e.ws?.url)try{let a=new URL(e.ws.url),h=a.port||"3000",I=a.hostname;l=a.pathname||"/",i$2=`ws://${I}:${h}${l==="/"?"":l}`;}catch{i$2=e.ws.url;}else i$2=`ws://${e.hostname}:${e.port}`;console.log(i$1(i("acp.field.ws_url"),i$2,15)),console.log(i$1(i("acp.field.ws_path"),l,15)),e.ws?(console.log(h(i("acp.websocket.config"))),console.log(i$1(i("acp.field.timeout"),`${e.ws.timeout??e.timeout}ms`,15)),console.log(i$1(i("acp.field.batch_size"),`${e.ws.batchSize??10}`,15)),console.log(i$1(i("acp.field.batch_interval"),`${e.ws.batchInterval??50}ms`,15)),console.log(i$1(i("acp.field.heartbeat"),`${e.ws.heartbeatInterval??3e4}ms`,15))):console.log(i$1(i("acp.field.timeout"),`${e.timeout}ms`,15));break}case "http":e.http?.baseUrl?console.log(i$1(i("acp.field.base_url"),e.http.baseUrl,15)):console.log(i$1(i("acp.field.host"),`${e.hostname}:${e.port}`,15)),e.http?.timeout?console.log(i$1(i("acp.field.timeout"),`${e.http.timeout}ms`,15)):console.log(i$1(i("acp.field.timeout"),`${e.timeout}ms`,15));break;case "stdio":console.log(i$1(i("acp.field.mode"),i("acp.mode.stdio"),15)),console.log(i$1(i("acp.field.protocol"),i("acp.protocol"),15)),console.log(i$1(i("acp.field.timeout"),`${e.timeout}ms`,15));break;default:console.log(i$1(i("acp.field.host"),`${e.hostname}:${e.port}`,15)),console.log(i$1(i("acp.field.timeout"),`${e.timeout}ms`,15));}console.log(i$1(i("acp.field.debug"),t.config.debug?c(s,a$4.success,i("common.enabled")):c(s,a$4.muted,i("common.disabled")),15));let o=getProxyConfig();if(o.enabled){let i$2=o.https||o.http||"configured";console.log(i$1(i("acp.field.proxy"),i$2,15));}console.log(k(60)),console.log(""),T.info("ACPServer started successfully"),wt();}function wt(){let r=process.env.EASBOT_RUN_MODE==="ephemeral"||!process.stdin.isTTY&&process.env.EASBOT_RUN_MODE!=="persistent",e=async t=>{T.debug(`Received ${t}, shutting down...`),r||console.log(`
|
|
8
|
+
${i("acp.shutdown.received",{vars:{signal:t}})}`);try{await V.destroy(),T.debug("EasbotAdapter state destroyed"),r||console.log(d(i("acp.shutdown.completed")));}catch(n){T.error("Error during shutdown",{error:n instanceof Error?n.message:String(n)});}r?process.kill(process.pid,"SIGKILL"):process.exit(0);};process.on("SIGINT",()=>{e("SIGINT").catch(console.error);}),process.on("SIGTERM",()=>{e("SIGTERM").catch(console.error);}),process.stdout.on("error",t=>{(t.code==="EPIPE"||t.code==="EIO")&&(T.info("stdout pipe broken, exiting"),e("stdout-broken").catch(()=>{r?process.kill(process.pid,"SIGKILL"):process.exit(0);}));});}async function Pt(r,e,t){T.debug("ACP command executed",{options:e});let n=t?.config?.debug??false,s=t?.config?.print_logs??false,o=t?.config?.log_level??"INFO";T.debug("Global options from context",{debug:t?.config?.debug,print_logs:t?.config?.print_logs,log_level:t?.config?.log_level,isDebug:n,printLogs:s,logLevel:o});try{let i$1=t.config.directory?Je.resolve(t.config.directory):process.cwd();T.debug("Working directory resolved",{directory:i$1});let l=a$2(i$1);if(!l.valid)throw T.error("Working directory validation failed",{directory:i$1,error:l.error}),new Error(`Invalid working directory: ${l.error}`);let a=l.normalizedPath;T.debug("Working directory validated",{validatedDirectory:a}),console.log(g(i("acp.directory.resolved",{vars:{cwd:a}}))),await a$3(a,async()=>{let h=await yt(a,e);if(T.debug("ACP server configuration",{channel:h.channel,port:h.port,hostname:h.hostname,timeout:h.timeout,enabled:h.enabled}),!h.enabled){T.warn("ACP server is disabled by configuration"),console.log(g(i("acp.disabled")));return}await Ct(a,h,t),T.info("ACP server started successfully");});}catch(i$1){T.error("Failed to start ACP server",{error:i$1 instanceof Error?i$1.message:String(i$1)}),console.error(e$1(i("acp.error.start_failed",{vars:{error:i$1 instanceof Error?i$1.message:String(i$1)}}))),process.exit(1);}}function Go(r,e){let t=r.command("acp").description(i("acp.command.description")).addHelpText("after",`
|
|
9
|
+
|
|
10
|
+
${i("acp.help.examples")}
|
|
11
|
+
$ agent acp # ${i("acp.help.example.default")}
|
|
12
|
+
$ agent acp --channel http # ${i("acp.help.example.http")}
|
|
13
|
+
$ agent acp --port 8080 # ${i("acp.help.example.port")}
|
|
14
|
+
$ agent acp --hostname 0.0.0.0 # ${i("acp.help.example.hostname")}
|
|
15
|
+
$ agent acp --channel ws --debug # ${i("acp.help.example.debug")}
|
|
16
|
+
|
|
17
|
+
${i("acp.help.env")}
|
|
18
|
+
ACP_CHANNEL ${i("acp.help.env.channel")}
|
|
19
|
+
ACP_PORT ${i("acp.help.env.port")}
|
|
20
|
+
ACP_HOSTNAME ${i("acp.help.env.hostname")}
|
|
21
|
+
ACP_TIMEOUT ${i("acp.help.env.timeout")}
|
|
22
|
+
ACP_ENABLED ${i("acp.help.env.enabled")}`);t.option("-c, --channel <type>",i("acp.option.channel")).option("-p, --port <number>",i("acp.option.port"),n=>parseInt(n,10)).option("-H, --hostname <address>",i("acp.option.hostname")).option("-t, --timeout <milliseconds>",i("acp.option.timeout"),n=>parseInt(n,10)),t.command("*",{isDefault:true}).action(async()=>{let n=t.opts();await Pt(t,n,e);});}export{Go as registerAcpCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{U as getACPClientsConfig,T as getACPServerConfig,X as getAcpAgentName,V as getAcpAgentRuntimeConfig,W as getAcpModelConfig,S as loadACPConfig}from'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-TYD2M4SP.mjs';import'./chunk-FXOUIXIL.mjs';import {a as a$2}from'./chunk-
|
|
1
|
+
import {a as a$3}from'./chunk-TYD2M4SP.mjs';import'./chunk-FXOUIXIL.mjs';import {a as a$2}from'./chunk-LNK3TPGD.mjs';import'./chunk-CQVEAYYW.mjs';import {l,d,e,h,i as i$1,b,c,a as a$4}from'./chunk-M3K32WJV.mjs';import'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import {a as a$1}from'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';var a=a$1.create({service:"cli-command-agent"});function W(C,c$1){let y=C.command("agent").description(i("agent.command.description"));y.command("list").description(i("agent.command.list.description")).action(async()=>{await a$2(c$1.config.directory,async()=>{try{a.debug("Listing agents");let{data:o}=await c$1.sdk.app.agents({});if(!o||o.length===0){console.log(l(i("agent.list.empty")));return}let r=[...o].sort((n,t)=>{let g="native"in n&&n.native,d="native"in t&&t.native;return g!==d?g?-1:1:n.name.localeCompare(t.name)});console.log(d(i("agent.list.success",{vars:{count:o.length}}))),console.log(""),console.log(a$3({columns:[{key:"name",header:i("agent.table.header.name"),minWidth:15},{key:"mode",header:i("agent.table.header.mode"),minWidth:10},{key:"native",header:i("agent.table.header.native"),minWidth:8}],rows:r.map(n=>({name:n.name,mode:"mode"in n&&n.mode||"primary",native:"native"in n&&n.native?i("common.yes"):i("common.no")})),width:process.stdout.columns||80,border:"unicode"})),a.debug("Agent list displayed",{count:o.length});}catch(o){a.error("Failed to list agents",{error:o instanceof Error?o.message:String(o)}),console.error(e(i("agent.list.error"))),process.exit(1);}});}),y.command("info <agent-id>").description(i("agent.command.info.description")).action(async o=>{await a$2(c$1.config.directory,async()=>{try{a.debug("Getting agent info",{agentId:o});let{data:r}=await c$1.sdk.app.agents({}),n=r?.find(t=>t.name===o);if(n||(console.error(e(i("agent.get.not_found",{vars:{agentId:o}}))),process.exit(1)),console.log(d(i("agent.get.success"))),console.log(""),console.log(h(i("agent.info.heading"))),console.log(""),console.log(i$1(i("agent.info.field.name")+":",n.name)),console.log(i$1(i("agent.info.field.mode")+":","mode"in n&&n.mode||"primary")),console.log(i$1(i("agent.info.field.native")+":","native"in n&&n.native?i("common.yes"):i("common.no"))),"permission"in n&&n.permission){console.log(i$1(i("agent.info.field.permission")+":",""));let t=b();console.log(c(t,a$4.muted,JSON.stringify(n.permission,null,2)));}a.debug("Agent info displayed",{agentId:o});}catch(r){a.error("Failed to get agent info",{agentId:o,error:r instanceof Error?r.message:String(r)}),console.error(e(i("agent.get.error"))),process.exit(1);}});}),y.command("create").description(i("agent.command.create.description")).requiredOption("--name <name>",i("agent.command.create.option.name")).option("--mode <mode>",i("agent.command.create.option.mode"),"chat").option("--permission <json>",i("agent.command.create.option.permission")).action(async o=>{await a$2(c$1.config.directory,async()=>{try{a.debug("Creating agent",{name:o.name,mode:o.mode}),console.log(h(i("agent.create.begin")));let{validateAgentName:r,validateAgentMode:n,validateJsonString:t}=await import('./input-validation-FWKKVCYC.mjs');r(o.name)||(a.error("Invalid agent name",{name:o.name}),console.error(e(i("agent.create.validation.name"))),process.exit(1));let g=o.mode||"primary";n(g)||(a.error("Invalid agent mode",{mode:o.mode}),console.error(e(i("agent.create.validation.mode"))),process.exit(1));let d$1;if(o.permission){let l=t(o.permission,"permission");l||(a.error("Invalid permission JSON format",{permission:o.permission}),console.error(e(i("agent.create.error",{vars:{error:"Invalid permission JSON format"}}))),process.exit(1)),d$1=l;}let{data:m}=await c$1.sdk.agent.create({name:o.name,mode:g,permission:d$1});if(m||(console.error(e(i("agent.create.error",{vars:{error:"Agent creation failed"}}))),process.exit(1)),console.log(d(i("agent.create.success",{vars:{name:m.name}}))),console.log(""),console.log(h(i("agent.info.heading"))),console.log(""),console.log(i$1(i("agent.info.field.name")+":",m.name)),console.log(i$1(i("agent.info.field.mode")+":",m.mode??"all")),console.log(i$1(i("agent.info.field.native")+":",m.native?i("common.yes"):i("common.no"))),m.permission){console.log(i$1(i("agent.info.field.permission")+":",""));let l=b();console.log(c(l,a$4.muted,JSON.stringify(m.permission,null,2)));}a.debug("Agent created successfully",{name:m.name});}catch(r){a.error("Failed to create agent",{name:o.name,error:r instanceof Error?r.message:String(r)}),console.error(e(i("agent.create.error",{vars:{error:r instanceof Error?r.message:String(r)}}))),process.exit(1);}});});}export{W as registerAgentCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {e}from'./chunk-M3K32WJV.mjs';import {j,
|
|
1
|
+
import {e}from'./chunk-M3K32WJV.mjs';import {j,na,k,Ma}from'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';import {basename}from'path';import {iife,Identifier}from'@easbot/utils';var D=a.create({service:"debug.agent"});function z(r,o,e$1){(async()=>{D.debug("Getting agent info",{agentName:o});let t=(await r.sdk.agent.get({agentID:o})).data;t||(console.error(e(i("debug.agent.error.not_found",{vars:{agentName:o,command:basename(process.execPath)}}))),process.exit(1));let a=t,d=await C(a),i$1=await P(a,d);if(e$1.tool){let c=d.find(A=>A.id===e$1.tool);c||(console.error(e(i("debug.agent.tool.error.not_found",{vars:{toolID:e$1.tool,agentName:o}}))),process.exit(1)),i$1[e$1.tool]===false&&(console.error(e(i("debug.agent.tool.error.disabled",{vars:{toolID:e$1.tool,agentName:o}}))),process.exit(1));let g=T(e$1.params),b=await E(a,r);D.debug("Executing tool",{toolID:e$1.tool,params:g});let y=await c.execute(g,b);console.log(JSON.stringify({tool:e$1.tool,input:g,result:y},null,2));return}let m={...t,tools:i$1};console.log(JSON.stringify(m,null,2));})();}async function C(r){let o=r.model??await j.defaultModel();return o.providerID||(o={...o,providerID:"default-provider"}),na.tools(o,r)}async function P(r,o){let e=k.disabled(o.map(t=>t.id),r.permission),s={};for(let t of o)s[t.id]=!e.has(t.id);return s}function T(r){if(!r)return {};let o=r.trim();if(o.length===0)return {};let e=iife(()=>{try{return JSON.parse(o)}catch(s){try{return new Function(`return (${o})`)()}catch(t){throw new Error(i("debug.agent.tool.params.parse_error",{vars:{jsonError:s,evalError:t}}))}}});if(!e||typeof e!="object"||Array.isArray(e))throw new Error(i("debug.agent.tool.params.must_be_object"));return e}async function E(r,o){let e=await Ma.create({title:`Debug tool run (${r.name})`}),s=Identifier.ascending("message"),t=r.model??await j.defaultModel();t.providerID||(t={...t,providerID:t.providerID||"default-provider"});let a=Date.now(),d={id:s,sessionID:e.id,role:"assistant",time:{created:a},parentID:s,modelID:t.modelID,providerID:t.providerID,mode:"debug",agent:r.name,path:{cwd:o.config.directory,root:o.config.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};await Ma.updateMessage(d);let i=k.merge(r.permission,e.permission??[]);return {sessionID:e.id,messageID:s,callID:Identifier.ascending("part"),agent:r.name,abort:new AbortController().signal,messages:[],metadata:()=>{},async ask(m){for(let c of m.patterns)if(k.evaluate(m.permission,c,i).action==="deny")throw new k.DeniedError(i)}}}export{z as registerAgentCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{h as createTuiApp,g as getGlobalErrorHandler,e as registerGlobalErrorHandler,f as unregisterGlobalErrorHandler}from'./chunk-CK4NOPWT.mjs';import'./chunk-CQVEAYYW.mjs';import'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as bootstrap,b as bootstrapProgram}from'./chunk-LNK3TPGD.mjs';import'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-
|
|
1
|
+
import {b as b$1}from'./chunk-JJFETXKH.mjs';import {a as a$1}from'./chunk-XPF2LJT2.mjs';import {Oa,xa}from'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import {b as b$2}from'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';import {Command}from'commander';import'path';import O from'fs/promises';import {parse}from'jsonc-parser';var y="easbot",h="EASBot - Multi-Agent Collaboration Ecosystem CLI Tool",P="build",x=["main","ops","explorer"];var b=a.create({service:"cli-config"});async function N(t){try{let o=await O.readFile(t,"utf-8");return parse(o)||{}}catch(o){if(o&&typeof o=="object"&&"code"in o){if(o.code==="ENOENT")return {};b.warn("Failed to read config file",{filePath:t,error:o.code});}else b.error("Failed to parse config file",{filePath:t,error:o instanceof Error?o.message:String(o)});return {}}}function T(...t){let o={};for(let n of t)for(let[e,i]of Object.entries(n))i!==void 0&&(typeof i=="object"&&!Array.isArray(i)&&i!==null?o[e]={...o[e],...i}:o[e]=i);return o}function k(){return {server:{port:3e3,hostname:"localhost"},agent:{},model:{},permission:{}}}async function w(t={}){let{cwd:o=process.cwd(),customConfigPath:n}=t,e=k();if(t.sdk)try{let{data:i}=await t.sdk.config.get({});i&&(e=i);}catch{}if(n){let i=await N(n);Object.keys(i).length>0&&(e=T(e,i));}return e.directory=o,e}async function A(t={}){let o=t.cwd||process.cwd(),n=t.root||Oa.worktree,e=xa({directory:o}),i=await w({cwd:o,root:n,sdk:e,customConfigPath:t.customConfigPath});return {programVersion:b$2.getVersion(),channelOptions:["stdio","http","ws"],agentOptions:`${i.default_agent||P}|${x.join("|")}`,config:i,sdk:e}}var j=[{commands:[{name:"tui",description:"\u542F\u52A8 TUI \u754C\u9762",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./tui-SVCBKLDD.mjs')).registerTuiCommand(t,o);}},{commands:[{name:"run",description:"\u8FD0\u884C\u5355\u6B21\u5BF9\u8BDD",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./run-ATMTXRAJ.mjs')).registerRunCommand(t,o);}},{commands:[{name:"generate",description:"\u751F\u6210 OpenAPI \u89C4\u8303",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./generate-NGTCWD3T.mjs')).registerGenerateCommand(t,o);}},{commands:[{name:"agent",description:"Agent \u7BA1\u7406\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./agent-L27ZE5IW.mjs')).registerAgentCommands(t,o);}},{commands:[{name:"session",description:"\u4F1A\u8BDD\u7BA1\u7406\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{let{registerSessionCommands:n}=await import('./session-QSAQNL2Z.mjs');n(t,o);}},{commands:[{name:"mcp",description:"MCP \u670D\u52A1\u5668\u7BA1\u7406",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./mcp-6F5MHKJC.mjs')).registerMcpCommands(t,o);}},{commands:[{name:"acp",description:"ACP Agent \u901A\u4FE1\u9002\u914D\u5668\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./acp-E24MSMFC.mjs')).registerAcpCommand(t,o);}},{commands:[{name:"debug",description:"\u8C03\u8BD5\u548C\u8BCA\u65AD\u5DE5\u5177",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./debug-WFVKKNMQ.mjs')).registerDebugCommands(t,o);}},{commands:[{name:"gateway",description:"Gateway \u670D\u52A1\u7BA1\u7406\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./gateway-NX63YLNB.mjs')).registerGatewayCommand(t,o);}},{commands:[{name:"auth",description:"Provider \u51ED\u636E\u7BA1\u7406",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./auth-3CQMCCCN.mjs')).registerAuthCommand(t,o);}},{commands:[{name:"export",description:"\u5BFC\u51FA\u4F1A\u8BDD\u6570\u636E",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./export-PNCMUMDM.mjs')).registerExportCommand(t,o);}},{commands:[{name:"github",description:"GitHub Agent \u7BA1\u7406",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./github-T2BVXCZH.mjs')).registerGithubCommand(t,o);}},{commands:[{name:"import",description:"\u5BFC\u5165\u4F1A\u8BDD\u6570\u636E",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./import-3Q6LMACX.mjs')).registerImportCommand(t,o);}},{commands:[{name:"pr",description:"PR \u68C0\u51FA\u548C\u4F1A\u8BDD\u5BFC\u5165",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./pr-CVTJCVMI.mjs')).registerPrCommand(t,o);}},{commands:[{name:"stats",description:"Token \u4F7F\u7528\u91CF\u548C\u6210\u672C\u7EDF\u8BA1",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./stats-QSNMP7FP.mjs')).registerStatsCommand(t,o);}},{commands:[{name:"update",description:"\u66F4\u65B0 Easbot CLI",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./update-DGH5TARR.mjs')).registerUpdateCommand(t,o);}}];async function B(t,o,n=process.argv){for(let e of j)await e.register({program:t,ctx:o,argv:n});}async function v(t,o,n=process.argv){await B(t,o,n);}function L(t,o){t.name(i("program.name")).description(i("program.description")),t.option("--cwd <directory>",i("program.option.cwd"),process.cwd()),t.option("--config <path>",i("program.option.config")),t.option("--print-logs",i("program.option.print_logs")),t.option("--log-level <level>",i("program.option.log_level"),"INFO"),t.option("--debug",i("program.option.debug")),t.helpOption("-h, --help",i("program.help.option")),t.helpCommand("help [command]",i("program.help.command")),t.configureHelp({sortSubcommands:true,sortOptions:true,optionTerm:n=>n.flags,subcommandTerm:n=>n.name()}),t.configureOutput({writeOut:n=>{process.stdout.write(E(n));},writeErr:n=>{process.stderr.write(E(n));},outputError:(n,e)=>{e(n);}}),t.addHelpText("afterAll",({command:n})=>n!==t?"":`
|
|
2
2
|
${i("program.help.examples")}:
|
|
3
3
|
easbot # ${i("help.example.tui")}
|
|
4
4
|
easbot tui --continue # ${i("help.example.tui_continue")}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as Bus}from'./chunk-7HB3V4GJ.mjs';import'./chunk-DEZT7DOH.mjs';import'./chunk-LVPNJIYT.mjs';import'./chunk-ZMABUCCZ.mjs';import'./chunk-ZBRXNYEM.mjs';import'./chunk-HJNJBNAS.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-UNBJ6Y7L.mjs';import'./chunk-UCS2W4UN.mjs';import'./chunk-NGFNJSSC.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-MKLPO5E6.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-6AVNQKBM.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {mkdir,readFile,readdir,rm,writeFile}from'fs/promises';import s from'path';import {xdgData,xdgCache,xdgConfig,xdgState}from'xdg-basedir';import O from'os';import {Filesystem}from'@easbot/utils';var p={name:"@easbot/agent",version:"0.2.
|
|
1
|
+
import {mkdir,readFile,readdir,rm,writeFile}from'fs/promises';import s from'path';import {xdgData,xdgCache,xdgConfig,xdgState}from'xdg-basedir';import O from'os';import {Filesystem}from'@easbot/utils';var p={name:"@easbot/agent",version:"0.2.35",description:"Core Agent for the easbot monorepo ecosystem",type:"module",bin:{easbot:"./dist/cli.mjs"},scripts:{dev:"cross-env NODE_ENV=development tsx src/cli.ts -- tui",start:"cross-env NODE_ENV=production node dist/cli.mjs tui --new",build:"tsup --env.NODE_ENV production",test:"vitest","test:run":"vitest run","test:ui":"vitest --ui","test:watch":"vitest --watch","test:coverage":"vitest run --coverage","test:unit":"vitest run --config ./vitest.unit.config.ts","test:unit:watch":"vitest --config ./vitest.unit.config.ts","test:integration":"vitest run --config ./vitest.integration.config.ts","test:integration:watch":"vitest --config ./vitest.integration.config.ts","test:e2e":"vitest run --config ./vitest.e2e.config.ts","test:e2e:watch":"vitest --config ./vitest.e2e.config.ts",lint:"biome check .","lint:fix":"biome check --write .","lint:fix:unsafe":"biome check --write --unsafe ./src","lint:report":"biome check --reporter=summary .",format:"biome format .","format:fix":"biome format --write .","type-check":"tsc --noEmit",clean:"npx rimraf dist node_modules",prepare:"echo 'agent: Environment ready for CLI usage'","publish:npm":"bash scripts/publish.sh","publish:npm:win":"powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"},keywords:["ai","agent","eas","bot","automation"],author:"houjallen",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/houjallen/easbot.git",directory:"packages/agent"},homepage:"https://github.com/houjallen/easbot/tree/main/packages/agent#readme",bugs:{url:"https://github.com/houjallen/easbot/issues"},files:["dist","README.md","README.en.md","LICENSE"],dependencies:{"@agentclientprotocol/sdk":"^0.25.0","@ai-sdk/alibaba":"^1.0.23","@ai-sdk/amazon-bedrock":"^4.0.105","@ai-sdk/anthropic":"^3.0.77","@ai-sdk/azure":"^3.0.64","@ai-sdk/cerebras":"^2.0.51","@ai-sdk/cohere":"3.0.35","@ai-sdk/deepinfra":"^2.0.51","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/gateway":"^3.0.114","@ai-sdk/google":"^3.0.73","@ai-sdk/google-vertex":"^4.0.128","@ai-sdk/groq":"^3.0.39","@ai-sdk/mistral":"^3.0.37","@ai-sdk/openai":"^3.0.63","@ai-sdk/openai-compatible":"^2.0.47","@ai-sdk/perplexity":"^3.0.33","@ai-sdk/provider":"^3.0.10","@ai-sdk/provider-utils":"^4.0.27","@ai-sdk/togetherai":"^2.0.51","@ai-sdk/vercel":"^2.0.49","@ai-sdk/xai":"^3.0.90","@aws-sdk/credential-providers":"^3.1047.0","@clack/prompts":"^1.4.0","@easbot/codebase":"workspace:*","@easbot/gateway":"workspace:*","@easbot/local-model-sdk":"workspace:*","@easbot/memory":"workspace:*","@easbot/mcp":"workspace:*","@easbot/note":"workspace:*","@easbot/ollama-sdk":"workspace:*","@easbot/plugin":"workspace:*","@easbot/sdk":"workspace:*","@easbot/tui":"workspace:*","@easbot/types":"workspace:*","@easbot/utils":"workspace:*","@hono/node-server":"^2.0.2","@hono/node-ws":"^1.3.1","@hono/standard-validator":"^0.2.2","@hono/zod-validator":"^0.7.6","@modelcontextprotocol/sdk":"^1.29.0","@openrouter/ai-sdk-provider":"^2.9.0","@parcel/watcher":"^2.5.6","@standard-schema/spec":"^1.1.0","@wasmer/wasi":"^1.2.2","@zip.js/zip.js":"^2.8.26",ai:"^6.0.182","ai-gateway-provider":"^3.1.3",ajv:"^8.20.0",axios:"^1.16.1","bash-parser":"^0.5.0","bonjour-service":"^1.4.0",chalk:"^5.6.2",clipboardy:"^5.3.1",commander:"^14.0.3","decimal.js":"^10.6.0",dotenv:"^17.4.2",diff:"^9.0.0","drizzle-orm":"^0.45.2","fast-check":"^4.8.0",fuzzysort:"^3.1.0","gitlab-ai-provider":"^6.6.0",glob:"^13.0.6","google-auth-library":"^10.6.2","gray-matter":"^4.0.3",hono:"^4.12.18","hono-openapi":"^1.3.0",ignore:"^7.0.5","jieba-wasm":"^2.4.0",jiti:"^2.7.0","jsonc-parser":"^3.3.1","lru-cache":"^11.3.6",minimatch:"^10.2.5","node-gyp":"^12.3.0","node-html-parser":"^7.1.0","node-pty":"^1.1.0",open:"^11.0.0",remeda:"^2.34.1","tree-sitter-bash":"^0.25.1",turndown:"^7.2.4",ulid:"^3.0.2",undici:"^8.3.0","vscode-jsonrpc":"^8.2.1","vscode-languageserver-types":"^3.17.5",which:"^6.0.1","why-is-node-running":"^3.2.2",ws:"^8.20.1","xdg-basedir":"5.1.0",zod:"^4.4.3","zod-to-json-schema":"^3.25.2"},devDependencies:{"@actions/core":"^3.0.1","@actions/github":"^9.1.1","@octokit/graphql":"^9.0.3","@octokit/rest":"^22.0.1","@octokit/webhooks-types":"^7.6.1","@types/node":"^25.8.0","@types/turndown":"^5.0.6","@types/which":"^3.0.4","@types/ws":"^8.18.1","@vitest/coverage-v8":"^4.1.6",esbuild:"^0.28.0","esbuild-plugin-alias":"^0.2.1",tsup:"^8.5.1",tsx:"^4.22.0",typescript:"^6.0.3",vitest:"^4.1.6"}};var l="easbot",d=Filesystem.normalize(s.join(xdgData,l)),S=Filesystem.normalize(s.join(xdgCache,l)),z=Filesystem.normalize(s.join(xdgConfig,l)),N=Filesystem.normalize(s.join(xdgState,l)),g;(e=>{e.Path={get home(){return Filesystem.normalize(process.env.EASBOT_TEST_HOME||O.homedir())},data:d,bin:Filesystem.normalize(s.join(d,"bin")),log:Filesystem.normalize(s.join(d,"log")),cache:S,config:z,state:N};function B(){return (process.env.PATH||process.env.Path||"")+s.delimiter+e.Path.bin}e.getPathWithBin=B;let t=null,o=null;async function b(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=p.version||"local";}catch{t="local";}return t||"local"}function f(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=p.version||"local";}catch{t="local";}return t||"local"}e.getVersion=f;function u(){if(o)return o;if(process.env.EASBOT_CHANNEL)return o=process.env.EASBOT_CHANNEL,o;let i=f();return i==="local"||i.includes("dev")?o="local":i.includes("beta")||i.includes("alpha")?o="preview":o="latest",o||"local"}e.getChannel=u;function C(){return u()==="local"}e.isLocal=C;function H(){return u()==="preview"}e.isPreview=H;let h=false,n=null;async function V(){if(!h)return n||(n=(async()=>{await b(),await Promise.all([mkdir(e.Path.data,{recursive:true}),mkdir(e.Path.config,{recursive:true}),mkdir(e.Path.state,{recursive:true}),mkdir(e.Path.log,{recursive:true}),mkdir(e.Path.bin,{recursive:true}),mkdir(e.Path.cache,{recursive:true})]).then(()=>{let c=process.env.PATH||process.env.Path||"";process.env.PATH=c+s.delimiter+e.Path.bin,process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let i="1",m=s.join(e.Path.cache,"version");if(await readFile(m,"utf-8").catch(()=>"0")!==i){try{let c=await readdir(e.Path.cache);await Promise.all(c.map(k=>rm(s.join(e.Path.cache,k),{recursive:!0,force:!0})));}catch{}await writeFile(m,i);}h=true;})(),n)}e.init=V;})(g||(g={}));
|
|
2
2
|
export{g as a};
|