@easbot/agent 0.2.42 → 0.2.43
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/command/builtin/loop.txt +10 -5
- package/dist/assets/txt/context/template/BOOT.txt +2 -0
- package/dist/assets/txt/scheduler/heartbeat.txt +18 -1
- package/dist/assets/txt/scheduler/scheduled.txt +17 -1
- package/dist/chunks/{acp-AJ7O6XNE.mjs → acp-OBY35HS7.mjs} +2 -2
- package/dist/chunks/adapter-loader-ZXPJJRRY.mjs +1 -0
- package/dist/chunks/{agent-SKRC54QG.mjs → agent-EJ64O3VC.mjs} +1 -1
- package/dist/chunks/{agent-VUPXBEWR.mjs → agent-WSRT77Z6.mjs} +1 -1
- package/dist/chunks/agent-service-registry-QA5V3B4G.mjs +1 -0
- package/dist/chunks/{app-EPNEAPMS.mjs → app-I6CHGBMN.mjs} +12 -12
- package/dist/chunks/{auth-34JK273T.mjs → auth-F3UJX6TK.mjs} +1 -1
- package/dist/chunks/bootstrap-O5UL3UT2.mjs +1 -0
- package/dist/chunks/build-program-LX6IAAHW.mjs +11 -0
- package/dist/chunks/bus-XKXFTFNZ.mjs +1 -0
- package/dist/chunks/{chunk-2YNYVTYT.mjs → chunk-3CQA7CJG.mjs} +1 -1
- package/dist/chunks/{chunk-BDS2JWYG.mjs → chunk-3UV6DBAA.mjs} +1 -1
- package/dist/chunks/{chunk-WGJIT5HU.mjs → chunk-4Q3JAZPL.mjs} +1 -1
- package/dist/chunks/{chunk-3472MC45.mjs → chunk-CDDE7L65.mjs} +1 -1
- package/dist/chunks/{chunk-JTVO3U27.mjs → chunk-EFJHO4OX.mjs} +1 -1
- package/dist/chunks/{chunk-EB3OP6TL.mjs → chunk-G63GWBVD.mjs} +1 -1
- package/dist/chunks/{chunk-J6VEDKPT.mjs → chunk-HIPEPY4E.mjs} +1 -1
- package/dist/chunks/{chunk-4OHDEBAX.mjs → chunk-LP2YYNMX.mjs} +1 -1
- package/dist/chunks/chunk-OSLGCE7R.mjs +1 -0
- package/dist/chunks/chunk-PT5TKWFJ.mjs +1051 -0
- package/dist/chunks/{chunk-UNBJ6Y7L.mjs → chunk-XQ3LMV3K.mjs} +2 -2
- package/dist/chunks/{chunk-PEMUENKB.mjs → chunk-ZH674M7Q.mjs} +1 -1
- package/dist/chunks/{command-CJGBEATT.mjs → command-34YNL5HZ.mjs} +1 -1
- package/dist/chunks/compaction-OCFEYJC4.mjs +1 -0
- package/dist/chunks/{config-YSZNIWZT.mjs → config-MLDSMYKU.mjs} +1 -1
- package/dist/chunks/{confirm-dialog-SJOXJWYU.mjs → confirm-dialog-PT62UY3W.mjs} +1 -1
- package/dist/chunks/{debug-GZCL57Q7.mjs → debug-GTUHAYVC.mjs} +3 -3
- package/dist/chunks/{export-4CIOZYMY.mjs → export-5BWFWBI3.mjs} +1 -1
- package/dist/chunks/file-P2YWB5Q7.mjs +1 -0
- package/dist/chunks/{gateway-D6XCB2OA.mjs → gateway-GFZFVEHP.mjs} +2 -2
- package/dist/chunks/{generate-NYQCTBY7.mjs → generate-FNIRYTGT.mjs} +1 -1
- package/dist/chunks/{github-IGWZXZRB.mjs → github-JPCEWX4N.mjs} +1 -1
- package/dist/chunks/global-HVRSDT3G.mjs +1 -0
- package/dist/chunks/{i18n-OMQXNLBR.mjs → i18n-4TNHSVRN.mjs} +1 -1
- package/dist/chunks/{import-TYN474UK.mjs → import-B5RTBC2W.mjs} +1 -1
- package/dist/chunks/installation-JDBMIGTK.mjs +1 -0
- package/dist/chunks/instance-5OB47GH5.mjs +1 -0
- package/dist/chunks/loader-GNE7KLKQ.mjs +1 -0
- package/dist/chunks/loader-J6SV3FLI.mjs +1 -0
- package/dist/chunks/lsp-QWPGRLGX.mjs +1 -0
- package/dist/chunks/{mcp-FYDYPGLE.mjs → mcp-5DZTVP6Z.mjs} +1 -1
- package/dist/chunks/mcp-KWZSND4L.mjs +1 -0
- package/dist/chunks/models-JIMJ74AN.mjs +1 -0
- package/dist/chunks/{pr-DQZIG2CT.mjs → pr-E7AEHZZT.mjs} +1 -1
- package/dist/chunks/preferences-KZ7TL4Q3.mjs +1 -0
- package/dist/chunks/project-3W6D3354.mjs +1 -0
- package/dist/chunks/prompt-7M7NMDG4.mjs +1 -0
- package/dist/chunks/provider-RGQTLMFK.mjs +1 -0
- package/dist/chunks/registry-AA7CYXUC.mjs +1 -0
- package/dist/chunks/revert-FOMRGDW5.mjs +1 -0
- package/dist/chunks/ripgrep-TBPFM3BV.mjs +1 -0
- package/dist/chunks/{run-EQ5GHPKF.mjs → run-MYXJU4RX.mjs} +1 -1
- package/dist/chunks/scheduler-YYOW743S.mjs +1 -0
- package/dist/chunks/server-SQMRITFT.mjs +1 -0
- package/dist/chunks/session-EPFSKATV.mjs +1 -0
- package/dist/chunks/session-FQ5O5XZY.mjs +1 -0
- package/dist/chunks/{session-R2LCLNAY.mjs → session-LWKQT4G7.mjs} +1 -1
- package/dist/chunks/{settings-panel-ZMAGAWRF.mjs → settings-panel-C32BQGOR.mjs} +1 -1
- package/dist/chunks/share-6NJ4W4CC.mjs +1 -0
- package/dist/chunks/snapshot-VO64Z4KV.mjs +1 -0
- package/dist/chunks/{stats-TREO4CFV.mjs → stats-6IILCYBN.mjs} +1 -1
- package/dist/chunks/storage-23DKEFPY.mjs +1 -0
- package/dist/chunks/{tui-FVQHBIJ7.mjs → tui-P4UKVVKY.mjs} +1 -1
- package/dist/chunks/{types-OIHWEQYC.mjs → types-2GDQRKMX.mjs} +1 -1
- package/dist/chunks/{types-GCXI5X7B.mjs → types-OCGSLJEP.mjs} +1 -1
- package/dist/chunks/{update-V3GTL4TX.mjs → update-NNMG3LC7.mjs} +1 -1
- package/dist/cli.mjs +2 -2
- package/package.json +13 -13
- package/dist/chunks/adapter-loader-VUS3UYMT.mjs +0 -1
- package/dist/chunks/agent-service-registry-DPO5SSXA.mjs +0 -1
- package/dist/chunks/bootstrap-3KXRWM6D.mjs +0 -1
- package/dist/chunks/build-program-2AR3LYQJ.mjs +0 -11
- package/dist/chunks/bus-QOWILU5Z.mjs +0 -1
- package/dist/chunks/chunk-2RSIOAZV.mjs +0 -1
- package/dist/chunks/chunk-XMIQEMED.mjs +0 -1051
- package/dist/chunks/compaction-R4RTVEDY.mjs +0 -1
- package/dist/chunks/file-G4WHJKUX.mjs +0 -1
- package/dist/chunks/global-5WFCDQ45.mjs +0 -1
- package/dist/chunks/installation-6S6OCY6F.mjs +0 -1
- package/dist/chunks/instance-YVRWMB6M.mjs +0 -1
- package/dist/chunks/loader-VV3FV5NS.mjs +0 -1
- package/dist/chunks/loader-XGUYA6ZM.mjs +0 -1
- package/dist/chunks/lsp-J7UR4JNX.mjs +0 -1
- package/dist/chunks/mcp-GEZSPY2W.mjs +0 -1
- package/dist/chunks/models-JNSS4QSZ.mjs +0 -1
- package/dist/chunks/preferences-QCM3RIAL.mjs +0 -1
- package/dist/chunks/project-53ZMRKRI.mjs +0 -1
- package/dist/chunks/prompt-XYHKPB7Q.mjs +0 -1
- package/dist/chunks/provider-2RFHZVX4.mjs +0 -1
- package/dist/chunks/registry-GGSZXBFC.mjs +0 -1
- package/dist/chunks/revert-7RBPZDWL.mjs +0 -1
- package/dist/chunks/ripgrep-U54LYBZO.mjs +0 -1
- package/dist/chunks/scheduler-3AYHIZGY.mjs +0 -1
- package/dist/chunks/server-ITUF2HX7.mjs +0 -1
- package/dist/chunks/session-5OU5P7UF.mjs +0 -1
- package/dist/chunks/session-XA4RMN7D.mjs +0 -1
- package/dist/chunks/share-45SYUA47.mjs +0 -1
- package/dist/chunks/snapshot-YC3DAH7Q.mjs +0 -1
- package/dist/chunks/storage-6F64537E.mjs +0 -1
|
@@ -40,7 +40,7 @@ Manually trigger a task.
|
|
|
40
40
|
|--------|-------------|
|
|
41
41
|
| --cron \<expr\> | Cron expression (required) |
|
|
42
42
|
| --type \<type\> | Task type: heartbeat (default) \| scheduled |
|
|
43
|
-
| --session \<
|
|
43
|
+
| --session \<id\> | Session ID (heartbeat required) |
|
|
44
44
|
| --mode \<mode\> | Mode: session (default) \| fork |
|
|
45
45
|
| --prompt \<text\> | Prompt (scheduled required) |
|
|
46
46
|
| --agent-type \<type\> | Agent type (default: default) |
|
|
@@ -62,14 +62,19 @@ Manually trigger a task.
|
|
|
62
62
|
|
|
63
63
|
## Examples
|
|
64
64
|
|
|
65
|
-
Create a heartbeat task:
|
|
65
|
+
Create a heartbeat task (every 5 minutes):
|
|
66
66
|
```
|
|
67
|
-
/loop create main-heartbeat --cron "*/5 * * * *" --session
|
|
67
|
+
/loop create main-heartbeat --cron "*/5 * * * *" --session ses_xxx --type heartbeat
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
-
Create a
|
|
70
|
+
Create a heartbeat task (at minute 5 of every hour):
|
|
71
71
|
```
|
|
72
|
-
/loop create
|
|
72
|
+
/loop create main-heartbeat --cron "5 * * * *" --session ses_xxx --type heartbeat
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Create a scheduled task (every hour at minute 0):
|
|
76
|
+
```
|
|
77
|
+
/loop create hourly-sync --cron "0 * * * *" --prompt Sync data --type scheduled
|
|
73
78
|
```
|
|
74
79
|
|
|
75
80
|
List all tasks:
|
|
@@ -28,6 +28,7 @@ I am {{name}}, my core mission is {{mission}}.
|
|
|
28
28
|
3. **ALWAYS** supplement with professional knowledge and reasoning
|
|
29
29
|
4. **ALWAYS** adjust expression within appropriate range
|
|
30
30
|
|
|
31
|
+
{{#if isMainAgent}}
|
|
31
32
|
## When to Update
|
|
32
33
|
**Defines timing for modifying other core files**
|
|
33
34
|
|
|
@@ -49,6 +50,7 @@ I am {{name}}, my core mission is {{mission}}.
|
|
|
49
50
|
### cleanup - Cleanup Rules
|
|
50
51
|
- Remove outdated content promptly
|
|
51
52
|
- Keep files consistent with actual state
|
|
53
|
+
{{/if}}
|
|
52
54
|
|
|
53
55
|
## Important files Index
|
|
54
56
|
{{files}}
|
|
@@ -1,3 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 心跳任务默认提示词模板
|
|
3
|
+
*
|
|
4
|
+
* 此模板用于生成心跳任务的系统提示词。
|
|
5
|
+
* 心跳任务用于定期检查 Agent 会话的健康状态。
|
|
6
|
+
*
|
|
7
|
+
* 支持的变量:
|
|
8
|
+
* - {{SESSION}}: 会话 ID
|
|
9
|
+
* - {{AGENT}}: Agent 名称
|
|
10
|
+
* - {{MODEL}}: 模型名称
|
|
11
|
+
* - {{TIME}}: ISO 格式时间
|
|
12
|
+
* - {{TIME_LOCAL}}: 本地格式时间
|
|
13
|
+
* - {{TIMESTAMP}}: Unix 时间戳
|
|
14
|
+
* - {{TASK_ID}}: 任务 ID
|
|
15
|
+
* - {{TASK_NAME}}: 任务名称
|
|
16
|
+
*/
|
|
17
|
+
|
|
1
18
|
Monitor the health status of the running agent on session {{SESSION}}.
|
|
2
19
|
|
|
3
20
|
## Always
|
|
@@ -11,4 +28,4 @@ Monitor the health status of the running agent on session {{SESSION}}.
|
|
|
11
28
|
- Execute any code or commands
|
|
12
29
|
- Make modifications to files or system
|
|
13
30
|
- Send messages to users or external systems
|
|
14
|
-
- Perform any actions that change state
|
|
31
|
+
- Perform any actions that change state
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 定时任务默认提示词模板
|
|
3
|
+
*
|
|
4
|
+
* 此模板用于生成定时任务的系统提示词。
|
|
5
|
+
* 定时任务用于在指定时间执行预定的任务。
|
|
6
|
+
*
|
|
7
|
+
* 支持的变量:
|
|
8
|
+
* - {{AGENT}}: Agent 类型
|
|
9
|
+
* - {{MODEL}}: 模型名称
|
|
10
|
+
* - {{TIME}}: ISO 格式时间
|
|
11
|
+
* - {{TIME_LOCAL}}: 本地格式时间
|
|
12
|
+
* - {{TIMESTAMP}}: Unix 时间戳
|
|
13
|
+
* - {{TASK_ID}}: 任务 ID
|
|
14
|
+
* - {{TASK_NAME}}: 任务名称
|
|
15
|
+
*/
|
|
16
|
+
|
|
1
17
|
Execute the scheduled task as instructed.
|
|
2
18
|
|
|
3
19
|
## Always
|
|
@@ -12,4 +28,4 @@ Execute the scheduled task as instructed.
|
|
|
12
28
|
- Attempt tasks outside the assigned scope
|
|
13
29
|
- Make assumptions beyond the task description
|
|
14
30
|
- Take actions not requested
|
|
15
|
-
- Leave tasks partially completed without explanation
|
|
31
|
+
- Leave tasks partially completed without explanation
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {a as a$2}from'./chunk-LAHYVX5K.mjs';import {a as a$3}from'./chunk-PEMUENKB.mjs';import'./chunk-VII7JKGB.mjs';import {g,e as e$1,d,k,i as i$1,b as b$3,h,c,a as a$4}from'./chunk-M3K32WJV.mjs';import {Ha,xa,Sa,ub,ja,ka,za,Aa,tb,R,Q}from'./chunk-XMIQEMED.mjs';import'./chunk-WGJIT5HU.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-3472MC45.mjs';import {k as k$1}from'./chunk-LGMGGNPW.mjs';import'./chunk-J6VEDKPT.mjs';import'./chunk-AAJAKVQY.mjs';import {e,f}from'./chunk-2RSIOAZV.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import {b as b$1}from'./chunk-4OHDEBAX.mjs';import'./chunk-EB3OP6TL.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-2YNYVTYT.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-BDS2JWYG.mjs';import {b as b$2}from'./chunk-X6ISXWBN.mjs';import'commander';import {parseModelId,PKG,createServer,getProxyConfig,Identifier,retry}from'@easbot/utils';import {applyPatch}from'diff';import Xe from'path';import {z}from'zod';import {WebSocketServer}from'ws';import {pathToFileURL}from'url';import {ndJsonStream,AgentSideConnection,RequestError}from'@agentclientprotocol/sdk';var _=a.create({service:"acp-event-bridge"}),et={Info:z.object({id:z.string(),content:z.string(),status:z.enum(["in_progress","pending","completed","cancelled"]),priority:z.enum(["high","medium","low"])})},W=class{constructor(e,t){b$2(this,"sdk");b$2(this,"connection");b$2(this,"abortController",null);b$2(this,"started",false);b$2(this,"permissionQueues",new Map);b$2(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$2(this,"acpService");this.sdk=e,this.connection=t;}setService(e){this.acpService=e;}async start(){if(this.started){_.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,_.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||_.error("event subscription failed",{error:e});});}async stop(){this.started&&(_.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this.permissionQueues.clear(),_.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=>{_.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(!this.connection){_.warn("No connection available to publish session status");return}try{await this.connection.extNotification("session.status",{sessionId:t,status:n});}catch(s){_.error("Failed to publish session status via extNotification",{sessionId:t,status:n,error:s});}}async handleSessionDeleted(e){let{sessionId:t}=e;if(!this.connection){_.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."}}});}catch(n){_.error("Failed to notify session deletion to client",{sessionId:t,error:n});}}async handlePermissionAsked(e){let{id:t,sessionId:n,permission:s,tool:r,metadata:i}=e,a=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let u=i?.directory??"",P=s==="external_directory"&&i?.tool?Se(i.tool):Se(s),I=s==="external_directory"&&i?.tool?ve(i.tool,i):ve(s,i),p=await this.connection.requestPermission({sessionId:n,toolCall:{callId:r?.callId??t,status:"pending",title:s,rawInput:i,kind:P,locations:(I??[]).map(m=>m.path)},options:this.permissionOptions}).catch(async m=>{_.error("failed to request permission from ACP",{error:m,permissionId:t,sessionId:n}),await this.sdk.permission.reply({requestId:t,reply:"reject",directory:u});});if(p){if(p.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestId:t,reply:"reject",directory:u});return}if(p.outcome.optionId!=="reject"&&s==="edit"){let m=i?.filepath??i?.filePath??"",l=i?.diff??"";if(m&&l){let c=PKG.file(m),f=await c.exists()?await c.text():"",g=tt(f,l);g&&await this.connection.extMethod("client.writeTextFile",{sessionId:n,path:m,content:g});}}await this.sdk.permission.reply({requestId:t,reply:p.outcome.optionId,directory:u});}}).catch(u=>{_.error("failed to handle permission",{error:u,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,r="";_.debug("Handling question asked in ACP bridge",{requestId:t,sessionId:n,questionCount:s.length});try{let i=await this.connection.extMethod("client.requestQuestion",{sessionId:n,requestId:t,questions:s});if(!i){_.warn("Question request returned no result"),await this.sdk.question.reject({requestId:t,directory:r});return}i.outcome==="selected"&&i.answers&&i.answers.length>0?await this.sdk.question.reply({requestId:t,answers:i.answers.map(d=>[d.answer]),directory:r}):await this.sdk.question.reject({requestId:t,directory:r});}catch(i){_.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:r});}}async handleMessagePartUpdated(e){let{part:t}=e,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"&&_.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:r,messageId:i}=e,d=Se(s);switch(r.status){case "pending":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:s,kind:d,status:"pending",locations:[],rawInput:{},_meta:{messageId:i}}}).catch(a=>{_.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:d,title:s,locations:ve(s,r.input),rawInput:r.input,_meta:{messageId:i}}}).catch(a=>{_.error("failed to send tool in_progress to ACP",{error:a});});return;case "completed":{let a=[{type:"content",content:{type:"text",text:r.output}}];if(d==="edit"){let u=r.input,P=u.filePath??u.filepath??"",I=u.oldString??"",p=u.newString??u.content??"";a.push({type:"diff",path:P,oldText:I,newText:p});}if(s==="todo"){let u=et.Info.array().safeParse(JSON.parse(r.output));u.success&&r.input.operation==="write"&&await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:u.data.map(P=>{let I=P.status==="cancelled"?"completed":P.status;return {priority:P.priority,status:I,content:P.content}})}}).catch(P=>{_.error("failed to send session update for todo",{error:P});});}await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:d,content:a,title:r.title??s,rawInput:r.input,rawOutput:{output:r.output,metadata:r.metadata},_meta:{messageId:i}}}).catch(u=>{_.error("failed to send tool completed to ACP",{error:u});});return}case "error":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:d,title:s,rawInput:r.input,content:[{type:"content",content:{type:"text",text:r.error}}],rawOutput:{error:r.error},_meta:{messageId:i}}}).catch(a=>{_.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(r=>{_.error("failed to send text to ACP",{error:r});});}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(r=>{_.error("failed to send reasoning to ACP",{error:r});});}async handleStepFinishPart(e){let{sessionId:t,messageId:n,tokens:s}=e;if(!this.connection)return;let r=(s?.input??0)+(s?.reasoning??0),i=await this.getContextLimit(t,n);await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:r,size:i,_meta:{messageId:n}}}).catch(d=>{_.error("failed to send usage_update for step-finish",{error:d});});}async getContextLimit(e,t){try{let s=(await this.sdk.session.messages({sessionId:e}).then(r=>r.data).catch(()=>{}))?.find(r=>r.info.id===t);if(s){let r=s.info;if(r.providerId&&r.modelId)return (await this.sdk.config.providers({}).then(u=>u.data?.providers??[]).catch(()=>[])).find(u=>u.id===r.providerId)?.models[r.modelId]?.limit?.context??2e5}}catch(n){_.debug("failed to get context limit",{error:n});}return 2e5}};function Se(o){switch(o.toLowerCase()){case "bash":return "execute";case "webfetch":return "fetch";case "edit":case "patch":case "write":return "edit";case "grep":case "glob":case "lsp":case "context7_resolve_library_id":case "context7_get_library_docs":return "search";case "list":case "read":return "read";default:return "other"}}function ve(o,e){if(!e)return [];switch(o.toLowerCase()){case "read":case "edit":case "write":case "patch":case "lsp":{let n=e.filePath??e.filepath??"";return n?[{path:n}]:[]}case "glob":case "grep":return e.path?[{path:e.path}]:[];case "list":return e.path?[{path:e.path}]:[];case "bash":case "shell":{let n=e.cwd??"";return n?[{path:n}]:[]}case "external_directory":{let n=e.tool?.toLowerCase(),s=e.filepath??"",r=e.realPath??"",i=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return r?[{path:r}]:s?[{path:s}]:[];if(n==="list"||n==="glob"||n==="grep"){let a=r??s,u=a?Xe.posix.dirname(a):i;return u?[{path:u}]:[]}let d=r??s;return d?[{path:d}]:i?[{path:i}]:[]}default:return []}}function tt(o,e){try{let t=applyPatch(o,e);return t===!1?null:t}catch{return null}}var D={HTTP:"http",STDIO:"stdio",WEBSOCKET:"websocket"},Y=class o extends Error{constructor(t,n=[]){super(t);b$2(this,"conflictingModes");this.name="ServiceModeConflictError",this.conflictingModes=n,Object.setPrototypeOf(this,o.prototype);}getConflictingModesDescription(){return this.conflictingModes.length===0?"No modes specified":this.conflictingModes.join(", ")}};function nt(o){let e=[];return o.channel&&e.push(o.channel),e}function Le(o){let e=nt(o);if(e.length===0)throw new Y("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw new Y(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var De={channel:D.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"}),V="EAS_";function $e(o){return !(!o||o.trim()===""||o.startsWith("-")||o.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(o))}function ze(o){return Number.isInteger(o)&&o>=1&&o<=65535}function Be(o){return Number.isFinite(o)&&o>0}function He(o){let e={...De,...o};try{Le(e);}catch(t){throw t instanceof Y&&q.error("Invalid service mode configuration",{message:t.message,conflictingModes:t.conflictingModes}),t}if(e.port!==void 0&&!ze(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&&!$e(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&&!Be(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===D.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 st(){let o={},e=process.env[`${V}ACP_CHANNEL`];if(e){let a=e.toLowerCase();Object.values(D).includes(a)?o.channel=a:q.warn("Invalid EAS_ACP_CHANNEL environment variable",{value:e});}let t=process.env[`${V}ACP_PORT`];if(t){let a=parseInt(t,10);ze(a)?o.port=a:q.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${V}ACP_HOSTNAME`];n&&($e(n)?o.hostname=n:q.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let s=process.env[`${V}ACP_TIMEOUT`];if(s){let a=parseInt(s,10);Be(a)?o.timeout=a:q.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:s});}let r=process.env[`${V}ACP_HISTORY_SCOPE`];r&&(["session","peer","global"].includes(r)?o.historyScope=r:q.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:r}));let i=process.env[`${V}ACP_HISTORY_WINDOW_SIZE`];if(i){let a=parseInt(i,10);Number.isInteger(a)&&a>0?o.historyWindowSize=a:q.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:i});}let d=process.env[`${V}ACP_DEGRADE_POLICY`];return d&&(["polling_only","streaming_first"].includes(d)?o.degradePolicy=d:q.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:d})),q.debug("Config loaded from environment",{config:o}),o}function je(o){let e=st(),t={...e,...o};return q.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:o,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}var ye=a.create({service:"acp-rpc-handler"}),ot={INTERNAL_ERROR:-32603},Z=class{constructor(e){b$2(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:s}=e;ye.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:s});try{let r;switch(t){case "initialize":r=await this.handleInitialize(n);break;case "authenticate":r=await this.handleAuthenticate(n);break;case "session.new":case "newSession":r=await this.handleNewSession(n);break;case "session.load":case "loadSession":r=await this.handleLoadSession(n);break;case "session.close":case "closeSession":r=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":r=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),r={success:!0};break;case "session.list":case "listSessions":r=await this.handleListSessions(n);break;case "session.fork":case "forkSession":r=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":r=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":r=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":r=await this.handleSetSessionConfigOption(n);break;case "status":r=this.handleStatus();break;case "subscriptions":r=this.handleSubscriptions();break;default:throw ye.warn("Unknown method",{method:t}),new Error(`Method not found: ${t}`)}return {jsonrpc:"2.0",id:s,result:r}}catch(r){return ye.error("AcpRpcHandler error",{method:t,error:r instanceof Error?r.message:String(r)}),{jsonrpc:"2.0",id:s,error:{code:ot.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)}}}}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 ie=a.create({service:"server-agent-side-connection"}),X=class{constructor(){b$2(this,"broadcaster",null);b$2(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;ie.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return ie.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async extMethod(e,t){return ie.debug("ServerAgentSideConnection.extMethod",{method:e}),{}}async extNotification(e,t){if(ie.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 j=a.create({service:"http-server"});async function We(o,e){if(j.info("Starting HTTP server",{port:e.port,hostname:e.hostname}),e.channel!==D.HTTP)throw new Error("Invalid channel type for HTTP server");let t=new Map,n=new Map,s=new X,r={broadcast:(c,f)=>{P(c,f);}};s.setBroadcaster(r);let i=new Z(o),d=o.getSDK();if(!d)throw new Error("SDK not configured");let a=new W(d,s);a.setService(o),await a.start();let u=(c,f)=>{let g=t.get(c);if(!g)return false;try{return g.controller.enqueue(new TextEncoder().encode(f)),g.lastHeartbeat=Date.now(),!0}catch(h){return j.warn("Failed to push to SSE connection",{connectionId:c,error:h instanceof Error?h.message:String(h)}),false}},P=(c,f)=>{let g=n.get(c);if(!g||g.size===0)return;let S={jsonrpc:"2.0",method:f.update.sessionUpdate,params:{sessionId:c,...f.update,timestamp:Date.now()}},v=`data: ${JSON.stringify(S)}
|
|
1
|
+
import {a as a$2}from'./chunk-LAHYVX5K.mjs';import {a as a$3}from'./chunk-ZH674M7Q.mjs';import'./chunk-VII7JKGB.mjs';import {g,e as e$1,d,k,i as i$1,b as b$3,h,c,a as a$4}from'./chunk-M3K32WJV.mjs';import {Ha,xa,Sa,ub,ja,ka,za,Aa,tb,R,Q}from'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import {k as k$1}from'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import {e,f}from'./chunk-OSLGCE7R.mjs';import {i}from'./chunk-XQ3LMV3K.mjs';import {b as b$1}from'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-3UV6DBAA.mjs';import {b as b$2}from'./chunk-X6ISXWBN.mjs';import'commander';import {parseModelId,PKG,createServer,getProxyConfig,Identifier,retry}from'@easbot/utils';import {applyPatch}from'diff';import Xe from'path';import {z}from'zod';import {WebSocketServer}from'ws';import {pathToFileURL}from'url';import {ndJsonStream,AgentSideConnection,RequestError}from'@agentclientprotocol/sdk';var _=a.create({service:"acp-event-bridge"}),et={Info:z.object({id:z.string(),content:z.string(),status:z.enum(["in_progress","pending","completed","cancelled"]),priority:z.enum(["high","medium","low"])})},W=class{constructor(e,t){b$2(this,"sdk");b$2(this,"connection");b$2(this,"abortController",null);b$2(this,"started",false);b$2(this,"permissionQueues",new Map);b$2(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$2(this,"acpService");this.sdk=e,this.connection=t;}setService(e){this.acpService=e;}async start(){if(this.started){_.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,_.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||_.error("event subscription failed",{error:e});});}async stop(){this.started&&(_.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.abortController=null,this.permissionQueues.clear(),_.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=>{_.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(!this.connection){_.warn("No connection available to publish session status");return}try{await this.connection.extNotification("session.status",{sessionId:t,status:n});}catch(s){_.error("Failed to publish session status via extNotification",{sessionId:t,status:n,error:s});}}async handleSessionDeleted(e){let{sessionId:t}=e;if(!this.connection){_.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."}}});}catch(n){_.error("Failed to notify session deletion to client",{sessionId:t,error:n});}}async handlePermissionAsked(e){let{id:t,sessionId:n,permission:s,tool:r,metadata:i}=e,a=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let u=i?.directory??"",P=s==="external_directory"&&i?.tool?Se(i.tool):Se(s),I=s==="external_directory"&&i?.tool?ve(i.tool,i):ve(s,i),p=await this.connection.requestPermission({sessionId:n,toolCall:{callId:r?.callId??t,status:"pending",title:s,rawInput:i,kind:P,locations:(I??[]).map(m=>m.path)},options:this.permissionOptions}).catch(async m=>{_.error("failed to request permission from ACP",{error:m,permissionId:t,sessionId:n}),await this.sdk.permission.reply({requestId:t,reply:"reject",directory:u});});if(p){if(p.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestId:t,reply:"reject",directory:u});return}if(p.outcome.optionId!=="reject"&&s==="edit"){let m=i?.filepath??i?.filePath??"",l=i?.diff??"";if(m&&l){let c=PKG.file(m),f=await c.exists()?await c.text():"",g=tt(f,l);g&&await this.connection.extMethod("client.writeTextFile",{sessionId:n,path:m,content:g});}}await this.sdk.permission.reply({requestId:t,reply:p.outcome.optionId,directory:u});}}).catch(u=>{_.error("failed to handle permission",{error:u,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,r="";_.debug("Handling question asked in ACP bridge",{requestId:t,sessionId:n,questionCount:s.length});try{let i=await this.connection.extMethod("client.requestQuestion",{sessionId:n,requestId:t,questions:s});if(!i){_.warn("Question request returned no result"),await this.sdk.question.reject({requestId:t,directory:r});return}i.outcome==="selected"&&i.answers&&i.answers.length>0?await this.sdk.question.reply({requestId:t,answers:i.answers.map(d=>[d.answer]),directory:r}):await this.sdk.question.reject({requestId:t,directory:r});}catch(i){_.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:r});}}async handleMessagePartUpdated(e){let{part:t}=e,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"&&_.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:r,messageId:i}=e,d=Se(s);switch(r.status){case "pending":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:s,kind:d,status:"pending",locations:[],rawInput:{},_meta:{messageId:i}}}).catch(a=>{_.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:d,title:s,locations:ve(s,r.input),rawInput:r.input,_meta:{messageId:i}}}).catch(a=>{_.error("failed to send tool in_progress to ACP",{error:a});});return;case "completed":{let a=[{type:"content",content:{type:"text",text:r.output}}];if(d==="edit"){let u=r.input,P=u.filePath??u.filepath??"",I=u.oldString??"",p=u.newString??u.content??"";a.push({type:"diff",path:P,oldText:I,newText:p});}if(s==="todo"){let u=et.Info.array().safeParse(JSON.parse(r.output));u.success&&r.input.operation==="write"&&await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:u.data.map(P=>{let I=P.status==="cancelled"?"completed":P.status;return {priority:P.priority,status:I,content:P.content}})}}).catch(P=>{_.error("failed to send session update for todo",{error:P});});}await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:d,content:a,title:r.title??s,rawInput:r.input,rawOutput:{output:r.output,metadata:r.metadata},_meta:{messageId:i}}}).catch(u=>{_.error("failed to send tool completed to ACP",{error:u});});return}case "error":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:d,title:s,rawInput:r.input,content:[{type:"content",content:{type:"text",text:r.error}}],rawOutput:{error:r.error},_meta:{messageId:i}}}).catch(a=>{_.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(r=>{_.error("failed to send text to ACP",{error:r});});}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(r=>{_.error("failed to send reasoning to ACP",{error:r});});}async handleStepFinishPart(e){let{sessionId:t,messageId:n,tokens:s}=e;if(!this.connection)return;let r=(s?.input??0)+(s?.reasoning??0),i=await this.getContextLimit(t,n);await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:r,size:i,_meta:{messageId:n}}}).catch(d=>{_.error("failed to send usage_update for step-finish",{error:d});});}async getContextLimit(e,t){try{let s=(await this.sdk.session.messages({sessionId:e}).then(r=>r.data).catch(()=>{}))?.find(r=>r.info.id===t);if(s){let r=s.info;if(r.providerId&&r.modelId)return (await this.sdk.config.providers({}).then(u=>u.data?.providers??[]).catch(()=>[])).find(u=>u.id===r.providerId)?.models[r.modelId]?.limit?.context??2e5}}catch(n){_.debug("failed to get context limit",{error:n});}return 2e5}};function Se(o){switch(o.toLowerCase()){case "bash":return "execute";case "webfetch":return "fetch";case "edit":case "patch":case "write":return "edit";case "grep":case "glob":case "lsp":case "context7_resolve_library_id":case "context7_get_library_docs":return "search";case "list":case "read":return "read";default:return "other"}}function ve(o,e){if(!e)return [];switch(o.toLowerCase()){case "read":case "edit":case "write":case "patch":case "lsp":{let n=e.filePath??e.filepath??"";return n?[{path:n}]:[]}case "glob":case "grep":return e.path?[{path:e.path}]:[];case "list":return e.path?[{path:e.path}]:[];case "bash":case "shell":{let n=e.cwd??"";return n?[{path:n}]:[]}case "external_directory":{let n=e.tool?.toLowerCase(),s=e.filepath??"",r=e.realPath??"",i=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return r?[{path:r}]:s?[{path:s}]:[];if(n==="list"||n==="glob"||n==="grep"){let a=r??s,u=a?Xe.posix.dirname(a):i;return u?[{path:u}]:[]}let d=r??s;return d?[{path:d}]:i?[{path:i}]:[]}default:return []}}function tt(o,e){try{let t=applyPatch(o,e);return t===!1?null:t}catch{return null}}var D={HTTP:"http",STDIO:"stdio",WEBSOCKET:"websocket"},Y=class o extends Error{constructor(t,n=[]){super(t);b$2(this,"conflictingModes");this.name="ServiceModeConflictError",this.conflictingModes=n,Object.setPrototypeOf(this,o.prototype);}getConflictingModesDescription(){return this.conflictingModes.length===0?"No modes specified":this.conflictingModes.join(", ")}};function nt(o){let e=[];return o.channel&&e.push(o.channel),e}function Le(o){let e=nt(o);if(e.length===0)throw new Y("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw new Y(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var De={channel:D.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"}),V="EAS_";function $e(o){return !(!o||o.trim()===""||o.startsWith("-")||o.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(o))}function ze(o){return Number.isInteger(o)&&o>=1&&o<=65535}function Be(o){return Number.isFinite(o)&&o>0}function He(o){let e={...De,...o};try{Le(e);}catch(t){throw t instanceof Y&&q.error("Invalid service mode configuration",{message:t.message,conflictingModes:t.conflictingModes}),t}if(e.port!==void 0&&!ze(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&&!$e(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&&!Be(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===D.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 st(){let o={},e=process.env[`${V}ACP_CHANNEL`];if(e){let a=e.toLowerCase();Object.values(D).includes(a)?o.channel=a:q.warn("Invalid EAS_ACP_CHANNEL environment variable",{value:e});}let t=process.env[`${V}ACP_PORT`];if(t){let a=parseInt(t,10);ze(a)?o.port=a:q.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${V}ACP_HOSTNAME`];n&&($e(n)?o.hostname=n:q.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let s=process.env[`${V}ACP_TIMEOUT`];if(s){let a=parseInt(s,10);Be(a)?o.timeout=a:q.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:s});}let r=process.env[`${V}ACP_HISTORY_SCOPE`];r&&(["session","peer","global"].includes(r)?o.historyScope=r:q.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:r}));let i=process.env[`${V}ACP_HISTORY_WINDOW_SIZE`];if(i){let a=parseInt(i,10);Number.isInteger(a)&&a>0?o.historyWindowSize=a:q.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:i});}let d=process.env[`${V}ACP_DEGRADE_POLICY`];return d&&(["polling_only","streaming_first"].includes(d)?o.degradePolicy=d:q.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:d})),q.debug("Config loaded from environment",{config:o}),o}function je(o){let e=st(),t={...e,...o};return q.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:o,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}var ye=a.create({service:"acp-rpc-handler"}),ot={INTERNAL_ERROR:-32603},Z=class{constructor(e){b$2(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:s}=e;ye.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:s});try{let r;switch(t){case "initialize":r=await this.handleInitialize(n);break;case "authenticate":r=await this.handleAuthenticate(n);break;case "session.new":case "newSession":r=await this.handleNewSession(n);break;case "session.load":case "loadSession":r=await this.handleLoadSession(n);break;case "session.close":case "closeSession":r=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":r=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),r={success:!0};break;case "session.list":case "listSessions":r=await this.handleListSessions(n);break;case "session.fork":case "forkSession":r=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":r=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":r=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":r=await this.handleSetSessionConfigOption(n);break;case "status":r=this.handleStatus();break;case "subscriptions":r=this.handleSubscriptions();break;default:throw ye.warn("Unknown method",{method:t}),new Error(`Method not found: ${t}`)}return {jsonrpc:"2.0",id:s,result:r}}catch(r){return ye.error("AcpRpcHandler error",{method:t,error:r instanceof Error?r.message:String(r)}),{jsonrpc:"2.0",id:s,error:{code:ot.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)}}}}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 ie=a.create({service:"server-agent-side-connection"}),X=class{constructor(){b$2(this,"broadcaster",null);b$2(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;ie.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return ie.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async extMethod(e,t){return ie.debug("ServerAgentSideConnection.extMethod",{method:e}),{}}async extNotification(e,t){if(ie.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 j=a.create({service:"http-server"});async function We(o,e){if(j.info("Starting HTTP server",{port:e.port,hostname:e.hostname}),e.channel!==D.HTTP)throw new Error("Invalid channel type for HTTP server");let t=new Map,n=new Map,s=new X,r={broadcast:(c,f)=>{P(c,f);}};s.setBroadcaster(r);let i=new Z(o),d=o.getSDK();if(!d)throw new Error("SDK not configured");let a=new W(d,s);a.setService(o),await a.start();let u=(c,f)=>{let g=t.get(c);if(!g)return false;try{return g.controller.enqueue(new TextEncoder().encode(f)),g.lastHeartbeat=Date.now(),!0}catch(h){return j.warn("Failed to push to SSE connection",{connectionId:c,error:h instanceof Error?h.message:String(h)}),false}},P=(c,f)=>{let g=n.get(c);if(!g||g.size===0)return;let S={jsonrpc:"2.0",method:f.update.sessionUpdate,params:{sessionId:c,...f.update,timestamp:Date.now()}},v=`data: ${JSON.stringify(S)}
|
|
2
2
|
|
|
3
3
|
`;for(let E of g)u(E,v)||(t.delete(E),g.delete(E));},I=(c,f)=>(s.addSession(c),new ReadableStream({start:g=>{let h={id:f,controller:g,sessionId:c,createdAt:Date.now(),lastHeartbeat:Date.now()};t.set(f,h),n.has(c)||n.set(c,new Set),n.get(c).add(f),j.info("SSE client connected",{connectionId:f,sessionId:c});let S=`data: ${JSON.stringify({type:"connected",connectionId:f,sessionId:c})}
|
|
4
4
|
|
|
5
5
|
`;g.enqueue(new TextEncoder().encode(S));},cancel:()=>{let g=t.get(f);if(g){t.delete(f);let h=n.get(g.sessionId);h&&(h.delete(f),h.size===0&&(n.delete(g.sessionId),s.removeSession(g.sessionId))),j.info("SSE client disconnected",{connectionId:f,sessionId:g.sessionId});}}})),p=setInterval(()=>{let c=Date.now(),f=3e5;for(let[g,h]of t.entries())if(c-h.lastHeartbeat>f){j.warn("SSE connection timeout, closing",{connectionId:g});try{h.controller.close();}catch{}t.delete(g);let S=n.get(h.sessionId);S&&S.delete(g);}else try{h.controller.enqueue(new TextEncoder().encode(`: heartbeat
|
|
6
6
|
|
|
7
|
-
`)),h.lastHeartbeat=c;}catch{}},1e4),m=[{method:"post",path:"/acp",handler:async c=>{let f=await c.req.json().catch(()=>null);if(!f||typeof f!="object")return c.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}},400);let g=f;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(S=>{j.error("HTTP server: session.prompt error",{error:String(S)});}),c.json({jsonrpc:"2.0",id:g.id,result:{accepted:true}},202);let h=await i.handle(g);if(g.method==="initialize"){let S=`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;return c.json(h,200,{"Acp-Connection-Id":S})}return c.json(h)}},{method:"get",path:"/acp",handler:c=>{let f=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 S=f||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(g){let k=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,R=I(g,k);return new Response(R,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":S,"Acp-Session-Id":g}})}let v=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,E=I("__connection__",v);return new Response(E,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":S}})}},{method:"delete",path:"/acp",handler:async c=>{let f=c.req.header("Acp-Connection-Id");return j.debug("HTTP server: connection terminated",{connectionId:f}),c.json({success:true})}}],l=createServer({port:e.port,hostname:e.hostname,routes:m,timeout:e.timeout,cors:true});return j.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:l,stop:async()=>{j.info("Stopping HTTP server"),clearInterval(p),await a.stop();for(let c of t.values())try{c.controller.close();}catch{}t.clear(),n.clear(),s.clearSessions(),await l.stop(),j.info("HTTP server stopped");}}}var B=a.create({service:"websocket-server"});function ct(o){try{let e=new URL(o),t=e.hostname,n=parseInt(e.port,10);if(t&&!Number.isNaN(n)&&n>0&&n<=65535)return {port:n,hostname:t}}catch{}}async function Fe(o,e){let t=e.ws?ct(e.ws.url):void 0,n=t?.port??e.port??3e3,s=t?.hostname??e.hostname??"localhost",r="/acp";if(B.info("Starting WebSocket server",{port:n,hostname:s,wsUrl:e.ws?.url}),e.channel!==D.WEBSOCKET)throw new Error("Invalid channel type for WebSocket server");let i=new Map,d=new Map,a=new X,u={broadcast:(h,S)=>{m(h,S);}};a.setBroadcaster(u);let P=new Z(o),I=o.getSDK();if(!I)throw new Error("SDK not configured");let p=new W(I,a);p.setService(o),await p.start();let m=(h,S)=>{let E={jsonrpc:"2.0",method:S.update.sessionUpdate,params:{sessionId:h,...S.update,timestamp:Date.now()}},k=JSON.stringify(E);for(let[R,z]of d.entries())if(z.subscribedSessions.has(h)){let A=i.get(R);A&&A.ws.readyState===A.ws.OPEN&&A.ws.send(k);}},l=h=>{for(let[S,v]of i.entries())if(v.ws===h)return S},c={onOpen:(h,S)=>{let v=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;i.set(v,{id:v,ws:S,createdAt:Date.now()}),d.set(v,{clientId:v,subscribedSessions:new Set}),B.info("WebSocket client connected",{clientId:v}),S.send(JSON.stringify({type:"connected",clientId:v}));},onMessage:async(h,S)=>{try{let v=JSON.parse(h.data.toString());if(v.type==="ping"){S.send(JSON.stringify({type:"pong"}));return}let E=l(S);if(!E)return;let k,R;if(v.type==="message"||v.type==="request")k={jsonrpc:"2.0",id:v.id,method:v.method,params:v.params},R=v.sessionId;else if(v.jsonrpc==="2.0"&&v.method)k={jsonrpc:"2.0",id:v.id,method:v.method,params:v.params},R=v.params?.sessionId;else {B.warn("WebSocket server: unknown message format",{data:v});return}if(k.method==="session.subscribe"){if(R){let A=d.get(E);A&&(A.subscribedSessions.add(R),a.addSession(R));}S.send(JSON.stringify({type:"response",id:k.id,result:{subscribed:!0,sessionId:R}}));return}if(k.method==="session.unsubscribe"){if(R){let A=d.get(E);A&&(A.subscribedSessions.delete(R),A.subscribedSessions.size===0&&a.removeSession(R));}S.send(JSON.stringify({type:"response",id:k.id,result:{unsubscribed:!0,sessionId:R}}));return}if(k.method==="session.interrupt"){let A={jsonrpc:"2.0",method:"session.cancel",params:{sessionId:R}},L=await P.handle(A);S.send(JSON.stringify({type:"response",id:k.id,result:L.result,error:L.error}));return}if(k.method==="session.prompt"){if(S.send(JSON.stringify({jsonrpc:"2.0",id:k.id,result:{accepted:!0}})),R){let A=i.get(E);A&&(A.sessionId=R);let L=d.get(E);L&&(L.subscribedSessions.add(R),a.addSession(R));}P.handle(k).catch(A=>{B.error("WebSocket server: session.prompt error",{error:String(A)});});return}if(R){let A=i.get(E);A&&(A.sessionId=R);let L=d.get(E);L&&(L.subscribedSessions.add(R),a.addSession(R));}let z=await P.handle(k);S.send(JSON.stringify({type:"response",id:z.id,result:z.result,error:z.error}));}catch(v){B.error("WebSocket server: error handling message",{error:String(v)});}},onClose:(h,S)=>{let v=l(S);if(v){i.delete(v);let E=d.get(v);if(E){for(let k of E.subscribedSessions)a.removeSession(k);d.delete(v);}B.info("WebSocket client disconnected",{clientId:v});}},onError:(h,S)=>{B.error("WebSocket error",{error:h.type});}},f=createServer({port:n,hostname:s,routes:[{method:"post",path:"/acp",handler:async h=>{let S=await h.req.json().catch(()=>null);if(!S||typeof S!="object")return h.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}});let v=S;if(!v.method||v.jsonrpc!=="2.0")return h.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request"}});let E=await P.handle(v);return h.json(E)}},{method:"delete",path:"/acp",handler:async h=>{let S=h.req.header("Acp-Connection-Id");return B.debug("WebSocket server: connection terminated",{connectionId:S}),h.json({success:true})}}],timeout:e.timeout,cors:true}),g=f.raw;if(g){let h=new WebSocketServer({noServer:true});g.on("upgrade",(S,v,E)=>{try{let R=new URL(S.url||"/",`http://${S.headers.host}`).pathname,z=S.headers.upgrade?.toLowerCase();R===r&&z==="websocket"&&h.handleUpgrade(S,v,E,A=>{c.onOpen?.({type:"open"},A),A.on("message",L=>{c.onMessage?.({data:L},A);}),A.on("close",(L,Je)=>{c.onClose?.({code:L,reason:Je},A);}),A.on("error",L=>{c.onError?.({type:"error",message:L.message},A);});});}catch{}});}return B.info("WebSocket server started",{url:e.ws?.url||`ws://${s}:${n}`,path:r}),{server:f,stop:async()=>{B.info("Stopping WebSocket server"),await p.stop();for(let h of i.values())try{h.ws.close();}catch{}i.clear(),d.clear(),a.clearSessions(),await f.stop(),B.info("WebSocket server stopped");}}}var ae=a.create({service:"acp-server"});async function Ge(o,e){let t=je(He(e||{}));ae.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,s;switch(t.channel){case D.HTTP:({server:n,stop:s}=await We(o,t));break;case D.WEBSOCKET:({server:n,stop:s}=await Fe(o,t));break;default:throw new Error(`Unsupported service mode: ${t.channel}`)}let r={type:t.channel,server:n,agent:o,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:r.type,url:dt(t)}),r}function dt(o){switch(o.channel){case D.STDIO:return "stdio://process";case D.HTTP:return `http://${o.hostname}:${o.port}`;case D.WEBSOCKET:return `ws://${o.hostname}:${o.port}`;default:return "unknown://"}}async function lt(o){await Promise.all(o.map(async e=>{try{await e.stop();}catch(t){ae.error("Error stopping server",{type:e.type,error:String(t)});}}));}async function Ve(o){await lt([o]);}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"}),oe=class{constructor(e){b$2(this,"sessions",new Map);b$2(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 r=await this.sdk.session.get({sessionId:e,directory:t},{throwOnError:true}).then(a=>a.data),i=s,d={id:e,cwd:t,mcpServers:n,createdAt:new Date(r.time.created),model:i};return ce.debug("loading_session",{state:d}),this.sessions.set(e,d),d}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 b=a.create({service:"acp-service"}),re=class{constructor(e,t){b$2(this,"config");b$2(this,"serviceMode");b$2(this,"connection");b$2(this,"sdk");b$2(this,"connectionRegistry",null);b$2(this,"sessionRouter",null);b$2(this,"sessionManager");b$2(this,"executorInitialized",false);b$2(this,"status","initializing");this.connection=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.sessionManager=new oe(this.sdk),t.connectionRegistry&&(this.connectionRegistry=t.connectionRegistry),t.sessionRouter&&(this.sessionRouter=t.sessionRouter),b.info("ACPService instance created",{channel:t.channel.type,hasConnection:!!e,hasProvidedRegistry:!!t.connectionRegistry,hasProvidedRouter:!!t.sessionRouter});}async initializeExecutor(){if(this.executorInitialized){b.warn("Executor components already initialized");return}this.connectionRegistry||(this.connectionRegistry=await ja.create(),b.debug("ConnectionRegistry created")),this.sessionRouter||(this.sessionRouter=ka.fromRegistry({resolve:e=>this.connectionRegistry.resolve(e),getConnectionsByPeer:e=>this.connectionRegistry.getConnectionsByAgent(e),getConnectionsByService:e=>this.connectionRegistry.getConnectionsByService(e)}),b.debug("SessionRouter created")),this.executorInitialized=true,b.info("Executor components initialized");}setStatus(e,t="agent"){let n=this.status;if(n===e)return;this.status=e,b.debug("Agent status changed",{oldStatus:n,newStatus:e,agentId:t});}getStatus(){return this.status}authenticate(e){return Promise.resolve(void 0)}async newSession(e){b.debug("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 d=await this.sessionManager.create(i,t,e.mcpServers,s),a=await this.buildSessionStateResponse(d.id,t);return {sessionId:d.id,...a,_meta:{}}}async loadSession(e){b.debug("ACP loadSession requested",{sessionId:e.sessionId});let t=e.cwd,s=(await this.sdk.model.default())?.data;return await this.sessionManager.load(e.sessionId,t,e.mcpServers,s),{...await this.buildSessionStateResponse(e.sessionId,t),_meta:{}}}async prompt(e){let t=e.sessionId,n=this.sessionManager.get(t),s=n.cwd,i=n.model??(await this.sdk.model.default())?.data,d=n.agent??(await this.sdk.agent.default({directory:s}))?.data?.name??"build";await this.sendAvailableCommandsUpdate(t,s);let a=[];for(let p of e.prompt)switch(p.type){case "text":{let m=p.annotations?.audience,l=m?.length===1&&m[0]==="assistant",c=m?.length===1&&m[0]==="user";a.push({type:"text",text:p.text,...l&&{synthetic:true},...c&&{ignored:true}});break}case "image":{let m=this.parseUri(p.uri??""),l=m.type==="file"?m.filename:"image";p.data?a.push({type:"file",url:`data:${p.mimeType};base64,${p.data}`,filename:l,mime:p.mimeType}):p.uri?.startsWith("http:")&&a.push({type:"file",url:p.uri,filename:l,mime:p.mimeType});break}case "resource_link":{let m=this.parseUri(p.uri);p.name&&m.type==="file"&&(m.filename=p.name),a.push(m);break}case "resource":{let m=p.resource;if("text"in m&&m.text)a.push({type:"text",text:m.text});else if("blob"in m&&m.blob&&m.mimeType){let l=this.parseUri(m.uri??""),c=l.type==="file"?l.filename:"file";a.push({type:"file",url:`data:${m.mimeType};base64,${m.blob}`,filename:c,mime:m.mimeType});}break}}b.info("prompt parts",{sessionId:t,parts:a});let u=(()=>{let p=a.filter(c=>c.type==="text").map(c=>c.text).join("").trim();if(!p.startsWith("/"))return;let[m,...l]=p.slice(1).split(/\s+/);return {name:m,args:l.join(" ").trim()}})(),P=p=>({totalTokens:p.tokens.input+p.tokens.output+p.tokens.reasoning+(p.tokens.cache?.read??0)+(p.tokens.cache?.write??0),inputTokens:p.tokens.input,outputTokens:p.tokens.output,thoughtTokens:p.tokens.reasoning||void 0,cachedReadTokens:p.tokens.cache?.read||void 0,cachedWriteTokens:p.tokens.cache?.write||void 0});if(!u){let m=(await this.sdk.session.prompt({sessionId:t,model:{providerId:i.providerId,modelId:i.modelId},parts:a,agent:d,directory:s,variant:n.variant,contextMode:n.contextMode})).data?.info;return {stopReason:"end_turn",usage:m?P(m):void 0,_meta:{}}}let I=await this.sdk.command.list({directory:s},{throwOnError:true}).then(p=>p.data?.find(m=>m.name===u.name));if(I){let p=await za.get(u.name),m=await Aa.command({sessionId:t,agent:d,model:i.providerId+"/"+i.modelId,arguments:u.args,command:I.name});if(await this.sendUsageUpdate(t,s),p?.commandType==="local"&&this.connection){let l=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:l}}});}return {stopReason:"end_turn",usage:m.info?P({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(u.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=>{b.warn("SDK abort failed",{sessionId:e.sessionId,error:String(s)});}),b.debug("Session cancelled",{sessionId:e.sessionId});}catch(s){throw b.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(u=>u.data).catch(u=>{b.error("failed to fetch messages for usage update",{error:u});});if(!n)return;let s=n.filter(u=>u.info.role==="assistant"),r=s[s.length-1];if(!r)return;let i=r.info,d=await this.getContextLimit(i.providerId,i.modelId,t);if(!d)return;let a=i.tokens.input+(i.tokens.cache?.read??0);await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:a,size:d}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.connection)try{let s=(await this.sdk.command.list({directory:t},{throwOnError:!0})).data?.map(r=>({name:r.name,description:r.description??""}))??[];await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:s}});}catch(n){b.error("failed to send available commands update",{error:n});}}async sendConfigOptionUpdate(e,t,n){if(this.connection)try{let r=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!r||r.length===0)return;await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:r}});}catch(s){b.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){b.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(d=>d.data?.providers??[]).catch(d=>(b.error("failed to get providers for context limit",{error:d}),[]))).find(d=>d.id===e)?.models[t]?.limit.context??2e5:null}async unstable_forkSession(e){b.info("ACP forkSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.mcpServers??[],r=(await this.sdk.model.default())?.data,i=await this.sdk.session.fork({sessionId:e.sessionId,directory:t},{throwOnError:true}).then(P=>P.data);if(!i)throw new Error("Fork session returned no data");let d=i.id;await this.sessionManager.load(d,t,n,r);let u=await this.buildSessionStateResponse(d,t);return b.info("fork_session",{sessionId:d,mcpServers:n.length}),{sessionId:d,...u,_meta:{}}}async resumeSession(e){b.debug("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 b.info("resume_session",{sessionId:n,mcpServers:s.length}),{...a,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,r=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(I=>I.data??[])).toSorted((I,p)=>p.time.updated-I.time.updated),d=(t?r.filter(I=>I.time.updated<t):r).slice(0,n),a=d.map(I=>({sessionId:I.id,cwd:I.directory,title:I.title??`Session ${I.id}`,updatedAt:new Date(I.time.updated).toISOString()})),u=d[d.length-1],P=d.length===n&&u?String(u.time.updated):void 0;return {sessions:a,nextCursor:P}}async setSessionMode(e){b.debug("ACP setSessionMode requested",{sessionId:e.sessionId,modeId:e.modeId}),this.sessionManager.setMode(e.sessionId,e.modeId);let t=this.sessionManager.get(e.sessionId);return await this.sendCurrentModeUpdate(e.sessionId,e.modeId),await this.sendConfigOptionUpdate(e.sessionId,t.cwd),{_meta:{}}}async setSessionConfigOption(e$1){if(b.debug("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 r=this.parseModelSelection(s);this.sessionManager.setModel(e$1.sessionId,r.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 b.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,r=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 l=m.models??{};return Object.keys(l).map(c=>({modelId:`${m.id}/${c}`,name:`${m.id}/${c}`}))});}catch(p){b.warn("failed to build available models for session state",{sessionId:e$1,error:p instanceof Error?p.message:String(p)});}r&&!i.some(p=>p.modelId===r)&&(i=[{modelId:r,name:r},...i]);let d=[];try{d=((await this.sdk.app.agents({directory:t})).data??[]).filter(l=>l.hidden!==!0&&l.mode!=="subagent").map(l=>({id:l.name,name:l.name,description:l.description}));}catch(p){b.warn("failed to build available agents for session state",{sessionId:e$1,error:p instanceof Error?p.message:String(p)});}let a=n?.modeId,u=n?.variant??"low",P=n?.contextMode??f,I=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e$1,t),{models:r?{currentModelId:r,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:r??"",options:i.map(p=>({value:p.modelId,name:p.name,description:p.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:I,options:d.map(p=>({value:p.id,name:p.name,description:p.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:u,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:P,options:e.map(p=>({value:p,name:p.charAt(0).toUpperCase()+p.slice(1)}))}]}}parseModelSelection(e){let{provider:t,model:n}=parseModelId(e);return t&&n?{model:{providerId:t,modelId:n}}:{model:{providerId:"unknown",modelId:e}}}setConnection(e){this.connection=e,b.debug("ACPService connection updated");}getConnection(){return this.connection}abortConnection(){this.connection&&b.debug("Connection aborted");}closeConnection(){this.connection&&b.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(){b.info("Disposing ACPService"),this.sessionManager&&(this.sessionManager.dispose?.(),b.debug("SessionManager disposed")),this.connectionRegistry&&(await this.connectionRegistry.close(),this.connectionRegistry=null,b.debug("ConnectionRegistry closed")),this.sessionRouter=null,this.executorInitialized=false,b.info("ACPService disposed");}};var U=a.create({service:"easbot-agent"}),ee=class o extends re{constructor(t,n){super(t,n);b$2(this,"acpEventBridge",null);b$2(this,"server",null);b$2(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 o(void 0,t);if(n&&t.stdioStream){let{stream:r}=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)},d=new AgentSideConnection(()=>i,r);s.setConnection(d);}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 Ge(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 Ve(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 W(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 o extends Error{constructor(t,n,s){super(t);b$2(this,"type");b$2(this,"stage");b$2(this,"cause");this.type="AdapterEnvironmentInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,o);}},te=a.create({service:"adapter.bootstrap"}),Ce;function St(){return Ce||(Ce=Sa.state(async()=>({initialized:false,initPromise:null,instancePromise:null,handlersInstalled:false,directory:".easbot",sdk:null,activeChannel:null,agent:null,acpConnection:null}),async o=>{let e=o.agent;e&&await e.stop().catch(()=>{}),o.agent=null,o.sdk=null,o.acpConnection=null;})),Ce}async function H(){return St()()}function Qe(o){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=o.code;return e.includes(t??"")}function vt(o){o.handlersInstalled||(process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));Qe(t)||te.error("unhandled promise rejection",{error:t.message,stack:t.stack});}),process.on("uncaughtException",e=>{Qe(e)||(te.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));}),o.handlersInstalled=true);}async function yt(o){return o.instancePromise||(o.instancePromise=Sa.provide({directory:o.directory,init:ub,fn:async()=>{te.debug("instance bootstrap completed");}}).then(()=>{})),o.instancePromise}async function Ct(){try{await Sa.dispose(),te.debug("instance disposed");}catch(o){te.warn("failed to dispose instance",{error:o instanceof Error?o.message:String(o)});}}var K;(m=>{function o(l,c){return l.sdk||(l.sdk=xa({directory:c})),l.sdk}function e(l){switch(l){case "http":return "http";case "stdio":return "stdio";case "websocket":return "websocket";default:return "stdio"}}async function t(l){let c=await H();if(c.initialized)return;if(c.initPromise)return c.initPromise;let f={directory:l?.directory??".easbot",initModels:l?.initModels??true,printLogs:l?.printLogs??false,logLevel:l?.logLevel??"INFO",channel:l?.channel??"stdio"};if(c.directory=f.directory,o(c,c.directory),c.activeChannel&&c.activeChannel!==f.channel)throw new Error(`Adapter already initialized with channel ${c.activeChannel}, cannot re-init with ${f.channel}`);return c.activeChannel=f.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:f.printLogs??!1,level:f.logLevel??"INFO"});}catch(g){throw new F("Failed to initialize log infrastructure","log",g instanceof Error?g:void 0)}if(f.initModels)try{b$1();}catch(g){throw new F("Failed to initialize models refresh","models",g instanceof Error?g:void 0)}try{vt(c);}catch(g){throw new F("Failed to install unhandled exception handlers","handlers",g instanceof Error?g:void 0)}try{await yt(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 l=await H();if(l.initialized){await Ha.stop().catch(()=>{});try{let{MCP:c}=await import('./mcp-GEZSPY2W.mjs'),f=await c.clients();for(let[g,h]of Object.entries(f))await h.disconnect().catch(()=>{});}catch{}l.agent&&(await l.agent.stop().catch(()=>{}),l.agent=null),await Ct(),l.initialized=false,l.initPromise=null,l.instancePromise=null,l.activeChannel=null,l.sdk=null,l.agent=null,l.acpConnection=null;}}m.destroy=n;async function s(){return (await H()).initialized}m.isInitialized=s;async function r(l){let c=await H();c.agent=l;}m.setAgent=r;async function i(){return (await H()).agent}m.getAgent=i;async function d(){let c=(await H()).agent?.getServerInstance();return c||null}m.getServer=d;async function a$2(){return (await H()).sdk}m.getSDK=a$2;async function u(){return (await H()).acpConnection}m.getACPConnection=u;async function P(){let l=await H(),c=!!l.agent?.getServerInstance();return {initialized:l.initialized,directory:l.directory,activeChannel:l.activeChannel,hasSDK:!!l.sdk,hasAgent:!!l.agent,hasACPConnection:!!l.acpConnection,hasServer:c}}m.getState=P;async function I(l){await t({channel:l.channel,directory:l.directory});let c=await H(),f=o(c,c.directory);if(l.channel==="stdio")return p({directory:l.directory});if(c.agent?.getServerInstance()&&c.activeChannel&&c.activeChannel!==l.channel)throw new Error(`ACP service already started with channel ${c.activeChannel}, cannot switch to ${l.channel}`);if(c.agent){let v=c.agent.getServerInstance();if(v)return {sdk:f,agent:c.agent,server:v}}let h=await ee.create({serviceMode:e(l.channel),acp:{sdk:f},acpServerConfig:l,channel:{type:l.channel,timeout:l.timeout}});await h.start();let S=h.getServerInstance();if(!S)throw new Error("ACP server failed to start");return c.agent=h,c.activeChannel=l.channel,{sdk:f,agent:h,server:S}}m.ensureACPService=I;async function p(l){await t({channel:"stdio",directory:l.directory});let c=await H(),f=o(c,c.directory);if(c.agent)return {sdk:f,agent:c.agent};let g=new WritableStream({write(E){return new Promise((k,R)=>{try{process.stdout.write(E)?k():process.stdout.once("drain",k);}catch(z){let A=z;A.code==="EPIPE"||A.code==="EIO"?R(new Error("stdout pipe broken")):R(z);}})}}),h=new ReadableStream({start(E){process.stdin.on("data",k=>{E.enqueue(new Uint8Array(k));}),process.stdin.on("end",()=>E.close()),process.stdin.on("error",k=>E.error(k));}}),S=ndJsonStream(g,h),v=await ee.create({serviceMode:"stdio",acp:{sdk:f},channel:{type:"stdio",timeout:6e4},stdioStream:{stream:S}});return c.acpConnection=v.getConnection()??null,await v.start(),c.agent=v,c.activeChannel="stdio",te.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:f,agent:v}}m.ensureACPServiceStdio=p;})(K||(K={}));var C=a.create({service:"cli-command-acp"}),$=null,G=null,de=null;function It(o){switch(o.channel){case "websocket":return o.ws?.url?o.ws.url:`ws://${o.hostname}:${o.port}`;case "http":return o.http?.baseUrl?o.http.baseUrl:`http://${o.hostname}:${o.port}`;default:return "stdio://local"}}async function Et(o){if(o.channel==="stdio"){C.debug("Skipping gateway registration for stdio mode");return}let e=await k$1();if(!e){C.debug("No gateway URL configured, skipping registration");return}let t=o.agentId||Identifier.ascending("agent"),n=o.name||"ACP Agent";de=t,C.debug("Preparing gateway registration",{agentId:t,agentName:n,configName:o.name,configAgentId:o.agentId});let s=It(o),r=6e4,i=()=>{G||(G=setInterval(async()=>{if($&&$.getState()==="connected")try{await $.agentHeartbeat(t),C.debug("Gateway heartbeat sent",{agentId:t});}catch(d){C.warn("Gateway heartbeat failed",{error:String(d)});}},r),C.debug("Gateway heartbeat timer started",{agentId:t}));};$=new Q({url:e,type:"acp",id:`acp-${t}`,heartbeat:{enabled:true,interval:r}}),$.onStateChange(async d=>{C.debug("Gateway state changed",{state:d}),d==="connected"?$.registerAgent({agentId:t,name:n,address:s,capabilities:[o.channel],metadata:{hostname:o.hostname,port:o.port,channel:o.channel}}).then(()=>{C.info("Registered to gateway",{agentId:t,agentName:n,address:s,capabilities:[o.channel]}),i();}).catch(a=>{C.warn("Registration failed, will retry...",{error:String(a)}),retry(async()=>{$&&$.getState()==="connected"&&await $.registerAgent({agentId:t,name:n,address:s,capabilities:[o.channel],metadata:{hostname:o.hostname,port:o.port,channel:o.channel}});},{attempts:3,delay:3e4}).then(()=>i()).catch(u=>C.warn("Registration retry failed",{error:String(u)}));}):d==="disconnected"&&(G&&(clearInterval(G),G=null,C.debug("Gateway heartbeat timer stopped")),de=null);});}async function Rt(){G&&(clearInterval(G),G=null,C.debug("Gateway heartbeat timer stopped"));let o=de;if(de=null,$&&o)try{await $.deregisterAgent(o),C.debug("Agent deregistered from gateway",{agentId:o});}catch(e){C.warn("Failed to deregister agent",{error:String(e)});}if($){try{await $.disconnect(),C.debug("Disconnected from gateway");}catch(e){C.warn("Failed to disconnect from gateway",{error:String(e)});}$=null;}}async function kt(o,e){let t=await tb.getACPServerConfig();C.debug("Merging ACP configuration",{baseConfig:{channel:t.channel,port:t.port,hostname:t.hostname,timeout:t.timeout,name:t.name,agentId:t.agentId},cliOptions:{channel:e.channel,port:e.port,hostname:e.hostname,timeout:e.timeout}});let n={};if(e.channel!==void 0){let r=e.channel.toLowerCase();Object.values(R).includes(r)?(n.channel=r,C.debug("CLI override: channel",{value:n.channel})):C.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,C.debug("CLI override: port",{value:n.port})):C.warn("Invalid port from command line",{value:e.port})),e.hostname!==void 0&&(n.hostname=e.hostname,C.debug("CLI override: hostname",{value:n.hostname})),e.timeout!==void 0&&(e.timeout>0?(n.timeout=e.timeout,C.debug("CLI override: timeout",{value:n.timeout})):C.warn("Invalid timeout from command line",{value:e.timeout})),e.hostname!==void 0||e.port!==void 0){let r=e.hostname??t.hostname??"127.0.0.1",i=e.port??t.port??3e3;t.ws&&(n.ws={...t.ws,url:`ws://${r}:${i}`}),t.http&&(n.http={...t.http,baseUrl:`http://${r}:${i}`}),C.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),C.debug("CLI override: ws.timeout and http.timeout updated",{timeout:e.timeout}));let s={...t,...n};return C.debug("Merged ACP configuration",{channel:s.channel,port:s.port,hostname:s.hostname,timeout:s.timeout}),s}async function xt(o,e,t){C.info("Starting ACP service",{channel:e.channel,port:e.port,hostname:e.hostname,debug:t.config.debug}),await K.init({directory:o,printLogs:t.config.print_logs,logLevel:t.config.log_level,channel:e.channel});await K.ensureACPService(e);await Et(e),console.log(""),console.log(d(i("acp.server.started"))),console.log(k(60)),console.log(i$1(i("acp.field.directory"),o,15)),console.log(i$1(i("acp.field.worktree"),Sa.project.worktree||"N/A",15)),console.log(i$1(i("acp.field.channel"),e.channel,15));let s=b$3();switch(e.channel){case "websocket":{let i$2,d="/";if(e.ws?.url)try{let a=new URL(e.ws.url),u=a.port||"3000",P=a.hostname;d=a.pathname||"/",i$2=`ws://${P}:${u}${d==="/"?"":d}`;}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"),d,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 r=getProxyConfig();if(r.enabled){let i$2=r.https||r.http||"configured";console.log(i$1(i("acp.field.proxy"),i$2,15));}console.log(k(60)),console.log(""),C.info("ACPServer started successfully"),_t();}function _t(){let o=process.env.EASBOT_RUN_MODE==="ephemeral"||!process.stdin.isTTY&&process.env.EASBOT_RUN_MODE!=="persistent",e=async t=>{C.debug(`Received ${t}, shutting down...`),o||console.log(`
|
|
7
|
+
`)),h.lastHeartbeat=c;}catch{}},1e4),m=[{method:"post",path:"/acp",handler:async c=>{let f=await c.req.json().catch(()=>null);if(!f||typeof f!="object")return c.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}},400);let g=f;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(S=>{j.error("HTTP server: session.prompt error",{error:String(S)});}),c.json({jsonrpc:"2.0",id:g.id,result:{accepted:true}},202);let h=await i.handle(g);if(g.method==="initialize"){let S=`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;return c.json(h,200,{"Acp-Connection-Id":S})}return c.json(h)}},{method:"get",path:"/acp",handler:c=>{let f=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 S=f||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(g){let k=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,R=I(g,k);return new Response(R,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":S,"Acp-Session-Id":g}})}let v=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,E=I("__connection__",v);return new Response(E,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":S}})}},{method:"delete",path:"/acp",handler:async c=>{let f=c.req.header("Acp-Connection-Id");return j.debug("HTTP server: connection terminated",{connectionId:f}),c.json({success:true})}}],l=createServer({port:e.port,hostname:e.hostname,routes:m,timeout:e.timeout,cors:true});return j.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:l,stop:async()=>{j.info("Stopping HTTP server"),clearInterval(p),await a.stop();for(let c of t.values())try{c.controller.close();}catch{}t.clear(),n.clear(),s.clearSessions(),await l.stop(),j.info("HTTP server stopped");}}}var B=a.create({service:"websocket-server"});function ct(o){try{let e=new URL(o),t=e.hostname,n=parseInt(e.port,10);if(t&&!Number.isNaN(n)&&n>0&&n<=65535)return {port:n,hostname:t}}catch{}}async function Fe(o,e){let t=e.ws?ct(e.ws.url):void 0,n=t?.port??e.port??3e3,s=t?.hostname??e.hostname??"localhost",r="/acp";if(B.info("Starting WebSocket server",{port:n,hostname:s,wsUrl:e.ws?.url}),e.channel!==D.WEBSOCKET)throw new Error("Invalid channel type for WebSocket server");let i=new Map,d=new Map,a=new X,u={broadcast:(h,S)=>{m(h,S);}};a.setBroadcaster(u);let P=new Z(o),I=o.getSDK();if(!I)throw new Error("SDK not configured");let p=new W(I,a);p.setService(o),await p.start();let m=(h,S)=>{let E={jsonrpc:"2.0",method:S.update.sessionUpdate,params:{sessionId:h,...S.update,timestamp:Date.now()}},k=JSON.stringify(E);for(let[R,z]of d.entries())if(z.subscribedSessions.has(h)){let A=i.get(R);A&&A.ws.readyState===A.ws.OPEN&&A.ws.send(k);}},l=h=>{for(let[S,v]of i.entries())if(v.ws===h)return S},c={onOpen:(h,S)=>{let v=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;i.set(v,{id:v,ws:S,createdAt:Date.now()}),d.set(v,{clientId:v,subscribedSessions:new Set}),B.info("WebSocket client connected",{clientId:v}),S.send(JSON.stringify({type:"connected",clientId:v}));},onMessage:async(h,S)=>{try{let v=JSON.parse(h.data.toString());if(v.type==="ping"){S.send(JSON.stringify({type:"pong"}));return}let E=l(S);if(!E)return;let k,R;if(v.type==="message"||v.type==="request")k={jsonrpc:"2.0",id:v.id,method:v.method,params:v.params},R=v.sessionId;else if(v.jsonrpc==="2.0"&&v.method)k={jsonrpc:"2.0",id:v.id,method:v.method,params:v.params},R=v.params?.sessionId;else {B.warn("WebSocket server: unknown message format",{data:v});return}if(k.method==="session.subscribe"){if(R){let A=d.get(E);A&&(A.subscribedSessions.add(R),a.addSession(R));}S.send(JSON.stringify({type:"response",id:k.id,result:{subscribed:!0,sessionId:R}}));return}if(k.method==="session.unsubscribe"){if(R){let A=d.get(E);A&&(A.subscribedSessions.delete(R),A.subscribedSessions.size===0&&a.removeSession(R));}S.send(JSON.stringify({type:"response",id:k.id,result:{unsubscribed:!0,sessionId:R}}));return}if(k.method==="session.interrupt"){let A={jsonrpc:"2.0",method:"session.cancel",params:{sessionId:R}},L=await P.handle(A);S.send(JSON.stringify({type:"response",id:k.id,result:L.result,error:L.error}));return}if(k.method==="session.prompt"){if(S.send(JSON.stringify({jsonrpc:"2.0",id:k.id,result:{accepted:!0}})),R){let A=i.get(E);A&&(A.sessionId=R);let L=d.get(E);L&&(L.subscribedSessions.add(R),a.addSession(R));}P.handle(k).catch(A=>{B.error("WebSocket server: session.prompt error",{error:String(A)});});return}if(R){let A=i.get(E);A&&(A.sessionId=R);let L=d.get(E);L&&(L.subscribedSessions.add(R),a.addSession(R));}let z=await P.handle(k);S.send(JSON.stringify({type:"response",id:z.id,result:z.result,error:z.error}));}catch(v){B.error("WebSocket server: error handling message",{error:String(v)});}},onClose:(h,S)=>{let v=l(S);if(v){i.delete(v);let E=d.get(v);if(E){for(let k of E.subscribedSessions)a.removeSession(k);d.delete(v);}B.info("WebSocket client disconnected",{clientId:v});}},onError:(h,S)=>{B.error("WebSocket error",{error:h.type});}},f=createServer({port:n,hostname:s,routes:[{method:"post",path:"/acp",handler:async h=>{let S=await h.req.json().catch(()=>null);if(!S||typeof S!="object")return h.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}});let v=S;if(!v.method||v.jsonrpc!=="2.0")return h.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request"}});let E=await P.handle(v);return h.json(E)}},{method:"delete",path:"/acp",handler:async h=>{let S=h.req.header("Acp-Connection-Id");return B.debug("WebSocket server: connection terminated",{connectionId:S}),h.json({success:true})}}],timeout:e.timeout,cors:true}),g=f.raw;if(g){let h=new WebSocketServer({noServer:true});g.on("upgrade",(S,v,E)=>{try{let R=new URL(S.url||"/",`http://${S.headers.host}`).pathname,z=S.headers.upgrade?.toLowerCase();R===r&&z==="websocket"&&h.handleUpgrade(S,v,E,A=>{c.onOpen?.({type:"open"},A),A.on("message",L=>{c.onMessage?.({data:L},A);}),A.on("close",(L,Je)=>{c.onClose?.({code:L,reason:Je},A);}),A.on("error",L=>{c.onError?.({type:"error",message:L.message},A);});});}catch{}});}return B.info("WebSocket server started",{url:e.ws?.url||`ws://${s}:${n}`,path:r}),{server:f,stop:async()=>{B.info("Stopping WebSocket server"),await p.stop();for(let h of i.values())try{h.ws.close();}catch{}i.clear(),d.clear(),a.clearSessions(),await f.stop(),B.info("WebSocket server stopped");}}}var ae=a.create({service:"acp-server"});async function Ge(o,e){let t=je(He(e||{}));ae.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,s;switch(t.channel){case D.HTTP:({server:n,stop:s}=await We(o,t));break;case D.WEBSOCKET:({server:n,stop:s}=await Fe(o,t));break;default:throw new Error(`Unsupported service mode: ${t.channel}`)}let r={type:t.channel,server:n,agent:o,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:r.type,url:dt(t)}),r}function dt(o){switch(o.channel){case D.STDIO:return "stdio://process";case D.HTTP:return `http://${o.hostname}:${o.port}`;case D.WEBSOCKET:return `ws://${o.hostname}:${o.port}`;default:return "unknown://"}}async function lt(o){await Promise.all(o.map(async e=>{try{await e.stop();}catch(t){ae.error("Error stopping server",{type:e.type,error:String(t)});}}));}async function Ve(o){await lt([o]);}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"}),oe=class{constructor(e){b$2(this,"sessions",new Map);b$2(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 r=await this.sdk.session.get({sessionId:e,directory:t},{throwOnError:true}).then(a=>a.data),i=s,d={id:e,cwd:t,mcpServers:n,createdAt:new Date(r.time.created),model:i};return ce.debug("loading_session",{state:d}),this.sessions.set(e,d),d}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 b=a.create({service:"acp-service"}),re=class{constructor(e,t){b$2(this,"config");b$2(this,"serviceMode");b$2(this,"connection");b$2(this,"sdk");b$2(this,"connectionRegistry",null);b$2(this,"sessionRouter",null);b$2(this,"sessionManager");b$2(this,"executorInitialized",false);b$2(this,"status","initializing");this.connection=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.sessionManager=new oe(this.sdk),t.connectionRegistry&&(this.connectionRegistry=t.connectionRegistry),t.sessionRouter&&(this.sessionRouter=t.sessionRouter),b.info("ACPService instance created",{channel:t.channel.type,hasConnection:!!e,hasProvidedRegistry:!!t.connectionRegistry,hasProvidedRouter:!!t.sessionRouter});}async initializeExecutor(){if(this.executorInitialized){b.warn("Executor components already initialized");return}this.connectionRegistry||(this.connectionRegistry=await ja.create(),b.debug("ConnectionRegistry created")),this.sessionRouter||(this.sessionRouter=ka.fromRegistry({resolve:e=>this.connectionRegistry.resolve(e),getConnectionsByPeer:e=>this.connectionRegistry.getConnectionsByAgent(e),getConnectionsByService:e=>this.connectionRegistry.getConnectionsByService(e)}),b.debug("SessionRouter created")),this.executorInitialized=true,b.info("Executor components initialized");}setStatus(e,t="agent"){let n=this.status;if(n===e)return;this.status=e,b.debug("Agent status changed",{oldStatus:n,newStatus:e,agentId:t});}getStatus(){return this.status}authenticate(e){return Promise.resolve(void 0)}async newSession(e){b.debug("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 d=await this.sessionManager.create(i,t,e.mcpServers,s),a=await this.buildSessionStateResponse(d.id,t);return {sessionId:d.id,...a,_meta:{}}}async loadSession(e){b.debug("ACP loadSession requested",{sessionId:e.sessionId});let t=e.cwd,s=(await this.sdk.model.default())?.data;return await this.sessionManager.load(e.sessionId,t,e.mcpServers,s),{...await this.buildSessionStateResponse(e.sessionId,t),_meta:{}}}async prompt(e){let t=e.sessionId,n=this.sessionManager.get(t),s=n.cwd,i=n.model??(await this.sdk.model.default())?.data,d=n.agent??(await this.sdk.agent.default({directory:s}))?.data?.name??"build";await this.sendAvailableCommandsUpdate(t,s);let a=[];for(let p of e.prompt)switch(p.type){case "text":{let m=p.annotations?.audience,l=m?.length===1&&m[0]==="assistant",c=m?.length===1&&m[0]==="user";a.push({type:"text",text:p.text,...l&&{synthetic:true},...c&&{ignored:true}});break}case "image":{let m=this.parseUri(p.uri??""),l=m.type==="file"?m.filename:"image";p.data?a.push({type:"file",url:`data:${p.mimeType};base64,${p.data}`,filename:l,mime:p.mimeType}):p.uri?.startsWith("http:")&&a.push({type:"file",url:p.uri,filename:l,mime:p.mimeType});break}case "resource_link":{let m=this.parseUri(p.uri);p.name&&m.type==="file"&&(m.filename=p.name),a.push(m);break}case "resource":{let m=p.resource;if("text"in m&&m.text)a.push({type:"text",text:m.text});else if("blob"in m&&m.blob&&m.mimeType){let l=this.parseUri(m.uri??""),c=l.type==="file"?l.filename:"file";a.push({type:"file",url:`data:${m.mimeType};base64,${m.blob}`,filename:c,mime:m.mimeType});}break}}b.info("prompt parts",{sessionId:t,parts:a});let u=(()=>{let p=a.filter(c=>c.type==="text").map(c=>c.text).join("").trim();if(!p.startsWith("/"))return;let[m,...l]=p.slice(1).split(/\s+/);return {name:m,args:l.join(" ").trim()}})(),P=p=>({totalTokens:p.tokens.input+p.tokens.output+p.tokens.reasoning+(p.tokens.cache?.read??0)+(p.tokens.cache?.write??0),inputTokens:p.tokens.input,outputTokens:p.tokens.output,thoughtTokens:p.tokens.reasoning||void 0,cachedReadTokens:p.tokens.cache?.read||void 0,cachedWriteTokens:p.tokens.cache?.write||void 0});if(!u){let m=(await this.sdk.session.prompt({sessionId:t,model:{providerId:i.providerId,modelId:i.modelId},parts:a,agent:d,directory:s,variant:n.variant,contextMode:n.contextMode})).data?.info;return {stopReason:"end_turn",usage:m?P(m):void 0,_meta:{}}}let I=await this.sdk.command.list({directory:s},{throwOnError:true}).then(p=>p.data?.find(m=>m.name===u.name));if(I){let p=await za.get(u.name),m=await Aa.command({sessionId:t,agent:d,model:i.providerId+"/"+i.modelId,arguments:u.args,command:I.name});if(await this.sendUsageUpdate(t,s),p?.commandType==="local"&&this.connection){let l=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:l}}});}return {stopReason:"end_turn",usage:m.info?P({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(u.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=>{b.warn("SDK abort failed",{sessionId:e.sessionId,error:String(s)});}),b.debug("Session cancelled",{sessionId:e.sessionId});}catch(s){throw b.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(u=>u.data).catch(u=>{b.error("failed to fetch messages for usage update",{error:u});});if(!n)return;let s=n.filter(u=>u.info.role==="assistant"),r=s[s.length-1];if(!r)return;let i=r.info,d=await this.getContextLimit(i.providerId,i.modelId,t);if(!d)return;let a=i.tokens.input+(i.tokens.cache?.read??0);await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:a,size:d}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.connection)try{let s=(await this.sdk.command.list({directory:t},{throwOnError:!0})).data?.map(r=>({name:r.name,description:r.description??""}))??[];await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:s}});}catch(n){b.error("failed to send available commands update",{error:n});}}async sendConfigOptionUpdate(e,t,n){if(this.connection)try{let r=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!r||r.length===0)return;await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:r}});}catch(s){b.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){b.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(d=>d.data?.providers??[]).catch(d=>(b.error("failed to get providers for context limit",{error:d}),[]))).find(d=>d.id===e)?.models[t]?.limit.context??2e5:null}async unstable_forkSession(e){b.info("ACP forkSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.mcpServers??[],r=(await this.sdk.model.default())?.data,i=await this.sdk.session.fork({sessionId:e.sessionId,directory:t},{throwOnError:true}).then(P=>P.data);if(!i)throw new Error("Fork session returned no data");let d=i.id;await this.sessionManager.load(d,t,n,r);let u=await this.buildSessionStateResponse(d,t);return b.info("fork_session",{sessionId:d,mcpServers:n.length}),{sessionId:d,...u,_meta:{}}}async resumeSession(e){b.debug("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 b.info("resume_session",{sessionId:n,mcpServers:s.length}),{...a,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,r=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(I=>I.data??[])).toSorted((I,p)=>p.time.updated-I.time.updated),d=(t?r.filter(I=>I.time.updated<t):r).slice(0,n),a=d.map(I=>({sessionId:I.id,cwd:I.directory,title:I.title??`Session ${I.id}`,updatedAt:new Date(I.time.updated).toISOString()})),u=d[d.length-1],P=d.length===n&&u?String(u.time.updated):void 0;return {sessions:a,nextCursor:P}}async setSessionMode(e){b.debug("ACP setSessionMode requested",{sessionId:e.sessionId,modeId:e.modeId}),this.sessionManager.setMode(e.sessionId,e.modeId);let t=this.sessionManager.get(e.sessionId);return await this.sendCurrentModeUpdate(e.sessionId,e.modeId),await this.sendConfigOptionUpdate(e.sessionId,t.cwd),{_meta:{}}}async setSessionConfigOption(e$1){if(b.debug("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 r=this.parseModelSelection(s);this.sessionManager.setModel(e$1.sessionId,r.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 b.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,r=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 l=m.models??{};return Object.keys(l).map(c=>({modelId:`${m.id}/${c}`,name:`${m.id}/${c}`}))});}catch(p){b.warn("failed to build available models for session state",{sessionId:e$1,error:p instanceof Error?p.message:String(p)});}r&&!i.some(p=>p.modelId===r)&&(i=[{modelId:r,name:r},...i]);let d=[];try{d=((await this.sdk.app.agents({directory:t})).data??[]).filter(l=>l.hidden!==!0&&l.mode!=="subagent").map(l=>({id:l.name,name:l.name,description:l.description}));}catch(p){b.warn("failed to build available agents for session state",{sessionId:e$1,error:p instanceof Error?p.message:String(p)});}let a=n?.modeId,u=n?.variant??"low",P=n?.contextMode??f,I=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e$1,t),{models:r?{currentModelId:r,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:r??"",options:i.map(p=>({value:p.modelId,name:p.name,description:p.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:I,options:d.map(p=>({value:p.id,name:p.name,description:p.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:u,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:P,options:e.map(p=>({value:p,name:p.charAt(0).toUpperCase()+p.slice(1)}))}]}}parseModelSelection(e){let{provider:t,model:n}=parseModelId(e);return t&&n?{model:{providerId:t,modelId:n}}:{model:{providerId:"unknown",modelId:e}}}setConnection(e){this.connection=e,b.debug("ACPService connection updated");}getConnection(){return this.connection}abortConnection(){this.connection&&b.debug("Connection aborted");}closeConnection(){this.connection&&b.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(){b.info("Disposing ACPService"),this.sessionManager&&(this.sessionManager.dispose?.(),b.debug("SessionManager disposed")),this.connectionRegistry&&(await this.connectionRegistry.close(),this.connectionRegistry=null,b.debug("ConnectionRegistry closed")),this.sessionRouter=null,this.executorInitialized=false,b.info("ACPService disposed");}};var U=a.create({service:"easbot-agent"}),ee=class o extends re{constructor(t,n){super(t,n);b$2(this,"acpEventBridge",null);b$2(this,"server",null);b$2(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 o(void 0,t);if(n&&t.stdioStream){let{stream:r}=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)},d=new AgentSideConnection(()=>i,r);s.setConnection(d);}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 Ge(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 Ve(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 W(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 o extends Error{constructor(t,n,s){super(t);b$2(this,"type");b$2(this,"stage");b$2(this,"cause");this.type="AdapterEnvironmentInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,o);}},te=a.create({service:"adapter.bootstrap"}),Ce;function St(){return Ce||(Ce=Sa.state(async()=>({initialized:false,initPromise:null,instancePromise:null,handlersInstalled:false,directory:".easbot",sdk:null,activeChannel:null,agent:null,acpConnection:null}),async o=>{let e=o.agent;e&&await e.stop().catch(()=>{}),o.agent=null,o.sdk=null,o.acpConnection=null;})),Ce}async function H(){return St()()}function Qe(o){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=o.code;return e.includes(t??"")}function vt(o){o.handlersInstalled||(process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));Qe(t)||te.error("unhandled promise rejection",{error:t.message,stack:t.stack});}),process.on("uncaughtException",e=>{Qe(e)||(te.error("uncaught exception",{error:e.message,stack:e.stack}),process.exit(1));}),o.handlersInstalled=true);}async function yt(o){return o.instancePromise||(o.instancePromise=Sa.provide({directory:o.directory,init:ub,fn:async()=>{te.debug("instance bootstrap completed");}}).then(()=>{})),o.instancePromise}async function Ct(){try{await Sa.dispose(),te.debug("instance disposed");}catch(o){te.warn("failed to dispose instance",{error:o instanceof Error?o.message:String(o)});}}var K;(m=>{function o(l,c){return l.sdk||(l.sdk=xa({directory:c})),l.sdk}function e(l){switch(l){case "http":return "http";case "stdio":return "stdio";case "websocket":return "websocket";default:return "stdio"}}async function t(l){let c=await H();if(c.initialized)return;if(c.initPromise)return c.initPromise;let f={directory:l?.directory??".easbot",initModels:l?.initModels??true,printLogs:l?.printLogs??false,logLevel:l?.logLevel??"INFO",channel:l?.channel??"stdio"};if(c.directory=f.directory,o(c,c.directory),c.activeChannel&&c.activeChannel!==f.channel)throw new Error(`Adapter already initialized with channel ${c.activeChannel}, cannot re-init with ${f.channel}`);return c.activeChannel=f.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:f.printLogs??!1,level:f.logLevel??"INFO"});}catch(g){throw new F("Failed to initialize log infrastructure","log",g instanceof Error?g:void 0)}if(f.initModels)try{b$1();}catch(g){throw new F("Failed to initialize models refresh","models",g instanceof Error?g:void 0)}try{vt(c);}catch(g){throw new F("Failed to install unhandled exception handlers","handlers",g instanceof Error?g:void 0)}try{await yt(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 l=await H();if(l.initialized){await Ha.stop().catch(()=>{});try{let{MCP:c}=await import('./mcp-KWZSND4L.mjs'),f=await c.clients();for(let[g,h]of Object.entries(f))await h.disconnect().catch(()=>{});}catch{}l.agent&&(await l.agent.stop().catch(()=>{}),l.agent=null),await Ct(),l.initialized=false,l.initPromise=null,l.instancePromise=null,l.activeChannel=null,l.sdk=null,l.agent=null,l.acpConnection=null;}}m.destroy=n;async function s(){return (await H()).initialized}m.isInitialized=s;async function r(l){let c=await H();c.agent=l;}m.setAgent=r;async function i(){return (await H()).agent}m.getAgent=i;async function d(){let c=(await H()).agent?.getServerInstance();return c||null}m.getServer=d;async function a$2(){return (await H()).sdk}m.getSDK=a$2;async function u(){return (await H()).acpConnection}m.getACPConnection=u;async function P(){let l=await H(),c=!!l.agent?.getServerInstance();return {initialized:l.initialized,directory:l.directory,activeChannel:l.activeChannel,hasSDK:!!l.sdk,hasAgent:!!l.agent,hasACPConnection:!!l.acpConnection,hasServer:c}}m.getState=P;async function I(l){await t({channel:l.channel,directory:l.directory});let c=await H(),f=o(c,c.directory);if(l.channel==="stdio")return p({directory:l.directory});if(c.agent?.getServerInstance()&&c.activeChannel&&c.activeChannel!==l.channel)throw new Error(`ACP service already started with channel ${c.activeChannel}, cannot switch to ${l.channel}`);if(c.agent){let v=c.agent.getServerInstance();if(v)return {sdk:f,agent:c.agent,server:v}}let h=await ee.create({serviceMode:e(l.channel),acp:{sdk:f},acpServerConfig:l,channel:{type:l.channel,timeout:l.timeout}});await h.start();let S=h.getServerInstance();if(!S)throw new Error("ACP server failed to start");return c.agent=h,c.activeChannel=l.channel,{sdk:f,agent:h,server:S}}m.ensureACPService=I;async function p(l){await t({channel:"stdio",directory:l.directory});let c=await H(),f=o(c,c.directory);if(c.agent)return {sdk:f,agent:c.agent};let g=new WritableStream({write(E){return new Promise((k,R)=>{try{process.stdout.write(E)?k():process.stdout.once("drain",k);}catch(z){let A=z;A.code==="EPIPE"||A.code==="EIO"?R(new Error("stdout pipe broken")):R(z);}})}}),h=new ReadableStream({start(E){process.stdin.on("data",k=>{E.enqueue(new Uint8Array(k));}),process.stdin.on("end",()=>E.close()),process.stdin.on("error",k=>E.error(k));}}),S=ndJsonStream(g,h),v=await ee.create({serviceMode:"stdio",acp:{sdk:f},channel:{type:"stdio",timeout:6e4},stdioStream:{stream:S}});return c.acpConnection=v.getConnection()??null,await v.start(),c.agent=v,c.activeChannel="stdio",te.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:f,agent:v}}m.ensureACPServiceStdio=p;})(K||(K={}));var C=a.create({service:"cli-command-acp"}),$=null,G=null,de=null;function It(o){switch(o.channel){case "websocket":return o.ws?.url?o.ws.url:`ws://${o.hostname}:${o.port}`;case "http":return o.http?.baseUrl?o.http.baseUrl:`http://${o.hostname}:${o.port}`;default:return "stdio://local"}}async function Et(o){if(o.channel==="stdio"){C.debug("Skipping gateway registration for stdio mode");return}let e=await k$1();if(!e){C.debug("No gateway URL configured, skipping registration");return}let t=o.agentId||Identifier.ascending("agent"),n=o.name||"ACP Agent";de=t,C.debug("Preparing gateway registration",{agentId:t,agentName:n,configName:o.name,configAgentId:o.agentId});let s=It(o),r=6e4,i=()=>{G||(G=setInterval(async()=>{if($&&$.getState()==="connected")try{await $.agentHeartbeat(t),C.debug("Gateway heartbeat sent",{agentId:t});}catch(d){C.warn("Gateway heartbeat failed",{error:String(d)});}},r),C.debug("Gateway heartbeat timer started",{agentId:t}));};$=new Q({url:e,type:"acp",id:`acp-${t}`,heartbeat:{enabled:true,interval:r}}),$.onStateChange(async d=>{C.debug("Gateway state changed",{state:d}),d==="connected"?$.registerAgent({agentId:t,name:n,address:s,capabilities:[o.channel],metadata:{hostname:o.hostname,port:o.port,channel:o.channel}}).then(()=>{C.info("Registered to gateway",{agentId:t,agentName:n,address:s,capabilities:[o.channel]}),i();}).catch(a=>{C.warn("Registration failed, will retry...",{error:String(a)}),retry(async()=>{$&&$.getState()==="connected"&&await $.registerAgent({agentId:t,name:n,address:s,capabilities:[o.channel],metadata:{hostname:o.hostname,port:o.port,channel:o.channel}});},{attempts:3,delay:3e4}).then(()=>i()).catch(u=>C.warn("Registration retry failed",{error:String(u)}));}):d==="disconnected"&&(G&&(clearInterval(G),G=null,C.debug("Gateway heartbeat timer stopped")),de=null);});}async function Rt(){G&&(clearInterval(G),G=null,C.debug("Gateway heartbeat timer stopped"));let o=de;if(de=null,$&&o)try{await $.deregisterAgent(o),C.debug("Agent deregistered from gateway",{agentId:o});}catch(e){C.warn("Failed to deregister agent",{error:String(e)});}if($){try{await $.disconnect(),C.debug("Disconnected from gateway");}catch(e){C.warn("Failed to disconnect from gateway",{error:String(e)});}$=null;}}async function kt(o,e){let t=await tb.getACPServerConfig();C.debug("Merging ACP configuration",{baseConfig:{channel:t.channel,port:t.port,hostname:t.hostname,timeout:t.timeout,name:t.name,agentId:t.agentId},cliOptions:{channel:e.channel,port:e.port,hostname:e.hostname,timeout:e.timeout}});let n={};if(e.channel!==void 0){let r=e.channel.toLowerCase();Object.values(R).includes(r)?(n.channel=r,C.debug("CLI override: channel",{value:n.channel})):C.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,C.debug("CLI override: port",{value:n.port})):C.warn("Invalid port from command line",{value:e.port})),e.hostname!==void 0&&(n.hostname=e.hostname,C.debug("CLI override: hostname",{value:n.hostname})),e.timeout!==void 0&&(e.timeout>0?(n.timeout=e.timeout,C.debug("CLI override: timeout",{value:n.timeout})):C.warn("Invalid timeout from command line",{value:e.timeout})),e.hostname!==void 0||e.port!==void 0){let r=e.hostname??t.hostname??"127.0.0.1",i=e.port??t.port??3e3;t.ws&&(n.ws={...t.ws,url:`ws://${r}:${i}`}),t.http&&(n.http={...t.http,baseUrl:`http://${r}:${i}`}),C.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),C.debug("CLI override: ws.timeout and http.timeout updated",{timeout:e.timeout}));let s={...t,...n};return C.debug("Merged ACP configuration",{channel:s.channel,port:s.port,hostname:s.hostname,timeout:s.timeout}),s}async function xt(o,e,t){C.info("Starting ACP service",{channel:e.channel,port:e.port,hostname:e.hostname,debug:t.config.debug}),await K.init({directory:o,printLogs:t.config.print_logs,logLevel:t.config.log_level,channel:e.channel});await K.ensureACPService(e);await Et(e),console.log(""),console.log(d(i("acp.server.started"))),console.log(k(60)),console.log(i$1(i("acp.field.directory"),o,15)),console.log(i$1(i("acp.field.worktree"),Sa.project.worktree||"N/A",15)),console.log(i$1(i("acp.field.channel"),e.channel,15));let s=b$3();switch(e.channel){case "websocket":{let i$2,d="/";if(e.ws?.url)try{let a=new URL(e.ws.url),u=a.port||"3000",P=a.hostname;d=a.pathname||"/",i$2=`ws://${P}:${u}${d==="/"?"":d}`;}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"),d,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 r=getProxyConfig();if(r.enabled){let i$2=r.https||r.http||"configured";console.log(i$1(i("acp.field.proxy"),i$2,15));}console.log(k(60)),console.log(""),C.info("ACPServer started successfully"),_t();}function _t(){let o=process.env.EASBOT_RUN_MODE==="ephemeral"||!process.stdin.isTTY&&process.env.EASBOT_RUN_MODE!=="persistent",e=async t=>{C.debug(`Received ${t}, shutting down...`),o||console.log(`
|
|
8
8
|
${i("acp.shutdown.received",{vars:{signal:t}})}`);try{await Rt(),C.debug("Gateway deregistration completed"),await K.destroy(),C.debug("EasbotAdapter state destroyed"),o||console.log(d(i("acp.shutdown.completed")));}catch(n){C.error("Error during shutdown",{error:n instanceof Error?n.message:String(n)});}o?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")&&(C.info("stdout pipe broken, exiting"),e("stdout-broken").catch(()=>{o?process.kill(process.pid,"SIGKILL"):process.exit(0);}));});}async function Tt(o,e,t){C.debug("ACP command executed",{options:e});let n=t?.config?.debug??false,s=t?.config?.print_logs??false,r=t?.config?.log_level??"INFO";C.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:r});try{let i$1=t.config.directory?Xe.resolve(t.config.directory):process.cwd();C.debug("Working directory resolved",{directory:i$1});let d=a$2(i$1);if(!d.valid)throw C.error("Working directory validation failed",{directory:i$1,error:d.error}),new Error(`Invalid working directory: ${d.error}`);let a=d.normalizedPath;C.debug("Working directory validated",{validatedDirectory:a}),console.log(g(i("acp.directory.resolved",{vars:{cwd:a}}))),await a$3(a,async()=>{let u=await kt(a,e);if(C.debug("ACP server configuration",{channel:u.channel,port:u.port,hostname:u.hostname,timeout:u.timeout,enabled:u.enabled}),!u.enabled){C.warn("ACP server is disabled by configuration"),console.log(g(i("acp.disabled")));return}await xt(a,u,t),C.info("ACP server started successfully");});}catch(i$1){C.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 xo(o,e){let t=o.command("acp").description(i("acp.command.description")).addHelpText("after",`
|
|
9
9
|
|
|
10
10
|
${i("acp.help.examples")}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{V as getACPClientsConfig,U as getACPServerConfig,Y as getAcpAgentName,W as getAcpAgentRuntimeConfig,X as getAcpModelConfig,T as loadACPConfig}from'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-MYI75W3D.mjs';import'./chunk-CQVEAYYW.mjs';import'./chunk-FXOUIXIL.mjs';import {a as a$2}from'./chunk-
|
|
1
|
+
import {a as a$3}from'./chunk-MYI75W3D.mjs';import'./chunk-CQVEAYYW.mjs';import'./chunk-FXOUIXIL.mjs';import {a as a$2}from'./chunk-ZH674M7Q.mjs';import {l,d,e,h,i as i$1,b,c,a as a$4}from'./chunk-M3K32WJV.mjs';import'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import {i}from'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import {a as a$1}from'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.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,ma,k,Qa}from'./chunk-
|
|
1
|
+
import {e}from'./chunk-M3K32WJV.mjs';import {j,ma,k,Qa}from'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import {i}from'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.mjs';import'./chunk-X6ISXWBN.mjs';import {basename}from'path';import {iife,Identifier}from'@easbot/utils';var b=a.create({service:"debug.agent"});function z(r,o,e$1){(async()=>{b.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,l=await P(a),i$1=await T(a,l);if(e$1.tool){let c=l.find(x=>x.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=E(e$1.params),y=await R(a,r);b.debug("Executing tool",{toolID:e$1.tool,params:g});let A=await c.execute(g,y);console.log(JSON.stringify({tool:e$1.tool,input:g,result:A},null,2));return}let m={...t,tools:i$1};console.log(JSON.stringify(m,null,2));})();}async function P(r){let o=r.model??await j.defaultModel();return o.providerId||(o={...o,providerId:"default-provider"}),ma.tools(o,r)}async function T(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 E(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 R(r,o){let e=await Qa.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(),l={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 Qa.updateMessage(l);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{Z as AgentServices}from'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.mjs';import'./chunk-X6ISXWBN.mjs';
|