@easbot/agent 0.2.40 → 0.2.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/txt/tool/agent-client.txt +6 -10
- package/dist/chunks/acp-AJ7O6XNE.mjs +22 -0
- package/dist/chunks/adapter-loader-VUS3UYMT.mjs +1 -0
- package/dist/chunks/{agent-SXVN3QRB.mjs → agent-SKRC54QG.mjs} +1 -1
- package/dist/chunks/{agent-BS6BU766.mjs → agent-VUPXBEWR.mjs} +1 -1
- package/dist/chunks/agent-service-registry-DPO5SSXA.mjs +1 -0
- package/dist/chunks/app-EPNEAPMS.mjs +58 -0
- package/dist/chunks/{auth-SUHJJM24.mjs → auth-34JK273T.mjs} +1 -1
- package/dist/chunks/bootstrap-3KXRWM6D.mjs +1 -0
- package/dist/chunks/build-program-2AR3LYQJ.mjs +11 -0
- package/dist/chunks/bus-QOWILU5Z.mjs +1 -0
- package/dist/chunks/chunk-2YNYVTYT.mjs +2 -0
- package/dist/chunks/{chunk-XQXI2ZHB.mjs → chunk-3472MC45.mjs} +1 -1
- package/dist/chunks/{chunk-ZG2HQDXQ.mjs → chunk-4OHDEBAX.mjs} +1 -1
- package/dist/chunks/chunk-BDS2JWYG.mjs +2 -0
- package/dist/chunks/{chunk-O2JOXYKG.mjs → chunk-EB3OP6TL.mjs} +1 -1
- package/dist/chunks/chunk-IJVW4VME.mjs +1 -0
- package/dist/chunks/{chunk-ZFGVQIO5.mjs → chunk-J6VEDKPT.mjs} +1 -1
- package/dist/chunks/{chunk-IXO5FAWI.mjs → chunk-JTVO3U27.mjs} +1 -1
- package/dist/chunks/chunk-LGMGGNPW.mjs +1 -0
- package/dist/chunks/{chunk-TYD2M4SP.mjs → chunk-MYI75W3D.mjs} +1 -1
- package/dist/chunks/{chunk-3Q4UCILK.mjs → chunk-PEMUENKB.mjs} +1 -1
- package/dist/chunks/{chunk-H45MZAM6.mjs → chunk-WGJIT5HU.mjs} +1 -1
- package/dist/chunks/chunk-XMIQEMED.mjs +1051 -0
- package/dist/chunks/{command-B7POR3LZ.mjs → command-CJGBEATT.mjs} +1 -1
- package/dist/chunks/compaction-R4RTVEDY.mjs +1 -0
- package/dist/chunks/config-YSZNIWZT.mjs +1 -0
- package/dist/chunks/debug-GZCL57Q7.mjs +3 -0
- package/dist/chunks/event-2JDHF3UV.mjs +1 -0
- package/dist/chunks/file-G4WHJKUX.mjs +1 -0
- package/dist/chunks/gateway-D6XCB2OA.mjs +16 -0
- package/dist/chunks/gateway-loader-OH3VCEUD.mjs +1 -0
- package/dist/chunks/{generate-JBIFOTPV.mjs → generate-NYQCTBY7.mjs} +1 -1
- package/dist/chunks/{github-XXJJ62IF.mjs → github-IGWZXZRB.mjs} +2 -2
- package/dist/chunks/global-5WFCDQ45.mjs +1 -0
- package/dist/chunks/{import-37R7O4NM.mjs → import-TYN474UK.mjs} +1 -1
- package/dist/chunks/installation-6S6OCY6F.mjs +1 -0
- package/dist/chunks/instance-YVRWMB6M.mjs +1 -0
- package/dist/chunks/loader-VV3FV5NS.mjs +1 -0
- package/dist/chunks/loader-XGUYA6ZM.mjs +1 -0
- package/dist/chunks/lsp-J7UR4JNX.mjs +1 -0
- package/dist/chunks/{mcp-X4FA7X53.mjs → mcp-FYDYPGLE.mjs} +1 -1
- package/dist/chunks/mcp-GEZSPY2W.mjs +1 -0
- package/dist/chunks/models-JNSS4QSZ.mjs +1 -0
- package/dist/chunks/{pr-WCMJT7VY.mjs → pr-DQZIG2CT.mjs} +1 -1
- package/dist/chunks/preferences-QCM3RIAL.mjs +1 -0
- package/dist/chunks/project-53ZMRKRI.mjs +1 -0
- package/dist/chunks/prompt-XYHKPB7Q.mjs +1 -0
- package/dist/chunks/provider-2RFHZVX4.mjs +1 -0
- package/dist/chunks/registry-GGSZXBFC.mjs +1 -0
- package/dist/chunks/revert-7RBPZDWL.mjs +1 -0
- package/dist/chunks/ripgrep-U54LYBZO.mjs +1 -0
- package/dist/chunks/{run-PN7YADL6.mjs → run-EQ5GHPKF.mjs} +1 -1
- package/dist/chunks/scheduler-3AYHIZGY.mjs +1 -0
- package/dist/chunks/server-ITUF2HX7.mjs +1 -0
- package/dist/chunks/session-5OU5P7UF.mjs +1 -0
- package/dist/chunks/{session-FVNB4WZV.mjs → session-R2LCLNAY.mjs} +1 -1
- package/dist/chunks/session-XA4RMN7D.mjs +1 -0
- package/dist/chunks/share-45SYUA47.mjs +1 -0
- package/dist/chunks/snapshot-YC3DAH7Q.mjs +1 -0
- package/dist/chunks/{stats-RPGHGZUR.mjs → stats-TREO4CFV.mjs} +1 -1
- package/dist/chunks/storage-6F64537E.mjs +1 -0
- package/dist/chunks/{tui-ABXWVS6I.mjs → tui-FVQHBIJ7.mjs} +1 -1
- package/dist/chunks/types-OIHWEQYC.mjs +1 -0
- package/dist/chunks/{update-SO2ZPDG3.mjs → update-V3GTL4TX.mjs} +1 -1
- package/dist/cli.mjs +5 -5
- package/package.json +15 -14
- package/dist/chunks/acp-SMAI7EJF.mjs +0 -22
- package/dist/chunks/adapter-loader-X3GZRT3I.mjs +0 -1
- package/dist/chunks/app-4GCI3HZT.mjs +0 -1
- package/dist/chunks/bootstrap-SVDRDCAU.mjs +0 -1
- package/dist/chunks/build-program-U2HDARWA.mjs +0 -11
- package/dist/chunks/bus-SGXNL3LP.mjs +0 -1
- package/dist/chunks/chunk-CCRIJZBK.mjs +0 -1
- package/dist/chunks/chunk-DJYON7M6.mjs +0 -2
- package/dist/chunks/chunk-JII5HRIF.mjs +0 -2
- package/dist/chunks/chunk-VLDQ4LGX.mjs +0 -59
- package/dist/chunks/chunk-YGFGAD5H.mjs +0 -1050
- package/dist/chunks/chunk-ZBRXNYEM.mjs +0 -1
- package/dist/chunks/compaction-4CV7NS2Z.mjs +0 -1
- package/dist/chunks/config-JY4V5KGI.mjs +0 -1
- package/dist/chunks/debug-LXNXB4VY.mjs +0 -3
- package/dist/chunks/event-NO7SFKKX.mjs +0 -1
- package/dist/chunks/file-Q7BJ3BEC.mjs +0 -1
- package/dist/chunks/gateway-HTBKKYKV.mjs +0 -16
- package/dist/chunks/gateway-loader-6P6BTWQP.mjs +0 -1
- package/dist/chunks/global-FDT3NNWD.mjs +0 -1
- package/dist/chunks/installation-WZEFRTPQ.mjs +0 -1
- package/dist/chunks/instance-AK3F7UK2.mjs +0 -1
- package/dist/chunks/loader-2FMNUQDJ.mjs +0 -1
- package/dist/chunks/loader-JWZHDUVM.mjs +0 -1
- package/dist/chunks/lsp-N672BWEP.mjs +0 -1
- package/dist/chunks/mcp-JIUYQ7QS.mjs +0 -1
- package/dist/chunks/models-OEA6XF6K.mjs +0 -1
- package/dist/chunks/preferences-EUHOPNM3.mjs +0 -1
- package/dist/chunks/project-WTLNG2LH.mjs +0 -1
- package/dist/chunks/prompt-6OETS3YU.mjs +0 -1
- package/dist/chunks/provider-DC7XQTFP.mjs +0 -1
- package/dist/chunks/registry-ZXV6XNKB.mjs +0 -1
- package/dist/chunks/revert-PEILY52K.mjs +0 -1
- package/dist/chunks/ripgrep-4XTDDATX.mjs +0 -1
- package/dist/chunks/scheduler-2U6D3A47.mjs +0 -1
- package/dist/chunks/server-23WY43I2.mjs +0 -1
- package/dist/chunks/session-2ZGF74EQ.mjs +0 -1
- package/dist/chunks/session-CQ3VGE4U.mjs +0 -1
- package/dist/chunks/share-V2US2NJE.mjs +0 -1
- package/dist/chunks/snapshot-3CGXXTES.mjs +0 -1
- package/dist/chunks/storage-GQ3NTV5N.mjs +0 -1
- package/dist/chunks/tui-Y47JRG6G.mjs +0 -1
- package/dist/chunks/types-BFRURHUE.mjs +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Manage a full-duplex conversation channel with another easbot agent endpoint over HTTP or WebSocket.
|
|
2
2
|
|
|
3
3
|
Inputs (kept minimal):
|
|
4
|
-
- operation: connect | list | discover | capabilities | send | status |
|
|
4
|
+
- operation: connect | list | discover | capabilities | send | status | interrupt | close
|
|
5
5
|
- baseUrl: target easbot service base URL (required for connect, e.g. ws://localhost:3000)
|
|
6
|
-
- connectionId: local connection id (required for remote ops: capabilities/send/interrupt/close
|
|
6
|
+
- connectionId: local connection id (required for remote ops: capabilities/send/interrupt/close; auto-resolved from baseUrl if not provided)
|
|
7
7
|
- prompt: message to send (required for send)
|
|
8
8
|
|
|
9
9
|
Operations:
|
|
@@ -32,15 +32,12 @@ Operations:
|
|
|
32
32
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
33
33
|
- Returns: connection state including sessionId, baseUrl, status
|
|
34
34
|
|
|
35
|
-
7.
|
|
36
|
-
- Returns: server config (channel, port, hostname) and managedConnections count
|
|
37
|
-
|
|
38
|
-
8. interrupt: Cancel remote session and cleanup local interaction state
|
|
35
|
+
7. interrupt: Cancel remote session and cleanup local interaction state
|
|
39
36
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
40
37
|
- Sends interrupt signal to remote server, cancels subscription
|
|
41
38
|
- Use when you need to abort an ongoing interaction
|
|
42
39
|
|
|
43
|
-
|
|
40
|
+
8. close: Release local connection state and cleanup all interaction resources
|
|
44
41
|
- Required: connectionId (auto-resolved from baseUrl)
|
|
45
42
|
- Always call close when done to prevent resource leaks
|
|
46
43
|
|
|
@@ -52,7 +49,7 @@ Connection Flow:
|
|
|
52
49
|
5. Use discover to find available services before connecting
|
|
53
50
|
|
|
54
51
|
Local vs Remote Operations:
|
|
55
|
-
- Local (no remote RPC):
|
|
52
|
+
- Local (no remote RPC): list, discover
|
|
56
53
|
- Remote (requires connectionId after connect): capabilities, send, status, interrupt, close
|
|
57
54
|
|
|
58
55
|
Round Control:
|
|
@@ -64,7 +61,6 @@ Round Control:
|
|
|
64
61
|
Returns:
|
|
65
62
|
- Standard tool result: { title, metadata: { count, ... }, output: XML format }
|
|
66
63
|
- Output format is XML-like for easy parsing:
|
|
67
|
-
- <config>: configuration info
|
|
68
64
|
- <connections>: list of active connections
|
|
69
65
|
- <connection>: single connection details
|
|
70
66
|
- <services>: discovered agent services
|
|
@@ -79,4 +75,4 @@ Notes:
|
|
|
79
75
|
- Use `interrupt` to abort an ongoing interaction before completion
|
|
80
76
|
- Pure URL connection: no service registration needed, just provide baseUrl
|
|
81
77
|
- Use discover to find available agent services before connecting
|
|
82
|
-
- Supports HTTP and WebSocket channels only
|
|
78
|
+
- Supports HTTP and WebSocket channels only
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-LAHYVX5K.mjs';import {a as a$3}from'./chunk-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)}
|
|
2
|
+
|
|
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
|
+
|
|
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
|
+
|
|
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(`
|
|
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
|
+
|
|
10
|
+
${i("acp.help.examples")}
|
|
11
|
+
$ agent acp # ${i("acp.help.example.default")}
|
|
12
|
+
$ agent acp --channel http # ${i("acp.help.example.http")}
|
|
13
|
+
$ agent acp --port 8080 # ${i("acp.help.example.port")}
|
|
14
|
+
$ agent acp --hostname 0.0.0.0 # ${i("acp.help.example.hostname")}
|
|
15
|
+
$ agent acp --channel ws --debug # ${i("acp.help.example.debug")}
|
|
16
|
+
|
|
17
|
+
${i("acp.help.env")}
|
|
18
|
+
ACP_CHANNEL ${i("acp.help.env.channel")}
|
|
19
|
+
ACP_PORT ${i("acp.help.env.port")}
|
|
20
|
+
ACP_HOSTNAME ${i("acp.help.env.hostname")}
|
|
21
|
+
ACP_TIMEOUT ${i("acp.help.env.timeout")}
|
|
22
|
+
ACP_ENABLED ${i("acp.help.env.enabled")}`);t.option("-c, --channel <type>",i("acp.option.channel")).option("-p, --port <number>",i("acp.option.port"),n=>parseInt(n,10)).option("-H, --hostname <address>",i("acp.option.hostname")).option("-t, --timeout <milliseconds>",i("acp.option.timeout"),n=>parseInt(n,10)),t.command("*",{isDefault:true}).action(async()=>{let n=t.opts();await Tt(t,n,e);});}export{xo as registerAcpCommand};
|
|
@@ -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-XMIQEMED.mjs';import'./chunk-WGJIT5HU.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-3472MC45.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-J6VEDKPT.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-UNBJ6Y7L.mjs';import'./chunk-4OHDEBAX.mjs';import'./chunk-EB3OP6TL.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-2YNYVTYT.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-BDS2JWYG.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$3}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-PEMUENKB.mjs';import {l,d,e,h,i as i$1,b,c,a as a$4}from'./chunk-M3K32WJV.mjs';import'./chunk-XMIQEMED.mjs';import'./chunk-WGJIT5HU.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-3472MC45.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-J6VEDKPT.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-2RSIOAZV.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import'./chunk-4OHDEBAX.mjs';import'./chunk-EB3OP6TL.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-2YNYVTYT.mjs';import {a as a$1}from'./chunk-LFYBZHOI.mjs';import'./chunk-BDS2JWYG.mjs';import'./chunk-X6ISXWBN.mjs';var a=a$1.create({service:"cli-command-agent"});function W(C,c$1){let y=C.command("agent").description(i("agent.command.description"));y.command("list").description(i("agent.command.list.description")).action(async()=>{await a$2(c$1.config.directory,async()=>{try{a.debug("Listing agents");let{data:o}=await c$1.sdk.app.agents({});if(!o||o.length===0){console.log(l(i("agent.list.empty")));return}let r=[...o].sort((n,t)=>{let g="native"in n&&n.native,d="native"in t&&t.native;return g!==d?g?-1:1:n.name.localeCompare(t.name)});console.log(d(i("agent.list.success",{vars:{count:o.length}}))),console.log(""),console.log(a$3({columns:[{key:"name",header:i("agent.table.header.name"),minWidth:15},{key:"mode",header:i("agent.table.header.mode"),minWidth:10},{key:"native",header:i("agent.table.header.native"),minWidth:8}],rows:r.map(n=>({name:n.name,mode:"mode"in n&&n.mode||"primary",native:"native"in n&&n.native?i("common.yes"):i("common.no")})),width:process.stdout.columns||80,border:"unicode"})),a.debug("Agent list displayed",{count:o.length});}catch(o){a.error("Failed to list agents",{error:o instanceof Error?o.message:String(o)}),console.error(e(i("agent.list.error"))),process.exit(1);}});}),y.command("info <agent-id>").description(i("agent.command.info.description")).action(async o=>{await a$2(c$1.config.directory,async()=>{try{a.debug("Getting agent info",{agentId:o});let{data:r}=await c$1.sdk.app.agents({}),n=r?.find(t=>t.name===o);if(n||(console.error(e(i("agent.get.not_found",{vars:{agentId:o}}))),process.exit(1)),console.log(d(i("agent.get.success"))),console.log(""),console.log(h(i("agent.info.heading"))),console.log(""),console.log(i$1(i("agent.info.field.name")+":",n.name)),console.log(i$1(i("agent.info.field.mode")+":","mode"in n&&n.mode||"primary")),console.log(i$1(i("agent.info.field.native")+":","native"in n&&n.native?i("common.yes"):i("common.no"))),"permission"in n&&n.permission){console.log(i$1(i("agent.info.field.permission")+":",""));let t=b();console.log(c(t,a$4.muted,JSON.stringify(n.permission,null,2)));}a.debug("Agent info displayed",{agentId:o});}catch(r){a.error("Failed to get agent info",{agentId:o,error:r instanceof Error?r.message:String(r)}),console.error(e(i("agent.get.error"))),process.exit(1);}});}),y.command("create").description(i("agent.command.create.description")).requiredOption("--name <name>",i("agent.command.create.option.name")).option("--mode <mode>",i("agent.command.create.option.mode"),"chat").option("--permission <json>",i("agent.command.create.option.permission")).action(async o=>{await a$2(c$1.config.directory,async()=>{try{a.debug("Creating agent",{name:o.name,mode:o.mode}),console.log(h(i("agent.create.begin")));let{validateAgentName:r,validateAgentMode:n,validateJsonString:t}=await import('./input-validation-FWKKVCYC.mjs');r(o.name)||(a.error("Invalid agent name",{name:o.name}),console.error(e(i("agent.create.validation.name"))),process.exit(1));let g=o.mode||"primary";n(g)||(a.error("Invalid agent mode",{mode:o.mode}),console.error(e(i("agent.create.validation.mode"))),process.exit(1));let d$1;if(o.permission){let l=t(o.permission,"permission");l||(a.error("Invalid permission JSON format",{permission:o.permission}),console.error(e(i("agent.create.error",{vars:{error:"Invalid permission JSON format"}}))),process.exit(1)),d$1=l;}let{data:m}=await c$1.sdk.agent.create({name:o.name,mode:g,permission:d$1});if(m||(console.error(e(i("agent.create.error",{vars:{error:"Agent creation failed"}}))),process.exit(1)),console.log(d(i("agent.create.success",{vars:{name:m.name}}))),console.log(""),console.log(h(i("agent.info.heading"))),console.log(""),console.log(i$1(i("agent.info.field.name")+":",m.name)),console.log(i$1(i("agent.info.field.mode")+":",m.mode??"all")),console.log(i$1(i("agent.info.field.native")+":",m.native?i("common.yes"):i("common.no"))),m.permission){console.log(i$1(i("agent.info.field.permission")+":",""));let l=b();console.log(c(l,a$4.muted,JSON.stringify(m.permission,null,2)));}a.debug("Agent created successfully",{name:m.name});}catch(r){a.error("Failed to create agent",{name:o.name,error:r instanceof Error?r.message:String(r)}),console.error(e(i("agent.create.error",{vars:{error:r instanceof Error?r.message:String(r)}}))),process.exit(1);}});});}export{W as registerAgentCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {e}from'./chunk-M3K32WJV.mjs';import {j,
|
|
1
|
+
import {e}from'./chunk-M3K32WJV.mjs';import {j,ma,k,Qa}from'./chunk-XMIQEMED.mjs';import'./chunk-WGJIT5HU.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-3472MC45.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-J6VEDKPT.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-2RSIOAZV.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import'./chunk-4OHDEBAX.mjs';import'./chunk-EB3OP6TL.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-2YNYVTYT.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import'./chunk-BDS2JWYG.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-XMIQEMED.mjs';import'./chunk-WGJIT5HU.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-3472MC45.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-J6VEDKPT.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-2RSIOAZV.mjs';import'./chunk-UNBJ6Y7L.mjs';import'./chunk-4OHDEBAX.mjs';import'./chunk-EB3OP6TL.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-2YNYVTYT.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-BDS2JWYG.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-CQVEAYYW.mjs';import {na,ta,va,ua,qa,ra,sa,Ka,oa,pa,za,Q,la}from'./chunk-XMIQEMED.mjs';import {b as b$2}from'./chunk-WGJIT5HU.mjs';import {c}from'./chunk-IJVW4VME.mjs';import'./chunk-3472MC45.mjs';import {k,c as c$1}from'./chunk-LGMGGNPW.mjs';import'./chunk-J6VEDKPT.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-2RSIOAZV.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import'./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$2}from'./chunk-BDS2JWYG.mjs';import {b}from'./chunk-X6ISXWBN.mjs';import {Input,truncateToWidth,isKeyRelease,getKeybindings,Container,Text,Markdown,Editor,matchesKey,Key}from'@easbot/tui';import {randomUUID}from'crypto';import {loadTextFile,Shell,parseModelId,Filesystem}from'@easbot/utils';import {readdirSync,existsSync}from'fs';import zt from'path';import {pathToFileURL}from'url';import {SdkEventBus,SdkEventBridge,SdkEventType}from'@easbot/gateway';var $e=class extends Editor{constructor(t,n){super(t,n);b(this,"onEscape");b(this,"onCtrlC");b(this,"onCtrlD");b(this,"onCtrlG");b(this,"onCtrlL");b(this,"onCtrlO");b(this,"onCtrlP");b(this,"onCtrlT");b(this,"inputHandlerManager");}setInputHandlerManager(t){this.inputHandlerManager=t;}addToHistory(t){this.inputHandlerManager?.isHistoryBrowsing()||super.addToHistory(t);}handleInput(t){t.includes("\x1B")||t.includes("\r")||t.includes(`
|
|
2
|
+
`);let n=matchesKey(t,Key.up)||matchesKey(t,Key.down);if(n&&this.inputHandlerManager?this.inputHandlerManager.setHistoryBrowsing(true):this.inputHandlerManager&&!n&&(matchesKey(t,Key.ctrl("l"))||matchesKey(t,Key.ctrl("o"))||matchesKey(t,Key.ctrl("p"))||matchesKey(t,Key.ctrl("g"))||matchesKey(t,Key.ctrl("t"))||matchesKey(t,Key.escape)||matchesKey(t,Key.ctrl("c"))||matchesKey(t,Key.ctrl("d"))||this.inputHandlerManager.setHistoryBrowsing(false)),matchesKey(t,Key.ctrl("l"))&&this.onCtrlL){this.onCtrlL();return}if(matchesKey(t,Key.ctrl("o"))&&this.onCtrlO){this.onCtrlO();return}if(matchesKey(t,Key.ctrl("p"))&&this.onCtrlP){this.onCtrlP();return}if(matchesKey(t,Key.ctrl("g"))&&this.onCtrlG){this.onCtrlG();return}if(matchesKey(t,Key.ctrl("t"))&&this.onCtrlT){this.onCtrlT();return}if(matchesKey(t,Key.escape)){if(this.isShowingAutocomplete()){super.handleInput(t);return}if(this.onEscape){this.onEscape();return}}if(matchesKey(t,Key.ctrl("c"))&&this.onCtrlC){this.onCtrlC();return}if(matchesKey(t,Key.ctrl("d"))){this.getText().length===0&&this.onCtrlD&&this.onCtrlD();return}super.handleInput(t);}};var C={text:"#E8E3D5",dim:"#7B7F87",accent:"#F6C453",accentSoft:"#F2A65A",border:"#3C414B",userBg:"#2B2F36",userText:"#5A9F7A",userLabel:"#5A9F7A",systemText:"#9BA3B2",systemLabel:"#7B7F87",assistantLabel:"#B85C5C",subagentLabel:"#9B72CF",subagentBg:"#2A2535",toolPendingBg:"#1F2A2F",toolSuccessBg:"#1E2D23",toolErrorBg:"#2F1F1F",toolTitle:"#F6C453",toolOutput:"#E1DACB",quote:"#8CC8FF",quoteBorder:"#3B4D6B",code:"#F0C987",codeBorder:"#343A45",link:"#7DD3A5",error:"#F97066",success:"#7DD3A5"},I=s=>e=>`\x1B[38;2;${Lt(s)}m${e}\x1B[0m`,Ie=s=>e=>`\x1B[48;2;${Lt(s)}m${e}\x1B[0m`,ye=s=>`\x1B[1m${s}\x1B[0m`,nt=s=>`\x1B[3m${s}\x1B[0m`;function Lt(s){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);if(!e)return "255;255;255";let t=Number.parseInt(e[1]||"0",16),n=Number.parseInt(e[2]||"0",16),i=Number.parseInt(e[3]||"0",16);return `${t};${n};${i}`}var rs={selectedPrefix:s=>I(C.accent)(s),selectedText:s=>ye(I(C.accent)(s)),description:s=>I(C.dim)(s),scrollInfo:s=>I(C.dim)(s),noMatch:s=>I(C.dim)(s)},Z={fg:I(C.text),assistantText:s=>s,dim:I(C.dim),accent:I(C.accent),accentSoft:I(C.accentSoft),success:I(C.success),error:I(C.error),header:s=>ye(I(C.accent)(s)),system:I(C.systemText),userBg:Ie(C.userBg),userText:I(C.userText),userLabel:s=>I(C.userLabel)(s),systemLabel:s=>I(C.systemLabel)(s),assistantLabel:s=>I(C.assistantLabel)(s),subagentLabel:s=>I(C.subagentLabel)(s),subagentBg:Ie(C.subagentBg),subagent:s=>I(C.subagentLabel)(s),toolTitle:I(C.toolTitle),toolOutput:I(C.toolOutput),toolPendingBg:Ie(C.toolPendingBg),toolSuccessBg:Ie(C.toolSuccessBg),toolErrorBg:Ie(C.toolErrorBg),border:I(C.border),bold:ye,italic:nt,user:s=>I(C.userText)(s),assistant:s=>I(C.text)(s),code:I(C.code),quote:I(C.quote),link:I(C.link),tool:I(C.toolTitle),thinking:s=>nt(I(C.dim)(s)),warning:I(C.accentSoft),muted:I(C.dim),highlight:s=>ye(I(C.accent)(s))},os=rs;function as(s,e){let t=s.split(`
|
|
3
|
+
`);if(!e)return t.map(a=>I(C.code)(a));let n={keyword:I("#C586C0"),string:I("#CE9178"),comment:I("#6A9955"),number:I("#B5CEA8"),function:I("#DCDCAA"),type:I("#4EC9B0"),operator:I("#D4D4D4"),default:I(C.code)},i=e.toLowerCase();return i==="typescript"||i==="ts"||i==="javascript"||i==="js"?t.map(a=>ls(a,n)):i==="python"||i==="py"?t.map(a=>ds(a,n)):i==="bash"||i==="sh"||i==="shell"?t.map(a=>cs(a,n)):i==="json"?t.map(a=>us(a,n)):t.map(a=>n.default(a))}function ls(s,e){if(s.trim().startsWith("//"))return e.comment?.(s)??s;let t=/\b(const|let|var|function|async|await|return|if|else|for|while|class|interface|type|import|export|from|default|new|this|super|extends|implements)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"`])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\b\d+(\.\d+)?\b/g,i=>e.number?.(i)??i),n}function ds(s,e){if(s.trim().startsWith("#"))return e.comment?.(s)??s;let t=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|with|async|await|lambda|yield|pass|break|continue|None|True|False)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\b\d+(\.\d+)?\b/g,i=>e.number?.(i)??i),n}function cs(s,e){if(s.trim().startsWith("#"))return e.comment?.(s)??s;let t=/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|export|source|alias)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\$\{?[\w_]+\}?/g,i=>e.type?.(i)??i),n}function us(s,e){let t=s;return t=t.replace(/"([^"]+)":/g,(n,i)=>`${e.type?.(`"${i}"`)??`"${i}"`}: `),t=t.replace(/:\s*"([^"]+)"/g,(n,i)=>`: ${e.string?.(`"${i}"`)??`"${i}"`}`),t=t.replace(/:\s*(\d+(\.\d+)?)/g,(n,i)=>`: ${e.number?.(i)??i}`),t=t.replace(/:\s*(true|false|null)/g,(n,i)=>`: ${e.keyword?.(i)??i}`),t}var Ce={heading:s=>ye(I(C.accent)(s)),link:s=>I(C.link)(s),linkUrl:s=>I(C.dim)(s),code:s=>I(C.code)(s),codeBlock:s=>I(C.code)(s),codeBlockBorder:s=>I(C.codeBorder)(s),quote:s=>I(C.quote)(s),quoteBorder:s=>I(C.quoteBorder)(s),hr:s=>I(C.border)(s),listBullet:s=>I(C.accentSoft)(s),bold:ye,italic:nt,strikethrough:s=>`\x1B[9m${s}\x1B[0m`,underline:s=>`\x1B[4m${s}\x1B[0m`,highlightCode:as,codeBlockIndent:" "},_t={borderColor:s=>I(C.border)(s),selectList:os};var K=a.create({service:"cli-tui-chatlog"}),it=null;function gs(){if(it)return it;let s=i("tui.system.tool_executing",{vars:{tool:""}}).split(":")[0]?.trim()||"",e=i("tui.system.tool_completed",{vars:{tool:""}}).split(":")[0]?.trim()||"",t=i("tui.system.tool_failed",{vars:{tool:""}}).split(":")[0]?.trim()||"",n=[],i$1=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return s&&s!=="tui.system.tool_executing"&&n.push(new RegExp(i$1(s),"i")),e&&e!=="tui.system.tool_completed"&&n.push(new RegExp(i$1(e),"i")),t&&t!=="tui.system.tool_failed"&&n.push(new RegExp(i$1(t),"i")),n.push(/[⚙🔧]\s*(执行工具|Executing tool)/iu,/[✓✅]\s*(工具完成|工具执行完成|Tool completed|Tool execution completed)/iu,/[✗❌]\s*(工具失败|工具执行失败|Tool failed|Tool execution failed)/iu),it=n,n}var He=class extends Container{constructor(){super();b(this,"messages",[]);b(this,"maxMessages",1e3);b(this,"containerWidth",80);b(this,"getState");b(this,"cachedProtocolMetadata",null);b(this,"_cachedPrimaryAgents",null);}init(){this.addSystem(i("tui.system.welcome")),this.addSystem(i("tui.system.help_hint"));}setStateGetter(t){this.getState=t,this.loadProtocolMetadata();}async loadProtocolMetadata(){let t=this.getState?.();if(t?.sdk)try{let n=await t.sdk.app.context({});n.data?.protocolMetadata&&(this.cachedProtocolMetadata=n.data.protocolMetadata);}catch(n){K.debug("Failed to load protocol metadata",{error:n});}}setWidth(t){this.containerWidth=t;}addUser(t,n,i){this.addMessage("user",t,n,i);}addAssistant(t,n,i){this.addMessage("assistant",t,n,i);}addSystem(t,n,i){this.addMessage("system",t,n,i);}addMessage(t,n,i,a){if(K.debug("addMessage called",{type:t,content:n.substring(0,100),id:i,currentMessagesCount:this.messages.length}),i&&this.messages.findIndex(l=>l.id===i)!==-1){K.debug("Message with same ID already exists, skipping",{id:i});return}this.messages.push({type:t,content:n,timestamp:Date.now(),id:i,metadata:a}),K.debug("After push, messages count",{count:this.messages.length}),this.messages.length>this.maxMessages&&(this.messages=this.messages.slice(-this.maxMessages)),K.debug("Calling updateChildren"),this.updateChildren(),K.debug("updateChildren completed");}clear(){this.messages=[],this.updateChildren();}updateChildren(){let t=this.getState?.(),n=t?.toolsExpanded??false,i=t?.showThinking??false,a=t?.verboseLevel??"off",o=t?.messageLimit??50;K.debug("updateChildren called",{messagesCount:this.messages.length,childrenBeforeClear:this.children.length,toolsExpanded:n,showThinking:i,verboseLevel:a,messageLimit:o}),this.children=[],K.debug("Children cleared",{childrenAfterClear:this.children.length});let l=new Set,c=0,u=this.messages.slice(-o);K.debug("Applied message limit",{originalCount:this.messages.length,limitedCount:u.length,messageLimit:o});for(let d of u){if(d.id&&l.has(d.id)){K.debug("Skipping duplicate ID",{id:d.id});continue}if(!n&&this.shouldFilterToolMessage(d)){K.debug("Filtering tool message (tools collapsed)",{content:d.content.substring(0,50),metadata:d.metadata});continue}if(d.id&&!i&&this.shouldFilterThinkingMessage(d)){K.debug("Filtering thinking message (thinking mode off)",{content:d.content.substring(0,50),metadata:d.metadata});continue}if(d.id&&a==="off"&&this.shouldFilterBackgroundAgentMessage(d)){K.debug("Filtering background agent message (verbose off)",{content:d.content.substring(0,50),agent:d.metadata?.agent});continue}if(d.type==="assistant"&&this.shouldFilterAssistantMessage(d.content)){K.debug("Filtering assistant metadata",{content:d.content.substring(0,50)});continue}d.id&&l.add(d.id),K.debug("Rendering message",{type:d.type,content:d.content.substring(0,50),id:d.id,hasId:!!d.id,metadata:d.metadata}),this.renderMessage(d),c++;}K.debug("updateChildren completed",{childrenAfterRender:this.children.length,renderedCount:c}),this.invalidate();}shouldFilterSystemMessage(t){return gs().some(i=>i.test(t))}shouldFilterToolMessage(t){return t.metadata?.isTool===true?true:t.type==="system"?this.shouldFilterSystemMessage(t.content):false}shouldFilterThinkingMessage(t){return t.metadata?.isThinking===true}shouldFilterBackgroundAgentMessage(t){let n=t.metadata?.agent;if(!n)return false;let i=this.getState?.();if(!i?.sdk)return false;let a=async()=>{try{return ((await i.sdk.app.agents({})).data||[]).filter(c=>c.mode==="primary"&&c.hidden!==!0).map(c=>c.name)}catch{return []}};return this._cachedPrimaryAgents?!this._cachedPrimaryAgents.includes(n):(a().then(o=>{this._cachedPrimaryAgents=o,this.updateChildren();}),false)}shouldFilterAssistantMessage(t){return /^>\s+[\w-]+(\s+·\s+[\w-]+)?$/.test(t.trim())}renderMessage(t){if(!t.content||t.content.trim()===""){K.debug("Skipping empty message in render",{type:t.type,id:t.id});return}let n=new Date(t.timestamp).toLocaleTimeString();switch(t.type){case "user":{if(t.metadata?.isSubagentResult){let l=t.metadata.agent||"SubAgent",c=Z.subagentLabel(`[${n}] ${l}: `),u=new Text(c,1,0);this.addChild(u);let p=new Markdown(t.content,0,0,Ce).render(this.containerWidth-2);for(let M of p){let B=new Text(M,1,0);this.addChild(B);}break}let i$1=Z.userLabel(`[${n}] ${i("tui.chatlog.user_prefix")}: `),a=new Text(i$1,1,0);if(this.addChild(a),t.content.trim().startsWith("/")){let l=Z.accent(t.content),c=new Text(l,1,0);this.addChild(c);}else {let l=Z.userText(t.content),u=new Markdown(l,0,0,Ce).render(this.containerWidth-2);for(let d of u){let p=new Text(d,1,0);this.addChild(p);}}break}case "assistant":{let i$1=i("tui.chatlog.assistant_prefix");this.cachedProtocolMetadata?.name?i$1=this.cachedProtocolMetadata.name:t.metadata?.agent&&(i$1=t.metadata.agent);let a=Z.assistantLabel(`[${n}] ${i$1}: `),o=new Text(a,1,0);this.addChild(o);let c=new Markdown(t.content,0,0,Ce).render(this.containerWidth-2);for(let u of c){let d=new Text(u,1,0);this.addChild(d);}break}case "system":{let i$1=Z.systemLabel(`[${n}] ${i("tui.chatlog.system_prefix")}: `),a=new Text(i$1,1,0);this.addChild(a);let o=Z.system(t.content),c=new Markdown(o,0,0,Ce).render(this.containerWidth-2);for(let u of c){let d=new Text(u,1,0);this.addChild(d);}break}}}};var ps={q:"exit",quit:"exit",h:"help",s:"status",a:"agent",m:"model",sess:"session",skills:"skill",commands:"command",mcps:"mcp",models:"model",agents:"agent",sessions:"session",btw:"command"},hs=new Set(["btw","sync","abort","compact"]);function $t(s){let e=s.replace(/^\//,"").trim();if(!e)return {name:"",args:""};let[t="",...n]=e.split(/\s+/),i=t.toLowerCase();return hs.has(i)?{name:"command",args:e}:{name:ps[i]??i,args:n.join(" ").trim()}}var rt=[{name:"help",description:i("tui.command.help.description")},{name:"status",description:i("tui.command.status.description")},{name:"command",description:i("tui.command.command.description")},{name:"agent",description:i("tui.command.agent.description")},{name:"session",description:i("tui.command.session.description")},{name:"new",description:i("tui.command.new.description")},{name:"fork",description:i("tui.command.fork.description")},{name:"reset",description:i("tui.command.reset.description")},{name:"model",description:i("tui.command.model.description")},{name:"settings",description:i("tui.command.settings.description")},{name:"verbose",description:i("tui.command.verbose.description")},{name:"thinking",description:i("tui.command.thinking.description")},{name:"abort",description:i("tui.command.abort.description")},{name:"clear",description:i("tui.command.clear.description")},{name:"compact",description:i("tui.command.compact.description")},{name:"skill",description:i("tui.command.skill.description")},{name:"mcp",description:i("tui.command.mcp.description")},{name:"exit",description:i("tui.command.exit.description")}];async function Rt(s,e){let t=[...rt];if(s)try{let i=(await s.command.list({contextMode:e})).data||[],a=new Set(rt.map(o=>o.name));for(let o of i)a.has(o.name)||t.push({name:o.name,description:o.description||""});}catch(n){console.error("Failed to fetch dynamic commands:",n);}return t}function Ht(){return rt}function Ft(){let s=[];return s.push("# "+i("tui.help.title")),s.push(""),s.push("## "+i("tui.help.section.basic")),s.push("- `"+i("tui.help.command.help")+"`"),s.push("- `"+i("tui.help.command.status")+"`"),s.push("- `"+i("tui.help.command.command")+"`"),s.push(""),s.push("## "+i("tui.help.section.agent")),s.push("- `"+i("tui.help.command.agent")+"`"),s.push(""),s.push("## "+i("tui.help.section.session")),s.push("- `"+i("tui.help.command.session")+"`"),s.push("- `"+i("tui.help.command.new")+"`"),s.push("- `"+i("tui.help.command.fork")+"`"),s.push("- `"+i("tui.help.command.reset")+"`"),s.push(""),s.push("## "+i("tui.help.section.model")),s.push("- `"+i("tui.help.command.model")+"`"),s.push(""),s.push("## "+i("tui.help.section.settings")),s.push("- `"+i("tui.help.command.settings")+"`"),s.push("- `"+i("tui.help.command.verbose")+"`"),s.push("- `"+i("tui.help.command.thinking")+"`"),s.push(""),s.push("## "+i("tui.help.section.operations")),s.push("- `"+i("tui.help.command.abort")+"`"),s.push("- `"+i("tui.help.command.clear")+"`"),s.push("- `"+i("tui.help.command.compact")+"`"),s.push(""),s.push("## "+i("tui.help.section.skill")),s.push("- `"+i("tui.help.command.skill")+"`"),s.push("- `"+i("tui.help.command.mcp")+"`"),s.push(""),s.push("## "+i("tui.help.section.exit")),s.push("- `"+i("tui.help.command.exit")+"`"),s.push(""),s.push("## "+i("tui.help.section.local")),s.push("- `"+i("tui.help.command.local")+"`"),s.push(""),s.push("## "+i("tui.help.section.shortcuts")),s.push("- `"+i("tui.help.shortcut.ctrl_c")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_d")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_l")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_p")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_g")+"`"),s.push("- `"+i("tui.help.shortcut.esc")+"`"),s.join(`
|
|
4
|
+
`)}var fs=/[\s\-_./:#@]/;function Dt(s,e){return e===0||fs.test(s[e-1]??"")}function Bt(s,e){if(!e)return null;let t=s.toLowerCase(),n=e.toLowerCase(),i=t.length-n.length;if(i<0)return null;for(let a=0;a<=i;a++)if(t.startsWith(n,a)&&Dt(t,a))return a;return null}function ys(s,e){if(s.length===0)return 0;if(s.length>e.length)return null;let t=0,n=0,i=-1,a=0;for(let o=0;o<e.length&&t<s.length;o++)if(e[o]===s[t]){let l=Dt(e,o);i===o-1?(a++,n-=a*5):(a=0,i>=0&&(n+=(o-i-1)*2)),l&&(n-=10),n+=o*.1,i=o,t++;}return t<s.length?null:n}function Ut(s,e){let t=e.trim();if(!t)return s;let n=t.split(/\s+/).filter(a=>a.length>0);if(n.length===0)return s;let i=[];for(let a of s){let o=a.searchTextLower??"",l=0,c=true;for(let u of n){let d=ys(u,o);if(d!==null)l+=d;else {c=false;break}}c&&i.push({item:a,score:l});}return i.sort((a,o)=>a.score-o.score),i.map(a=>a.item)}var ws="\x1B",qt=new RegExp(`${ws}\\[[0-9;]*m`,"g"),X=class X{constructor(e,t,n){b(this,"items");b(this,"filteredItems");b(this,"selectedIndex",0);b(this,"maxVisible");b(this,"theme");b(this,"searchInput");b(this,"regexCache",new Map);b(this,"onSelect");b(this,"onCancel");b(this,"onSelectionChange");b(this,"compareByScore",(e,t)=>e.tier!==t.tier?e.tier-t.tier:e.score!==t.score?e.score-t.score:this.getItemLabel(e.item).localeCompare(this.getItemLabel(t.item)));this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.searchInput=new Input;}getCachedRegex(e){let t=this.regexCache.get(e);return t||(t=new RegExp(this.escapeRegex(e),"gi"),this.regexCache.set(e,t)),t}updateFilter(){let e=this.searchInput.getValue().trim();e?this.filteredItems=this.smartFilter(e):this.filteredItems=this.items,this.selectedIndex=0,this.notifySelectionChange();}smartFilter(e){let t=e.toLowerCase(),n=[],i=[];for(let o of this.items){let l=this.getItemLabel(o),c=o.description??"",u=a$1(l).toLowerCase(),d=a$1(c).toLowerCase(),p=u.indexOf(t);if(p!==-1){n.push({item:o,tier:0,score:p});continue}let M=Bt(u,t);if(M!==null){n.push({item:o,tier:1,score:M});continue}let B=d.indexOf(t);if(B!==-1){n.push({item:o,tier:2,score:B});continue}let T=o.searchText??"";i.push({item:o,searchTextLower:[l,c,T].map(y=>a$1(y)).filter(Boolean).join(" ").toLowerCase()});}n.sort(this.compareByScore);let a=Ut(i,t);return [...n.map(o=>o.item),...a.map(o=>o.item)]}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}getItemLabel(e){return e.label||e.value}splitAnsiParts(e){let t=[];qt.lastIndex=0;let n=0,i;for(;(i=qt.exec(e))!==null;)i.index>n&&t.push({text:e.slice(n,i.index),isAnsi:false}),t.push({text:i[0],isAnsi:true}),n=i.index+i[0].length;return n<e.length&&t.push({text:e.slice(n),isAnsi:false}),t}highlightMatch(e,t){let n=t.trim().split(/\s+/).map(o=>o.toLowerCase()).filter(o=>o.length>0);if(n.length===0)return e;let i=Array.from(new Set(n)).toSorted((o,l)=>l.length-o.length),a=this.splitAnsiParts(e);for(let o of i){let l=this.getCachedRegex(o),c=[];for(let u of a){if(u.isAnsi){c.push(u);continue}l.lastIndex=0;let d=u.text.replace(l,p=>this.theme.matchHighlight(p));if(d===u.text){c.push(u);continue}c.push(...this.splitAnsiParts(d));}a=c;}return a.map(o=>o.text).join("")}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1));}invalidate(){this.searchInput.invalidate();}render(e){let t=[],i=this.theme.searchPrompt("search: "),a=Math.max(1,e-b$1(i)),l=this.searchInput.render(a)[0]??"";t.push(`${i}${this.theme.searchInput(l)}`),t.push("");let c=this.searchInput.getValue().trim();if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matches")),t;let u=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),d=Math.min(u+this.maxVisible,this.filteredItems.length);for(let p=u;p<d;p++){let M=this.filteredItems[p];if(!M)continue;let B=p===this.selectedIndex;t.push(this.renderItemLine(M,B,e,c));}if(this.filteredItems.length>this.maxVisible){let p=`${this.selectedIndex+1}/${this.filteredItems.length}`;t.push(this.theme.scrollInfo(` ${p}`));}return t}renderItemLine(e,t,n,i){let a=t?"\u2192 ":" ",o=a.length,l=this.getItemLabel(e),c=e.description;if(c){let B=this.getDescriptionLayout(n,o);if(B){let T=truncateToWidth(l,B.maxValueWidth,""),y=this.highlightMatch(T,i),k=b$1(y),h=B.availableWidth-k-B.spacingWidth;if(h>=X.DESCRIPTION_MIN_WIDTH){let se=" ".repeat(B.spacingWidth),H=truncateToWidth(c,h,""),F=this.highlightMatch(H,i),x=t?F:this.theme.description(F),g=`${a}${y}${se}${x}`;return t?this.theme.selectedText(g):g}}}let u=n-o-2,d=truncateToWidth(l,u,""),p=this.highlightMatch(d,i),M=`${a}${p}`;return t?this.theme.selectedText(M):M}getDescriptionLayout(e,t){if(e<=X.DESCRIPTION_LAYOUT_MIN_WIDTH)return null;let n=Math.max(1,e-t-X.RIGHT_MARGIN_WIDTH),i=n-X.DESCRIPTION_MIN_WIDTH-X.DESCRIPTION_SPACING_WIDTH;return i<1?null:{availableWidth:n,maxValueWidth:i,spacingWidth:X.DESCRIPTION_SPACING_WIDTH}}handleInput(e){if(isKeyRelease(e))return;let t=getKeybindings(),n=!this.searchInput.getValue().trim();if(t.matches(e,"tui.select.up")||t.matches(e,"tui.editor.cursorUp")||n&&e==="k"){this.selectedIndex=Math.max(0,this.selectedIndex-1),this.notifySelectionChange();return}if(t.matches(e,"tui.select.down")||t.matches(e,"tui.editor.cursorDown")||n&&e==="j"){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+1),this.notifySelectionChange();return}if(t.matches(e,"tui.select.confirm")){let o=this.filteredItems[this.selectedIndex];o&&this.onSelect&&this.onSelect(o);return}if(t.matches(e,"tui.select.cancel")){this.onCancel&&this.onCancel();return}let i=this.searchInput.getValue();this.searchInput.handleInput(e);let a=this.searchInput.getValue();i!==a&&this.updateFilter();}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e);}getSelectedItem(){return this.filteredItems[this.selectedIndex]??null}};b(X,"DESCRIPTION_LAYOUT_MIN_WIDTH",40),b(X,"DESCRIPTION_MIN_WIDTH",12),b(X,"DESCRIPTION_SPACING_WIDTH",2),b(X,"RIGHT_MARGIN_WIDTH",2);var Fe=X;var ce=a.create({service:"cli-tui-selectors"}),Is={selectedPrefix:s=>`\x1B[36m${s}\x1B[0m`,selectedText:s=>`\x1B[1;36m${s}\x1B[0m`,description:s=>`\x1B[90m${s}\x1B[0m`,scrollInfo:s=>`\x1B[90m${s}\x1B[0m`,noMatch:s=>`\x1B[90m${s}\x1B[0m`,searchPrompt:s=>`\x1B[36m${s}\x1B[0m`,searchInput:s=>s,matchHighlight:s=>`\x1B[1;33m${s}\x1B[0m`};function ue(s,e){ce.debug("Creating searchable select list",{itemsCount:s.length,title:e.title});let t=e.maxVisible??10,n=new Fe(s,t,Is);return e.onSelect&&(n.onSelect=e.onSelect),e.onCancel&&(n.onCancel=e.onCancel),n}function De(s,e){ce.info("Creating model selector with data");let t=[];for(let[n,i]of Object.entries(s))if(i?.models)for(let[a,o]of Object.entries(i.models))t.push({label:`${i.name} - ${o.name}`,value:`${n}/${a}`,description:o.family||""});return ce.debug("Model list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.model.title"),placeholder:e.placeholder||i("tui.selector.model.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Be(s,e){ce.info("Creating session selector with data",{count:s.length});let t=s.map(n=>({label:n.title||n.id,value:n.id,description:`\u66F4\u65B0\u65F6\u95F4: ${n.time?.updated?new Date(n.time.updated).toLocaleString():"\u672A\u77E5"}`}));return ce.debug("Session list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.session.title"),placeholder:e.placeholder||i("tui.selector.session.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Ue(s,e){ce.info("Creating agent selector with data",{count:s.length});let t=s.map(n=>({label:n.name,value:n.name,description:n.description||(n.mode?`\u6A21\u5F0F: ${n.mode}`:"")}));return ce.debug("Agent list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.agent.title"),placeholder:e.placeholder||i("tui.selector.agent.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}var A=a.create({service:"cli-tui-command-handlers"});async function xs(s,e,t){let n=[];n.push("## "+i("tui.handler.status.title")),n.push(""),n.push("### "+i("tui.handler.status.system_info")),n.push("- **"+i("tui.handler.status.system")+"**: "+i("tui.handler.status.ok")),n.push("- **"+i("tui.handler.status.directory")+"**: `"+e+"`"),n.push(""),n.push("### "+i("tui.handler.status.global_paths")),n.push("- **home**: `"+a$2.Path.home+"`"),n.push("- **data**: `"+a$2.Path.data+"`"),n.push("- **bin**: `"+a$2.Path.bin+"`"),n.push("- **log**: `"+a$2.Path.log+"`"),n.push("- **cache**: `"+a$2.Path.cache+"`"),n.push("- **config**: `"+a$2.Path.config+"`"),n.push("- **state**: `"+a$2.Path.state+"`"),n.push(""),n.push("### "+i("tui.handler.status.session_info")),n.push("- **Agent**: "+(s.agent||i("tui.handler.status.not_set"))),n.push("- **Session**: "+(s.currentSessionKey||i("tui.handler.status.not_set"))),n.push("- **Model**: "+(s.sessionInfo.model||i("tui.handler.status.not_set"))),n.push(""),n.push("### Gateway");try{let i=t?.client,a=await c$1(),o=a.path||"",l=o.endsWith("/")?o.slice(0,-1):o,c=`ws://${a.hostname}:${a.port}${l}`;if(i){let u=i.getState();if(u==="connected")try{let d=await i.getStatus();n.push("- **Status**: connected"),n.push(`- **URL**: \`${c}\``),n.push(`- **Connections**: ${d.connections??0}`),n.push(`- **Sessions**: ${d.sessions??0}`),n.push(`- **Message Subscriptions**: ${d.messageSubscriptions??0}`),n.push(`- **Agent Subscriptions**: ${d.agentSubscriptions??0}`),d.agents&&n.push(`- **Agents**: ${d.agents.total??0} (healthy: ${d.agents.healthy??0}, unhealthy: ${d.agents.unhealthy??0})`);}catch{n.push("- **Status**: connected (status fetch failed)"),n.push(`- **URL**: \`${c}\``);}else n.push("- **Status**: "+u),n.push(`- **URL**: \`${c}\``);}else n.push("- **Status**: not initialized"),n.push(`- **URL**: \`${c}\``);}catch(i){A.error("Failed to get Gateway status",{error:String(i)}),n.push("- **Status**: error");}n.push("");try{let a=(await s.sdk.command.list({})).data||[],o=a.filter(u=>u.source==="skill"),l=a.filter(u=>u.source==="mcp"),c=a.filter(u=>u.source==="command");if(n.push("### "+i("tui.handler.status.skills")+" ("+o.length+")"),o.length>0){let u=o.map(d=>d.name).join(", ");n.push(u);}n.push("");try{let d=(await s.sdk.mcp.status({})).data||{},M=(await s.sdk.mcp.tools({})).data||{},B=Object.entries(d).filter(([,T])=>T.status==="connected");if(n.push("### "+i("tui.handler.status.mcp")+" ("+B.length+")"),B.length>0)for(let[T]of B){let y=M[T]||[];y.length>0?n.push("- **"+T+"** ("+y.length+"): "+y.join(", ")):n.push("- **"+T+"**");}n.push("");}catch(u){A.error("Failed to get MCP status",{error:u}),n.push("### "+i("tui.handler.status.mcp")+" (0)"),n.push("");}if(n.push("### "+i("tui.handler.status.commands")+" ("+c.length+")"),c.length>0){let u=c.map(d=>d.name).join(", ");n.push(u);}n.push(""),n.push("### "+i("tui.handler.status.services"));try{if(!s.sdk?.lsp)A.warn("SDK or LSP API is not initialized"),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let u=await s.sdk.lsp.status({});if(!u||typeof u!="object")A.warn("LSP status response is not a valid object",{response:u,responseType:typeof u}),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let d=Array.isArray(u.data)?u.data:[];if(n.push("- **LSP ("+d.length+")**: "),d.length>0){let p=d.filter(M=>M&&typeof M=="object").map(M=>M?.name||"unknown").join(", ");n.push(" "+p);}else n.push(" "+i("tui.handler.status.no_lsp"));}}}catch(u){A.error("Failed to get LSP status",{error:u}),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));}}catch(i$1){A.error("Failed to get command list for status",{error:i$1}),n.push(""),n.push("_"+i("tui.handler.status.error_loading")+"_");}return n.join(`
|
|
5
|
+
`)}function Ot(s,e){let{chatLog:t,tui:n,directory:i$1,openOverlay:a,closeOverlay:o,requestExit:l,setActivityStatus:c$1,updateFooter:u,refreshSessionInfo:d,loadHistory:p,setSession:M,refreshAgents:B,abortActive:T}=s,y=()=>{o();},k=async(H,F,x,g)=>{try{if(!F){A.warn("Cannot publish command event: no session ID",{name:H});return}await pa(e,za.Event.Executed,{name:H,sessionId:F,arguments:x,messageId:g}),A.debug("Command event published",{name:H,sessionId:F,messageId:g});}catch(f){A.error("Failed to publish command event",{name:H,sessionId:F,messageId:g,error:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0});}},ge=async(H,F)=>{let{name:x,args:g}=$t(H);if(x){try{switch(x){case "help":t.addSystem(Ft()),await k("help",e.currentSessionId||"",g||"",randomUUID());break;case "commands":case "command":case "cmds":case "cmd":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="command");if(b.length===0){t.addSystem(i("tui.handler.command.empty")),await k(x,e.currentSessionId||"",g||"",randomUUID());break}if(g){let v=g.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("command",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.command.not_found",{vars:{name:W}})),await k(x,e.currentSessionId||"",g,randomUUID());break}let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/command ${v.value} `):await se("command",v.value,e,t,c$1);},onCancel:y});a(E);}catch(f){A.error("Failed to handle command",{error:f}),t.addSystem(i("tui.handler.command.error",{vars:{error:String(f)}}));}await k(x,e.currentSessionId||"","",randomUUID());break}case "status":t.addSystem(await xs(e,i$1,s.gatewayManager)),await k("status",e.currentSessionId||"",g||"",randomUUID());break;case "agents":case "agent":if(g)e.agent=g,t.addSystem(i("tui.handler.agent.switched",{vars:{agentId:g}})),u(),await b$2(e),await k(x,e.currentSessionId||"",g,randomUUID());else {let L=(await ta(e)).filter(w=>w.mode==="primary"&&w.hidden!==!0),b=Ue(L,{onSelect:async w=>{e.agent=w.value,t.addSystem(i("tui.handler.agent.switched",{vars:{agentId:w.value}})),u(),y(),await b$2(e);},onCancel:y});a(b),await k(x,e.currentSessionId||"","",randomUUID());}break;case "sessions":case "session":if(g&&M)await M(g),u(),await k(x,e.currentSessionId||"",g,randomUUID());else {let f=await ua(e),L=Be(f,{onSelect:async b=>{M&&await M(b.value),u(),y();},onCancel:y});a(L),await k(x,e.currentSessionId||"","",randomUUID());}break;case "models":case "model":if(g)e.sessionInfo.model=g,t.addSystem(i("tui.handler.model.set",{vars:{model:g}})),u(),await b$2(e),await k(x,e.currentSessionId||"",g,randomUUID());else {let f=await va(e),L=De(f,{onSelect:async b=>{e.sessionInfo.model=b.value,t.addSystem(i("tui.handler.model.set",{vars:{model:b.value}})),u(),y(),await b$2(e);},onCancel:y});a(L),await k(x,e.currentSessionId||"","",randomUUID());}break;case "fork":{try{c$1(i("tui.handler.fork.begin"));let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,A.debug("Aborted running agent before forking session",{sessionId:f});}catch(L){A.warn("Failed to abort agent before forking, continuing anyway",{error:L});}if(t.clear(),t.init(),f){let b=(await e.sdk.session.fork({sessionId:f})).data;b&&(e.currentSessionId=b.id,e.currentSessionKey=b.title||b.slug||b.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e));}await oa(e,t),p&&await p(),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),c$1(i("tui.status.ready"));}catch(f){A.error("Failed to fork session",{error:f}),t.addSystem(i("tui.handler.fork.error",{vars:{error:String(f)}})),c$1(i("tui.status.error"));}await k("fork",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);break}case "new":{try{c$1(i("tui.handler.new.begin"));let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,A.debug("Aborted running agent before creating new session",{sessionId:f});}catch(E){A.warn("Failed to abort agent before creating new session, continuing anyway",{error:E});}t.clear(),t.init();let L=e.instanceContext.directory,w=(await e.sdk.session.create({directory:L})).data;w&&(e.currentSessionId=w.id,e.currentSessionKey=w.title||w.slug||w.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e)),await oa(e,t),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),c$1(i("tui.status.ready"));}catch(f){A.error("Failed to create new session",{error:f}),t.addSystem(i("tui.handler.new.error",{vars:{error:String(f)}})),c$1(i("tui.status.error"));}await k("new",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);break}case "reset":{try{let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,A.debug("Aborted running agent before reset",{sessionId:f});}catch(L){A.warn("Failed to abort agent before reset, continuing anyway",{error:L});}t.clear(),t.init(),t.addSystem(i("tui.handler.session.reset")),p&&await p(),await oa(e,t),u();}catch(f){A.error("Failed to reset session",{error:f}),t.addSystem(i("tui.handler.session.reset_error",{vars:{error:String(f)}}));}await k("reset",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);break}case "settings":{A.debug("Opening settings panel");let{createSettingsPanel:f}=await import('./settings-panel-ZMAGAWRF.mjs'),L=f({currentSettings:{thinkingLevel:e.thinkingLevel,showThinking:e.showThinking,verboseLevel:e.verboseLevel,messageLimit:e.messageLimit,toolsExpanded:e.toolsExpanded,localShellPermission:e.localShellPermission,contextMode:e.contextMode},onChange:(b,w)=>{switch(b){case "thinkingLevel":e.thinkingLevel=w,t.addSystem(i("tui.handler.thinking_level.set",{vars:{level:w}}));break;case "showThinking":e.showThinking=w==="true",A.debug("showThinking changed",{newValue:w,showThinking:e.showThinking}),t.addSystem(e.showThinking?i("tui.hint.show_thinking_on"):i("tui.hint.show_thinking_off"));break;case "verboseLevel":e.verboseLevel=w,t.addSystem(i("tui.handler.verbose_level.set",{vars:{level:w}}));break;case "messageLimit":e.messageLimit=Number.parseInt(w,10),t.addSystem(i("tui.handler.message_limit.set",{vars:{limit:w}}));break;case "toolsExpanded":e.toolsExpanded=w==="true",A.debug("toolsExpanded changed",{newValue:w,toolsExpanded:e.toolsExpanded}),t.addSystem(e.toolsExpanded?i("tui.hint.tools_expanded"):i("tui.hint.tools_collapsed"));break;case "localShellPermission":e.localShellPermission=w,A.debug("localShellPermission changed",{newValue:w,localShellPermission:e.localShellPermission}),t.addSystem(i("tui.shell.permission.updated",{vars:{permission:w}}));break;case "contextMode":{let E=w;e.contextMode=E,A.debug("contextMode changed",{newValue:w,contextMode:E}),t.addSystem(i("tui.handler.context_mode.set",{vars:{mode:E}})),e.currentSessionId&&e.sdk.session.contextMode.set({sessionId:e.currentSessionId,mode:E}).catch(v=>{A.error("Failed to update session contextMode",{error:v,sessionId:e.currentSessionId});});break}}b$2(e).then(async()=>{try{A.debug("Publishing HeaderRefresh event",{id:b,newValue:w}),await pa(e,c.StatusBarRefresh,{reason:`settings changed: ${b}`});}catch(E){A.error("Failed to publish HeaderRefresh event",{error:E});}}).catch(E=>{A.error("Failed to save TUI state after settings change",{error:E,id:b});});},onCancel:y});a(L),await k("settings",e.currentSessionId||"",g||"",randomUUID());break}case "verbose":if(!g){t.addSystem(i("tui.handler.verbose.usage")),await k(x,e.currentSessionId||"","",randomUUID());break}if(g!=="on"&&g!=="off"){t.addSystem(i("tui.handler.verbose.invalid",{vars:{value:g}})),await k(x,e.currentSessionId||"",g,randomUUID());break}e.verboseLevel=g,t.addSystem(i("tui.handler.verbose.set",{vars:{level:g}})),await b$2(e),await k(x,e.currentSessionId||"",g,randomUUID());break;case "thinking":if(!g){t.addSystem(i("tui.handler.thinking.usage")),await k(x,e.currentSessionId||"","",randomUUID());break}e.thinkingLevel=g,t.addSystem(i("tui.handler.thinking.set",{vars:{level:g}})),await b$2(e),await k("thinking",e.currentSessionId||"",g||"",randomUUID());break;case "clear":{A.debug("Opening clear confirmation dialog");let{createConfirmDialog:f}=await import('./confirm-dialog-SJOXJWYU.mjs'),L=f({message:i("tui.dialog.clear.message"),onConfirm:async()=>{try{c$1(i("tui.handler.clear.begin")),y();let b=e.currentSessionId;if(b&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:b}),e.activeChatRunId=null,A.debug("Aborted running agent before clearing session",{sessionId:b});}catch(v){A.warn("Failed to abort agent before clearing, continuing anyway",{error:v});}t.clear(),t.init(),b&&await e.sdk.session.delete({sessionId:b});let E=(await e.sdk.session.create({directory:e.instanceContext.directory})).data;E&&(e.currentSessionId=E.id,e.currentSessionKey=E.title||E.slug||E.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e)),await oa(e,t),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),t.addSystem(i("tui.handler.clear.success")),c$1(i("tui.status.ready"));}catch(b){A.error("Failed to clear chat history",{error:b}),t.addSystem(i("tui.handler.clear.error",{vars:{error:String(b)}})),c$1(i("tui.status.error"));}await k("clear",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);},onCancel:()=>{t.addSystem(i("tui.clear.cancel")),y();}});a(L);break}case "skills":case "skill":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="skill");if(b.length===0){t.addSystem(i("tui.handler.skill.empty")),await k(x,e.currentSessionId||"",g||"",randomUUID());break}if(g){let v=g.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("skill",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.skill.not_found",{vars:{name:W}})),await k(x,e.currentSessionId||"",g,randomUUID());break}A.debug("Opening skill selector");let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/skill ${v.value} `):await se("skill",v.value,e,t,c$1);},onCancel:y});a(E),await k(x,e.currentSessionId||"","",randomUUID());}catch(f){A.error("Failed to handle skill",{error:f}),t.addSystem(i("tui.handler.skill.error",{vars:{error:String(f)}})),await k(x,e.currentSessionId||"",g||"",randomUUID());}break}case "mcps":case "mcp":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="mcp");if(b.length===0){t.addSystem(i("tui.handler.mcp.empty")),await k(x,e.currentSessionId||"",g||"",randomUUID());break}if(g){let v=g.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("mcp",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.mcp.not_found",{vars:{name:W}})),await k(x,e.currentSessionId||"",g,randomUUID());break}A.debug("Opening MCP prompt selector");let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/mcp ${v.value} `):await se("mcp",v.value,e,t,c$1);},onCancel:y});a(E);}catch(f){A.error("Failed to handle MCP prompt",{error:f}),t.addSystem(i("tui.handler.mcp.error",{vars:{error:String(f)}}));}await k(x,e.currentSessionId||"","",randomUUID());break}case "exit":case "quit":await k(x,e.currentSessionId||"",g||"",randomUUID()),l();break;default:A.debug("Unknown command, sending as message"),await h(H);break}}catch(f){let L=f instanceof Error?f.message:String(f);A.error("Command execution failed",{command:x,args:g,error:L,stack:f instanceof Error?f.stack:void 0}),t.addSystem(i("tui.handler.command.error",{vars:{command:x,error:L}}));}A.debug("handleCommand completed");}},h=async(H,F,x)=>{try{let g=randomUUID();if(e.activeChatRunId=g,c$1(i("tui.handler.send.sending")),!e.currentSessionId)throw new Error("No active session");let f;if(e.sessionInfo.model){let{provider:w,model:E}=parseModelId(e.sessionInfo.model);w&&E&&(f={providerId:w,modelId:E});}let L=[{type:"text",text:H}];if(F&&F.length>0)for(let w of F)L.push({type:"file",url:w.url,filename:w.filename,mime:w.mime});x&&L.push({type:"agent",name:x});let b=await e.sdk.session.prompt({sessionId:e.currentSessionId,parts:L,agent:e.agent||void 0,model:f,variant:e.thinkingLevel,contextMode:e.contextMode});if(b.data&&e.currentSessionId&&await k("message",e.currentSessionId,H,b.data.info?.id||randomUUID()),b.data){let w=b.data.parts?.filter(E=>E.type==="text")||[];for(let E of w)"text"in E&&E.text&&t.addAssistant(E.text,b.data.info?.id);}e.activeChatRunId=null,c$1("");}catch(g){e.activeChatRunId=null;let f=g instanceof Error?g.message:String(g),L=g instanceof Error?g.name:"Error";t.addSystem(i("tui.handler.send.error",{vars:{error:f}})),c$1(i("tui.handler.send.error_status")),A.error("Failed to send message",{error:f,errorName:L,sessionId:e.currentSessionId,hasModel:!!e.sessionInfo.model,stack:g instanceof Error?g.stack:void 0});}},se=async(H,F,x,g,f,L)=>{try{let b=H==="skill"?i("tui.handler.skill.executing"):H==="command"?i("tui.handler.command.executing"):i("tui.handler.mcp.executing");if(g.addSystem(b+`: ${F}`),f(i("tui.handler.executing",{vars:{command:F}})),!x.currentSessionId)throw new Error("No active session");let w;x.sessionInfo.model&&(w=x.sessionInfo.model);let E=L?[{type:"text",text:L}]:void 0,W=(await x.sdk.session.command({sessionId:x.currentSessionId,command:F,arguments:L??"",agent:x.agent||void 0,model:w,variant:x.thinkingLevel,contextMode:x.contextMode,parts:E})).data,Y=W?.metadata?.commandType;if(W?.success)Y==="local"&&g.addSystem(i("tui.handler.local.completed")+`: ${F}
|
|
6
|
+
`+i("tui.handler.local.output")+`:
|
|
7
|
+
`+W.output);else {let ee=W?.error??"Command execution failed",q=H==="skill"?"tui.handler.skill.error":H==="command"?"tui.handler.command.error":"tui.handler.mcp.error";g.addSystem(i(q,{vars:{command:F,error:ee}}));}f("");}catch(b){let w=b instanceof Error?b.message:String(b),E=b instanceof Error?b.name:"Error",v=H==="skill"?i("tui.handler.skill.error"):H==="command"?i("tui.handler.command.error"):i("tui.handler.mcp.error");g.addSystem(v+`: ${F}
|
|
8
|
+
${w}`),f(i("tui.status.error")),A.error("Failed to execute command",{type:H,name:F,error:w,errorName:E,sessionId:x.currentSessionId,stack:b instanceof Error?b.stack:void 0});}};return {handleCommand:ge,sendMessage:h,gatewayManager:s.gatewayManager}}var R=a.create({service:"cli-tui-events"});function Wt(s){return e=>{try{if(e.type==="message.updated"){As(s,e);return}if(e.type==="message.part.updated"){Ps(s,e);return}if(e.type==="session.status"){qs(s,e);return}if(e.type==="session.error"){Os(s,e);return}if(e.type==="agent.updated"){Ws(s,e);return}if(e.type==="session.updated"){Ns(s,e);return}if(e.type==="permission.asked"){Gs(s,e);return}if(e.type==="question.asked"){Qs(s,e);return}}catch(t){R.error("Event handling failed",{eventType:e.type,error:t instanceof Error?t.message:String(t)});}}}function As(s,e){if(e.type!=="message.updated")return;let{properties:t}=e,{info:n}=t,i=s.state?.currentSessionId||s.sessionId;if(!(i&&n.sessionId!==i)&&s.state&&"model"in n&&n.model){let a=`${n.model.providerId}/${n.model.modelId}`;s.state.sessionInfo.model=a,s.updateFooter&&s.updateFooter();}}function Ps(s,e){if(e.type!=="message.part.updated")return;let{properties:t}=e,{part:n}=t;if(!n){R.warn("Message part is undefined",{event:e,properties:t,propertiesType:typeof t,propertiesKeys:t?Object.keys(t):[]});return}let i=s.state?.currentSessionId||s.sessionId;i&&n.sessionId!==i||Ms(s,n);}function Ms(s,e){if(e.type==="tool"){Ds(s,e);return}if(e.type==="text"){if("time"in e&&e.time&&"end"in e.time&&e.time.end){Bs(s,e);return}if(!("time"in e)){Es(s,e);return}}if(e.type==="reasoning"&&"time"in e&&e.time&&"end"in e.time&&e.time.end){Us(s,e);return}if(e.type==="step-start"){Ls(s);return}if(e.type==="step-finish"){_s(s,e);return}if(e.type==="subtask-result"){$s(s,e);return}}function Es(s,e){let t=e.text?.trim();t&&s.chatLog.addUser(t,e.messageId);}function Ls(s){s.setActivityStatus(i("tui.status.executing_step"));}function _s(s,e){s.setActivityStatus(i("tui.status.step_completed")),s.state&&e.tokens&&Hs(s,e.tokens);}function $s(s,e){let t=Ka.formatSubtaskResultPart(e);s.chatLog.addUser(t,e.id,{agent:e.agent,isSubagentResult:true,subtaskResultPart:{taskId:e.taskId,source:e.source,agent:e.agent,status:e.status,result:e.result,error:e.error,duration:e.duration,rounds:e.rounds,time:e.time,metadata:e.metadata}});}async function Rs(s){let e=s.sessionInfo.model;if(!e)return null;let{provider:t,model:n}=parseModelId(e);if(!t||!n)return null;try{return ((await s.sdk.config.providers({})).data?.providers??[]).find(c=>c.id===t)?.models?.[n]?.limit?.context??null}catch(i){return R.warn("Failed to get context limit from model config",{error:i,providerId:t,modelId:n}),null}}function Hs(s,e){let t=e.input+e.output+e.reasoning+e.cache.read+e.cache.write;s.state.sessionInfo.totalTokens=t,s.state.sessionInfo.contextTokens||Rs(s.state).then(n=>{s.state.sessionInfo.contextTokens=n??2e5,s.updateFooter&&s.updateFooter();});}function Fs(s){let e=s.state?.status==="running"||s.state?.status==="completed"?s.state.input:void 0;if(!e)return;let t=e.filePath??e.filepath??e.path,n=e.title;return t?n=Filesystem.normalize(t):e.url&&(n=e.url),n}function Ds(s,e){if(!e.state){R.warn("Tool part missing state",{tool:e.tool,partType:e.type});return}let t=Fs(e),n=t?`${e.tool} ${t}`:e.tool;if(e.state.status==="running"&&(s.setActivityStatus(i("tui.status.executing_tool",{vars:{tool:e.tool}})),s.chatLog.addSystem(i("tui.system.tool_executing",{vars:{tool:n}}),e.id,{isTool:true,toolName:e.tool,toolCallId:e.callId,toolStatus:"executing",title:t})),e.state.status==="completed"&&(s.setActivityStatus(i("tui.status.tool_completed")),s.chatLog.addSystem(i("tui.system.tool_completed",{vars:{tool:n}}),e.id,{isTool:true,toolName:e.tool,toolCallId:e.callId,toolStatus:"completed",result:e.state.output,title:t}),s.state?.toolsExpanded&&s.state?.verboseLevel==="on"&&e.state.output)){let a=(typeof e.state.output=="string"?e.state.output:JSON.stringify(e.state.output,null,2)).trim();a&&s.chatLog.addSystem(`Tool output:
|
|
9
|
+
`+a);}e.state.status==="error"&&(s.setActivityStatus(i("tui.status.tool_failed")),s.chatLog.addSystem(i("tui.system.tool_failed",{vars:{tool:n}}),e.id,{isTool:true,toolName:e.tool,toolCallId:e.callId,toolStatus:"failed",error:e.state.error,title:t}));}function Bs(s,e){let t=e.text?.trim();t&&(s.chatLog.addAssistant(t,e.messageId),s.setActivityStatus(i("tui.status.receiving")));}function Us(s,e){let t=e.text?.trim();if(!t){R.warn("Reasoning part has no text, skipping",{partId:e.id});return}if(t=t.replace("[REDACTED]","").trim(),!t){R.warn("Reasoning part is redacted, skipping",{partId:e.id});return}if(t=t.trim(),!t){R.warn("Reasoning part has no content after cleanup",{partId:e.id});return}if(R.debug("Adding reasoning message to ChatLog",{textLength:t.length,partId:e.id,showThinking:s.state?.showThinking,hasTimeEnd:"time"in e&&e.time&&"end"in e.time?!!e.time.end:false}),s.chatLog.addSystem(i("tui.system.thinking",{vars:{text:t}}),e.id,{isThinking:true}),R.debug("Reasoning message added, requesting render"),s.state?.pendingQuestion){s.state.questionDisplayTimer&&(clearTimeout(s.state.questionDisplayTimer),s.state.questionDisplayTimer=null,R.debug("Question display fallback timer cleared (reasoning-end)"));let n=s.state.pendingQuestion;if(n.questions.length>0){let i=n.questions[0];i&&(R.debug("Show first question after reasoning-end",{header:i.header,question:i.question,optionCount:i.options?.length||0}),Nt(s,i,0,n.questions.length));}}}function qs(s,e){let{properties:t}=e,{sessionId:n,status:i$1}=t,a=s.state?.currentSessionId||s.sessionId;if(!(a&&n!==a)){if(R.debug("Session status",{status:i$1.type,sessionId:n}),i$1.type==="idle"){if(s.state){if(s.state.questionDisplayTimer&&(clearTimeout(s.state.questionDisplayTimer),s.state.questionDisplayTimer=null,R.debug("Question display fallback timer cleared (session idle)")),s.state.pendingQuestion){let o=s.state.pendingQuestion.id;R.debug("Rejecting pending question due to session idle",{questionId:o,sessionId:n}),s.state.pendingQuestion=null,s.chatLog.addSystem(i("tui.question.cancelled")),s.state.sdk.question.reject({requestId:o}).catch(l=>{R.error("Failed to reject question",{error:l});});}if(s.state.pendingPermission){let o=s.state.pendingPermission.sessionId,l=s.state.pendingPermission.id;R.debug("Rejecting pending permission due to session idle",{permissionId:l,sessionId:n}),s.state.pendingPermission=null,s.chatLog.addSystem(i("tui.permission.cancelled")),s.state.sdk.permission.respond({sessionId:o,permissionId:l,response:"reject"}).catch(c=>{R.error("Failed to reject permission",{error:c});});}}s.setActivityStatus(i("tui.status.ready"));}i$1.type==="running"&&s.setActivityStatus(i("tui.status.running")),i$1.type==="waiting"&&s.setActivityStatus(i("tui.status.waiting"));}}function Os(s,e){let{properties:t}=e,{sessionId:n,error:i$1}=t,a=s.state?.currentSessionId||s.sessionId;if(a&&n!==a)return;R.error("Session error",{error:i$1,sessionId:n});let o=String(i$1.name);"data"in i$1&&i$1.data&&"message"in i$1.data&&(o=String(i$1.data.message)),s.chatLog.addSystem(i("tui.system.error",{vars:{message:o}})),s.setActivityStatus(i("tui.status.error"));}function Ws(s,e){let{properties:t}=e,{agentId:n}=t;R.debug("Agent updated (backend event)",{agentId:n});}function Ns(s,e){let{properties:t}=e,{info:n}=t,i=s.state?.currentSessionId||s.sessionId;i&&n.id!==i||(R.debug("Session updated",{sessionId:n.id,title:n.title}),s.state&&(s.state.currentSessionKey=n.title||n.id,n.model&&(s.state.sessionInfo.model=`${n.model.providerId}/${n.model.modelId}`)),s.updateFooter&&s.updateFooter());}function Gs(s,e){let{properties:t}=e,n=t,i$1=s.state?.currentSessionId||s.sessionId;if(i$1&&n.sessionId!==i$1){R.debug("Ignore permission request from other session",{sessionId:n.sessionId,currentSessionId:i$1});return}R.debug("Received permission request",{permission:n.permission,patterns:n.patterns,sessionId:n.sessionId}),s.state&&(s.state.pendingPermission={id:n.id,sessionId:n.sessionId,permission:n.permission,patterns:n.patterns});let a=`
|
|
10
|
+
`+i("tui.permission.request_header")+`
|
|
11
|
+
`;a+=i("tui.permission.type",{vars:{type:n.permission}})+`
|
|
12
|
+
`,a+=i("tui.permission.targets",{vars:{targets:n.patterns.join(", ")}})+`
|
|
13
|
+
`,a+=`
|
|
14
|
+
`+i("tui.permission.options")+`
|
|
15
|
+
`,a+=" [y] "+i("tui.permission.once")+`
|
|
16
|
+
`,a+=" [a] "+i("tui.permission.always")+`
|
|
17
|
+
`,a+=" [n] "+i("tui.permission.reject")+`
|
|
18
|
+
`,s.chatLog.addSystem(a),s.setActivityStatus(i("tui.status.waiting_permission"));}function Qs(s,e){let{properties:t}=e,n=t,i$1=s.state?.currentSessionId||s.sessionId;if(i$1&&n.sessionId!==i$1){R.debug("Ignore question request from other session",{sessionId:n.sessionId,currentSessionId:i$1});return}if(R.debug("Received question request",{id:n.id,sessionId:n.sessionId,questionCount:n.questions.length,questions:n.questions.map(a=>({header:a.header,optionCount:a.options?.length||0}))}),s.state){s.state.pendingQuestion={id:n.id,sessionId:n.sessionId,questions:n.questions,currentQuestionIndex:0,collectedAnswers:[]},R.debug("pendingQuestion set to state (deferred display)",{id:n.id,questionCount:n.questions.length}),s.state.questionDisplayTimer&&(clearTimeout(s.state.questionDisplayTimer),R.debug("Cleared existing question display fallback timer"));let a=2e3;s.state.questionDisplayTimer=setTimeout(()=>{if(s.state?.pendingQuestion&&s.state.pendingQuestion.id===n.id){R.debug("Question display fallback triggered (no reasoning-end)",{questionId:n.id,timeout:a});let o=s.state.pendingQuestion.questions[0];o&&Nt(s,o,0,s.state.pendingQuestion.questions.length),s.state&&(s.state.questionDisplayTimer=null);}},a),R.debug("Question display fallback timer started",{questionId:n.id,timeout:a});}s.setActivityStatus(i("tui.status.waiting_answer"));}function Nt(s,e,t,n){let i$1="tui.question.header",a={current:t+1,total:n},o=i(i$1,{vars:a});R.debug("displayQuestion - i18n translation test",{key:i$1,vars:a,result:o,isTranslated:o!==i$1,resultLength:o.length});let l=`
|
|
19
|
+
`+o+`
|
|
20
|
+
`;if(l+=e.header+`
|
|
21
|
+
`,l+=e.question+`
|
|
22
|
+
`,e.options&&e.options.length>0){let c=i("tui.question.options");R.debug("displayQuestion - options translation",{key:"tui.question.options",result:c,isTranslated:c!=="tui.question.options"}),l+=`
|
|
23
|
+
`+c+`
|
|
24
|
+
`;for(let u=0;u<e.options.length;u++){let d=e.options[u];d&&(l+=` [${u+1}] ${d.label}`,d.description&&(l+=` - ${d.description}`),l+=`
|
|
25
|
+
`);}e.custom!==false?e.multiple?l+=`
|
|
26
|
+
`+i("tui.question.hint.custom_enabled_multiple")+`
|
|
27
|
+
`:l+=`
|
|
28
|
+
`+i("tui.question.hint.custom_enabled")+`
|
|
29
|
+
`:e.multiple?l+=`
|
|
30
|
+
`+i("tui.question.hint.custom_disabled_multiple")+`
|
|
31
|
+
`:l+=`
|
|
32
|
+
`+i("tui.question.hint.custom_disabled")+`
|
|
33
|
+
`;}R.debug("displayQuestion - final message",{messageLength:l.length,messagePreview:l.substring(0,100)}),s.chatLog.addSystem(l);}var J=a.create({service:"cli-tui-session-actions"});async function Gt(s){J.debug("Refreshing agent list");try{s.setActivityStatus(i("tui.session.loading_agents"));let n=((await s.sdk.app.agents({})).data||[]).map(i=>i.name);return J.info("Agent list loaded",{count:n.length}),s.setActivityStatus(i("tui.status.ready")),n}catch(e){return J.error("Failed to refresh agent list",{error:e}),s.chatLog.addSystem(i("tui.session.agents_failed",{vars:{error:String(e)}})),s.setActivityStatus(i("tui.status.error")),[]}}async function at(s,e){J.debug("Refreshing session info",{sessionId:e});try{s.setActivityStatus(i("tui.session.loading_info"));let n=(await s.sdk.session.get({sessionId:e})).data;return J.info("Session info loaded",{sessionId:e}),s.setActivityStatus(i("tui.status.ready")),n??null}catch(t){return J.error("Failed to refresh session info",{sessionId:e,error:t}),s.chatLog.addSystem(i("tui.session.info_failed",{vars:{error:String(t)}})),s.setActivityStatus(i("tui.status.error")),null}}async function qe(s,e,t){J.info("Loading history",{sessionId:e,limit:t});try{s.setActivityStatus(i("tui.session.loading_history"));let i$1=(await s.sdk.session.messages({sessionId:e,limit:t})).data||[];J.info("History loaded",{sessionId:e,count:i$1.length});for(let a=0;a<i$1.length;a++){let o=i$1[a],l=o?.info?.role;if(l==="user"){let u=(o?.parts?.filter(p=>p.type==="text")||[]).map(p=>("text"in p?p.text:"")||"").join(`
|
|
34
|
+
`),d=o?.parts?.filter(p=>p.type==="subtask-result")||[];for(let p of d)if("agent"in p&&"taskId"in p){let M=Ka.formatSubtaskResultPart(p);s.chatLog.addUser(M,o?.info?.id,{agent:p.agent||"SubAgent",isSubagentResult:!0,subtaskResultPart:{taskId:p.taskId,source:p.source,agent:p.agent,status:p.status,result:p.result,error:p.error,duration:p.duration,rounds:p.rounds,time:p.time,metadata:p.metadata}});}u&&s.chatLog.addUser(u,o?.info?.id,{agent:o?.info?.agent});}else if(l==="assistant"){let u=(o?.parts?.filter(d=>d.type==="text")||[]).map(d=>("text"in d?d.text:"")||"").join(`
|
|
35
|
+
`);u&&s.chatLog.addAssistant(u,o?.info?.id,{agent:o?.info?.agent});}else if(l==="system"){let u=(o?.parts?.filter(d=>d.type==="text")||[]).map(d=>("text"in d?d.text:"")||"").join(`
|
|
36
|
+
`);s.chatLog.addSystem(u,o?.info?.id,{agent:o?.info?.agent});}}return s.setActivityStatus(i("tui.status.ready")),i$1}catch(n){return J.error("Failed to load history",{sessionId:e,error:n}),s.chatLog.addSystem(i("tui.session.history_failed",{vars:{error:String(n)}})),s.setActivityStatus(i("tui.status.error")),[]}}async function Qt(s,e,t){J.debug("Switching session",{sessionId:e});try{t.currentSessionId=e,t.currentSessionKey=e,t.historyLoaded=!1;let n=await at(s,e);n&&(t.currentSessionKey=n.title||e,t.sessionInfo.model=n.model,t.sessionInfo.modelProvider=n.modelProvider);let{loadTuiState:i$1,saveTuiStateToStorage:a}=await import('./preferences-QCM3RIAL.mjs'),o=await i$1(e);t.toolsExpanded=o.toolsExpanded,t.showThinking=o.showThinking,t.thinkingLevel=o.thinkingLevel,t.verboseLevel=o.verboseLevel,t.messageLimit=o.messageLimit,t.localShellPermission=o.localShellPermission,o.model&&(t.sessionInfo.model=o.model),o.agent&&(t.agent=o.agent),J.debug("Session preferences loaded",{sessionId:e,model:t.sessionInfo.model,agent:t.agent,thinkingLevel:t.thinkingLevel}),await a(t),await qe(s,e,t.messageLimit),t.historyLoaded=!0,s.chatLog.addSystem(i("tui.session.switched",{vars:{sessionId:e}}));}catch(n){J.error("Failed to switch session",{sessionId:e,error:n}),s.chatLog.addSystem(i("tui.session.switch_failed",{vars:{error:String(n)}})),s.setActivityStatus(i("tui.status.error"));}}async function jt(s,e){J.debug("Aborting current run",{sessionId:e});try{s.setActivityStatus(i("tui.session.aborting"));let t=s.sdk.session.abort({sessionId:e}),n=new Promise((i$1,a)=>{setTimeout(()=>a(new Error(i("tui.abort.timeout"))),5e3);});await Promise.race([t,n]),s.chatLog.addSystem(i("tui.session.aborted")),s.setActivityStatus(i("tui.status.ready"));}catch(t){J.error("Failed to abort",{sessionId:e,error:t}),s.chatLog.addSystem(i("tui.session.abort_failed",{vars:{error:String(t)}})),s.setActivityStatus(i("tui.status.error"));}}function Kt(s,e){return {openOverlay:i=>{s.showOverlay(i);},closeOverlay:()=>{s.hasOverlay()&&s.hideOverlay(),s.setFocus(e);}}}var Oe=a.create({service:"tui-autocomplete"});function Vt(s){return new lt(s)}var lt=class{constructor(e){b(this,"basePath");b(this,"commands");b(this,"getAgents");this.basePath=e.basePath,this.commands=e.slashCommands,this.getAgents=e.getAgents;}updateCommands(e){this.commands=e;}setGetAgents(e){this.getAgents=e;}async getSuggestions(e,t,n,i){let o=(e[t]||"").slice(0,n),l=this.extractHashPrefix(o);if(l)return this.getFileSuggestions(l);let c=this.extractAtPrefix(o);return c?await this.getAgentSuggestions(c):o.startsWith("/")?this.getCommandSuggestions(o):null}applyCompletion(e,t,n,i,a){let o=e[t]||"",l=o.slice(0,n-a.length),c=o.slice(n);if(a.startsWith("#")){let u=i.label.endsWith("/"),d=u?i.value.replace(/\/$/,""):i.value,p=u?"":" ";return {lines:[...e.slice(0,t),l+d+p+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+d.length+p.length}}if(a.startsWith("@"))return {lines:[...e.slice(0,t),l+i.value+" "+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+i.value.length+1};if(a.startsWith("/")){let u="/"+i.value+" ";return {lines:[...e.slice(0,t),l+u+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+u.length}}return {lines:[...e.slice(0,t),l+i.value+" "+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+i.value.length+1}}async getCommandSuggestions(e){let t=e.indexOf(" ");if(t===-1){let c=e.slice(1),u=this.commands.filter(d=>d.name.toLowerCase().includes(c.toLowerCase())).map(d=>({value:d.name,label:d.name,description:d.description}));return u.length===0?null:{items:u.slice(0,50),prefix:e}}let n=e.slice(1,t),i=e.slice(t+1),a=this.commands.find(c=>c.name===n);if(!a?.getArgumentCompletions)return null;let o=a.getArgumentCompletions(i),l=o instanceof Promise?await o:o;return !l||l.length===0?null:{items:l.slice(0,50),prefix:i}}getFileSuggestions(e){let t=e.startsWith('#"')?e.slice(2):e.slice(1),n=e.startsWith('#"'),i=t.replace(/\\/g,"/");if(this.isDrivePath(i))return Oe.debug("Drive path, skip autocomplete",{normalizedPath:i}),null;let{targetPath:a,searchQuery:o}=this.parsePath(i),l=this.resolveBaseDir(a);try{let c;try{c=readdirSync(l,{withFileTypes:!0});}catch{return Oe.debug("Directory not found",{baseDir:l}),null}let u=[];for(let d of c){if(o&&!d.name.toLowerCase().includes(o.toLowerCase()))continue;let p=d.isDirectory(),M=a?`${a}${d.name}`:d.name;if(u.push({value:n?`#"${M}${p?"/":""}"`:`#${M}${p?"/":""}`,label:p?`${d.name}/`:d.name,description:M}),u.length>=50)break}return u.sort((d,p)=>{let M=d.label.endsWith("/"),B=p.label.endsWith("/");return M&&!B?-1:!M&&B?1:d.label.localeCompare(p.label)}),u.length===0?null:{items:u,prefix:e}}catch(c){return Oe.debug("File search failed",{error:c,targetPath:a}),null}}async getAgentSuggestions(e){if(!this.getAgents)return null;let t=e.slice(1);try{let i=(await this.getAgents()).filter(a=>a.hidden!==!0).filter(a=>a.name.toLowerCase().includes(t.toLowerCase())).map(a=>({value:`@${a.name}`,label:a.name,description:a.description}));return i.length===0?null:{items:i.slice(0,50),prefix:e}}catch(n){return Oe.debug("Agent search failed",{error:n,prefix:e}),null}}extractAtPrefix(e){let t=new Set([" "," ",'"',"'","="]);for(let n=e.length-1;n>=0;n--)if(t.has(e[n]??"")){let i=n+1;return e[i]==="@"?e.slice(i):null}return e.startsWith("@")?e:null}extractHashPrefix(e){let t=new Set([" "," ",'"',"'","="]);for(let n=e.length-1;n>=0;n--)if(t.has(e[n]??"")){let i=n+1;return e[i]==="#"?e.slice(i):null}return e.startsWith("#")?e:null}isDrivePath(e){return /^[A-Za-z]:[/\\]?$/.test(e)}parsePath(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?{targetPath:"",searchQuery:e}:{targetPath:e.slice(0,t+1),searchQuery:e.slice(t+1)}}resolveBaseDir(e){return e?zt.join(this.basePath,e):this.basePath}};function dt(s,e){let t=[],n=/(?<![\w`])#(\S+)/g,i;for(;(i=n.exec(s))!==null;){let a=i[1];if(!a)continue;let o=a.replace(/\\/g,"/"),l=Vs(o,e);existsSync(l)&&t.push({path:a,url:pathToFileURL(l).href,exists:true});}return {attachments:t,invalidPaths:[]}}function Vs(s,e){if(/^[A-Za-z]:[/\\]/.test(s))return s;let t=s.replace(/^[/\\]+/,"");return zt.join(e,t)}var G=a.create({service:"cli-tui-input-handlers"}),We=class{constructor(){b(this,"handlers",[]);b(this,"isBrowsingHistory",false);}register(e){this.handlers.push(e),G.debug("Register input handler",{name:e.name,total:this.handlers.length});}setHistoryBrowsing(e){this.isBrowsingHistory=e;}isHistoryBrowsing(){return this.isBrowsingHistory}async handle(e,t){let n=e.trim();if(n){this.isBrowsingHistory;for(let i of this.handlers)if(i.canHandle(n,t.state)){G.debug("Handle input with handler",{handler:i.name,input:n.substring(0,50)}),await i.handle(n,t);return}G.warn("No handler can process input",{input:n.substring(0,50)});}}getPrompt(e){for(let t of this.handlers)if(t.getPrompt&&t.canHandle("",e)){let n=t.getPrompt(e);if(n)return n}return "> "}},Ne=class{constructor(){b(this,"name","permission");}canHandle(e,t){return t.pendingPermission!==null}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=n.pendingPermission;if(!o)return;let l=e.toLowerCase().trim(),c;if(l==="y"||l==="yes")c="once";else if(l==="a"||l==="always")c="always";else if(l==="n"||l==="no"||l==="reject")c="reject";else {i$1.addSystem(i("tui.permission.invalid_input"));return}try{await ra(n,{requestId:o.id,reply:c}),n.pendingPermission=null;let u=c==="once"?i("tui.permission.once"):c==="always"?i("tui.permission.always"):i("tui.permission.reject");i$1.addSystem(i("tui.permission.replied",{vars:{reply:u}})),G.debug("Permission request replied",{requestId:o.id,reply:c});}catch(u){G.error("Failed to reply permission request",{error:u}),i$1.addSystem(i("tui.permission.error")),n.pendingPermission=null;}}getPrompt(e){return e.pendingPermission?i("tui.permission.prompt"):"> "}},Ge=class{constructor(){b(this,"name","question");}canHandle(e,t){return !(t.pendingQuestion===null||e.startsWith("/"))}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=n.pendingQuestion;if(!o){G.warn("QuestionInputHandler.handle - no pending question");return}G.debug("QuestionInputHandler.handle - processing input",{input:e.substring(0,50),currentIndex:o.currentQuestionIndex,totalQuestions:o.questions.length,requestId:o.id});let l=o.currentQuestionIndex,c=o.questions[l];if(!c){G.error("Current question does not exist",{currentIndex:l,totalQuestions:o.questions.length}),n.pendingQuestion=null;return}let u=this.parseAnswer(e,c);if(!u){G.debug("QuestionInputHandler.handle - invalid input",{input:e}),i$1.addSystem(i("tui.question.invalid_input"));return}if(G.debug("QuestionInputHandler.handle - answer parsed",{answer:u,answerLength:u.length}),o.collectedAnswers.push(u),o.currentQuestionIndex++,o.currentQuestionIndex<o.questions.length){G.debug("QuestionInputHandler.handle - showing next question",{nextIndex:o.currentQuestionIndex,totalQuestions:o.questions.length});let d=o.questions[o.currentQuestionIndex];d&&this.displayQuestion(d,o.currentQuestionIndex,o.questions.length,i$1);}else {G.debug("QuestionInputHandler.handle - all questions answered, calling API",{requestId:o.id,answerCount:o.collectedAnswers.length,answers:o.collectedAnswers});try{await sa(n,{requestId:o.id,answers:o.collectedAnswers}),n.pendingQuestion=null,i$1.addSystem(i("tui.question.completed",{vars:{count:o.collectedAnswers.length}})),G.debug("Question request completed",{requestId:o.id});}catch(d){G.error("Failed to reply question request",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,requestId:o.id,answers:o.collectedAnswers,errorType:d instanceof Error?d.constructor.name:typeof d});let p=d instanceof Error?d.message:String(d);i$1.addSystem(`${i("tui.question.error")}: ${p}`),n.pendingQuestion=null;}}}parseAnswer(e,t){let n=e.trim();if(!t.options||t.options.length===0)return [n];let i=n.match(/^(\d+(?:,\s*\d+)*)$/);if(i?.[1]){let o=i[1].split(",").map(l=>Number.parseInt(l.trim(),10)).filter(l=>l>0&&l<=t.options.length);if(o.length===0)return null;if(!t.multiple&&o.length>1){let l=o[0];if(l!==void 0){let c=t.options[l-1];if(c)return [c.label]}return null}return o.map(l=>{let c=t.options[l-1];return c?c.label:""}).filter(l=>l!=="")}return t.custom===false?null:[n]}displayQuestion(e,t,n,i$1){let a=`
|
|
37
|
+
${i("tui.question.header",{vars:{current:t+1,total:n}})}
|
|
38
|
+
`;if(a+=`${e.header}
|
|
39
|
+
`,a+=`${e.question}
|
|
40
|
+
`,e.options&&e.options.length>0){a+=`
|
|
41
|
+
`+i("tui.question.options")+`
|
|
42
|
+
`;for(let o=0;o<e.options.length;o++){let l=e.options[o];l&&(a+=` [${o+1}] ${l.label}`,l.description&&(a+=` - ${l.description}`),a+=`
|
|
43
|
+
`);}e.custom!==false?e.multiple?a+=`
|
|
44
|
+
`+i("tui.question.hint.custom_enabled_multiple")+`
|
|
45
|
+
`:a+=`
|
|
46
|
+
`+i("tui.question.hint.custom_enabled")+`
|
|
47
|
+
`:e.multiple?a+=`
|
|
48
|
+
`+i("tui.question.hint.custom_disabled_multiple")+`
|
|
49
|
+
`:a+=`
|
|
50
|
+
`+i("tui.question.hint.custom_disabled")+`
|
|
51
|
+
`;}i$1.addSystem(a);}getPrompt(e){let t=e.pendingQuestion;if(!t)return "> ";let n=t.currentQuestionIndex+1,i$1=t.questions.length;return i("tui.question.prompt",{vars:{current:n,total:i$1}})}},Qe=class{constructor(){b(this,"name","shell-permission");}canHandle(e,t){return t.pendingShellCommand!==null}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=e.toLowerCase().trim();if(o==="y"||o==="yes"){n.localShellPermission="on",await b$2(n),i$1.addSystem(i("tui.shell.permission.updated",{vars:{permission:"on"}}));let l=n.pendingShellCommand;n.pendingShellCommand=null,await new xe().executeCommand(l,t);}else o==="n"||o==="no"?(n.localShellPermission="off",await b$2(n),i$1.addSystem(i("tui.shell.permission.updated",{vars:{permission:"off"}})),n.pendingShellCommand=null):i$1.addSystem(i("tui.shell.permission.invalid"));}getPrompt(e){return i("tui.shell.permission.prompt")}},xe=class{constructor(){b(this,"name","shell");}canHandle(e,t){return e.startsWith("!")}async handle(e,t){let{chatLog:n,tui:i$1,setActivityStatus:a,state:o}=t,l=e.slice(1).trim();if(!l){n.addSystem(i("tui.shell.empty"));return}switch(o.localShellPermission){case "on":await this.executeCommand(l,t);break;case "off":n.addSystem(i("tui.shell.permission.off"));break;case "ask":o.pendingShellCommand=l,n.addSystem(i("tui.shell.permission.ask"));break}}async executeCommand(e,t){let{chatLog:n,tui:i$1,setActivityStatus:a}=t;try{n.addSystem(`\u6B63\u5728\u6267\u884C Shell \u547D\u4EE4: ${e}`),a(i("tui.shell.executing",{vars:{command:e}})),G.debug("Executing shell command",{command:e});let o=await Shell.run(void 0,e,{cwd:process.cwd()}),l="";o.stdout?.trim()&&(l+=`
|
|
52
|
+
${o.stdout}`),o.stderr?.trim()&&(l+=`
|
|
53
|
+
${o.stderr}`),l&&n.addSystem(l),n.addSystem(i("tui.shell.success",{vars:{code:o.code}})),a(""),G.debug("Shell command executed successfully",{command:e,exitCode:o.code,stdoutLength:o.stdout?.length||0,stderrLength:o.stderr?.length||0});}catch(o){G.error("Failed to execute shell command",{command:e,error:o instanceof Error?o.message:String(o)});let l=o instanceof Error?o.message:String(o);n.addSystem(i("tui.shell.error",{vars:{error:l}})),a("");}}getPrompt(e){return "$ "}},je=class{constructor(){b(this,"name","command");}canHandle(e,t){return e.startsWith("/")}async handle(e,t){t.handleCommand?await t.handleCommand(e,t):G.warn("handleCommand is not defined");}getPrompt(e){return "> "}},Ke=class{constructor(){b(this,"name","normal");}canHandle(e,t){return true}async handle(e,t){t.sendMessage?await t.sendMessage(e):G.warn("sendMessage is not defined");}getPrompt(e){return "> "}},ze=class{constructor(){b(this,"name","at-mention");}canHandle(e,t){if(e.startsWith("/")||e.startsWith("!"))return false;let n=e.trimStart();return n.startsWith("@")||n.startsWith("#")}async handle(e,t){let{chatLog:n,sendMessage:i,state:a}=t,o=e.trimStart();if(o.startsWith("@")){let l=o.slice(1).split(/\s+/)[0];if(!l)return;let c=e.replace(/@\S+/g,"").trim(),d=dt(e,a.instanceContext.directory).attachments.map(p=>({url:p.url,filename:p.path.split("/").pop()||p.path.split("\\").pop()||p.path,mime:"text/plain"}));i&&await i(c,d.length>0?d:void 0,l);return}if(o.startsWith("#")){let l=dt(e,a.instanceContext.directory);if(l.attachments.length===0)return;let c=e.replace(/#\S+/g,"").trim(),u=l.attachments.map(d=>({url:d.url,filename:d.path.split("/").pop()||d.path.split("\\").pop()||d.path,mime:"text/plain"}));i&&await i(c,u);return}}getPrompt(e){return "> "}};var Zs=loadTextFile("./banner.txt",import.meta.url),Xs=Zs();function Yt(){try{let s=Xs.replace("${Global.getVersion()}",a$2.getVersion());return s=s.replace("${t('tui.header.title')}",i("tui.header.title")),s}catch{return `EasBot v${a$2.getVersion()}
|
|
54
|
+
${i("tui.header.title")}
|
|
55
|
+
`}}var Ve=class{constructor(e){b(this,"log",a.create({service:"tui-gateway-message-handler"}));b(this,"config");b(this,"bridge");b(this,"eventBus");b(this,"bridgeStarted",false);this.config=e,this.eventBus=new SdkEventBus,this.bridge=new SdkEventBridge(e.state.sdk,this.eventBus);}async start(){if(!this.bridgeStarted){this.log.debug("Starting SdkEventBridge");try{await this.bridge.start(),this.bridgeStarted=!0,this.log.debug("SdkEventBridge started successfully");}catch(e){throw this.log.error("Failed to start SdkEventBridge",{error:String(e)}),e}}}async stop(){this.bridgeStarted&&(await this.bridge.stop(),this.bridgeStarted=false);}async sendMessage(e,t,n="output",i,a,o){let l=this.config.getGatewayClient();if(!l){this.log.warn("gatewayClient not available, skipping message send");return}await l.sendMessage(e,t,n,i,a,o??this.config.state.agent);}async handleMessage(e){if(!e?.id){this.log.warn("received incomplete message",{message:e});return}let t=e.metadata?.channel;if(!t?.chatId){this.log.warn("channelInfo missing chatId, cannot reply",{channelInfo:t});return}if(this.log.debug("Handling gateway message",{id:e.id,type:e.type,sessionId:e.sessionId,contentTypes:e.content.map(i=>i.type)}),e.type!=="input")return;let n=e.content.find(i=>i.type==="command");if(n){this.handleCommand(n,t,e.id,e.sessionId);return}this.handleTextMessage(e,t,e.id,e.sessionId);}async handleCommand(e,t,n,i$1){this.config.setActivityStatus?.(i("tui.handler.executing",{vars:{command:e.command}}));let a="prompt";try{a=((await this.config.state.sdk.command.list({})).data??[]).find(u=>u.name===e.command)?.commandType==="local"?"local":"prompt",this.log.debug("Command type determined",{command:e.command,commandType:a});}catch(o){this.log.warn("Failed to get command list, assuming prompt type",{error:String(o)});}try{if(a==="local"){await this.handleLocalCommand(e,t,n,i$1);return}await this.handlePromptCommand(e,t,n,i$1);}finally{this.config.setActivityStatus?.("");}}async handleLocalCommand(e,t,n,i){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for command"),await this.sendMessage(i,"Error: No active session","output",n,t);return}this.log.debug("Calling SDK command (local)",{command:e.command,arguments:e.arguments,sessionId:a});try{let o=await this.config.state.sdk.session.command({sessionId:a,command:e.command,arguments:e.arguments??"",agent:this.config.state.agent});if(o?.data?.success===!1){let c=o.data.error??"Command failed";this.log.debug("Command failed",{error:c}),await this.sendMessage(i,c,"output",n,t);return}let l=o?.data?.output??"";l&&(this.log.debug("Sending command result",{textLength:l.length}),await this.sendMessage(i,l,"output",n,t));}catch(o){this.log.error("SDK command error",{error:String(o)}),await this.sendMessage(i,`Command failed: ${String(o)}`,"output",n,t);}}async handlePromptCommand(e,t,n,i){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for prompt command"),await this.sendMessage(i,"Error: No active session","output",n,t);return}this.log.debug("Calling SDK command (prompt via events)",{command:e.command,arguments:e.arguments,sessionId:a});let o=this.eventBus.subscribeAll(l=>{if(l.type===SdkEventType.SDK_SESSION_UPDATE){let c=l.properties;if(c.sessionId!==a)return;this.log.debug("SDK_SESSION_UPDATE event received",{sessionId:c.sessionId,updateKeys:Object.keys(c.update),sessionUpdate:c.update.sessionUpdate});let u=this.assembleTextFromUpdate(c.update);u&&(this.log.debug("Sending prompt command result via event",{textLength:u.length}),this.sendMessage(i,u,"output",n,t));}});try{await this.config.state.sdk.session.command({sessionId:a,command:e.command,arguments:e.arguments??"",agent:this.config.state.agent});}catch(l){this.log.error("SDK command error",{error:String(l)}),await this.sendMessage(i,`Command failed: ${String(l)}`,"output",n,t);}finally{o();}}assembleTextFromUpdate(e){if(e.sessionUpdate==="agent_message_chunk"){let a=e.content;return a?.type==="text"&&a.text?a.text:""}let n=e.parts;return n?n.filter(a=>a.type==="text"&&a.time?.end).map(a=>a.text||"").join(`
|
|
56
|
+
`):""}async handleTextMessage(e,t,n,i$1){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for text message"),await this.sendMessage(i$1,"Error: No active session","output",n,t);return}let o=[];for(let T of e.content)if(T.type==="text"&&T.text)o.push({type:"text",text:T.text});else if(T.type==="image"){let y="";typeof T.image=="string"?y=T.image:T.image instanceof URL?y=T.image.toString():T.image instanceof Uint8Array&&(y=`data:${T.mime??"image/png"};base64,${Buffer.from(T.image).toString("base64")}`),y&&o.push({type:"file",url:y,mime:T.mime??"image/png"});}else if(T.type==="file"){let y="";typeof T.data=="string"?y=T.data:T.data instanceof URL?y=T.data.toString():T.data instanceof Uint8Array&&(y=`data:${T.mime??"application/octet-stream"};base64,${Buffer.from(T.data).toString("base64")}`),y&&o.push({type:"file",url:y,mime:T.mime??"application/octet-stream"});}if(o.length===0){this.log.debug("empty message (no text/file/image), skip");return}this.config.setActivityStatus?.(i("tui.status.sending"));let l=e.metadata?.system,{thinkingLevel:c,contextMode:u,sessionInfo:d}=this.config.state,p=d.model?parseModelId(d.model):{provider:"",model:""},M=p.provider&&p.model?{providerId:p.provider,modelId:p.model}:void 0;this.log.debug("Calling SDK prompt via events",{partsCount:o.length,sessionId:a,model:M});let B=this.eventBus.subscribeAll(T=>{if(T.type===SdkEventType.SDK_SESSION_UPDATE){let y=T.properties;if(y.sessionId!==a)return;this.log.debug("SDK_SESSION_UPDATE event received",{sessionId:y.sessionId,updateKeys:Object.keys(y.update),sessionUpdate:y.update.sessionUpdate});let k=this.assembleTextFromUpdate(y.update);k&&(this.log.debug("Sending prompt result via event",{textLength:k.length}),this.sendMessage(i$1,k,"output",n,t));}});try{await this.config.state.sdk.session.prompt({sessionId:a,parts:o,agent:this.config.state.agent,...M?{model:M}:{},...c?{variant:c}:{},...u?{contextMode:u}:{},...l?{system:l}:{}});}catch(T){this.log.error("SDK prompt error",{error:String(T)}),this.sendMessage(i$1,`Error: ${String(T)}`,"output",n,t);}finally{B(),this.config.setActivityStatus?.("");}}},ct=class{constructor(e){b(this,"log");b(this,"client");b(this,"config");b(this,"connected",false);this.config=e,this.log=a.create({service:"tui-gateway-client"});let t=e.sessionId?`tui_${e.sessionId}`:"tui_default";this.client=new Q({url:e.gatewayUrl,type:"tui",id:t,heartbeat:{enabled:true,interval:6e4}}),this.client.onMessage(async n=>{if(!n){this.log.warn("received undefined message from gateway");return}this.log.debug("received message from gateway",{messageId:n.id,sessionId:n.sessionId,type:n.type}),e.onMessage&&await e.onMessage(n);}),this.client.onStateChange(async n=>{if(this.connected=n==="connected",e.onStateChange?.(n),n==="connected")try{let i=this.config.sessionId;i&&await this.client.subscribe(i);}catch(i){this.log.error("failed to subscribe",{error:String(i)});}});}async connect(){if(this.connected){this.log.warn("already connected");return}this.log.info("gateway client initialized, heartbeat will handle auto-reconnect",{url:this.config.gatewayUrl});}async disconnect(){this.connected&&(this.log.info("disconnecting from gateway"),this.config.sessionId&&await this.client.unsubscribe(this.config.sessionId),await this.client.disconnect(),this.connected=false,this.config.onStateChange?.("disconnected"),this.log.info("disconnected from gateway"));}async sendMessage(e,t,n="output",i,a,o){if(!this.connected)throw new Error("Not connected to gateway");if(!e)throw new Error("No gateway session ID available");await this.client.sendMessage(e,{content:[{type:"text",text:t}],channel:a?.platform,chatId:a?.chatId,userId:a?.userId,replyToMessageId:i,processorId:"tui",agent:o??"tui"}),this.log.debug("message sent via HTTP",{gatewaySessionId:e,type:n,replyToMessageId:i,hasChannelInfo:!!a,agent:o});}async subscribeMessage(e){if(!this.connected)throw new Error("Not connected to gateway");await this.client.subscribe(e),this.log.debug("subscribed to session",{sessionId:e});}async unsubscribeMessage(e){if(!this.connected)throw new Error("Not connected to gateway");await this.client.unsubscribe(e),this.log.debug("unsubscribed from session",{sessionId:e});}isConnected(){return this.connected}getClientId(){return this.client.getId()}getSubscribedSessions(){return this.client.getSubscriptions()}getState(){return this.client.getState()}async getStatus(){return this.client.getStatus()}generateId(){return `tui_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};function Zt(s){return new ct(s)}var me=a.create({service:"gateway-manager"}),ut=class{constructor(e){b(this,"config");b(this,"_client",null);b(this,"messageHandler",null);b(this,"connected",false);this.config=e;}get client(){return this._client}isConnected(){return this.connected}async connect(e){if(await this.disconnect(),!e){me.debug("No session ID, skipping gateway connection");return}me.debug("Connecting to gateway",{sessionId:e});try{this.messageHandler=new Ve({state:this.config.state,getGatewayClient:()=>this._client,setActivityStatus:this.config.setActivityStatus}),await this.messageHandler.start(),this._client=Zt({gatewayUrl:this.config.gatewayUrl,sessionId:e,onMessage:async t=>{this.messageHandler&&this.messageHandler.handleMessage(t);},onStateChange:t=>{me.debug("Gateway connection state changed",{state:t}),this.config.onConnectionChange?.(t==="connected");}}),await this._client.connect(),this.connected=!0,me.debug("Gateway connected successfully",{sessionId:e});}catch(t){throw me.error("Failed to connect to gateway",{sessionId:e,error:String(t)}),await this.disconnect(),t}}async disconnect(){if(!(!this.connected&&!this._client&&!this.messageHandler)){me.debug("Disconnecting from gateway");try{this._client&&await this._client.disconnect();}finally{this.messageHandler&&(await this.messageHandler.stop(),this.messageHandler=null),this._client=null,this.connected=false,this.config.onConnectionChange?.(false),me.debug("Gateway disconnected");}}}};function Xt(s){return new ut(s)}var D=a.create({service:"cli-tui-app"}),mt=null;function nn(s){mt=s;}function rn(){mt=null;}function pr(){return mt}async function hr(s,e){process.env.EASBOT_TUI_MODE="1";let t=new Container,n=new Container,i$1=Yt(),a=new Text(Z.header(i$1),1,0);n.addChild(a),t.addChild(n);let o=new He;t.addChild(o),o.setWidth(s.terminal.columns);let l=s.requestRender.bind(s);s.requestRender=(m=false)=>{o.setWidth(s.terminal.columns),l(m);};let c=new Container;t.addChild(c);let u=null,d=null,p=()=>{u&&d||(c.clear(),u=new Text("",1,0),d=new Text("",1,0),c.addChild(u),c.addChild(d));},M=new Container,B=new Text("",1,0);M.addChild(B),t.addChild(M);let T=new Container,y=new $e(s,_t);T.addChild(y),t.addChild(T);let k$1=Ht(),ge=Vt({basePath:e.directory||process.cwd(),slashCommands:k$1});y.setAutocompleteProvider(ge);let{state:h,unsubscribe:se}=await na({options:e,agent:e.agent,model:e.model,sessionId:e.sessionId},s,o,()=>{q();});D.debug("TUI state initialized",{agent:h.agent,model:h.sessionInfo.model,sessionId:h.currentSessionId}),o.init(),ge.setGetAgents(async()=>ta(h));try{k$1=await Rt(h.sdk,h.contextMode),ge.updateCommands?.(k$1),D.debug("Dynamic commands loaded with contextMode",{contextMode:h.contextMode,count:k$1.length});}catch(m){D.warn("Failed to load dynamic commands, using static commands only",{error:m});}o.setStateGetter(()=>h);let H=i("tui.status.idle"),F=i("tui.status.connection.local"),x="",g=null,f=H,L=new Set([i("tui.handler.send.sending"),i("tui.status.thinking"),i("tui.status.receiving"),i("tui.status.running"),i("tui.status.waiting"),i("tui.status.executing_step"),i("tui.status.sending"),i("tui.status.waiting_permission"),i("tui.status.waiting_answer"),i("tui.status.step_completed"),i("tui.status.tool_completed")]),b=m=>{if(L.has(m))return true;let P=i("tui.status.executing_tool",{vars:{tool:""}}).split(":")[0];if(m.startsWith(P))return true;let _=i("tui.handler.executing",{vars:{command:""}}).split(":")[0];return !!m.startsWith(_)},w=m=>{let P=Math.max(0,Math.floor((Date.now()-m)/1e3));if(P<60)return `${P}s`;let _=Math.floor(P/60),U=P%60;return `${_}m ${U}s`},v=()=>{if(p(),!u||!d)return;let m=b(H);f!==H&&(m?g=Date.now():g=null,f=H);let P=i("tui.status.label"),_=H;if(m&&g){let ns=w(g);_=`${_} \u2022 ${ns}`;}let U=`${P} ${_} | ${F}`;u.setText(Z.header(U));let le=h.showThinking?i("tui.system.on"):i("tui.system.off"),fe=h.toolsExpanded?i("tui.system.on"):i("tui.system.off"),be=[`ctrl+l: ${i("tui.keyhints.model")} | ctrl+g: ${i("tui.keyhints.agent")} | ctrl+p: ${i("tui.keyhints.session")} | ctrl+t: ${i("tui.keyhints.thinking")}(${le}) | ctrl+o: ${i("tui.keyhints.tools")}(${fe})`];x&&be.push(x);let et=be.join(" | ");d.setText(Z.header(et)),u.invalidate(),d.invalidate();},W=()=>{},Y=()=>{let m=h.agent||"unknown",P=h.sessionInfo.model||"unknown",_=h.currentSessionKey||"new",le=((fe,Pe)=>{if(!fe||fe===0)return "";let be=fe.toLocaleString();if(Pe&&Pe>0){let et=Math.round(fe/Pe*100);return ` | Tokens: ${be} (${et}%)`}return ` | Tokens: ${be}`})(h.sessionInfo.totalTokens,h.sessionInfo.contextTokens);B.setText(Z.dim(i("tui.footer.info",{vars:{agent:m,model:P,session:_,tokens:le}}))),B.invalidate();};v(),Y();let ee=false,q=()=>{ee||(ee=true,queueMicrotask(()=>{ee=false,s.requestRender();}));},gt=setInterval(()=>{g&&b(H)&&v(),Y(),q();},1e3),es=()=>{gt&&clearInterval(gt);},{openOverlay:ke,closeOverlay:re}=Kt(s,y),Je=()=>{h.currentSessionId&&(console.log(`
|
|
57
|
+
|
|
58
|
+
`),console.log(i("tui.exit.resume_hint",{vars:{sessionId:h.currentSessionId}})),console.log("")),s.stop(),e.onExit&&e.onExit(),process.exit(0);},Se=m=>{H=m||i("tui.status.idle"),v(),q();},Ze=(m,P)=>{x=m,v(),q(),P&&P>0&&setTimeout(()=>{x="",v(),q();},P);},pe={tui:s,chatLog:o,setActivityStatus:Se,sdk:h.sdk},Ae=Ot({chatLog:o,tui:s,directory:e.directory||process.cwd(),openOverlay:ke,closeOverlay:re,requestExit:Je,setActivityStatus:Se,updateStatusBar:v,updateFooter:Y,refreshSessionInfo:async()=>{h.currentSessionId&&await at(pe,h.currentSessionId);},loadHistory:async()=>{h.currentSessionId&&await qe(pe,h.currentSessionId,h.messageLimit);},setSession:async m=>{o.clear(),await Qt(pe,m,h),v(),Y(),q();},refreshAgents:async()=>{await Gt(pe);},abortActive:async()=>{h.currentSessionId&&await jt(pe,h.currentSessionId);},setInputText:m=>{y.setText(m),q();},reconnectGateway:async m=>{await la(async()=>{ne&&(await ne.connect(m),pt.client=ne.client);},"TUI_RECONNECT_GATEWAY",{directory:e.directory});},gatewayManager:{client:null,isConnected:()=>ne?.isConnected()??false}},h),pt=Ae.gatewayManager,oe=new We;oe.register(new je),oe.register(new Ne),oe.register(new Ge),oe.register(new Qe),oe.register(new xe),oe.register(new ze),oe.register(new Ke),y.onSubmit=async m=>{let _=m.trim();if(y.setText(""),!_)return;y.addToHistory(_);let U={chatLog:o,tui:s,state:h,setActivityStatus:Se,updateStatusBar:v,updateFooter:Y,sendMessage:Ae.sendMessage,handleCommand:Ae.handleCommand};await oe.handle(_,U);};let Xe=0;y.onCtrlC=()=>{let m=y.getText(),P=Date.now();m.trim()?(y.setText(""),Ze(i("tui.hint.input_cleared"),3e3),Xe=P):P-Xe<=1e3?Je():(Ze(i("tui.hint.press_ctrlc_exit"),3e3),Xe=P);},y.onCtrlD=()=>{Je();},y.onEscape=()=>{s.hasOverlay()&&re();},y.onCtrlL=async()=>{try{let m=await va(h),P=De(m,{onSelect:async _=>{h.sessionInfo.model=_.value,o.addSystem(i("tui.handler.model.set",{vars:{model:_.value}})),re(),b$2(h).catch(U=>{D.error("Failed to save TUI state after model change",{error:U});}),Y(),q();},onCancel:()=>{re();}});ke(P);}catch(m){D.error("Failed to open model selector",{error:m}),o.addSystem(i("tui.selector.model.error",{vars:{error:String(m)}})),q();}},y.onCtrlP=async()=>{try{let m=await ua(h),P=Be(m,{onSelect:async _=>{h.currentSessionKey=_.value,o.addSystem(i("tui.handler.session.switched",{vars:{sessionKey:_.value}})),re(),Y(),q();},onCancel:()=>{re();}});ke(P);}catch(m){D.error("Failed to open session selector",{error:m}),o.addSystem(i("tui.selector.session.error",{vars:{error:String(m)}})),q();}},y.onCtrlG=async()=>{try{let P=(await ta(h)).filter(U=>U.mode==="primary"&&U.hidden!==!0),_=Ue(P,{onSelect:async U=>{h.agent=U.value,o.addSystem(i("tui.handler.agent.switched",{vars:{agentId:U.value}})),re(),b$2(h).catch(le=>{D.error("Failed to save TUI state after agent change",{error:le});}),Y(),q();},onCancel:()=>{re();}});ke(_);}catch(m){D.error("Failed to open agent selector",{error:m}),o.addSystem(i("tui.selector.agent.error",{vars:{error:String(m)}})),q();}},y.onCtrlT=()=>{h.showThinking=!h.showThinking,o.addSystem(i("tui.system.thinking_mode",{vars:{mode:h.showThinking?i("tui.system.on"):i("tui.system.off")}})),b$2(h).catch(m=>{D.error("Failed to save TUI state after Ctrl+T",{error:m});}),v(),q();},y.onCtrlO=()=>{h.toolsExpanded=!h.toolsExpanded;let m=i("tui.system.tools_output",{vars:{mode:h.toolsExpanded?i("tui.system.expanded"):i("tui.system.collapsed")}});o.addSystem(m),Ze(h.toolsExpanded?i("tui.hint.tools_expanded"):i("tui.hint.tools_collapsed"),2e3),b$2(h).catch(P=>{D.error("Failed to save TUI state after Ctrl+O",{error:P});}),v(),q();},s.setFocus(y);let ts={tui:s,chatLog:o,sessionId:h.currentSessionId,setActivityStatus:Se,updateStatusBar:v,updateFooter:Y,updateChatLog:W,state:h},ss=Wt(ts),{TuiEvent:he}=await import('./event-2JDHF3UV.mjs'),ht=()=>{},ft=()=>{},yt=()=>{},St=()=>{},bt=()=>{},vt=()=>{};ht=await qa(h,he.StatusBarRefresh,async m=>{D.debug("StatusBarRefresh event received",{reason:m.properties.reason}),v(),q();}),ft=await qa(h,he.FooterBarRefresh,async m=>{D.debug("FooterBarRefresh event received",{reason:m.properties.reason}),Y(),q();}),yt=await qa(h,he.ChatLogRefresh,async m=>{D.debug("ChatLogRefresh event received",{reason:m.properties.reason}),q();}),St=await qa(h,he.CommandExecute,async m=>{D.debug("TUI CommandExecute event received",{command:m.properties.command}),await Ae.handleCommand(m.properties.command,m.properties.inputHandlerContext);}),bt=await qa(h,he.PromptAppend,async m=>{D.debug("TUI PromptAppend event received",{text:m.properties.text});let P=y.getText();y.setText(P+m.properties.text),q();}),vt=await qa(h,he.ToastShow,async m=>{D.debug("TUI ToastShow event received",{message:m.properties.message});let{title:P,message:_,variant:U}=m.properties,le=U==="error"?"\u274C ":U==="warning"?"\u26A0\uFE0F ":U==="success"?"\u2705 ":"\u2139\uFE0F ";o.addSystem(`${le}${P?`[${P}] `:""}${_}`),q();}),nn((m,P)=>{let _=m instanceof Error?m.message:String(m),U=m instanceof Error?m.stack:void 0;D.error(`Global ${P} caught`,{type:P,message:_,stack:U,errorType:m instanceof Error?m.constructor.name:typeof m,fullError:m}),_.includes("No context found for instance")&&D.error("Instance context error detected",{currentSessionId:h.currentSessionId,instanceContext:h.instanceContext,stackTrace:U}),o.addSystem(i(`tui.error.global.${P}`,{vars:{error:_}})),q();});let wt=new AbortController,ne=null;return h.sdk.global.event({signal:wt.signal}).then(async({stream:m})=>{if(D.debug("SDK event subscription successful"),h.currentSessionId){let _=await k();_?(ne=Xt({gatewayUrl:_,state:h,setActivityStatus:Se,onConnectionChange:U=>{F=U?i("tui.status.connection.gateway_connected"):i("tui.status.connection.local"),v();}}),await ne.connect(h.currentSessionId),pt.client=ne.client):D.debug("No gateway URL configured, skipping gateway client");}(async()=>{try{for await(let _ of m){let U=_.payload;ss(U);}}catch(_){D.debug("Event stream ended",{error:_});}})();let P=e.onExit;e.onExit=async()=>{D.debug("Unsubscribe events"),wt.abort(),se(),ht(),ft(),yt(),St(),bt(),vt(),es(),rn(),ne&&(await ne.disconnect(),ne=null,D.debug("Gateway manager disconnected")),delete process.env.EASBOT_TUI_MODE,D.debug("Cleared TUI mode environment variable"),P&&await P();};}).catch(m=>{D.error("SDK event subscription failed",{error:m});}),h.currentSessionId&&!h.historyLoaded&&(async()=>{try{await qe(pe,h.currentSessionId,h.messageLimit),h.historyLoaded=!0;}catch(m){D.error("Failed to auto-load history messages",{error:m});}})(),e.prompt&&setTimeout(()=>{y.setText(e.prompt),y.onSubmit?.(e.prompt);},100),D.debug("TUI app component created"),t}export{hr as createTuiApp,pr as getGlobalErrorHandler,nn as registerGlobalErrorHandler,rn as unregisterGlobalErrorHandler};
|