@easbot/acp 0.3.43 → 0.3.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -6,7 +6,7 @@ English | [中文](./README.md)
6
6
 
7
7
  ## Version
8
8
 
9
- v0.3.43
9
+ v0.3.45
10
10
 
11
11
  ## Introduction
12
12
 
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  ## 版本
8
8
 
9
- v0.3.43
9
+ v0.3.45
10
10
 
11
11
  ## 简介
12
12
 
@@ -1 +1 @@
1
- 'use strict';var chunk6LGQ6YHX_cjs=require('./chunk-6LGQ6YHX.cjs');require('./chunk-SNWAB3QJ.cjs'),require('./chunk-OQH5ALTQ.cjs'),require('./chunk-6VF3MZ6H.cjs'),require('./chunk-663BEBE4.cjs'),require('./chunk-RGGMCKYA.cjs'),require('./chunk-ISDIC2R6.cjs');Object.defineProperty(exports,"AdapterBootstrap",{enumerable:true,get:function(){return chunk6LGQ6YHX_cjs.y}});Object.defineProperty(exports,"EasbotAdapter",{enumerable:true,get:function(){return chunk6LGQ6YHX_cjs.x}});Object.defineProperty(exports,"createAdapterEnvironmentInitializationError",{enumerable:true,get:function(){return chunk6LGQ6YHX_cjs.w}});
1
+ 'use strict';var chunkMIFRHOYO_cjs=require('./chunk-MIFRHOYO.cjs');require('./chunk-SNWAB3QJ.cjs'),require('./chunk-OQH5ALTQ.cjs'),require('./chunk-6VF3MZ6H.cjs'),require('./chunk-663BEBE4.cjs'),require('./chunk-RGGMCKYA.cjs'),require('./chunk-ISDIC2R6.cjs');Object.defineProperty(exports,"AdapterBootstrap",{enumerable:true,get:function(){return chunkMIFRHOYO_cjs.y}});Object.defineProperty(exports,"EasbotAdapter",{enumerable:true,get:function(){return chunkMIFRHOYO_cjs.x}});Object.defineProperty(exports,"createAdapterEnvironmentInitializationError",{enumerable:true,get:function(){return chunkMIFRHOYO_cjs.w}});
@@ -1 +1 @@
1
- export{y as AdapterBootstrap,x as EasbotAdapter,w as createAdapterEnvironmentInitializationError}from'./chunk-KAXUGIGH.mjs';import'./chunk-B3ANZALB.mjs';import'./chunk-ZGY6CLVQ.mjs';import'./chunk-FAYVTNTB.mjs';import'./chunk-ZZK2JEUF.mjs';import'./chunk-WFIRDYOS.mjs';import'./chunk-HQBRVVXS.mjs';
1
+ export{y as AdapterBootstrap,x as EasbotAdapter,w as createAdapterEnvironmentInitializationError}from'./chunk-ONPG7IJS.mjs';import'./chunk-B3ANZALB.mjs';import'./chunk-ZGY6CLVQ.mjs';import'./chunk-FAYVTNTB.mjs';import'./chunk-ZZK2JEUF.mjs';import'./chunk-WFIRDYOS.mjs';import'./chunk-HQBRVVXS.mjs';
@@ -0,0 +1,8 @@
1
+ 'use strict';var chunkSNWAB3QJ_cjs=require('./chunk-SNWAB3QJ.cjs'),chunkRGGMCKYA_cjs=require('./chunk-RGGMCKYA.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var z={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var le=z.languages,de=le.filter(e=>e.supported).map(e=>e.value),x={defaultLocale:"zh-CN",timeZone:"Asia/Shanghai",locales:de},C={},P=(e,r)=>{let t=C[e]||{translation:{}};return C[e]={translation:{...t.translation,...r.translation}},C[e]},R=(e=x.defaultLocale)=>(C[e]||P(e,{translation:{}}),{locale:e,resources:C[e]||{translation:{}}}),je=e=>R(e),Oe=e=>C[e];var pe={translation:{"cli.banner.title":"easbot-acp \u2014 EASBot ACP\uFF08Agent Communication Protocol\uFF09\u9002\u914D\u5C42","cli.banner.usage":"Usage: easbot acp [options] [command]","cli.banner.section.lifecycle":"\u547D\u4EE4\uFF08\u751F\u547D\u5468\u671F\uFF09:","cli.banner.section.server":"\u547D\u4EE4\uFF08\u670D\u52A1\uFF09:","cli.banner.section.external":"\u5916\u90E8\u63A5\u53E3:","cli.banner.hint.run_help":"\u8FD0\u884C `easbot-acp <command> --help` \u67E5\u770B\u8BE6\u60C5\u3002","cli.banner.global_flags":"\u5168\u5C40\u9009\u9879: --cwd <dir> --config <path> --log-level <L> --print-logs --debug","cli.banner.local.title":"\u72EC\u7ACB CLI:","cli.banner.local.agent":"Agent CLI \u7528\u6237: `easbot acp <command> ...`","cli.banner.local.standalone":"\u72EC\u7ACB\u7528\u6237: `easbot-acp <command> ...`","cli.cmd.init.description":"\u521D\u59CB\u5316 acp \u5DE5\u4F5C\u533A\uFF08\u521B\u5EFA .easbot/acp.json\uFF09","cli.cmd.status.description":"\u663E\u793A acp \u914D\u7F6E\u6458\u8981\uFF08\u670D\u52A1\u901A\u9053 / \u7AEF\u53E3 / \u5BA2\u6237\u7AEF\uFF09","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u914D\u7F6E\u53EF\u52A0\u8F7D / schema \u5408\u6CD5 / \u4F9D\u8D56\u5B8C\u6574\uFF09","cli.cmd.start.description":"\u542F\u52A8 ACP \u670D\u52A1\uFF08stdio / http / websocket\uFF09\u5E76\u963B\u585E","cli.cmd.config.description":"\u663E\u793A / \u66F4\u65B0 acp \u914D\u7F6E\uFF08get / set key=value\uFF09","cli.shared.show_help":"\u663E\u793A\u6B64\u5E2E\u52A9","cli.init.usage":"\u7528\u6CD5: easbot-acp init [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--force] [--json]","cli.init.opt.channel":"--channel \u9ED8\u8BA4\u901A\u9053\uFF08\u9ED8\u8BA4 websocket\uFF09","cli.init.opt.port":"--port HTTP/WebSocket \u7AEF\u53E3\uFF08\u9ED8\u8BA4 3000\uFF09","cli.init.opt.hostname":"--hostname \u4E3B\u673A\u540D\uFF08\u9ED8\u8BA4 localhost\uFF09","cli.init.opt.force":"--force, -f \u8986\u76D6\u5DF2\u5B58\u5728\u7684\u914D\u7F6E","cli.init.opt.json":"--json \u4EE5 JSON \u683C\u5F0F\u8F93\u51FA\uFF08\u65E0 ANSI\uFF09","cli.init.exists":"acp \u914D\u7F6E\u5DF2\u5B58\u5728\u4E8E {{path}}\uFF08\u4F7F\u7528 --force \u8986\u76D6\uFF09","cli.init.created":"\u2713 acp \u914D\u7F6E\u5DF2\u521D\u59CB\u5316\u5230 {{path}}","cli.init.title":"\u521D\u59CB\u5316 acp \u5DE5\u4F5C\u533A","cli.init.error.title":"\u521D\u59CB\u5316\u5931\u8D25","cli.init.error.field":"\u8DEF\u5F84","cli.init.error.hint":"\u4F7F\u7528 --force \u8986\u76D6\uFF0C\u6216\u76F4\u63A5\u7F16\u8F91\u5DF2\u6709\u6587\u4EF6\u3002","cli.start.usage":"\u7528\u6CD5: easbot-acp start [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--timeout <ms>]","cli.start.description":"\u542F\u52A8 ACP \u670D\u52A1\uFF0C\u963B\u585E\u76F4\u5230 Ctrl+C / SIGTERM\u3002","cli.start.channel_default":"\u901A\u9053\u9ED8\u8BA4\u503C\u4E3A acp.json \u4E2D\u7684 server.channel\uFF08\u9ED8\u8BA4: websocket\uFF09\u3002","cli.start.opt.channel":"--channel \u901A\u9053\u7C7B\u578B\uFF08\u8986\u76D6\u914D\u7F6E\u6587\u4EF6\uFF09","cli.start.opt.port":"--port \u7AEF\u53E3\uFF08\u9ED8\u8BA4 3000\uFF09","cli.start.opt.hostname":"--hostname \u4E3B\u673A\u540D\uFF08\u9ED8\u8BA4 localhost\uFF09","cli.start.opt.timeout":"--timeout <ms> \u8BF7\u6C42\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09","cli.status.usage":"\u7528\u6CD5: easbot-acp status [--json]","cli.status.field.directory":"\u5DE5\u4F5C\u76EE\u5F55","cli.status.field.server":"\u670D\u52A1","cli.status.field.server_channel":"\u670D\u52A1\u901A\u9053","cli.status.field.server_port":"\u670D\u52A1\u7AEF\u53E3","cli.status.field.server_hostname":"\u670D\u52A1\u4E3B\u673A\u540D","cli.status.field.server_enabled":"\u670D\u52A1\u542F\u7528","cli.status.field.clients":"\u5BA2\u6237\u7AEF\u6570\u91CF","cli.doctor.usage":"\u7528\u6CD5: easbot-acp doctor [--json]","cli.doctor.field.acp_json_path":"acp.json \u8DEF\u5F84","cli.doctor.field.acp_json_exists":"acp.json \u5B58\u5728","cli.doctor.field.config_loadable":"\u914D\u7F6E\u53EF\u52A0\u8F7D","cli.doctor.field.config_error":"\u914D\u7F6E\u9519\u8BEF","cli.doctor.field.sdk_version":"SDK \u7248\u672C","cli.doctor.yes":"\u662F","cli.doctor.no":"\u5426","cli.config.usage":"\u7528\u6CD5: easbot-acp config <get|set> [key] [value] [--json]","cli.config.description":"\u8BFB\u53D6\u6216\u5199\u5165 acp \u914D\u7F6E\u3002","cli.config.subcommands":"\u5B50\u547D\u4EE4:","cli.config.get_help":"get [key] \u663E\u793A\u5168\u90E8\u5B57\u6BB5\uFF08\u6216\u6307\u5B9A key\uFF09","cli.config.set_help":"set <key> <value> \u66F4\u65B0\u5B57\u6BB5\uFF08\u81EA\u52A8\u8BC6\u522B number / boolean\uFF09","cli.config.examples":"\u793A\u4F8B:","cli.config.example_get":" easbot-acp config get server.channel","cli.config.example_set":" easbot-acp config set server.port 8080","cli.config.opt.json":"--json \u4EE5 JSON \u683C\u5F0F\u8F93\u51FA","cli.config.no_subcommand":"config \u9700\u8981\u5B50\u547D\u4EE4: get | set","cli.config.invalid_key":"\u65E0\u6548\u7684 key: {{key}}","cli.config.set_done":"\u2713 \u5DF2\u8BBE\u7F6E {{key}} = {{value}}","cli.config.get_done":"{{key}}: {{value}}","cli.config.field.key":"key","cli.config.field.value":"\u503C","cli.config.error.invalid_key.title":"\u65E0\u6548\u7684 key","cli.config.error.field.key":"key","cli.config.error.invalid_key.hint":'\u4F7F\u7528\u70B9\u53F7\u8DEF\u5F84\uFF0C\u4F8B\u5982 "server.channel"\u3002',"cli.config.error.no_subcommand.title":"\u7F3A\u5C11\u5B50\u547D\u4EE4","cli.config.error.no_subcommand.hint":'\u4F7F\u7528 "easbot-acp config get [key]" \u6216 "easbot-acp config set <key> <value>"\u3002',"acp.cli.command_failed":"acp CLI \u547D\u4EE4\u5931\u8D25","acp.cli.command_failed_title":"\u547D\u4EE4\u6267\u884C\u5931\u8D25","acp.cli.error_prefix":"[acp] {{cwd}} :: {{command}} \u5931\u8D25: {{message}}","acp.cli.error.field.command":"\u547D\u4EE4","acp.cli.error_hint":"\u4F7F\u7528 --debug \u91CD\u8DD1\u4EE5\u67E5\u770B\u5B8C\u6574\u5806\u6808\u3002","acp.cli.json_error_failed":"JSON \u8F93\u51FA\u5931\u8D25: {{message}}","acp.error.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","acp.error.unknown_command.title":"\u672A\u77E5\u547D\u4EE4","acp.error.unknown_command.field":"\u547D\u4EE4","acp.error.field_label":"\u5B57\u6BB5","acp.error.message_label":"\u6D88\u606F","acp.error.hint_label":"\u63D0\u793A","acp.start.bootstrapping":"\u6B63\u5728\u542F\u52A8 ACP \u670D\u52A1","acp.start.started":"ACP \u670D\u52A1\u542F\u52A8\u6210\u529F","acp.server.started":"ACP \u670D\u52A1\u5DF2\u542F\u52A8","acp.server.started_head":"ACP \u670D\u52A1\u5DF2\u542F\u52A8","acp.field.directory":"\u5DE5\u4F5C\u76EE\u5F55","acp.field.channel":"\u901A\u9053","acp.field.host":"\u5730\u5740","acp.field.timeout":"\u8D85\u65F6","acp.shutdown.received":"\u6536\u5230\u4FE1\u53F7 {{signal}}\uFF0C\u6B63\u5728\u5173\u95ED","acp.shutdown.error":"\u5173\u95ED\u8FC7\u7A0B\u4E2D\u51FA\u9519","acp.shutdown.destroy_error":"EasbotAdapter.destroy \u5931\u8D25","acp.shutdown.stdout_broken":"stdout pipe \u65AD\u5F00\uFF0C\u8FDB\u7A0B\u9000\u51FA","acp.error.config_not_found":"acp \u914D\u7F6E\u672A\u627E\u5230; \u8BF7\u5148\u8FD0\u884C `easbot-acp init` \u521B\u5EFA .easbot/acp.json","acp.error.config_validation":"acp \u914D\u7F6E schema \u6821\u9A8C\u5931\u8D25: {{path}}","acp.error.server_start_failed":"\u670D\u52A1\u542F\u52A8\u5931\u8D25\uFF08\u901A\u9053={{channel}}, \u7AEF\u53E3={{port}}, code={{code}}\uFF09","acp.error.client_connection_failed":"\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5931\u8D25\uFF08clientId={{clientId}}, \u901A\u9053={{channel}}\uFF09","acp.error.rpc_parse_failed":"JSON-RPC frame \u89E3\u6790\u5931\u8D25\uFF08method={{method}}\uFF09"}},H=pe;var fe={translation:{"cli.banner.title":"easbot-acp \u2014 EASBot ACP (Agent Communication Protocol) Adapter","cli.banner.usage":"Usage: easbot acp [options] [command]","cli.banner.section.lifecycle":"Commands (lifecycle):","cli.banner.section.server":"Commands (server):","cli.banner.section.external":"External:","cli.banner.hint.run_help":"Run `easbot-acp <command> --help` for details.","cli.banner.global_flags":"Global flags: --cwd <dir> --config <path> --log-level <L> --print-logs --debug","cli.banner.local.title":"Standalone CLI:","cli.banner.local.agent":"Agent CLI users: `easbot acp <command> ...`","cli.banner.local.standalone":"Standalone users: `easbot-acp <command> ...`","cli.cmd.init.description":"Initialize acp workspace (creates .easbot/acp.json)","cli.cmd.status.description":"Show acp config summary (server channel / port / clients)","cli.cmd.doctor.description":"Run health checks (config loadable / schema valid / deps)","cli.cmd.start.description":"Start ACP server (stdio / http / websocket) and block","cli.cmd.config.description":"Show / update acp configuration (get / set key=value)","cli.shared.show_help":"Show this help","cli.init.usage":"Usage: easbot-acp init [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--force] [--json]","cli.init.opt.channel":"--channel Default channel (default: websocket)","cli.init.opt.port":"--port HTTP/WebSocket port (default: 3000)","cli.init.opt.hostname":"--hostname Hostname (default: localhost)","cli.init.opt.force":"--force, -f Overwrite existing config","cli.init.opt.json":"--json Output as JSON (no ANSI)","cli.init.exists":"acp config already exists at {{path}} (use --force to overwrite)","cli.init.created":"\u2713 acp config initialized at {{path}}","cli.init.title":"init acp workspace","cli.init.error.title":"init failed","cli.init.error.field":"path","cli.init.error.hint":"Pass --force to overwrite, or edit the existing file.","cli.start.usage":"Usage: easbot-acp start [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--timeout <ms>]","cli.start.description":"Start an ACP server. Blocks until Ctrl+C / SIGTERM.","cli.start.channel_default":"Channel defaults to acp.json server.channel (default: websocket).","cli.start.opt.channel":"--channel Channel type (overrides config file)","cli.start.opt.port":"--port Port (default: 3000)","cli.start.opt.hostname":"--hostname Hostname (default: localhost)","cli.start.opt.timeout":"--timeout <ms> Request timeout in milliseconds","cli.status.usage":"Usage: easbot-acp status [--json]","cli.status.field.directory":"directory","cli.status.field.server":"server","cli.status.field.server_channel":"server.channel","cli.status.field.server_port":"server.port","cli.status.field.server_hostname":"server.hostname","cli.status.field.server_enabled":"server.enabled","cli.status.field.clients":"clients","cli.doctor.usage":"Usage: easbot-acp doctor [--json]","cli.doctor.field.acp_json_path":"acp.json path","cli.doctor.field.acp_json_exists":"acp.json exists","cli.doctor.field.config_loadable":"config loadable","cli.doctor.field.config_error":"config error","cli.doctor.field.sdk_version":"SDK version","cli.doctor.yes":"yes","cli.doctor.no":"no","cli.config.usage":"Usage: easbot-acp config <get|set> [key] [value] [--json]","cli.config.description":"Read or write acp configuration.","cli.config.subcommands":"Subcommands:","cli.config.get_help":"get [key] Show all fields (or a specific key)","cli.config.set_help":"set <key> <value> Update a field (auto-detects number / boolean)","cli.config.examples":"Examples:","cli.config.example_get":" easbot-acp config get server.channel","cli.config.example_set":" easbot-acp config set server.port 8080","cli.config.opt.json":"--json Output as JSON","cli.config.no_subcommand":"config requires a subcommand: get | set","cli.config.invalid_key":"Invalid key: {{key}}","cli.config.set_done":"\u2713 set {{key}} = {{value}}","cli.config.get_done":"{{key}}: {{value}}","cli.config.field.key":"key","cli.config.field.value":"value","cli.config.error.invalid_key.title":"invalid key","cli.config.error.field.key":"key","cli.config.error.invalid_key.hint":'Use dotted path like "server.channel".',"cli.config.error.no_subcommand.title":"missing subcommand","cli.config.error.no_subcommand.hint":'Use "easbot-acp config get [key]" or "easbot-acp config set <key> <value>".',"acp.cli.command_failed":"acp CLI command failed","acp.cli.command_failed_title":"command failed","acp.cli.error_prefix":"[acp] {{cwd}} :: {{command}} failed: {{message}}","acp.cli.error.field.command":"command","acp.cli.error_hint":"Re-run with --debug for full stack.","acp.cli.json_error_failed":"JSON output failed: {{message}}","acp.error.unknown_command":"Unknown command: {{command}}","acp.error.unknown_command.title":"unknown command","acp.error.unknown_command.field":"command","acp.error.field_label":"field","acp.error.message_label":"message","acp.error.hint_label":"hint","acp.start.bootstrapping":"Bootstrapping ACP server","acp.start.started":"ACP server started successfully","acp.server.started":"ACP Server Started","acp.server.started_head":"ACP Server Started","acp.field.directory":"directory","acp.field.channel":"channel","acp.field.host":"address","acp.field.timeout":"timeout","acp.shutdown.received":"Received signal {{signal}}, shutting down...","acp.shutdown.error":"Error during shutdown","acp.shutdown.destroy_error":"EasbotAdapter.destroy failed","acp.shutdown.stdout_broken":"stdout pipe broken, exiting","acp.error.config_not_found":"acp config not found; run `easbot-acp init` first to create .easbot/acp.json","acp.error.config_validation":"acp config schema validation failed: {{path}}","acp.error.server_start_failed":"server start failed (channel={{channel}}, port={{port}}, code={{code}})","acp.error.client_connection_failed":"client connection failed (clientId={{clientId}}, channel={{channel}})","acp.error.rpc_parse_failed":"JSON-RPC frame parse failed (method={{method}})"}},K=fe;var ge=()=>{R("zh-CN"),R("en-US"),P("zh-CN",H),P("en-US",K);};ge();var O=new Map;var ue=e=>{if(O.has(e))return O.get(e);let r=/{{\s*(\w+)\s*}}/g,t=[],n;for(;(n=r.exec(e))!==null;){let i=n[1];i&&!t.includes(i)&&t.push(i);}let l=new RegExp("{{\\s*("+t.join("|")+")\\s*}}","g"),c={keys:t,regex:l};return O.set(e,c),c},G=(e,r)=>{if(!e||typeof e!="string")return "";if(!r||Object.keys(r).length===0)return e;let{regex:t,keys:n}=ue(e);return n.length===0||!n.some(c=>c in r)?e:e.replace(t,(c,i)=>{let p=r[i];return p==null?"":String(p)})},F=e=>{if(e&&x.locales.includes(e))return e;let r=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(r){let t=r.replace(/_/g,"-");if(x.locales.includes(t))return t;let n=t.split("-")[0];if(n==="zh")return "zh-CN";if(n==="en")return "en-US"}return x.defaultLocale},M=e=>R(e).resources,V=(e,r={})=>{let t=F(r.locale),l=M(t)?.translation[e];if(l&&typeof l=="string"){let c=G(l,r.vars);return c!=null?String(c):String(e)}if(t!==x.defaultLocale){let i=M(x.defaultLocale)?.translation[e];if(i&&typeof i=="string"){let p=G(i,r.vars);return p!=null?String(p):String(e)}}return String(r.fallback??e)},o=V,Ge=(e,r={})=>({message:V(e,r),locale:F(r.locale),context:r.context??{}});function q(){return {version:1,created_at:new Date().toISOString(),server:{enabled:true,channel:"websocket",port:3e3,hostname:"localhost",timeout:3e4,http:{baseUrl:"http://localhost:3000",timeout:3e5},ws:{url:"ws://localhost:3000",timeout:3e5,batchSize:10,batchInterval:50,heartbeatInterval:3e4}},clients:{clients:[{id:"easbot-self",name:"EasBot Self",type:"easbot",channel:"websocket",connection:{ws:{url:"ws://localhost:3000",timeout:3e5,batchSize:10,batchInterval:50,heartbeatInterval:3e4}},autoConnect:false,priority:0}],defaultClientId:"easbot-self"}}}chunkRGGMCKYA_cjs.b.WS;var ke={directory:"directory",server:"server",channel:"channel",port:"port",hostname:"hostname",enabled:"enabled",clients:"clients"},ye={acpJsonPath:"acp.json path",acpJsonExists:"acp.json exists",configLoadable:"config loadable",configError:"config error",sdkVersion:"SDK version"},_e={directory:"directory",channel:"channel",host:"address",timeout:"timeout"},we={key:"key",value:"value"};function N(e){return e?terminal.Symbol.colorize("\u2713","success"):terminal.Symbol.colorize("\u2717","error")}function Ae(e){return terminal.colorize(terminal.isRich(),terminal.theme.heading,e)}function Y(e){let r=[],t=e.skipped?"config already exists at":"initialized at",n=terminal.formatSuccess(`acp ${t} ${e.configPath}`);return r.push(n),e.channel!==void 0&&r.push(terminal.formatKeyValue("channel",e.channel)),r.join(`
2
+ `)}function Z(e,r){let t={...ke,...r},n=[];n.push(terminal.formatKeyValue(t.directory,e.directory)),n.push(` ${Ae(t.server)}`);let l=e.server??{},c=l.channel??"websocket",i=l.port??3e3,p=l.hostname??"localhost",g=l.enabled??true;return n.push(` ${terminal.formatKeyValue(t.channel,c)}`),n.push(` ${terminal.formatKeyValue(t.port,String(i))}`),n.push(` ${terminal.formatKeyValue(t.hostname,p)}`),n.push(` ${terminal.formatKeyValue(t.enabled,N(g))}`),n.push(terminal.formatKeyValue(t.clients,String(e.clientCount))),n.join(`
3
+ `)}function Q(e,r){let t={...ye,...r},n=[];return n.push(terminal.formatKeyValue(t.acpJsonPath,e.acpJsonPath)),n.push(terminal.formatKeyValue(t.acpJsonExists,N(e.acpJsonExists))),n.push(terminal.formatKeyValue(t.configLoadable,N(e.configLoadable))),n.push(terminal.formatKeyValue(t.sdkVersion,e.sdkVersion)),!e.configLoadable&&e.configError&&n.push(terminal.formatKeyValue(t.configError,e.configError)),n.join(`
4
+ `)}function X(e,r){let t={..._e,...r},n=[];return e.head&&n.push(terminal.formatSuccess(e.head)),n.push(terminal.formatKeyValue(t.directory,e.directory)),n.push(terminal.formatKeyValue(t.channel,e.channel)),n.push(terminal.formatKeyValue(t.host,e.host)),n.push(terminal.formatKeyValue(t.timeout,e.timeout)),n.join(`
5
+ `)}function ee(e,r){let t={...we,...r},n=[],l=e.key??"(root)";return n.push(terminal.formatKeyValue(t.key,l)),n.push(terminal.formatKeyValue(t.value,e.value)),n.join(`
6
+ `)}function te(e){return terminal.formatSuccess(`set ${e.key} = ${e.value}`)}var xe={field:"field",message:"message",hint:"hint"};function ne(e,r){let t={...xe,...r},n=[];return n.push(terminal.formatError(e.title)),e.field!==void 0&&n.push(terminal.formatKeyValue(t.field,e.value??"")),n.push(terminal.formatKeyValue(t.message,e.message)),e.hint&&n.push(terminal.formatKeyValue(t.hint,e.hint)),n.join(`
7
+ `)}var oe="@agentclientprotocol/sdk/unstable (workspace dep)",Le=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize acp workspace (.easbot/acp.json)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show acp config summary (server channel / port / clients)",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (config loadable, schema valid, deps)",group:"lifecycle"},{i18nKey:"cli.cmd.start.description",name:"start",description:"Start ACP server (stdio / http / websocket) and block",group:"server"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / update acp configuration (get / set key=value)",group:"external"}];function ce(){let e=[["lifecycle","cli.banner.section.lifecycle"],["server","cli.banner.section.server"],["external","cli.banner.section.external"]];return {usage:o("cli.banner.usage",{fallback:"Usage: easbot acp [options] [command]"}),description:o("cli.banner.title",{fallback:"EASBot ACP (Agent Communication Protocol) Adapter"}),options:[{flags:"-h, --help",description:o("cli.shared.show_help",{fallback:"Show this help"})}],sections:e.map(([r,t])=>({title:o(t),commands:Le.filter(n=>n.group===r).map(n=>({name:n.name,description:o(n.i18nKey,{fallback:n.description})}))})),footer:[o("cli.banner.global_flags",{fallback:"Global flags: --cwd <dir> --config <path> --log-level <L> --print-logs --debug"}),`${o("cli.banner.local.standalone",{fallback:"Standalone users"})}: easbot-acp <command>`,`${o("cli.banner.local.agent",{fallback:"Agent CLI users"})}: easbot acp <command>`]}}function pt(){terminal.renderCliHelp(ce());}function Ee(){terminal.renderCliHelp(ce());}var y=utils.Log.create({service:"acp.cli"}),re=false;async function Re(){if(!re){re=true;try{await chunkSNWAB3QJ_cjs.r();}catch(e){y.warn("registerBusinessErrors failed",{error:utils.errorMeta(e)});}}}function Te(e,r){let t={...e??{}};return r.channel!==void 0&&(t.channel=r.channel),r.port!==void 0&&(t.port=r.port),r.hostname!==void 0&&(t.hostname=r.hostname),r.timeout!==void 0&&(t.timeout=r.timeout),t}function I(e,r,t,n){let l=n?.exitCode??1;if(r)terminal.emitJsonError(e,t.message);else {let c=n?.labels??{field:o("acp.error.field_label",{fallback:"field"}),message:o("acp.error.message_label",{fallback:"message"}),hint:o("acp.error.hint_label",{fallback:"hint"})};terminal.printHuman([ne(t,c)],{title:"error",boxed:true,tone:"error",stream:"stderr"});}return {code:l,handled:l===1,command:l===1?e:null}}async function ft(e,r){let[t,...n]=e;if(!t)return Ee(),{code:0,handled:true,command:null};await Re();let l=n.includes("--json");try{switch(t){case "init":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.init.usage")),console.log(""),console.log(o("cli.init.opt.channel")),console.log(o("cli.init.opt.port")),console.log(o("cli.init.opt.hostname")),console.log(o("cli.init.opt.force")),console.log(o("cli.init.opt.json")),{code:0,handled:!0,command:t};let{AcpCache:c}=await import('./cache-5PSUWHGW.cjs'),i=await c.getConfigPath(),p=await c.exists(),g=n.includes("--force");if(p&&!g){let s=o("cli.init.exists",{vars:{path:i}});return y.warn(s),I(t,l,{title:o("cli.init.error.title",{fallback:"init failed"}),field:o("cli.init.error.field",{fallback:"path"}),value:i,message:s,hint:o("cli.init.error.hint",{fallback:"Pass --force to overwrite, or edit the existing file."})})}let d=q();for(let s=0;s<n.length;s++){let m=n[s],u=n[s+1];m==="--channel"&&u?(d.server={...d.server??{},channel:u},s++):m==="--port"&&u?(d.server={...d.server??{},port:Number(u)},s++):m==="--hostname"&&u&&(d.server={...d.server??{},hostname:u},s++);}await c.writeAcpJson(d);let h={configPath:i},a=d.server?.channel;return l?terminal.emitJsonOk(h,{command:t}):terminal.printHuman([Y({configPath:i,channel:a})],{title:o("cli.init.title",{fallback:"init acp workspace"}),boxed:!0}),{code:0,handled:!0,command:t}}case "start":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.start.usage")),console.log(""),console.log(o("cli.start.description")),console.log(o("cli.start.channel_default")),console.log(""),console.log(o("cli.start.opt.channel")),console.log(o("cli.start.opt.port")),console.log(o("cli.start.opt.hostname")),console.log(o("cli.start.opt.timeout")),{code:0,handled:!0,command:t};let c={};for(let b=0;b<n.length;b++){let w=n[b],v=n[b+1];w==="--channel"&&v?(c.channel=v,b++):w==="--port"&&v?(c.port=Number(v),b++):w==="--hostname"&&v?(c.hostname=v,b++):w==="--timeout"&&v&&(c.timeout=Number(v),b++);}let{loadConfig:i}=await import('./config-QMFC2VIL.cjs'),g=(await i()).server??{},d=Te(g,c),h=d.channel??"websocket",a=h==="stdio"||h==="http"||h==="websocket"?h:"websocket",s=typeof d.port=="number"?d.port:3e3,m=typeof d.hostname=="string"?d.hostname:"localhost",u=typeof d.timeout=="number"?d.timeout:3e4;y.info("Bootstrapping ACP server",{channel:a,port:s,hostname:m,timeout:u,agentId:d.agentId});let{EasbotAdapter:k}=await import('./bootstrap-62VQO6JQ.cjs'),{ChannelType:_}=await import('./types-MQMNYZEY.cjs');await k.init({directory:r?.cwd??process.cwd(),printLogs:!1,logLevel:"INFO",channel:a==="stdio"?_.STDIO:a==="http"?_.HTTP:_.WS});let L=await k.ensureACPService({...d,directory:r?.cwd??process.cwd(),enabled:!0,channel:a,port:s,hostname:m,timeout:u}),U=chunkSNWAB3QJ_cjs.t({channel:a,hostname:m,port:s})??`unknown://${m}:${s}`;y.info("ACP server started successfully",{type:L.server?.type,url:U});let ae={directory:o("acp.field.directory"),channel:o("acp.field.channel"),host:o("acp.field.host"),timeout:o("acp.field.timeout")};terminal.printHuman([X({directory:r?.cwd??process.cwd(),channel:a,host:U,timeout:`${u}ms`,head:o("acp.server.started_head",{fallback:"ACP Server Started"})},ae)],{title:o("acp.server.started"),boxed:!0}),await new Promise(b=>{let w=!1,v=E=>{w||(w=!0,y.info(`Received ${E}, shutting down ACP server`,{signal:E}),b());};process.once("SIGINT",()=>v("SIGINT")),process.once("SIGTERM",()=>v("SIGTERM")),process.stdout.on("error",E=>{(E.code==="EPIPE"||E.code==="EIO")&&(y.info("stdout pipe broken, exiting ACP server"),v("STDOUT-BROKEN"));});});try{await k.destroy();}catch(b){y.warn("EasbotAdapter.destroy failed",{error:utils.errorMeta(b)});}return {code:0,handled:!0,command:t}}case "status":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.status.usage")),{code:0,handled:!0,command:t};let{loadConfig:c,getConfigDirectory:i}=await import('./config-QMFC2VIL.cjs'),p=await c(),g={directory:i(),server:p.server,clientCount:p.clients?.clients?.length??0};if(l)terminal.emitJsonOk(g,{command:t});else {let d={directory:o("cli.status.field.directory"),server:o("cli.status.field.server"),channel:o("cli.status.field.server_channel"),port:o("cli.status.field.server_port"),hostname:o("cli.status.field.server_hostname"),enabled:o("cli.status.field.server_enabled"),clients:o("cli.status.field.clients")};terminal.printHuman([Z({directory:g.directory,server:g.server,clientCount:g.clientCount},d)],{title:"acp status",boxed:!0});}return {code:0,handled:!0,command:t}}case "doctor":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.doctor.usage")),{code:0,handled:!0,command:t};let{AcpCache:c}=await import('./cache-5PSUWHGW.cjs'),{loadConfig:i}=await import('./config-QMFC2VIL.cjs'),p=await c.getConfigPath(),g=await c.exists(),d=!1,h;try{await i(),d=!0;}catch(s){h=utils.errorMeta(s).message;}let a={acpJson:{path:p,exists:g},configLoadable:d,configError:h,sdkVersion:oe};if(l)terminal.emitJsonOk(a,{command:t});else {let s={acpJsonPath:o("cli.doctor.field.acp_json_path"),acpJsonExists:o("cli.doctor.field.acp_json_exists"),configLoadable:o("cli.doctor.field.config_loadable"),configError:o("cli.doctor.field.config_error"),sdkVersion:o("cli.doctor.field.sdk_version")};terminal.printHuman([Q({acpJsonPath:p,acpJsonExists:g,configLoadable:d,configError:h,sdkVersion:oe},s)],{title:"acp doctor",boxed:!0});}return {code:0,handled:!0,command:t}}case "config":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.config.usage")),console.log(""),console.log(o("cli.config.description")),console.log(o("cli.config.subcommands")),console.log(` ${o("cli.config.get_help")}`),console.log(` ${o("cli.config.set_help")}`),console.log(""),console.log(o("cli.config.examples")),console.log(o("cli.config.example_get")),console.log(o("cli.config.example_set")),{code:0,handled:!0,command:t};let c=n[0],i=n[1],p=n[2],{AcpCache:g}=await import('./cache-5PSUWHGW.cjs'),{clearConfigCache:d}=await import('./config-QMFC2VIL.cjs');if(c==="set"&&i!==void 0&&p!==void 0){let h=await g.getAcpJson()??{},a=i.split(".").filter(k=>k.length>0);if(a.length===0)return I(t,l,{title:o("cli.config.error.invalid_key.title",{fallback:"invalid key"}),field:o("cli.config.error.field.key",{fallback:"key"}),value:i,message:o("cli.config.invalid_key",{vars:{key:i}}),hint:o("cli.config.error.invalid_key.hint",{fallback:'Use dotted path like "server.channel".'})});let s=h;for(let k=0;k<a.length-1;k++){let _=a[k],L=s[_];(typeof L!="object"||L===null||Array.isArray(L))&&(s[_]={}),s=s[_];}let m=a[a.length-1],u=p;return p==="true"?u=!0:p==="false"?u=!1:/^-?\d+(\.\d+)?$/.test(p)&&(u=Number(p)),s[m]=u,await g.writeAcpJson(h),d(),l?terminal.emitJsonOk({key:i,value:u},{command:t}):terminal.printHuman([te({key:i,value:JSON.stringify(u)})],{title:"acp config set",boxed:!0}),{code:0,handled:!0,command:t}}if(c==="get"){let a=await g.getAcpJson()??{};if(i){let s=i.split(".");for(let m of s)if(a&&typeof a=="object"&&m in a)a=a[m];else {a=void 0;break}}if(l)terminal.emitJsonOk({key:i,value:a},{command:t});else {let s={key:o("cli.config.field.key"),value:o("cli.config.field.value")},m=a==null?String(a):typeof a=="object"?JSON.stringify(a,null,2):String(a);terminal.printHuman([ee({key:i,value:m},s)],{title:"acp config get",boxed:!0});}return {code:0,handled:!0,command:t}}return console.error(o("cli.config.usage")),I(t,l,{title:o("cli.config.error.no_subcommand.title",{fallback:"missing subcommand"}),message:o("cli.config.usage"),hint:o("cli.config.error.no_subcommand.hint",{fallback:'Use "easbot-acp config get [key]" or "easbot-acp config set <key> <value>".'})})}default:{let c=o("acp.error.unknown_command",{vars:{command:t}}),i=o("cli.banner.hint.run_help");return y.warn(c),I(t??"__unknown__",l,{title:o("acp.error.unknown_command.title",{fallback:"unknown command"}),field:o("acp.error.unknown_command.field",{fallback:"command"}),value:t,message:c,hint:i},{exitCode:2})}}}catch(c){let i=utils.errorMeta(c),p=i.message;y.error(`acp command ${t} failed`,{command:t,error:i});let g=r?.cwd??"",d=o("acp.cli.error_prefix",{vars:{cwd:g,command:t,message:p}});return I(t??"__unknown__",l,{title:o("acp.cli.command_failed_title",{fallback:"command failed"}),message:d,hint:o("acp.cli.error_hint",{fallback:"Re-run with --debug for full stack."})})}}
8
+ exports.a=le;exports.b=de;exports.c=x;exports.d=P;exports.e=R;exports.f=je;exports.g=Oe;exports.h=V;exports.i=o;exports.j=Ge;exports.k=Le;exports.l=pt;exports.m=Ee;exports.n=Te;exports.o=ft;
@@ -0,0 +1,8 @@
1
+ import {t,r}from'./chunk-B3ANZALB.mjs';import {b}from'./chunk-WFIRDYOS.mjs';import {Log,errorMeta}from'@easbot/utils';import {renderCliHelp,emitJsonOk,printHuman,emitJsonError,formatSuccess,formatKeyValue,formatError,Symbol,colorize,isRich,theme}from'@easbot/terminal';var H={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var de=H.languages,pe=de.filter(e=>e.supported).map(e=>e.value),S={defaultLocale:"zh-CN",timeZone:"Asia/Shanghai",locales:pe},L={},j=(e,r)=>{let t=L[e]||{translation:{}};return L[e]={translation:{...t.translation,...r.translation}},L[e]},T=(e=S.defaultLocale)=>(L[e]||j(e,{translation:{}}),{locale:e,resources:L[e]||{translation:{}}}),Oe=e=>T(e),Ne=e=>L[e];var fe={translation:{"cli.banner.title":"easbot-acp \u2014 EASBot ACP\uFF08Agent Communication Protocol\uFF09\u9002\u914D\u5C42","cli.banner.usage":"Usage: easbot acp [options] [command]","cli.banner.section.lifecycle":"\u547D\u4EE4\uFF08\u751F\u547D\u5468\u671F\uFF09:","cli.banner.section.server":"\u547D\u4EE4\uFF08\u670D\u52A1\uFF09:","cli.banner.section.external":"\u5916\u90E8\u63A5\u53E3:","cli.banner.hint.run_help":"\u8FD0\u884C `easbot-acp <command> --help` \u67E5\u770B\u8BE6\u60C5\u3002","cli.banner.global_flags":"\u5168\u5C40\u9009\u9879: --cwd <dir> --config <path> --log-level <L> --print-logs --debug","cli.banner.local.title":"\u72EC\u7ACB CLI:","cli.banner.local.agent":"Agent CLI \u7528\u6237: `easbot acp <command> ...`","cli.banner.local.standalone":"\u72EC\u7ACB\u7528\u6237: `easbot-acp <command> ...`","cli.cmd.init.description":"\u521D\u59CB\u5316 acp \u5DE5\u4F5C\u533A\uFF08\u521B\u5EFA .easbot/acp.json\uFF09","cli.cmd.status.description":"\u663E\u793A acp \u914D\u7F6E\u6458\u8981\uFF08\u670D\u52A1\u901A\u9053 / \u7AEF\u53E3 / \u5BA2\u6237\u7AEF\uFF09","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u914D\u7F6E\u53EF\u52A0\u8F7D / schema \u5408\u6CD5 / \u4F9D\u8D56\u5B8C\u6574\uFF09","cli.cmd.start.description":"\u542F\u52A8 ACP \u670D\u52A1\uFF08stdio / http / websocket\uFF09\u5E76\u963B\u585E","cli.cmd.config.description":"\u663E\u793A / \u66F4\u65B0 acp \u914D\u7F6E\uFF08get / set key=value\uFF09","cli.shared.show_help":"\u663E\u793A\u6B64\u5E2E\u52A9","cli.init.usage":"\u7528\u6CD5: easbot-acp init [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--force] [--json]","cli.init.opt.channel":"--channel \u9ED8\u8BA4\u901A\u9053\uFF08\u9ED8\u8BA4 websocket\uFF09","cli.init.opt.port":"--port HTTP/WebSocket \u7AEF\u53E3\uFF08\u9ED8\u8BA4 3000\uFF09","cli.init.opt.hostname":"--hostname \u4E3B\u673A\u540D\uFF08\u9ED8\u8BA4 localhost\uFF09","cli.init.opt.force":"--force, -f \u8986\u76D6\u5DF2\u5B58\u5728\u7684\u914D\u7F6E","cli.init.opt.json":"--json \u4EE5 JSON \u683C\u5F0F\u8F93\u51FA\uFF08\u65E0 ANSI\uFF09","cli.init.exists":"acp \u914D\u7F6E\u5DF2\u5B58\u5728\u4E8E {{path}}\uFF08\u4F7F\u7528 --force \u8986\u76D6\uFF09","cli.init.created":"\u2713 acp \u914D\u7F6E\u5DF2\u521D\u59CB\u5316\u5230 {{path}}","cli.init.title":"\u521D\u59CB\u5316 acp \u5DE5\u4F5C\u533A","cli.init.error.title":"\u521D\u59CB\u5316\u5931\u8D25","cli.init.error.field":"\u8DEF\u5F84","cli.init.error.hint":"\u4F7F\u7528 --force \u8986\u76D6\uFF0C\u6216\u76F4\u63A5\u7F16\u8F91\u5DF2\u6709\u6587\u4EF6\u3002","cli.start.usage":"\u7528\u6CD5: easbot-acp start [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--timeout <ms>]","cli.start.description":"\u542F\u52A8 ACP \u670D\u52A1\uFF0C\u963B\u585E\u76F4\u5230 Ctrl+C / SIGTERM\u3002","cli.start.channel_default":"\u901A\u9053\u9ED8\u8BA4\u503C\u4E3A acp.json \u4E2D\u7684 server.channel\uFF08\u9ED8\u8BA4: websocket\uFF09\u3002","cli.start.opt.channel":"--channel \u901A\u9053\u7C7B\u578B\uFF08\u8986\u76D6\u914D\u7F6E\u6587\u4EF6\uFF09","cli.start.opt.port":"--port \u7AEF\u53E3\uFF08\u9ED8\u8BA4 3000\uFF09","cli.start.opt.hostname":"--hostname \u4E3B\u673A\u540D\uFF08\u9ED8\u8BA4 localhost\uFF09","cli.start.opt.timeout":"--timeout <ms> \u8BF7\u6C42\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09","cli.status.usage":"\u7528\u6CD5: easbot-acp status [--json]","cli.status.field.directory":"\u5DE5\u4F5C\u76EE\u5F55","cli.status.field.server":"\u670D\u52A1","cli.status.field.server_channel":"\u670D\u52A1\u901A\u9053","cli.status.field.server_port":"\u670D\u52A1\u7AEF\u53E3","cli.status.field.server_hostname":"\u670D\u52A1\u4E3B\u673A\u540D","cli.status.field.server_enabled":"\u670D\u52A1\u542F\u7528","cli.status.field.clients":"\u5BA2\u6237\u7AEF\u6570\u91CF","cli.doctor.usage":"\u7528\u6CD5: easbot-acp doctor [--json]","cli.doctor.field.acp_json_path":"acp.json \u8DEF\u5F84","cli.doctor.field.acp_json_exists":"acp.json \u5B58\u5728","cli.doctor.field.config_loadable":"\u914D\u7F6E\u53EF\u52A0\u8F7D","cli.doctor.field.config_error":"\u914D\u7F6E\u9519\u8BEF","cli.doctor.field.sdk_version":"SDK \u7248\u672C","cli.doctor.yes":"\u662F","cli.doctor.no":"\u5426","cli.config.usage":"\u7528\u6CD5: easbot-acp config <get|set> [key] [value] [--json]","cli.config.description":"\u8BFB\u53D6\u6216\u5199\u5165 acp \u914D\u7F6E\u3002","cli.config.subcommands":"\u5B50\u547D\u4EE4:","cli.config.get_help":"get [key] \u663E\u793A\u5168\u90E8\u5B57\u6BB5\uFF08\u6216\u6307\u5B9A key\uFF09","cli.config.set_help":"set <key> <value> \u66F4\u65B0\u5B57\u6BB5\uFF08\u81EA\u52A8\u8BC6\u522B number / boolean\uFF09","cli.config.examples":"\u793A\u4F8B:","cli.config.example_get":" easbot-acp config get server.channel","cli.config.example_set":" easbot-acp config set server.port 8080","cli.config.opt.json":"--json \u4EE5 JSON \u683C\u5F0F\u8F93\u51FA","cli.config.no_subcommand":"config \u9700\u8981\u5B50\u547D\u4EE4: get | set","cli.config.invalid_key":"\u65E0\u6548\u7684 key: {{key}}","cli.config.set_done":"\u2713 \u5DF2\u8BBE\u7F6E {{key}} = {{value}}","cli.config.get_done":"{{key}}: {{value}}","cli.config.field.key":"key","cli.config.field.value":"\u503C","cli.config.error.invalid_key.title":"\u65E0\u6548\u7684 key","cli.config.error.field.key":"key","cli.config.error.invalid_key.hint":'\u4F7F\u7528\u70B9\u53F7\u8DEF\u5F84\uFF0C\u4F8B\u5982 "server.channel"\u3002',"cli.config.error.no_subcommand.title":"\u7F3A\u5C11\u5B50\u547D\u4EE4","cli.config.error.no_subcommand.hint":'\u4F7F\u7528 "easbot-acp config get [key]" \u6216 "easbot-acp config set <key> <value>"\u3002',"acp.cli.command_failed":"acp CLI \u547D\u4EE4\u5931\u8D25","acp.cli.command_failed_title":"\u547D\u4EE4\u6267\u884C\u5931\u8D25","acp.cli.error_prefix":"[acp] {{cwd}} :: {{command}} \u5931\u8D25: {{message}}","acp.cli.error.field.command":"\u547D\u4EE4","acp.cli.error_hint":"\u4F7F\u7528 --debug \u91CD\u8DD1\u4EE5\u67E5\u770B\u5B8C\u6574\u5806\u6808\u3002","acp.cli.json_error_failed":"JSON \u8F93\u51FA\u5931\u8D25: {{message}}","acp.error.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","acp.error.unknown_command.title":"\u672A\u77E5\u547D\u4EE4","acp.error.unknown_command.field":"\u547D\u4EE4","acp.error.field_label":"\u5B57\u6BB5","acp.error.message_label":"\u6D88\u606F","acp.error.hint_label":"\u63D0\u793A","acp.start.bootstrapping":"\u6B63\u5728\u542F\u52A8 ACP \u670D\u52A1","acp.start.started":"ACP \u670D\u52A1\u542F\u52A8\u6210\u529F","acp.server.started":"ACP \u670D\u52A1\u5DF2\u542F\u52A8","acp.server.started_head":"ACP \u670D\u52A1\u5DF2\u542F\u52A8","acp.field.directory":"\u5DE5\u4F5C\u76EE\u5F55","acp.field.channel":"\u901A\u9053","acp.field.host":"\u5730\u5740","acp.field.timeout":"\u8D85\u65F6","acp.shutdown.received":"\u6536\u5230\u4FE1\u53F7 {{signal}}\uFF0C\u6B63\u5728\u5173\u95ED","acp.shutdown.error":"\u5173\u95ED\u8FC7\u7A0B\u4E2D\u51FA\u9519","acp.shutdown.destroy_error":"EasbotAdapter.destroy \u5931\u8D25","acp.shutdown.stdout_broken":"stdout pipe \u65AD\u5F00\uFF0C\u8FDB\u7A0B\u9000\u51FA","acp.error.config_not_found":"acp \u914D\u7F6E\u672A\u627E\u5230; \u8BF7\u5148\u8FD0\u884C `easbot-acp init` \u521B\u5EFA .easbot/acp.json","acp.error.config_validation":"acp \u914D\u7F6E schema \u6821\u9A8C\u5931\u8D25: {{path}}","acp.error.server_start_failed":"\u670D\u52A1\u542F\u52A8\u5931\u8D25\uFF08\u901A\u9053={{channel}}, \u7AEF\u53E3={{port}}, code={{code}}\uFF09","acp.error.client_connection_failed":"\u5BA2\u6237\u7AEF\u8FDE\u63A5\u5931\u8D25\uFF08clientId={{clientId}}, \u901A\u9053={{channel}}\uFF09","acp.error.rpc_parse_failed":"JSON-RPC frame \u89E3\u6790\u5931\u8D25\uFF08method={{method}}\uFF09"}},K=fe;var ge={translation:{"cli.banner.title":"easbot-acp \u2014 EASBot ACP (Agent Communication Protocol) Adapter","cli.banner.usage":"Usage: easbot acp [options] [command]","cli.banner.section.lifecycle":"Commands (lifecycle):","cli.banner.section.server":"Commands (server):","cli.banner.section.external":"External:","cli.banner.hint.run_help":"Run `easbot-acp <command> --help` for details.","cli.banner.global_flags":"Global flags: --cwd <dir> --config <path> --log-level <L> --print-logs --debug","cli.banner.local.title":"Standalone CLI:","cli.banner.local.agent":"Agent CLI users: `easbot acp <command> ...`","cli.banner.local.standalone":"Standalone users: `easbot-acp <command> ...`","cli.cmd.init.description":"Initialize acp workspace (creates .easbot/acp.json)","cli.cmd.status.description":"Show acp config summary (server channel / port / clients)","cli.cmd.doctor.description":"Run health checks (config loadable / schema valid / deps)","cli.cmd.start.description":"Start ACP server (stdio / http / websocket) and block","cli.cmd.config.description":"Show / update acp configuration (get / set key=value)","cli.shared.show_help":"Show this help","cli.init.usage":"Usage: easbot-acp init [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--force] [--json]","cli.init.opt.channel":"--channel Default channel (default: websocket)","cli.init.opt.port":"--port HTTP/WebSocket port (default: 3000)","cli.init.opt.hostname":"--hostname Hostname (default: localhost)","cli.init.opt.force":"--force, -f Overwrite existing config","cli.init.opt.json":"--json Output as JSON (no ANSI)","cli.init.exists":"acp config already exists at {{path}} (use --force to overwrite)","cli.init.created":"\u2713 acp config initialized at {{path}}","cli.init.title":"init acp workspace","cli.init.error.title":"init failed","cli.init.error.field":"path","cli.init.error.hint":"Pass --force to overwrite, or edit the existing file.","cli.start.usage":"Usage: easbot-acp start [--channel <stdio|http|websocket>] [--port <n>] [--hostname <addr>] [--timeout <ms>]","cli.start.description":"Start an ACP server. Blocks until Ctrl+C / SIGTERM.","cli.start.channel_default":"Channel defaults to acp.json server.channel (default: websocket).","cli.start.opt.channel":"--channel Channel type (overrides config file)","cli.start.opt.port":"--port Port (default: 3000)","cli.start.opt.hostname":"--hostname Hostname (default: localhost)","cli.start.opt.timeout":"--timeout <ms> Request timeout in milliseconds","cli.status.usage":"Usage: easbot-acp status [--json]","cli.status.field.directory":"directory","cli.status.field.server":"server","cli.status.field.server_channel":"server.channel","cli.status.field.server_port":"server.port","cli.status.field.server_hostname":"server.hostname","cli.status.field.server_enabled":"server.enabled","cli.status.field.clients":"clients","cli.doctor.usage":"Usage: easbot-acp doctor [--json]","cli.doctor.field.acp_json_path":"acp.json path","cli.doctor.field.acp_json_exists":"acp.json exists","cli.doctor.field.config_loadable":"config loadable","cli.doctor.field.config_error":"config error","cli.doctor.field.sdk_version":"SDK version","cli.doctor.yes":"yes","cli.doctor.no":"no","cli.config.usage":"Usage: easbot-acp config <get|set> [key] [value] [--json]","cli.config.description":"Read or write acp configuration.","cli.config.subcommands":"Subcommands:","cli.config.get_help":"get [key] Show all fields (or a specific key)","cli.config.set_help":"set <key> <value> Update a field (auto-detects number / boolean)","cli.config.examples":"Examples:","cli.config.example_get":" easbot-acp config get server.channel","cli.config.example_set":" easbot-acp config set server.port 8080","cli.config.opt.json":"--json Output as JSON","cli.config.no_subcommand":"config requires a subcommand: get | set","cli.config.invalid_key":"Invalid key: {{key}}","cli.config.set_done":"\u2713 set {{key}} = {{value}}","cli.config.get_done":"{{key}}: {{value}}","cli.config.field.key":"key","cli.config.field.value":"value","cli.config.error.invalid_key.title":"invalid key","cli.config.error.field.key":"key","cli.config.error.invalid_key.hint":'Use dotted path like "server.channel".',"cli.config.error.no_subcommand.title":"missing subcommand","cli.config.error.no_subcommand.hint":'Use "easbot-acp config get [key]" or "easbot-acp config set <key> <value>".',"acp.cli.command_failed":"acp CLI command failed","acp.cli.command_failed_title":"command failed","acp.cli.error_prefix":"[acp] {{cwd}} :: {{command}} failed: {{message}}","acp.cli.error.field.command":"command","acp.cli.error_hint":"Re-run with --debug for full stack.","acp.cli.json_error_failed":"JSON output failed: {{message}}","acp.error.unknown_command":"Unknown command: {{command}}","acp.error.unknown_command.title":"unknown command","acp.error.unknown_command.field":"command","acp.error.field_label":"field","acp.error.message_label":"message","acp.error.hint_label":"hint","acp.start.bootstrapping":"Bootstrapping ACP server","acp.start.started":"ACP server started successfully","acp.server.started":"ACP Server Started","acp.server.started_head":"ACP Server Started","acp.field.directory":"directory","acp.field.channel":"channel","acp.field.host":"address","acp.field.timeout":"timeout","acp.shutdown.received":"Received signal {{signal}}, shutting down...","acp.shutdown.error":"Error during shutdown","acp.shutdown.destroy_error":"EasbotAdapter.destroy failed","acp.shutdown.stdout_broken":"stdout pipe broken, exiting","acp.error.config_not_found":"acp config not found; run `easbot-acp init` first to create .easbot/acp.json","acp.error.config_validation":"acp config schema validation failed: {{path}}","acp.error.server_start_failed":"server start failed (channel={{channel}}, port={{port}}, code={{code}})","acp.error.client_connection_failed":"client connection failed (clientId={{clientId}}, channel={{channel}})","acp.error.rpc_parse_failed":"JSON-RPC frame parse failed (method={{method}})"}},G=ge;var ue=()=>{T("zh-CN"),T("en-US"),j("zh-CN",K),j("en-US",G);};ue();var N=new Map;var me=e=>{if(N.has(e))return N.get(e);let r=/{{\s*(\w+)\s*}}/g,t=[],n;for(;(n=r.exec(e))!==null;){let i=n[1];i&&!t.includes(i)&&t.push(i);}let l=new RegExp("{{\\s*("+t.join("|")+")\\s*}}","g"),c={keys:t,regex:l};return N.set(e,c),c},M=(e,r)=>{if(!e||typeof e!="string")return "";if(!r||Object.keys(r).length===0)return e;let{regex:t,keys:n}=me(e);return n.length===0||!n.some(c=>c in r)?e:e.replace(t,(c,i)=>{let p=r[i];return p==null?"":String(p)})},V=e=>{if(e&&S.locales.includes(e))return e;let r=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(r){let t=r.replace(/_/g,"-");if(S.locales.includes(t))return t;let n=t.split("-")[0];if(n==="zh")return "zh-CN";if(n==="en")return "en-US"}return S.defaultLocale},F=e=>T(e).resources,q=(e,r={})=>{let t=V(r.locale),l=F(t)?.translation[e];if(l&&typeof l=="string"){let c=M(l,r.vars);return c!=null?String(c):String(e)}if(t!==S.defaultLocale){let i=F(S.defaultLocale)?.translation[e];if(i&&typeof i=="string"){let p=M(i,r.vars);return p!=null?String(p):String(e)}}return String(r.fallback??e)},o=q,Me=(e,r={})=>({message:q(e,r),locale:V(r.locale),context:r.context??{}});function W(){return {version:1,created_at:new Date().toISOString(),server:{enabled:true,channel:"websocket",port:3e3,hostname:"localhost",timeout:3e4,http:{baseUrl:"http://localhost:3000",timeout:3e5},ws:{url:"ws://localhost:3000",timeout:3e5,batchSize:10,batchInterval:50,heartbeatInterval:3e4}},clients:{clients:[{id:"easbot-self",name:"EasBot Self",type:"easbot",channel:"websocket",connection:{ws:{url:"ws://localhost:3000",timeout:3e5,batchSize:10,batchInterval:50,heartbeatInterval:3e4}},autoConnect:false,priority:0}],defaultClientId:"easbot-self"}}}b.WS;var ye={directory:"directory",server:"server",channel:"channel",port:"port",hostname:"hostname",enabled:"enabled",clients:"clients"},_e={acpJsonPath:"acp.json path",acpJsonExists:"acp.json exists",configLoadable:"config loadable",configError:"config error",sdkVersion:"SDK version"},we={directory:"directory",channel:"channel",host:"address",timeout:"timeout"},Ae={key:"key",value:"value"};function J(e){return e?Symbol.colorize("\u2713","success"):Symbol.colorize("\u2717","error")}function xe(e){return colorize(isRich(),theme.heading,e)}function Z(e){let r=[],t=e.skipped?"config already exists at":"initialized at",n=formatSuccess(`acp ${t} ${e.configPath}`);return r.push(n),e.channel!==void 0&&r.push(formatKeyValue("channel",e.channel)),r.join(`
2
+ `)}function Q(e,r){let t={...ye,...r},n=[];n.push(formatKeyValue(t.directory,e.directory)),n.push(` ${xe(t.server)}`);let l=e.server??{},c=l.channel??"websocket",i=l.port??3e3,p=l.hostname??"localhost",g=l.enabled??true;return n.push(` ${formatKeyValue(t.channel,c)}`),n.push(` ${formatKeyValue(t.port,String(i))}`),n.push(` ${formatKeyValue(t.hostname,p)}`),n.push(` ${formatKeyValue(t.enabled,J(g))}`),n.push(formatKeyValue(t.clients,String(e.clientCount))),n.join(`
3
+ `)}function X(e,r){let t={..._e,...r},n=[];return n.push(formatKeyValue(t.acpJsonPath,e.acpJsonPath)),n.push(formatKeyValue(t.acpJsonExists,J(e.acpJsonExists))),n.push(formatKeyValue(t.configLoadable,J(e.configLoadable))),n.push(formatKeyValue(t.sdkVersion,e.sdkVersion)),!e.configLoadable&&e.configError&&n.push(formatKeyValue(t.configError,e.configError)),n.join(`
4
+ `)}function ee(e,r){let t={...we,...r},n=[];return e.head&&n.push(formatSuccess(e.head)),n.push(formatKeyValue(t.directory,e.directory)),n.push(formatKeyValue(t.channel,e.channel)),n.push(formatKeyValue(t.host,e.host)),n.push(formatKeyValue(t.timeout,e.timeout)),n.join(`
5
+ `)}function te(e,r){let t={...Ae,...r},n=[],l=e.key??"(root)";return n.push(formatKeyValue(t.key,l)),n.push(formatKeyValue(t.value,e.value)),n.join(`
6
+ `)}function ne(e){return formatSuccess(`set ${e.key} = ${e.value}`)}var Se={field:"field",message:"message",hint:"hint"};function oe(e,r){let t={...Se,...r},n=[];return n.push(formatError(e.title)),e.field!==void 0&&n.push(formatKeyValue(t.field,e.value??"")),n.push(formatKeyValue(t.message,e.message)),e.hint&&n.push(formatKeyValue(t.hint,e.hint)),n.join(`
7
+ `)}var re="@agentclientprotocol/sdk/unstable (workspace dep)",Ee=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize acp workspace (.easbot/acp.json)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show acp config summary (server channel / port / clients)",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (config loadable, schema valid, deps)",group:"lifecycle"},{i18nKey:"cli.cmd.start.description",name:"start",description:"Start ACP server (stdio / http / websocket) and block",group:"server"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / update acp configuration (get / set key=value)",group:"external"}];function ae(){let e=[["lifecycle","cli.banner.section.lifecycle"],["server","cli.banner.section.server"],["external","cli.banner.section.external"]];return {usage:o("cli.banner.usage",{fallback:"Usage: easbot acp [options] [command]"}),description:o("cli.banner.title",{fallback:"EASBot ACP (Agent Communication Protocol) Adapter"}),options:[{flags:"-h, --help",description:o("cli.shared.show_help",{fallback:"Show this help"})}],sections:e.map(([r,t])=>({title:o(t),commands:Ee.filter(n=>n.group===r).map(n=>({name:n.name,description:o(n.i18nKey,{fallback:n.description})}))})),footer:[o("cli.banner.global_flags",{fallback:"Global flags: --cwd <dir> --config <path> --log-level <L> --print-logs --debug"}),`${o("cli.banner.local.standalone",{fallback:"Standalone users"})}: easbot-acp <command>`,`${o("cli.banner.local.agent",{fallback:"Agent CLI users"})}: easbot acp <command>`]}}function ft(){renderCliHelp(ae());}function Re(){renderCliHelp(ae());}var y=Log.create({service:"acp.cli"}),ie=false;async function Te(){if(!ie){ie=true;try{await r();}catch(e){y.warn("registerBusinessErrors failed",{error:errorMeta(e)});}}}function Ie(e,r){let t={...e??{}};return r.channel!==void 0&&(t.channel=r.channel),r.port!==void 0&&(t.port=r.port),r.hostname!==void 0&&(t.hostname=r.hostname),r.timeout!==void 0&&(t.timeout=r.timeout),t}function P(e,r,t,n){let l=n?.exitCode??1;if(r)emitJsonError(e,t.message);else {let c=n?.labels??{field:o("acp.error.field_label",{fallback:"field"}),message:o("acp.error.message_label",{fallback:"message"}),hint:o("acp.error.hint_label",{fallback:"hint"})};printHuman([oe(t,c)],{title:"error",boxed:true,tone:"error",stream:"stderr"});}return {code:l,handled:l===1,command:l===1?e:null}}async function gt(e,r){let[t$1,...n]=e;if(!t$1)return Re(),{code:0,handled:true,command:null};await Te();let l=n.includes("--json");try{switch(t$1){case "init":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.init.usage")),console.log(""),console.log(o("cli.init.opt.channel")),console.log(o("cli.init.opt.port")),console.log(o("cli.init.opt.hostname")),console.log(o("cli.init.opt.force")),console.log(o("cli.init.opt.json")),{code:0,handled:!0,command:t$1};let{AcpCache:c}=await import('./cache-O43SNRV2.mjs'),i=await c.getConfigPath(),p=await c.exists(),g=n.includes("--force");if(p&&!g){let s=o("cli.init.exists",{vars:{path:i}});return y.warn(s),P(t$1,l,{title:o("cli.init.error.title",{fallback:"init failed"}),field:o("cli.init.error.field",{fallback:"path"}),value:i,message:s,hint:o("cli.init.error.hint",{fallback:"Pass --force to overwrite, or edit the existing file."})})}let d=W();for(let s=0;s<n.length;s++){let m=n[s],u=n[s+1];m==="--channel"&&u?(d.server={...d.server??{},channel:u},s++):m==="--port"&&u?(d.server={...d.server??{},port:Number(u)},s++):m==="--hostname"&&u&&(d.server={...d.server??{},hostname:u},s++);}await c.writeAcpJson(d);let h={configPath:i},a=d.server?.channel;return l?emitJsonOk(h,{command:t$1}):printHuman([Z({configPath:i,channel:a})],{title:o("cli.init.title",{fallback:"init acp workspace"}),boxed:!0}),{code:0,handled:!0,command:t$1}}case "start":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.start.usage")),console.log(""),console.log(o("cli.start.description")),console.log(o("cli.start.channel_default")),console.log(""),console.log(o("cli.start.opt.channel")),console.log(o("cli.start.opt.port")),console.log(o("cli.start.opt.hostname")),console.log(o("cli.start.opt.timeout")),{code:0,handled:!0,command:t$1};let c={};for(let b=0;b<n.length;b++){let w=n[b],v=n[b+1];w==="--channel"&&v?(c.channel=v,b++):w==="--port"&&v?(c.port=Number(v),b++):w==="--hostname"&&v?(c.hostname=v,b++):w==="--timeout"&&v&&(c.timeout=Number(v),b++);}let{loadConfig:i}=await import('./config-FVZNV76C.mjs'),g=(await i()).server??{},d=Ie(g,c),h=d.channel??"websocket",a=h==="stdio"||h==="http"||h==="websocket"?h:"websocket",s=typeof d.port=="number"?d.port:3e3,m=typeof d.hostname=="string"?d.hostname:"localhost",u=typeof d.timeout=="number"?d.timeout:3e4;y.info("Bootstrapping ACP server",{channel:a,port:s,hostname:m,timeout:u,agentId:d.agentId});let{EasbotAdapter:k}=await import('./bootstrap-U2GTL57G.mjs'),{ChannelType:_}=await import('./types-GMPQJ4DC.mjs');await k.init({directory:r?.cwd??process.cwd(),printLogs:!1,logLevel:"INFO",channel:a==="stdio"?_.STDIO:a==="http"?_.HTTP:_.WS});let E=await k.ensureACPService({...d,directory:r?.cwd??process.cwd(),enabled:!0,channel:a,port:s,hostname:m,timeout:u}),D=t({channel:a,hostname:m,port:s})??`unknown://${m}:${s}`;y.info("ACP server started successfully",{type:E.server?.type,url:D});let se={directory:o("acp.field.directory"),channel:o("acp.field.channel"),host:o("acp.field.host"),timeout:o("acp.field.timeout")};printHuman([ee({directory:r?.cwd??process.cwd(),channel:a,host:D,timeout:`${u}ms`,head:o("acp.server.started_head",{fallback:"ACP Server Started"})},se)],{title:o("acp.server.started"),boxed:!0}),await new Promise(b=>{let w=!1,v=R=>{w||(w=!0,y.info(`Received ${R}, shutting down ACP server`,{signal:R}),b());};process.once("SIGINT",()=>v("SIGINT")),process.once("SIGTERM",()=>v("SIGTERM")),process.stdout.on("error",R=>{(R.code==="EPIPE"||R.code==="EIO")&&(y.info("stdout pipe broken, exiting ACP server"),v("STDOUT-BROKEN"));});});try{await k.destroy();}catch(b){y.warn("EasbotAdapter.destroy failed",{error:errorMeta(b)});}return {code:0,handled:!0,command:t$1}}case "status":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.status.usage")),{code:0,handled:!0,command:t$1};let{loadConfig:c,getConfigDirectory:i}=await import('./config-FVZNV76C.mjs'),p=await c(),g={directory:i(),server:p.server,clientCount:p.clients?.clients?.length??0};if(l)emitJsonOk(g,{command:t$1});else {let d={directory:o("cli.status.field.directory"),server:o("cli.status.field.server"),channel:o("cli.status.field.server_channel"),port:o("cli.status.field.server_port"),hostname:o("cli.status.field.server_hostname"),enabled:o("cli.status.field.server_enabled"),clients:o("cli.status.field.clients")};printHuman([Q({directory:g.directory,server:g.server,clientCount:g.clientCount},d)],{title:"acp status",boxed:!0});}return {code:0,handled:!0,command:t$1}}case "doctor":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.doctor.usage")),{code:0,handled:!0,command:t$1};let{AcpCache:c}=await import('./cache-O43SNRV2.mjs'),{loadConfig:i}=await import('./config-FVZNV76C.mjs'),p=await c.getConfigPath(),g=await c.exists(),d=!1,h;try{await i(),d=!0;}catch(s){h=errorMeta(s).message;}let a={acpJson:{path:p,exists:g},configLoadable:d,configError:h,sdkVersion:re};if(l)emitJsonOk(a,{command:t$1});else {let s={acpJsonPath:o("cli.doctor.field.acp_json_path"),acpJsonExists:o("cli.doctor.field.acp_json_exists"),configLoadable:o("cli.doctor.field.config_loadable"),configError:o("cli.doctor.field.config_error"),sdkVersion:o("cli.doctor.field.sdk_version")};printHuman([X({acpJsonPath:p,acpJsonExists:g,configLoadable:d,configError:h,sdkVersion:re},s)],{title:"acp doctor",boxed:!0});}return {code:0,handled:!0,command:t$1}}case "config":{if(n.includes("--help")||n.includes("-h"))return console.log(o("cli.config.usage")),console.log(""),console.log(o("cli.config.description")),console.log(o("cli.config.subcommands")),console.log(` ${o("cli.config.get_help")}`),console.log(` ${o("cli.config.set_help")}`),console.log(""),console.log(o("cli.config.examples")),console.log(o("cli.config.example_get")),console.log(o("cli.config.example_set")),{code:0,handled:!0,command:t$1};let c=n[0],i=n[1],p=n[2],{AcpCache:g}=await import('./cache-O43SNRV2.mjs'),{clearConfigCache:d}=await import('./config-FVZNV76C.mjs');if(c==="set"&&i!==void 0&&p!==void 0){let h=await g.getAcpJson()??{},a=i.split(".").filter(k=>k.length>0);if(a.length===0)return P(t$1,l,{title:o("cli.config.error.invalid_key.title",{fallback:"invalid key"}),field:o("cli.config.error.field.key",{fallback:"key"}),value:i,message:o("cli.config.invalid_key",{vars:{key:i}}),hint:o("cli.config.error.invalid_key.hint",{fallback:'Use dotted path like "server.channel".'})});let s=h;for(let k=0;k<a.length-1;k++){let _=a[k],E=s[_];(typeof E!="object"||E===null||Array.isArray(E))&&(s[_]={}),s=s[_];}let m=a[a.length-1],u=p;return p==="true"?u=!0:p==="false"?u=!1:/^-?\d+(\.\d+)?$/.test(p)&&(u=Number(p)),s[m]=u,await g.writeAcpJson(h),d(),l?emitJsonOk({key:i,value:u},{command:t$1}):printHuman([ne({key:i,value:JSON.stringify(u)})],{title:"acp config set",boxed:!0}),{code:0,handled:!0,command:t$1}}if(c==="get"){let a=await g.getAcpJson()??{};if(i){let s=i.split(".");for(let m of s)if(a&&typeof a=="object"&&m in a)a=a[m];else {a=void 0;break}}if(l)emitJsonOk({key:i,value:a},{command:t$1});else {let s={key:o("cli.config.field.key"),value:o("cli.config.field.value")},m=a==null?String(a):typeof a=="object"?JSON.stringify(a,null,2):String(a);printHuman([te({key:i,value:m},s)],{title:"acp config get",boxed:!0});}return {code:0,handled:!0,command:t$1}}return console.error(o("cli.config.usage")),P(t$1,l,{title:o("cli.config.error.no_subcommand.title",{fallback:"missing subcommand"}),message:o("cli.config.usage"),hint:o("cli.config.error.no_subcommand.hint",{fallback:'Use "easbot-acp config get [key]" or "easbot-acp config set <key> <value>".'})})}default:{let c=o("acp.error.unknown_command",{vars:{command:t$1}}),i=o("cli.banner.hint.run_help");return y.warn(c),P(t$1??"__unknown__",l,{title:o("acp.error.unknown_command.title",{fallback:"unknown command"}),field:o("acp.error.unknown_command.field",{fallback:"command"}),value:t$1,message:c,hint:i},{exitCode:2})}}}catch(c){let i=errorMeta(c),p=i.message;y.error(`acp command ${t$1} failed`,{command:t$1,error:i});let g=r?.cwd??"",d=o("acp.cli.error_prefix",{vars:{cwd:g,command:t$1,message:p}});return P(t$1??"__unknown__",l,{title:o("acp.cli.command_failed_title",{fallback:"command failed"}),message:d,hint:o("acp.cli.error_hint",{fallback:"Re-run with --debug for full stack."})})}}
8
+ export{de as a,pe as b,S as c,j as d,T as e,Oe as f,Ne as g,q as h,o as i,Me as j,Ee as k,ft as l,Re as m,Ie as n,gt as o};
@@ -0,0 +1,8 @@
1
+ 'use strict';var chunkSNWAB3QJ_cjs=require('./chunk-SNWAB3QJ.cjs'),chunkOQH5ALTQ_cjs=require('./chunk-OQH5ALTQ.cjs'),chunk6VF3MZ6H_cjs=require('./chunk-6VF3MZ6H.cjs'),chunk663BEBE4_cjs=require('./chunk-663BEBE4.cjs'),chunkRGGMCKYA_cjs=require('./chunk-RGGMCKYA.cjs'),chunkISDIC2R6_cjs=require('./chunk-ISDIC2R6.cjs'),utils=require('@easbot/utils'),fs$1=require('fs'),mt=require('path'),url=require('url'),diff=require('diff'),types=require('@easbot/types'),crypto=require('crypto'),unstable=require('@agentclientprotocol/sdk/unstable'),ws=require('ws');require('@easbot/sdk');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var mt__default=/*#__PURE__*/_interopDefault(mt);var E=utils.Log.create({service:"acp.event.bridge"}),G=class{constructor(e,t){chunkISDIC2R6_cjs.a(this,"sdk");chunkISDIC2R6_cjs.a(this,"peer");chunkISDIC2R6_cjs.a(this,"abortController",null);chunkISDIC2R6_cjs.a(this,"started",false);chunkISDIC2R6_cjs.a(this,"permissionQueues",new Map);chunkISDIC2R6_cjs.a(this,"_messageMetaCache",new Map);chunkISDIC2R6_cjs.a(this,"permissionOptions",[{optionId:"once",kind:"allow_once",name:"Allow once"},{optionId:"always",kind:"allow_always",name:"Always allow"},{optionId:"reject",kind:"reject_once",name:"Reject"}]);chunkISDIC2R6_cjs.a(this,"acpService");chunkISDIC2R6_cjs.a(this,"_cachedHiddenAgents",null);this.sdk=e,this.peer=t;}setService(e){this.acpService=e;}async start(){if(this.started){E.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,E.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||E.error("event subscription failed",{error:utils.errorMeta(e)});});}async stop(){this.started&&(E.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.permissionQueues.clear(),this._messageMetaCache.clear(),this._cachedHiddenAgents=null,E.info("ACP event bridge stopped"));}async runEventSubscription(){let e=this.abortController;if(e)for(;;){if(e.signal.aborted)return;let t=await this.sdk.global.event({signal:e.signal});for await(let n of t.stream){if(e.signal.aborted)return;let r=n?.payload;r&&await this.handleEvent(r).catch(o=>{E.error("failed to handle event",{error:utils.errorMeta(o),type:r.type});});}if(e.signal.aborted)return}}async handleEvent(e){switch(e.type){case "permission.asked":await this.handlePermissionAsked(e.properties);break;case "question.asked":await this.handleQuestionAsked(e.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(e.properties);break;case "session.status":await this.handleSessionStatus(e.properties);break;case "session.deleted":{let n=e.properties.info?.id??"";await this.handleSessionDeleted({sessionId:n});break}}}async handleSessionStatus(e){let{sessionId:t,status:n}=e;if(!this.peer){E.warn("No connection available to publish session status");return}try{await this.peer.notify("session_status_update",{sessionId:t,status:n});}catch(r){E.error("Failed to publish session status via notify",{sessionId:t,status:n,error:utils.errorMeta(r)});}n.type==="idle"&&(this.permissionQueues.delete(t),this.clearMessageMetaCache(t));}async handleSessionDeleted(e){let{sessionId:t}=e;if(!this.peer){E.warn("No connection available to notify session deletion");return}if(typeof t!="string"||t.length===0){E.debug("handleSessionDeleted: skipping, sessionId is missing or invalid",{sessionId:t});return}this.permissionQueues.delete(t),this.clearMessageMetaCache(t);try{await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"[System] Session has been deleted by the backend. This session is no longer available."}}});}catch(n){E.error("Failed to notify session deletion to client",{sessionId:t,error:utils.errorMeta(n)});}}async handlePermissionAsked(e){let{id:t,sessionId:n,permission:r,tool:o,metadata:d}=e,m=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let h=r==="external_directory"&&d?.tool?Ce(d.tool):Ce(r),b=r==="external_directory"&&d?.tool?Ae(d.tool,d):Ae(r,d),w=await this.peer.requestPermission({sessionId:n,toolCall:{toolCallId:o?.callId??t,status:"pending",title:r,rawInput:d,kind:h,locations:b??[]},options:this.permissionOptions}).catch(async y=>{E.error("failed to request permission from ACP",{error:utils.errorMeta(y),permissionId:t,sessionId:n}),await this.sdk.permission.reply({requestId:t,reply:"reject"});});if(w){if(w.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestId:t,reply:"reject"});return}if(w.outcome.optionId!=="reject"&&r==="edit"){let y=d?.filepath??d?.filePath??"",x=d?.diff??"";if(y&&x){let C=utils.PKG.file(y),c=await C.exists()?await C.text():"",i=ht(c,x);i&&await this.peer.request("client.writeTextFile",{sessionId:n,path:y,content:i});}}await this.sdk.permission.reply({requestId:t,reply:w.outcome.optionId});}}).catch(h=>{E.error("failed to handle permission",{error:utils.errorMeta(h),permissionId:t});}).finally(()=>{this.permissionQueues.get(n)===m&&this.permissionQueues.delete(n);});this.permissionQueues.set(n,m);}async handleQuestionAsked(e){let{id:t,sessionId:n,questions:r}=e;E.debug("Handling question asked in ACP bridge",{requestId:t,sessionId:n,questionCount:r.length});try{let o=await this.peer.request("client.requestQuestion",{sessionId:n,requestId:t,questions:r});if(!o){E.warn("Question request returned no result"),await this.sdk.question.reject({requestId:t});return}o.outcome==="selected"&&o.answers&&o.answers.length>0?await this.sdk.question.reply({requestId:t,answers:o.answers.map(d=>[d.answer])}):await this.sdk.question.reject({requestId:t});}catch(o){E.error("Failed to handle question via request",{error:utils.errorMeta(o),requestId:t,sessionId:n}),await this.sdk.question.reject({requestId:t});}}async handleMessagePartUpdated(e){let{part:t}=e,n=await this.getMessageMeta(t.sessionId,t.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(t.type==="tool"?await this.handleToolPart(t):t.type==="text"?await this.handleTextPart(t,e.delta):t.type==="reasoning"?await this.handleReasoningPart(t,e.delta):t.type==="step-finish"&&await this.handleStepFinishPart(t)));}async handleToolPart(e){let{sessionId:t,callId:n,tool:r,state:o,messageId:d}=e;if(!t){E.debug("AcpEventBridge: skipping tool part without sessionId",{callId:n,tool:r,messageId:d});return}let p=Ce(r);switch(o.status){case "pending":await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:r,kind:p,status:"pending",locations:[],rawInput:{},_meta:{messageId:d}}}).catch(m=>{E.error("failed to send tool pending to ACP",{error:utils.errorMeta(m)});});return;case "in_progress":await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"in_progress",kind:p,title:r,locations:Ae(r,o.input),rawInput:o.input,_meta:{messageId:d}}}).catch(m=>{E.error("failed to send tool in_progress to ACP",{error:utils.errorMeta(m)});});return;case "completed":{let m=[{type:"content",content:{type:"text",text:o.output}}];if(p==="edit"){let h=o.input,b=h.filePath??h.filepath??"",w=h.oldString??"",y=h.newString??h.content??"";m.push({type:"diff",path:b,oldText:w,newText:y});}if(r==="todo"){let h=types.TodoListSchema.safeParse(JSON.parse(o.output));h.success&&o.input.operation==="write"&&await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:h.data.map(b=>{let w=b.status==="cancelled"?"completed":b.status;return {priority:b.priority,status:w,content:b.content}})}}).catch(b=>{E.error("failed to send session update for todo",{error:utils.errorMeta(b)});});}await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:p,content:m,title:o.title??r,rawInput:o.input,rawOutput:{output:o.output,metadata:o.metadata},_meta:{messageId:d}}}).catch(h=>{E.error("failed to send tool completed to ACP",{error:utils.errorMeta(h)});});return}case "failed":await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:p,title:r,rawInput:o.input,content:[{type:"content",content:{type:"text",text:o.error}}],rawOutput:{error:o.error},_meta:{messageId:d}}}).catch(m=>{E.error("failed to send tool error to ACP",{error:utils.errorMeta(m)});});return}}async handleTextPart(e,t){if(e.ignored===true)return;if(!e.sessionId){E.debug("AcpEventBridge: skipping text part without sessionId",{messageId:e.messageId});return}if(!("time"in e&&e.time&&typeof e.time=="object"&&"end"in e.time&&!!e.time.end))return;let r=e.text;r&&await this.peer.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_message_chunk",messageId:e.messageId,content:{type:"text",text:r}}}).catch(o=>{E.error("failed to send text to ACP",{error:utils.errorMeta(o)});});}async handleReasoningPart(e,t){if(!e.sessionId){E.debug("AcpEventBridge: skipping reasoning part without sessionId",{messageId:e.messageId});return}if(!("time"in e&&e.time&&typeof e.time=="object"&&"end"in e.time&&!!e.time.end))return;let r=e.text;r&&await this.peer.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_thought_chunk",messageId:e.messageId,content:{type:"text",text:r}}}).catch(o=>{E.error("failed to send reasoning to ACP",{error:utils.errorMeta(o)});});}async handleStepFinishPart(e){let{sessionId:t,messageId:n,tokens:r}=e;if(!this.peer)return;if(!t){E.debug("AcpEventBridge: skipping step-finish part without sessionId",{messageId:n});return}let o=(r?.input??0)+(r?.reasoning??0),d=await this.getContextLimit(t,n);await this.peer.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:o,size:d,_meta:{messageId:n}}}).catch(p=>{E.error("failed to send usage_update for step-finish",{error:utils.errorMeta(p)});});}async getContextLimit(e,t){try{let r=(await this.sdk.session.messages({sessionId:e}).then(o=>o.data).catch(()=>{}))?.find(o=>o.info.id===t);if(r){let o=r.info;if(o.providerId&&o.modelId)return (await this.sdk.config.providers({}).then(h=>h.data?.providers??[]).catch(()=>[])).find(h=>h.id===o.providerId)?.models[o.modelId]?.limit?.context??2e5}}catch(n){E.errorDegradable("failed to get context limit",{error:utils.errorMeta(n)});}return 2e5}async getMessageMeta(e,t){let n=`${e}:${t}`,r=this._messageMetaCache.get(n);if(r)return r;let o=await this.sdk.session.message({sessionId:e,messageId:t},{throwOnError:true}).then(p=>p.data).catch(p=>{p instanceof Error&&p.name!=="NotFoundError"&&E.error("unexpected error when fetching message",{error:utils.errorMeta(p),sessionId:e,messageId:t});});if(!o)return;let d={role:o.info.role,agent:o.info.agent};return this._messageMetaCache.set(n,d),d}clearMessageMetaCache(e){let t=`${e}:`;for(let n of this._messageMetaCache.keys())n.startsWith(t)&&this._messageMetaCache.delete(n);}async shouldFilterAgent(e){if(!this._cachedHiddenAgents)try{let n=(await this.sdk.agent.list({})).data||[];this._cachedHiddenAgents=new Set(n.filter(r=>r.hidden===!0).map(r=>r.name));}catch{this._cachedHiddenAgents=new Set;}return this._cachedHiddenAgents.has(e)}};function Ce(s){switch(s.toLowerCase()){case "bash":return "execute";case "webfetch":return "fetch";case "edit":case "patch":case "write":return "edit";case "grep":case "glob":case "lsp":case "context7_resolve_library_id":case "context7_get_library_docs":return "search";case "list":case "read":return "read";default:return "other"}}function Ae(s,e){if(!e)return [];switch(s.toLowerCase()){case "read":case "edit":case "write":case "patch":case "lsp":{let n=e.filePath??e.filepath??"";return n?[{path:n}]:[]}case "glob":case "grep":return e.path?[{path:e.path}]:[];case "list":return e.path?[{path:e.path}]:[];case "bash":case "shell":{let n=e.cwd??"";return n?[{path:n}]:[]}case "external_directory":{let n=e.tool?.toLowerCase(),r=e.filepath??"",o=e.realPath??"",d=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return o?[{path:o}]:r?[{path:r}]:[];if(n==="list"||n==="glob"||n==="grep"){let m=o??r,h=m?mt__default.default.posix.dirname(m):d;return h?[{path:h}]:[]}let p=o??r;return p?[{path:p}]:d?[{path:d}]:[]}default:return []}}function ht(s,e){try{let t=diff.applyPatch(s,e);return t===!1?null:t}catch{return null}}var Z=utils.Log.create({service:"acp.connection.registry"});exports.b=void 0;(i=>{let s=null;async function e(){return s||(s=await c.create()),s}async function t(u){return s||(s=await c.create(u),Z.info("ServerConnectionRegistry initialized")),s}i.init=t;async function n(u){return (await e()).connect(u.baseUrl,u.localAgentId,u.remoteAgentId,u.remoteSessionId,u.localSessionId)}i.connect=n;async function r(u){return (await e()).resolve(u)}i.resolve=r;function o(u){if(s)return s.resolve(u)}i.resolveSync=o;async function d(u){(await e()).closeConnection(u);}i.close=d;async function p(u,a){(await e()).markDegraded(u,a);}i.markDegraded=p;async function m(u){return (await e()).getConnectionsByAgent(u)}i.getConnectionsByLocalAgent=m;async function h(u){return (await e()).getConnectionsByService(u)}i.getConnectionsByService=h;async function b(){return (await e()).getAllActiveConnections()}i.getAllActiveConnections=b;async function w(u,a){(await e()).updateLastSeenMessageId(u,a);}i.updateLastSeenMessageId=w;async function y(u,a){(await e()).updateSessionUpdates(u,a);}i.updateSessionUpdates=y;async function x(u,a){let l=await e(),g=l.resolve(u);g&&l.updateSessionUpdates(g.connectionId,a);}i.updateSessionUpdatesBySessionId=x;function C(u){if(s)return s.findConnectionIdBySubscriber(u)}i.findConnectionIdBySubscriber=C;class c{constructor(a){chunkISDIC2R6_cjs.a(this,"defaultHistoryScope");chunkISDIC2R6_cjs.a(this,"defaultHistoryWindowSize");chunkISDIC2R6_cjs.a(this,"defaultDegradePolicy");chunkISDIC2R6_cjs.a(this,"agentIndex",new Map);chunkISDIC2R6_cjs.a(this,"serviceIndex",new Map);chunkISDIC2R6_cjs.a(this,"connections",new Map);this.defaultHistoryScope=a?.defaultHistoryScope??"session",this.defaultHistoryWindowSize=a?.defaultHistoryWindowSize??10,this.defaultDegradePolicy=a?.defaultDegradePolicy??"streaming_first",Z.debug("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(a){return new c(a)}connect(a,l,g,I,f){let v=this.agentIndex.get(l);if(v)for(let M of v){let R=this.connections.get(M);if(R&&R.baseUrl===a&&R.status!=="closed")return I&&R.sessionId!==I&&(R.sessionId=I,R.sessionSequence=R.sessionSequence??[],R.sessionSequence.includes(I)||R.sessionSequence.push(I),R.remoteSessionStatus="idle"),f&&(R.localSessionId=f),R.updatedAt=Date.now(),{connectionId:R.connectionId,sessionId:R.sessionId,localAgentId:R.localAgentId,remoteAgentId:R.remoteAgentId,baseUrl:R.baseUrl}}let S=this.generateConnectionId(),_=I??`session-${this.generateShortId()}`,k={localAgentId:l,remoteAgentId:g,connectionId:S,sessionId:_,...f?{localSessionId:f}:{},baseUrl:a,historyScope:this.defaultHistoryScope,historyWindowSize:this.defaultHistoryWindowSize,degradePolicy:this.defaultDegradePolicy,updatedAt:Date.now(),status:"active",remoteSessionStatus:"idle"};return this.connections.set(S,k),this.agentIndex.has(l)||this.agentIndex.set(l,new Set),this.agentIndex.get(l).add(S),this.serviceIndex.has(a)||this.serviceIndex.set(a,new Set),this.serviceIndex.get(a).add(S),{connectionId:S,sessionId:_,localAgentId:l,remoteAgentId:g,baseUrl:a}}resolve(a,l=false){let g=this.connections.get(a);if(g)return g;let I=this.agentIndex.get(a);if(I&&I.size>0)for(let f of I){let v=this.connections.get(f);if(v&&v.status!=="closed")return v}for(let f of this.connections.values())if(f.status!=="closed"&&(f.sessionId===a||f.localSessionId===a))return f;if(l){let S=this.connect("http://localhost","system-local","system-remote",a);return this.connections.get(S.connectionId)}}closeConnection(a){let l=this.connections.get(a);if(!l)return;this.connections.delete(a);let g=this.agentIndex.get(l.localAgentId);g&&(g.delete(a),g.size===0&&this.agentIndex.delete(l.localAgentId));let I=this.serviceIndex.get(l.baseUrl);I&&(I.delete(a),I.size===0&&this.serviceIndex.delete(l.baseUrl)),Z.debug("connection closed and removed",{connectionId:a,localAgentId:l.localAgentId,remoteAgentId:l.remoteAgentId});}markDegraded(a,l){let g=this.connections.get(a);g&&(g.status="degraded",g.updatedAt=Date.now(),Z.debug("connection marked degraded",{connectionId:a,reason:l}));}getConnectionsByAgent(a){let l=this.agentIndex.get(a);return l?Array.from(l).map(g=>this.connections.get(g)).filter(g=>g!==void 0&&g.status!=="closed"):[]}getConnectionsByService(a){let l=this.serviceIndex.get(a);return l?Array.from(l).map(g=>this.connections.get(g)).filter(g=>g!==void 0&&g.status!=="closed"):[]}getAllActiveConnections(){return Array.from(this.connections.values()).filter(a=>a.status!=="closed")}updateLastSeenMessageId(a,l){let g=this.connections.get(a);g&&(g.lastSeenMessageId=l,g.updatedAt=Date.now());}updateSessionUpdates(a,l){let g=this.connections.get(a);g&&(l.availableCommands!==void 0&&(g.availableCommands=l.availableCommands),l.configOptions!==void 0&&(g.configOptions=l.configOptions),l.currentModeId!==void 0&&(g.currentModeId=l.currentModeId),l.remoteSessionStatus!==void 0&&(g.remoteSessionStatus=l.remoteSessionStatus),g.updatedAt=Date.now(),Z.debug("connection session updates",{connectionId:a,hasCommands:!!l.availableCommands,hasConfig:!!l.configOptions,hasMode:!!l.currentModeId}));}findConnectionIdBySubscriber(a){for(let[l,g]of this.connections)if(g.subscriber===a)return l}generateConnectionId(){return `conn-${this.generateShortId()}`}generateShortId(){return crypto.createHash("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").substring(0,8)}async close(){this.connections.clear(),this.agentIndex.clear(),this.serviceIndex.clear(),s=null,Z.info("connection registry closed");}}i.ConnectionRegistry=c;})(exports.b||(exports.b={}));var j=utils.Log.create({service:"acp.connection.router"}),Ct=(o=>(o.EMPTY_CONTEXT="EMPTY_CONTEXT",o.AMBIGUOUS_ROUTE="AMBIGUOUS_ROUTE",o.NOT_FOUND="NOT_FOUND",o.CONNECTION_CLOSED="CONNECTION_CLOSED",o.MISSING_REQUIRED_PARAMS="MISSING_REQUIRED_PARAMS",o))(Ct||{});function pe(s,e,t){return new chunkSNWAB3QJ_cjs.c.RoutingError({message:e,code:s,context:t})}var we=class s{static create(){return new s}constructor(){j.info("session router created");}route(e){if(!this.isValidContext(e))return {success:false,error:"routing context is empty or invalid"};try{return e.connectionId?this.routeByConnectionId(e.connectionId):e.localAgentId&&e.baseUrl?this.routeByPeerAndBaseUrl(e.localAgentId,e.baseUrl):e.baseUrl&&e.sessionId?this.routeByBaseUrlAndSessionId(e.baseUrl,e.sessionId):{success:!1,error:"insufficient routing parameters: need connectionId, or localAgentId+baseUrl, or baseUrl+sessionId"}}catch(t){let n=utils.errorMeta(t).message;return j.error("routing failed",{context:e,error:utils.errorMeta(t)}),{success:false,error:n}}}routeOrThrow(e){let t=this.route(e);if(!t.success)throw pe(this.getErrorCode(t.error),t.error??"routing failed",e);if(!t.connectionId)throw pe("NOT_FOUND","connection not found",e);let n=this.getConnectionState(t.connectionId);if(!n)throw pe("NOT_FOUND","connection state not found",e);if(n.status==="closed")throw pe("CONNECTION_CLOSED","connection is closed",e);return n}registerConnection(e){return !e.connectionId||!e.localAgentId||!e.remoteAgentId||!e.baseUrl||!e.sessionId?{success:false,error:"invalid connection state: missing required fields"}:(j.debug("connection registered",{connectionId:e.connectionId,localAgentId:e.localAgentId,remoteAgentId:e.remoteAgentId,baseUrl:e.baseUrl}),{success:true,connectionId:e.connectionId,sessionId:e.sessionId,localAgentId:e.localAgentId,remoteAgentId:e.remoteAgentId,baseUrl:e.baseUrl})}unregisterConnection(e){let t=this.getConnectionState(e);return t?(j.debug("connection unregistered",{connectionId:e,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}),true):(j.debug("connection not found for unregister",{connectionId:e}),false)}isValidContext(e){return !!(e.connectionId||e.remoteAgentId||e.baseUrl||e.sessionId)}routeByConnectionId(e){let t=this.getConnectionState(e);return t?t.status==="closed"?{success:false,error:`connection is closed: ${e}`}:{success:true,connectionId:t.connectionId,sessionId:t.sessionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}:{success:false,error:`connection not found: ${e}`}}routeByPeerAndBaseUrl(e,t){let r=this.getConnectionsByPeer(e).filter(d=>d.baseUrl===t&&d.status!=="closed");if(r.length===0)return {success:false,error:`no connection found for localAgentId=${e}, baseUrl=${t}`};if(r.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${e}, baseUrl=${t}`};let o=r[0];return {success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}}routeByBaseUrlAndSessionId(e,t){let r=this.getConnectionsByService(e).filter(d=>d.sessionId===t&&d.status!=="closed");if(r.length===0)return {success:false,error:`no connection found for baseUrl=${e}, sessionId=${t}`};if(r.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${e}, sessionId=${t}`};let o=r[0];return {success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}}getConnectionState(e){j.warn("getConnectionState not implemented, returning undefined",{connectionId:e});}getConnectionsByPeer(e){return j.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:e}),[]}getConnectionsByService(e){return j.warn("getConnectionsByService not implemented, returning empty array",{baseUrl:e}),[]}getErrorCode(e){return e?e.includes("empty")||e.includes("invalid")?"EMPTY_CONTEXT":e.includes("ambiguous")?"AMBIGUOUS_ROUTE":e.includes("not found")?"NOT_FOUND":e.includes("closed")?"CONNECTION_CLOSED":e.includes("insufficient")||e.includes("missing")?"MISSING_REQUIRED_PARAMS":"NOT_FOUND":"NOT_FOUND"}},ge=class s extends we{constructor(t){super();chunkISDIC2R6_cjs.a(this,"registry");this.registry=t,j.info("registry session router created");}static fromRegistry(t){return new s(t)}getConnectionState(t){return this.registry.resolve(t)}getConnectionsByPeer(t){return this.registry.getConnectionsByPeer(t)}getConnectionsByService(t){return this.registry.getConnectionsByService(t)}};var Pe=["general","coder"],Ne="general";var me=utils.Log.create({service:"acp.session"}),ne=class{constructor(e){chunkISDIC2R6_cjs.a(this,"sessions",new Map);chunkISDIC2R6_cjs.a(this,"sdk");this.sdk=e;}tryGet(e){return this.sessions.get(e)}async create(e,t,n,r){let d={id:e,cwd:t,mcpServers:n,createdAt:new Date,model:r};return me.info("creating_session",{state:d}),this.sessions.set(e,d),d}async load(e,t,n,r){let o=await this.sdk.session.get({sessionId:e},{throwOnError:true}).then(m=>m.data),d=r,p={id:e,cwd:t,mcpServers:n,createdAt:new Date(o.time.created),model:d};return me.debug("loading_session",{state:p}),this.sessions.set(e,p),p}get(e){let t=this.sessions.get(e);if(!t)throw me.error("session not found",{sessionId:e}),unstable.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(),me.debug("all sessions cleared");}resolveConnectionState(e){}};var P=utils.Log.create({service:"acp.acp.service"}),se=class{constructor(e,t){chunkISDIC2R6_cjs.a(this,"config");chunkISDIC2R6_cjs.a(this,"serviceMode");chunkISDIC2R6_cjs.a(this,"peer");chunkISDIC2R6_cjs.a(this,"sdk");chunkISDIC2R6_cjs.a(this,"connectionRegistry",null);chunkISDIC2R6_cjs.a(this,"sessionRouter",null);chunkISDIC2R6_cjs.a(this,"sessionManager");chunkISDIC2R6_cjs.a(this,"executorInitialized",false);chunkISDIC2R6_cjs.a(this,"status","initializing");this.peer=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.sessionManager=new ne(this.sdk),t.connectionRegistry&&(this.connectionRegistry=t.connectionRegistry),t.sessionRouter&&(this.sessionRouter=t.sessionRouter),P.info("ACPService instance created",{channel:t.channel.type,hasPeer:!!e,hasProvidedRegistry:!!t.connectionRegistry,hasProvidedRouter:!!t.sessionRouter});}async initializeExecutor(){if(this.executorInitialized){P.warn("Executor components already initialized");return}this.connectionRegistry||(this.connectionRegistry=await exports.b.init(),P.debug("ServerConnectionRegistry initialized")),this.sessionRouter||(this.sessionRouter=ge.fromRegistry({resolve:e=>this.connectionRegistry.resolve(e),getConnectionsByPeer:e=>this.connectionRegistry.getConnectionsByAgent(e),getConnectionsByService:e=>this.connectionRegistry.getConnectionsByService(e)}),P.debug("SessionRouter created")),this.executorInitialized=true,P.info("Executor components initialized");}setStatus(e,t="agent"){let n=this.status;if(n===e)return;this.status=e,P.debug("Agent status changed",{oldStatus:n,newStatus:e,agentId:t});}getStatus(){return this.status}authenticate(e){return Promise.resolve(void 0)}async newSession(e){P.debug("ACP newSession requested",{cwd:e.cwd});let t=e.cwd,r=(await this.sdk.model.default())?.data,d=(await this.sdk.session.create({directory:t})).data?.id;if(!d)throw new utils.NameErrors.OperationFailedError({message:"Failed to create session: no session ID returned",operation:"acp-session-create"});let p=await this.sessionManager.create(d,t,e.mcpServers,r),m=await this.buildSessionStateResponse(p.id,t);return {sessionId:p.id,...m,_meta:{}}}async loadSession(e){P.debug("ACP loadSession requested",{sessionId:e.sessionId});let t=e.cwd,r=(await this.sdk.model.default())?.data;return await this.sessionManager.load(e.sessionId,t,e.mcpServers,r),{...await this.buildSessionStateResponse(e.sessionId,t),_meta:{}}}async prompt(e){let t=e.sessionId,n=this.sessionManager.get(t),r=n.cwd,o=e._meta??{},d=typeof o.agent=="string"&&o.agent?o.agent:void 0,p=typeof o.model=="string"&&o.model?utils.parseModelId(o.model):void 0,m=n.model,h=p?.providerId?{providerId:p.providerId,modelId:p.modelId}:p?.modelId?{providerId:m?.providerId??"",modelId:p.modelId}:m??(await this.sdk.model.default())?.data,b=d??n.agent??(await this.sdk.agent.default())?.data?.name??"build";this.sendAvailableCommandsUpdate(t).catch(C=>{P.warn("Failed to send initial available commands update",{sessionId:t,directory:r,error:utils.errorMeta(C)});});let w=[];for(let C of e.prompt)switch(C.type){case "text":{let c=C.annotations?.audience,i=c?.length===1&&c[0]==="assistant",u=c?.length===1&&c[0]==="user";w.push({type:"text",text:C.text,...i&&{synthetic:true},...u&&{ignored:true}});break}case "image":{let c=this.parseUri(C.uri??""),i=c.type==="file"?c.filename:"image";C.data?w.push({type:"file",url:`data:${C.mimeType};base64,${C.data}`,filename:i,mime:C.mimeType}):C.uri?.startsWith("http:")&&w.push({type:"file",url:C.uri,filename:i,mime:C.mimeType});break}case "resource_link":{let c=this.parseUri(C.uri);C.name&&c.type==="file"&&(c.filename=C.name),w.push(c);break}case "resource":{let c=C.resource;if("text"in c&&c.text)w.push({type:"text",text:c.text});else if("blob"in c&&c.blob&&c.mimeType){let i=this.parseUri(c.uri??""),u=i.type==="file"?i.filename:"file";w.push({type:"file",url:`data:${c.mimeType};base64,${c.blob}`,filename:u,mime:c.mimeType});}break}}P.debug("prompt parts",{sessionId:t,parts:w});let y=(()=>{let C=w.filter(l=>l.type==="text").map(l=>l.text).join("").trim();if(!C.startsWith("/"))return;let c=utils.ParseCommand.tokenize(C.slice(1));if(c.length===0)return;let[i,...u]=c,a=u.join(" ").trim();return P.debug("command",{name:i,args:a}),{name:i,args:a}})();if(!y)return this.sdk.session.prompt({sessionId:t,model:{providerId:h.providerId,modelId:h.modelId},parts:w,agent:b,variant:n.variant,contextMode:n.contextMode}).catch(C=>{P.error("prompt execution failed",{sessionId:t,error:utils.errorMeta(C)});}),{stopReason:"end_turn",_meta:{}};let x=await this.sdk.command.get({name:y.name},{throwOnError:true}).then(C=>C.data);if(x)return x.commandType==="local"&&this.peer?(this.sdk.session.command({sessionId:t,command:x.name,arguments:y.args??"",agent:b,model:utils.formatModelId(h),variant:n.variant,contextMode:n.contextMode,parts:w}).then(async C=>{let c=C.data?.success?C.data.output:`[Error] ${C.data?.error??"Command execution failed"}`;this.peer?.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}});let i=await this.getContextLimit(h.providerId,h.modelId,r);i&&this.peer?.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:0,size:i}});}).catch(C=>{P.error("local command execution failed",{command:x.name,error:utils.errorMeta(C)});}),{stopReason:"end_turn",_meta:{}}):(this.sdk.session.command({sessionId:t,command:x.name,arguments:y.args??"",agent:b,model:utils.formatModelId(h),variant:n.variant,contextMode:n.contextMode,parts:w}).catch(C=>{P.error("prompt command execution failed",{command:x.name,error:utils.errorMeta(C)});}),{stopReason:"end_turn",_meta:{}});switch(y.name){case "compact":if(!h.providerId||!h.modelId)throw new utils.NameErrors.MissingFieldError({message:"Model providerId and modelId are required for compact command",field:"model"});await this.sdk.session.summarize({sessionId:t,providerId:h.providerId,modelId:h.modelId},{throwOnError:true});break}return await this.sendUsageUpdate(t,r),{stopReason:"end_turn",_meta:{}}}async cancel(e){this.sessionManager.tryGet(e.sessionId)?.cwd??"";try{this.sdk&&await this.sdk.session.abort({sessionId:e.sessionId}).catch(r=>{P.warn("SDK abort failed",{sessionId:e.sessionId,error:utils.errorMeta(r)});}),P.debug("Session cancelled",{sessionId:e.sessionId});}catch(r){throw P.error("Failed to cancel session",{sessionId:e.sessionId,error:utils.errorMeta(r)}),r}}parseUri(e){try{if(e.startsWith("file://")){let t=e.slice(7),n=t.split("/").pop()||t;return {type:"file",url:e,filename:n,mime:"text/plain"}}if(e.startsWith("zed://")){let n=new URL(e).searchParams.get("path");if(n){let r=n.split("/").pop()||n;return {type:"file",url:url.pathToFileURL(n).href,filename:r,mime:"text/plain"}}}return {type:"text",text:e}}catch{return {type:"text",text:e}}}async sendUsageUpdate(e,t){if(!this.sdk||!this.peer)return;if(!e){P.debug("sendUsageUpdate: skipping, sessionId is empty");return}let n=await this.sdk.session.messages({sessionId:e},{throwOnError:true}).then(h=>h.data).catch(h=>{P.error("failed to fetch messages for usage update",{error:utils.errorMeta(h)});});if(!n)return;let r=n.filter(h=>h.info.role==="assistant"),o=r[r.length-1];if(!o)return;let d=o.info,p=await this.getContextLimit(d.providerId,d.modelId,t);if(!p)return;let m=d.tokens.input+(d.tokens.cache?.read??0);await this.peer.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:m,size:p}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.peer){if(!e){P.debug("sendAvailableCommandsUpdate: skipping, sessionId is empty");return}try{let r=this.sessionManager.get(e)?.contextMode,d=(await this.sdk.command.list({contextMode:r},{throwOnError:!0})).data?.filter(p=>!p.hidden).map(p=>({name:p.name,description:p.description??""}))??[];await this.peer.sessionUpdate({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:d}});}catch(n){P.error("failed to send available commands update",{error:utils.errorMeta(n)});}}}async sendConfigOptionUpdate(e,t,n){if(this.peer){if(!e){P.debug("sendConfigOptionUpdate: skipping, sessionId is empty");return}try{let o=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!o||o.length===0)return;await this.peer.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:o}});}catch(r){P.error("failed to send config_option_update to ACP client",{sessionId:e,error:utils.errorMeta(r)});}}}async sendCurrentModeUpdate(e,t){if(this.peer){if(!e){P.debug("sendCurrentModeUpdate: skipping, sessionId is empty");return}try{await this.peer.sessionUpdate({sessionId:e,update:{sessionUpdate:"current_mode_update",currentModeId:t}});}catch(n){P.error("failed to send current_mode_update to ACP client",{sessionId:e,modeId:t,error:utils.errorMeta(n)});}}}async getContextLimit(e,t,n){return this.sdk?(await this.sdk.config.providers({}).then(p=>p.data?.providers??[]).catch(p=>(P.error("failed to get providers for context limit",{error:utils.errorMeta(p)}),[]))).find(p=>p.id===e)?.models[t]?.limit.context??2e5:null}async unstable_forkSession(e){P.debug("ACP forkSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.mcpServers??[],o=(await this.sdk.model.default())?.data,d=await this.sdk.session.fork({sessionId:e.sessionId,directory:t},{throwOnError:true}).then(b=>b.data);if(!d)throw new utils.NameErrors.OperationFailedError({message:"Fork session returned no data",operation:"acp-session-fork"});let p=d.id;await this.sessionManager.load(p,t,n,o);let h=await this.buildSessionStateResponse(p,t);return P.debug("fork_session",{sessionId:p,mcpServers:n.length}),{sessionId:p,...h,_meta:{}}}async resumeSession(e){P.debug("ACP resumeSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.sessionId,r=e.mcpServers??[],d=(await this.sdk.model.default())?.data;await this.sessionManager.load(n,t,r,d);let m=await this.buildSessionStateResponse(n,t);return P.debug("resume_session",{sessionId:n,mcpServers:r.length}),{...m,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,o=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(w=>w.data??[])).toSorted((w,y)=>y.time.updated-w.time.updated),p=(t?o.filter(w=>w.time.updated<t):o).slice(0,n),m=p.map(w=>({sessionId:w.id,cwd:w.directory,title:w.title??`Session ${w.id}`,updatedAt:new Date(w.time.updated).toISOString()})),h=p[p.length-1],b=p.length===n&&h?String(h.time.updated):void 0;return {sessions:m,nextCursor:b}}async setSessionMode(e){P.debug("ACP setSessionMode requested",{sessionId:e.sessionId,modeId:e.modeId}),this.sessionManager.setMode(e.sessionId,e.modeId);let t=this.sessionManager.get(e.sessionId);return await this.sendCurrentModeUpdate(e.sessionId,e.modeId),await this.sendConfigOptionUpdate(e.sessionId,t.cwd),{_meta:{}}}async setSessionConfigOption(e){if(P.debug("ACP setSessionConfigOption requested",{sessionId:e.sessionId,configId:e.configId,value:e.value}),e.configId==="model"){let r=typeof e.value=="string"?e.value:void 0;if(r){let o=this.parseModelSelection(r);this.sessionManager.setModel(e.sessionId,o.model);}}else if(e.configId==="agent"){let r=typeof e.value=="string"?e.value:void 0;this.sessionManager.setAgent(e.sessionId,r);}else if(e.configId==="thought_level"){let r=typeof e.value=="string"?e.value:void 0;this.sessionManager.setVariant(e.sessionId,r);}else if(e.configId==="context_mode"){let r=typeof e.value=="string"&&Pe.includes(e.value)?e.value:void 0;this.sessionManager.setContextMode(e.sessionId,r);}let t=this.sessionManager.get(e.sessionId),n=await this.buildSessionStateResponse(e.sessionId,t.cwd);return await this.sendConfigOptionUpdate(e.sessionId,t.cwd,n),{_meta:{},configOptions:n.configOptions??[]}}async closeSession(e){return P.debug("ACP closeSession requested",{sessionId:e.sessionId}),await this.cancel({sessionId:e.sessionId}),this.sessionManager.close(e.sessionId),{_meta:{}}}async buildSessionStateResponse(e,t){let n=this.sessionManager.tryGet(e),r=n?.model??(await this.sdk.model.default())?.data,o=r?.providerId&&r?.modelId?utils.formatModelId(r):void 0,d=[];try{d=(await this.sdk.config.providers({}).then(x=>x.data?.providers??[])).flatMap(x=>{let C=x.models??{};return Object.keys(C).map(c=>({modelId:`${x.id}/${c}`,name:`${x.id}/${c}`}))});}catch(y){P.warn("failed to build available models for session state",{sessionId:e,error:utils.errorMeta(y)});}o&&!d.some(y=>y.modelId===o)&&(d=[{modelId:o,name:o},...d]);let p=[];try{p=((await this.sdk.agent.list({})).data??[]).filter(C=>C.hidden!==!0&&C.mode!=="subagent").map(C=>({id:C.name,name:C.name,description:C.description}));}catch(y){P.warn("failed to build available agents for session state",{sessionId:e,error:utils.errorMeta(y)});}let m=n?.modeId,h=n?.variant??"low",b=n?.contextMode??Ne,w=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e,t),{models:o?{currentModelId:o,availableModels:d}:void 0,modes:m?{currentModeId:m,availableModes:[{id:m,name:m}]}:void 0,configOptions:[{id:"model",name:"Model",category:"model",type:"select",currentValue:o??"",options:d.map(y=>({value:y.modelId,name:y.name,description:y.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:w,options:p.map(y=>({value:y.id,name:y.name,description:y.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:h,options:[{value:"off",name:"Off"},{value:"low",name:"Low"},{value:"medium",name:"Medium"},{value:"high",name:"High"}]},{id:"context_mode",name:"Context Mode",category:"context_mode",type:"select",currentValue:b,options:Pe.map(y=>({value:y,name:y.charAt(0).toUpperCase()+y.slice(1)}))}]}}parseModelSelection(e){let t=utils.parseModelId(e);if(t.providerId&&t.modelId)return {model:{providerId:t.providerId,modelId:t.modelId}};throw new utils.NameErrors.InvalidArgumentError({message:`Invalid model id: "${e}" (expected format: <providerId>/<modelId>)`,param:"modelId"})}setPeer(e){this.peer=e,P.debug("ACPService peer updated");}getPeer(){return this.peer}abortConnection(){this.peer&&P.debug("Connection aborted");}closeConnection(){this.peer&&P.debug("Connection closed");}getServerConnectionRegistry(){return this.connectionRegistry}getSessionRouter(){return this.sessionRouter}createConnection(e,t,n,r){if(!this.connectionRegistry)throw new utils.NameErrors.OperationFailedError({message:"ServerConnectionRegistry not initialized. Call initializeExecutor() first.",operation:"acp-connect"});if(!t||!n)throw new utils.NameErrors.MissingFieldError({message:"localAgentId and remoteAgentId are required",field:"agentIds"});return this.connectionRegistry.connect(e,t,n,r)}async routeToConnection(e){if(!this.sessionRouter)throw new utils.NameErrors.OperationFailedError({message:"SessionRouter not initialized. Call initializeExecutor() first.",operation:"acp-route"});return this.sessionRouter.route(e)}async dispose(){P.info("Disposing ACPService"),this.sessionManager&&(this.sessionManager.dispose?.(),P.debug("SessionManager disposed")),this.connectionRegistry&&(await this.connectionRegistry.close(),this.connectionRegistry=null,P.debug("ServerConnectionRegistry closed")),this.sessionRouter=null,this.executorInitialized=false,P.info("ACPService disposed");}};var oe=class{constructor(e){chunkISDIC2R6_cjs.a(this,"context");this.context=e;}async sessionUpdate(e){await this.context.notify(unstable.methods.client.session.update,e);}async requestPermission(e){return await this.context.request(unstable.methods.client.session.requestPermission,e)}async request(e,t){return await this.context.request(e,t)??{}}async notify(e,t){await this.context.notify(e,t);}};var F={HTTP:chunkRGGMCKYA_cjs.b.HTTP,STDIO:chunkRGGMCKYA_cjs.b.STDIO,WEBSOCKET:chunkRGGMCKYA_cjs.b.WS};function He(s,e=[]){return new chunkSNWAB3QJ_cjs.c.ServiceModeConflictError({message:s,conflictingModes:e})}function xt(s){let e=[];return s.channel&&e.push(s.channel),e}function ze(s){let e=xt(s);if(e.length===0)throw He("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw He(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var be={channel:F.WEBSOCKET,port:3e3,hostname:"localhost",timeout:3e4,historyScope:"session",historyWindowSize:10,degradePolicy:"streaming_first",sessionExpireMs:300*1e3};var B=utils.Log.create({service:"acp.server.config"}),Q="EAS_";function Le(s){return !(!s||s.trim()===""||s.startsWith("-")||s.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(s))}function Fe(s){return Number.isInteger(s)&&s>=1&&s<=65535}function $e(s){return Number.isFinite(s)&&s>0}function _t(s){let e={...be,...s};try{ze(e);}catch(t){throw chunkSNWAB3QJ_cjs.f(t)&&B.error("Invalid service mode configuration",{message:utils.errorMeta(t).message,conflictingModes:t.data.conflictingModes}),t}if(e.port!==void 0&&!Fe(e.port))throw B.error("Invalid port configuration",{port:e.port}),new utils.NameErrors.InvalidArgumentError({message:`Invalid port number: ${e.port}. Must be between 1 and 65535`,param:"port"});if(e.hostname!==void 0&&!Le(e.hostname))throw B.error("Invalid hostname configuration",{hostname:e.hostname}),new utils.NameErrors.InvalidArgumentError({message:`Invalid hostname: ${e.hostname}`,param:"hostname"});if(e.timeout!==void 0&&!$e(e.timeout))throw B.error("Invalid timeout configuration",{timeout:e.timeout}),new utils.NameErrors.InvalidArgumentError({message:`Invalid timeout: ${e.timeout}. Must be a positive number`,param:"timeout"});if(e.channel===F.STDIO&&e.stdio&&(!e.stdio.command||e.stdio.command.trim()===""))throw B.error("Invalid stdio configuration",{command:e.stdio.command}),new utils.NameErrors.MissingFieldError({message:"STDIO command is required",field:"command"});return B.debug("ACPServer config loaded",{channel:e.channel,port:e.port,hostname:e.hostname}),e}function We(){let s={},e=process.env[`${Q}ACP_CHANNEL`];if(e){let m=e.toLowerCase();Object.values(F).includes(m)?s.channel=m:B.warn("Invalid EAS_ACP_CHANNEL environment variable",{value:e});}let t=process.env[`${Q}ACP_PORT`];if(t){let m=parseInt(t,10);Fe(m)?s.port=m:B.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${Q}ACP_HOSTNAME`];n&&(Le(n)?s.hostname=n:B.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let r=process.env[`${Q}ACP_TIMEOUT`];if(r){let m=parseInt(r,10);$e(m)?s.timeout=m:B.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:r});}let o=process.env[`${Q}ACP_HISTORY_SCOPE`];o&&(["session","peer","global"].includes(o)?s.historyScope=o:B.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:o}));let d=process.env[`${Q}ACP_HISTORY_WINDOW_SIZE`];if(d){let m=parseInt(d,10);Number.isInteger(m)&&m>0?s.historyWindowSize=m:B.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:d});}let p=process.env[`${Q}ACP_DEGRADE_POLICY`];return p&&(["polling_only","streaming_first"].includes(p)?s.degradePolicy=p:B.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:p})),B.debug("Config loaded from environment",{config:s}),s}function fs(s){let e=We(),t={...e,...s};return B.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:s,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}function je(s){let e=We(),t={...be,...e,...s},n=_t(t);return B.info("ACPServer config resolved (default < env < explicit)",{env:{channel:e.channel,port:e.port,hostname:e.hostname},explicit:{channel:s.channel,port:s.port,hostname:s.hostname},final:{channel:n.channel,port:n.port,hostname:n.hostname}}),n}var Re=utils.Log.create({service:"acp.server.rpc-handler"}),K={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,INTERNAL_ERROR:-32603},X=class{constructor(e){chunkISDIC2R6_cjs.a(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:r}=e;Re.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:r});try{let o;switch(t){case "initialize":o=await this.handleInitialize(n);break;case "authenticate":o=await this.handleAuthenticate(n);break;case "session.new":case "newSession":o=await this.handleNewSession(n);break;case "session.load":case "loadSession":o=await this.handleLoadSession(n);break;case "session.close":case "closeSession":o=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":o=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),o={success:!0};break;case "session.list":case "listSessions":o=await this.handleListSessions(n);break;case "session.fork":case "forkSession":o=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":o=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":o=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":o=await this.handleSetSessionConfigOption(n);break;case "status":o=this.handleStatus();break;case "subscriptions":o=this.handleSubscriptions();break;default:throw Re.warn("Unknown method",{method:t}),new utils.NameErrors.NotFoundError({message:`Method not found: ${t}`,location:"rpc-method"})}return {jsonrpc:"2.0",id:r,result:o}}catch(o){return Re.error("AcpRpcHandler error",{method:t,error:utils.errorMeta(o)}),{jsonrpc:"2.0",id:r,error:{code:K.INTERNAL_ERROR,message:utils.errorMeta(o).message}}}}async handleInitialize(e){return this.agent.initialize(e)}async handleAuthenticate(e){return this.agent.authenticate(e)}async handleNewSession(e){return this.agent.newSession(e)}async handleLoadSession(e){return this.agent.loadSession(e)}async handleCloseSession(e){return this.agent.closeSession(e)}async handlePrompt(e){return this.agent.prompt(e)}async handleCancel(e){return this.agent.cancel(e)}async handleListSessions(e){return this.agent.listSessions(e)}async handleForkSession(e){return this.agent.unstable_forkSession(e)}async handleResumeSession(e){return this.agent.resumeSession(e)}async handleSetSessionMode(e){return this.agent.setSessionMode(e)}async handleSetSessionConfigOption(e){return this.agent.setSessionConfigOption(e)}handleStatus(){return {status:"running",channel:"http",timestamp:Date.now(),uptime:process.uptime()}}handleSubscriptions(){return {sessions:[]}}};var he=utils.Log.create({service:"acp.server.agent-side-connection"}),ee=class{constructor(){chunkISDIC2R6_cjs.a(this,"broadcaster",null);chunkISDIC2R6_cjs.a(this,"sessionIds",new Set);chunkISDIC2R6_cjs.a(this,"sessionRefCounts",new Map);}setBroadcaster(e){this.broadcaster=e;}addSession(e){this.sessionIds.add(e),this.sessionRefCounts.set(e,(this.sessionRefCounts.get(e)??0)+1);}removeSession(e){let t=this.sessionRefCounts.get(e)??0;if(t<=1){this.sessionRefCounts.delete(e),this.sessionIds.delete(e);return}this.sessionRefCounts.set(e,t-1);}clearSessions(){this.sessionIds.clear(),this.sessionRefCounts.clear();}getSessions(){return Array.from(this.sessionIds)}async sessionUpdate(e){let{sessionId:t,update:n}=e;he.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return he.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async request(e,t){return he.debug("ServerAgentSideConnection.request",{method:e}),{}}async notify(e,t){if(he.debug("ServerAgentSideConnection.notify",{method:e,params:t}),this.broadcaster&&t){let n=t.sessionId||t.sessionId;if(n&&this.sessionIds.has(n)){let r={sessionId:n,update:{sessionUpdate:e,...t}};this.broadcaster.broadcast(n,r);}}}};var z=utils.Log.create({service:"acp.server.http"});async function Qe(s,e){if(z.info("Starting HTTP server",{port:e.port,hostname:e.hostname}),e.channel!==F.HTTP)throw new utils.NameErrors.InvalidArgumentError({message:`Invalid channel type for HTTP server: ${e.channel}`,param:"channel"});let t=new Map,n=new Map,r=new ee,o={broadcast:(i,u)=>{b(i,u);}};r.setBroadcaster(o);let d=new X(s),p=s.getSDK();if(!p)throw new utils.NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let m=new G(p,r);m.setService(s);let h=(i,u)=>{let a=t.get(i);if(!a)return false;try{return a.controller.enqueue(new TextEncoder().encode(u)),a.lastHeartbeat=Date.now(),!0}catch(l){return z.warn("Failed to push to SSE connection",{connectionId:i,error:utils.errorMeta(l)}),false}},b=(i,u)=>{let a=n.get(i);if(!a||a.size===0)return;let g={jsonrpc:"2.0",method:u.update.sessionUpdate,params:{sessionId:i,...u.update,timestamp:Date.now()}},I=`data: ${JSON.stringify(g)}
2
+
3
+ `;for(let f of a)h(f,I)||(t.delete(f),a.delete(f),r.removeSession(i));},w=(i,u)=>(r.addSession(i),new ReadableStream({start:async a=>{let l={id:u,controller:a,sessionId:i,createdAt:Date.now(),lastHeartbeat:Date.now()};t.set(u,l),n.has(i)||n.set(i,new Set),n.get(i).add(u),z.debug("SSE client connected",{connectionId:u,sessionId:i});let g=`data: ${JSON.stringify({type:"connected",connectionId:u,sessionId:i})}
4
+
5
+ `;a.enqueue(new TextEncoder().encode(g)),s.sendAvailableCommandsUpdate(i).catch(I=>{z.warn("Failed to send initial available commands update",{sessionId:i,connectionId:u,error:utils.errorMeta(I)});});},cancel:()=>{let a=t.get(u);if(a){t.delete(u);let l=n.get(a.sessionId);l&&(l.delete(u),l.size===0&&n.delete(a.sessionId)),r.removeSession(a.sessionId),z.debug("SSE client disconnected",{connectionId:u,sessionId:a.sessionId});}}})),y=null,x=()=>{y||(y=setInterval(()=>{let i=Date.now(),u=3e5;for(let[a,l]of t.entries())if(i-l.lastHeartbeat>u){z.warn("SSE connection timeout, closing",{connectionId:a});try{l.controller.close();}catch{}t.delete(a);let g=n.get(l.sessionId);g&&(g.delete(a),g.size===0&&n.delete(l.sessionId)),r.removeSession(l.sessionId);}else try{l.controller.enqueue(new TextEncoder().encode(`: heartbeat
6
+
7
+ `)),l.lastHeartbeat=i;}catch{}},1e4));},C=[{method:"post",path:"/acp",handler:async i=>{let u=await i.req.json().catch(()=>null);if(!u||typeof u!="object")return i.json({jsonrpc:"2.0",error:{code:K.PARSE_ERROR,message:"Parse error"}},400);let a=u;if(!a.method||a.jsonrpc!=="2.0")return i.json({jsonrpc:"2.0",error:{code:K.INVALID_REQUEST,message:"Invalid Request"}},400);if(a.method==="session.prompt")return d.handle(a).catch(g=>{z.error("HTTP server: session.prompt error",{error:utils.errorMeta(g)});}),i.json({jsonrpc:"2.0",id:a.id,result:{accepted:true}},202);let l=await d.handle(a);if(a.method==="initialize"){let g=`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;return i.json(l,200,{"Acp-Connection-Id":g})}return i.json(l)}},{method:"get",path:"/acp",handler:i=>{let u=i.req.header("Acp-Connection-Id"),a=i.req.header("Acp-Session-Id");if(!i.req.header("Accept")?.includes("text/event-stream"))return i.json({error:"Not Acceptable"},406);let g=u||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(a){let v=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,S=w(a,v);return new Response(S,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":g,"Acp-Session-Id":a}})}let I=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,f=w("__connection__",I);return new Response(f,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":g}})}},{method:"delete",path:"/acp",handler:async i=>{let u=i.req.header("Acp-Connection-Id");return z.debug("HTTP server: connection terminated",{connectionId:u}),i.json({success:true})}}],c=utils.createServer({port:e.port,hostname:e.hostname,routes:C,timeout:e.timeout,cors:true});try{await m.start(),s.setPeer(r),x();}catch(i){throw z.error("HTTP server: failed to start background resources, cleaning up",{error:utils.errorMeta(i)}),await m.stop().catch(()=>{}),y&&(clearInterval(y),y=null),await c.stop().catch(()=>{}),i}return z.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:c,stop:async()=>{z.info("Stopping HTTP server"),y&&(clearInterval(y),y=null),await m.stop();for(let i of t.values())try{i.controller.close();}catch{}t.clear(),n.clear(),r.clearSessions(),await c.stop(),z.info("HTTP server stopped");}}}var H=utils.Log.create({service:"acp.server.websocket"});function zt(s){try{let e=new URL(s),t=e.hostname,n=parseInt(e.port,10);if(t&&!Number.isNaN(n)&&n>0&&n<=65535)return {port:n,hostname:t}}catch{}}async function Ye(s,e){let t=e.ws?zt(e.ws.url):void 0,n=t?.port??e.port??3e3,r=t?.hostname??e.hostname??"localhost",o="/acp";if(H.info("Starting WebSocket server",{port:n,hostname:r,wsUrl:e.ws?.url}),e.channel!==F.WEBSOCKET)throw new utils.NameErrors.InvalidArgumentError({message:`Invalid channel type for WebSocket server: ${e.channel}`,param:"channel"});let d=new Map,p=new Map,m=new ee,h={broadcast:(f,v)=>{x(f,v);}};m.setBroadcaster(h);let b=new X(s),w=s.getSDK();if(!w)throw new utils.NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let y=new G(w,m);y.setService(s);let x=(f,v)=>{let _={jsonrpc:"2.0",method:v.update.sessionUpdate,params:{sessionId:f,...v.update,timestamp:Date.now()}},k=JSON.stringify(_);for(let[M,R]of p.entries())if(R.subscribedSessions.has(f)){let O=d.get(M);O&&O.ws.readyState===O.ws.OPEN&&O.ws.send(k);}},C=f=>{for(let[v,S]of d.entries())if(S.ws===f)return v},c=(f,v)=>{let S=p.get(f);S&&(S.subscribedSessions.has(v)||(S.subscribedSessions.add(v),m.addSession(v)));},i=(f,v)=>{let S=p.get(f);S&&S.subscribedSessions.has(v)&&(S.subscribedSessions.delete(v),m.removeSession(v));},u={onOpen:(f,v)=>{let S=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;d.set(S,{id:S,ws:v,createdAt:Date.now()}),p.set(S,{clientId:S,subscribedSessions:new Set}),H.debug("WebSocket client connected",{clientId:S}),v.send(JSON.stringify({type:"connected",clientId:S}));},onMessage:async(f,v)=>{try{let S=JSON.parse(f.data.toString());if(S.type==="ping"){v.send(JSON.stringify({type:"pong"}));return}let _=C(v);if(!_)return;let k,M;if(S.type==="message"||S.type==="request")k={jsonrpc:"2.0",id:S.id,method:S.method,params:S.params},M=S.sessionId;else if(S.jsonrpc==="2.0"&&S.method)k={jsonrpc:"2.0",id:S.id,method:S.method,params:S.params},M=S.params?.sessionId;else {H.warn("WebSocket server: unknown message format",{data:S});return}if(k.method==="session.subscribe"){M&&(c(_,M),s.sendAvailableCommandsUpdate(M).catch(O=>{H.warn("Failed to send initial available commands update",{sessionId:M,error:utils.errorMeta(O)});})),v.send(JSON.stringify({type:"response",id:k.id,result:{subscribed:!0,sessionId:M}}));return}if(k.method==="session.unsubscribe"){M&&i(_,M),v.send(JSON.stringify({type:"response",id:k.id,result:{unsubscribed:!0,sessionId:M}}));return}if(k.method==="session.interrupt"){let O={jsonrpc:"2.0",method:"session.cancel",params:{sessionId:M}},le=await b.handle(O);v.send(JSON.stringify({type:"response",id:k.id,result:le.result,error:le.error}));return}if(k.method==="session.prompt"){if(v.send(JSON.stringify({jsonrpc:"2.0",id:k.id,result:{accepted:!0}})),M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}b.handle(k).catch(O=>{H.error("WebSocket server: session.prompt error",{error:utils.errorMeta(O)});});return}if(M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}let R=await b.handle(k);v.send(JSON.stringify({type:"response",id:R.id,result:R.result,error:R.error}));}catch(S){H.error("WebSocket server: error handling message",{error:utils.errorMeta(S)});}},onClose:(f,v)=>{let S=C(v);if(S){d.delete(S);let _=p.get(S);if(_){for(let k of _.subscribedSessions)m.removeSession(k);p.delete(S);}H.debug("WebSocket client disconnected",{clientId:S});}},onError:(f,v)=>{H.error("WebSocket error",{error:f.type});}},a=utils.createServer({port:n,hostname:r,routes:[{method:"post",path:"/acp",handler:async f=>{let v=await f.req.json().catch(()=>null);if(!v||typeof v!="object")return f.json({jsonrpc:"2.0",error:{code:K.PARSE_ERROR,message:"Parse error"}},400);let S=v;if(!S.method||S.jsonrpc!=="2.0")return f.json({jsonrpc:"2.0",error:{code:K.INVALID_REQUEST,message:"Invalid Request"}},400);let _=await b.handle(S);return f.json(_)}},{method:"delete",path:"/acp",handler:async f=>{let v=f.req.header("Acp-Connection-Id");return H.debug("WebSocket server: connection terminated",{connectionId:v}),f.json({success:true})}}],timeout:e.timeout,cors:true}),l=a.raw,g=null,I=null;l&&(g=new ws.WebSocketServer({noServer:true}),I=(f,v,S)=>{try{let k=new URL(f.url||"/",`http://${f.headers.host}`).pathname,M=f.headers.upgrade?.toLowerCase();k===o&&M==="websocket"&&g.handleUpgrade(f,v,S,R=>{u.onOpen?.({type:"open"},R),R.on("message",O=>{u.onMessage?.({data:O},R);}),R.on("close",(O,le)=>{u.onClose?.({code:O,reason:le},R);}),R.on("error",O=>{u.onError?.({type:"error",message:utils.errorMeta(O).message},R);});});}catch{}},l.on("upgrade",I));try{await y.start(),s.setPeer(m);}catch(f){if(H.error("WebSocket server: failed to start background resources, cleaning up",{error:utils.errorMeta(f)}),await y.stop().catch(()=>{}),l&&I&&(l.off("upgrade",I),I=null),g){try{await new Promise(v=>g.close(()=>v()));}catch{}g=null;}throw await a.stop().catch(()=>{}),f}return H.info("WebSocket server started",{url:e.ws?.url||`ws://${r}:${n}`,path:o}),{server:a,stop:async()=>{H.info("Stopping WebSocket server"),await y.stop(),l&&I&&(l.off("upgrade",I),I=null);for(let f of d.values())try{f.ws.close();}catch{}if(d.clear(),p.clear(),m.clearSessions(),g){try{await new Promise(f=>g.close(()=>f()));}catch{}g=null;}await a.stop(),H.info("WebSocket server stopped");}}}var ie=utils.Log.create({service:"acp.server.core"});async function Je(s,e){let t=je(e||{});ie.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,r;switch(t.channel){case F.HTTP:({server:n,stop:r}=await Qe(s,t));break;case F.WEBSOCKET:({server:n,stop:r}=await Ye(s,t));break;default:throw new utils.NameErrors.InvalidArgumentError({message:`Unsupported service mode: ${t.channel}`,param:"channel"})}let o={type:t.channel,server:n,agent:s,stop:async()=>{ie.info("Stopping ACPServer",{type:t.channel}),await r();},healthCheck:async()=>{if(typeof n=="object"&&n!==null&&"healthCheck"in n){let d=n.healthCheck;if(typeof d=="function")return d()}return true}};return ie.info("ACPServer started successfully",{type:o.type,url:Wt(t)}),o}function Wt(s){return chunkSNWAB3QJ_cjs.t({channel:s.channel,hostname:s.hostname,port:s.port})??"unknown://"}async function jt(s){await Promise.all(s.map(async e=>{try{await e.stop();}catch(t){ie.error("Error stopping server",{type:e.type,error:utils.errorMeta(t)});}}));}async function Ze(s){await jt([s]);}function Ks(s){return {type:s.channel,server:null,agent:null,stop:async()=>{ie.warn("Server not started, nothing to stop");},healthCheck:async()=>false}}var Zt=url.fileURLToPath(chunkISDIC2R6_cjs.b),Xt=mt.dirname(Zt),tt="0.0.0";try{let s=mt.join(Xt,"..","package.json");tt=JSON.parse(fs$1.readFileSync(s,"utf-8")).version??"0.0.0";}catch{}var q=utils.Log.create({service:"acp.easbot-agent"}),ae=class s extends se{constructor(t,n){super(t,n);chunkISDIC2R6_cjs.a(this,"acpEventBridge",null);chunkISDIC2R6_cjs.a(this,"server",null);chunkISDIC2R6_cjs.a(this,"isAgentInitialized",false);chunkISDIC2R6_cjs.a(this,"connection",null);q.info("EasBotAgent instance created",{serviceMode:this.serviceMode});}static async create(t){q.info("creating EasBotAgent",{serviceMode:t.serviceMode});let n=t.serviceMode==="stdio",r=new s(void 0,t);if(n&&t.stdioStream){let{stream:o}=t.stdioStream,d=r.createAgentApp();r.connection=d.connect(o);}return q.info("EasBotAgent created successfully",{serviceMode:t.serviceMode,hasConnection:n&&!!t.stdioStream}),r}createAgentApp(){return unstable.agent({name:"EasBot Agent"}).onConnect(t=>{this.setPeer(new oe(t.client));}).onRequest(unstable.methods.agent.initialize,({params:t})=>this.initialize(t)).onRequest(unstable.methods.agent.session.new,({params:t})=>this.newSession(t)).onRequest(unstable.methods.agent.session.load,({params:t})=>this.loadSession(t)).onRequest(unstable.methods.agent.session.prompt,({params:t})=>this.prompt(t)).onRequest(unstable.methods.agent.session.list,({params:t})=>this.listSessions(t)).onRequest(unstable.methods.agent.session.fork,({params:t})=>this.unstable_forkSession(t)).onRequest(unstable.methods.agent.session.resume,({params:t})=>this.resumeSession(t)).onRequest(unstable.methods.agent.session.close,({params:t})=>this.closeSession(t)).onRequest(unstable.methods.agent.session.setMode,({params:t})=>this.setSessionMode(t)).onRequest(unstable.methods.agent.session.setConfigOption,({params:t})=>this.setSessionConfigOption(t)).onRequest(unstable.methods.agent.authenticate,({params:t})=>this.authenticate(t)).onNotification(unstable.methods.agent.session.cancel,({params:t})=>this.cancel(t))}async initialize(t){return q.info("ACP initialize requested",{protocolVersion:t.protocolVersion}),this.isAgentInitialized||await this.initializeAgent(),{protocolVersion:t.protocolVersion,agentCapabilities:{loadSession:true,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:tt,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){q.warn("EasBotAgent already initialized");return}q.info("initializing EasBotAgent internals");try{await this.initializeExecutor(),this.config.acpServerConfig||await this.initializeAcpEventBridge(),this.isAgentInitialized=!0,this.setStatus("ready"),q.info("EasBotAgent internals initialized successfully");}catch(t){throw this.setStatus("error"),q.error("failed to initialize EasBotAgent",{error:utils.errorMeta(t)}),t}}async start(){if(this.status==="running"){q.warn("EasBotAgent already running");return}this.isAgentInitialized||await this.initializeAgent();let t=this.config;t.acpServerConfig&&!this.server&&(this.server=await Je(this,t.acpServerConfig)),this.setStatus("running"),q.info("EasBotAgent started");}async stop(){if(this.status==="stopped"){q.warn("EasBotAgent already stopped");return}q.info("stopping EasBotAgent");try{this.server&&(await Ze(this.server),this.server=null),this.acpEventBridge&&(await this.acpEventBridge.stop(),this.acpEventBridge=null),this.connection&&(this.connection.close(),this.connection=null),await this.dispose(),this.setStatus("stopped"),this.isAgentInitialized=!1,q.info("EasBotAgent stopped successfully");}catch(t){throw this.setStatus("error"),q.error("error stopping EasBotAgent",{error:utils.errorMeta(t)}),t}}async initializeAcpEventBridge(){if(this.acpEventBridge){q.warn("ACP event bridge already initialized");return}let n=this.config.acp?.sdk,r=this.getPeer();if(!n)throw q.error("Cannot initialize ACP event bridge: missing SDK client"),new utils.NameErrors.MissingFieldError({message:"SDK client is required for ACP event bridge",field:"sdk"});if(!r)throw q.error("Cannot initialize ACP event bridge: missing ACP peer"),new utils.NameErrors.MissingFieldError({message:"ACP peer is required for ACP event bridge",field:"peer"});this.acpEventBridge=new G(n,r),this.acpEventBridge.setService(this),await this.acpEventBridge.start(),q.info("ACP event bridge initialized");}getServiceMode(){return this.serviceMode}getServerInstance(){return this.server}getSDK(){return this.sdk}};var $=utils.Log.create({service:"acp.bootstrap.gateway"}),st=6e4;function sn(s){if(s.channel===chunkRGGMCKYA_cjs.b.WS){let t=s.ws?.url??chunkSNWAB3QJ_cjs.t({channel:"websocket",hostname:s.hostname,port:s.port});return t?t.includes("/acp")?t:`${t.replace(/\/$/,"")}/acp`:`unknown://${s.hostname}:${s.port}`}return s.channel===chunkRGGMCKYA_cjs.b.HTTP&&s.http?.baseUrl?s.http.baseUrl:chunkSNWAB3QJ_cjs.t({channel:s.channel,hostname:s.hostname,port:s.port})??`unknown://${s.hostname}:${s.port}`}var ce=null;async function ot(s){if(s.channel===chunkRGGMCKYA_cjs.b.STDIO)return $.debug("Skipping gateway registration for stdio mode"),false;let e=chunk663BEBE4_cjs.l();if(!e)return $.debug("No gateway URL configured, skipping registration"),false;if(!e.autoRegister)return $.debug("Gateway auto-registration disabled, skipping registration"),false;if(ce)return $.debug("Gateway registration already active, skipping"),false;let t=s.agentId||utils.Identifier.ascending("agent"),n=s.name||"ACP Agent",r=sn(s),o={client:null,agentId:t,cycleTimer:null,registered:false,epoch:0,registerChain:Promise.resolve(),attemptRegister:async()=>{},active:true};ce=o;let d=async()=>{if(!o.active)throw new utils.NameErrors.OperationFailedError({operation:"acp-gateway-register",message:"Registration session is no longer active"});if(o.client.getState()!=="connected")throw new utils.NameErrors.OperationFailedError({operation:"acp-gateway-register",message:"Gateway not connected"});await o.client.registerAgent({agentId:t,name:n,address:r,capabilities:[s.channel],metadata:{hostname:s.hostname,port:s.port,channel:s.channel}});},p=async()=>{!o.active||o.registered||o.client.getState()==="connected"&&(o.registerChain=o.registerChain.then(async()=>{if(!o.active||o.registered||o.client.getState()!=="connected")return;let h=o.epoch;try{if(await d(),h!==o.epoch){$.debug("Discarding stale registration result",{agentId:t,epochAtStart:h,epoch:o.epoch});return}o.registered=!0,$.info("Registered to gateway",{agentId:t,agentName:n,address:r});}catch(b){o.registered=false,$.errorDegradable("Agent registration failed, will retry on next cycle",{error:utils.errorMeta(b),agentId:t});}}),await o.registerChain);};o.attemptRegister=p;let m=h=>{o.active&&(h==="connected"?(o.epoch+=1,o.registered=false,p(),on(o)):h==="disconnected"&&(o.registered=false));};return o.client=new utils.GatewayClient({baseUrl:e.url,type:"acp",id:`acp-${t}`,heartbeat:{enabled:true,interval:st},onStateChange:h=>{m(h);}}),true}function on(s){s.cycleTimer||(s.cycleTimer=setInterval(()=>{rn(s);},st));}async function rn(s){if(s.active&&s.client.getState()==="connected"){if(!s.registered){await s.attemptRegister();return}try{await s.client.agentHeartbeat(s.agentId);}catch(e){$.errorDegradable("Agent heartbeat failed",{error:utils.errorMeta(e)});}}}function an(s){s.cycleTimer&&(clearInterval(s.cycleTimer),s.cycleTimer=null);}async function rt(){let s=ce;if(s){s.active=false,ce=null,an(s);try{await s.client.deregisterAgent(s.agentId),$.debug("Agent deregistered from gateway",{agentId:s.agentId});}catch(e){$.errorDegradable("Failed to deregister agent",{error:utils.errorMeta(e)});}try{await s.client.disconnect();}catch(e){$.errorDegradable("Failed to disconnect from gateway",{error:utils.errorMeta(e)});}}}function Ro(){return ce!==null}function it(s,e,t){return new chunkSNWAB3QJ_cjs.c.AdapterEnvironmentInitializationError({message:s,stage:e},t?{cause:t}:void 0)}var Y=utils.Log.create({service:"acp.bootstrap"}),ct=utils.State.holder(()=>{try{let s=chunk663BEBE4_cjs.f().directory;return s?utils.Filesystem.normalize(s):"__acp_bootstrap_global__"}catch{return "__acp_bootstrap_global__"}},async()=>({initialized:false,initPromise:null,instancePromise:null,handlersInstalled:false,unhandledRejectionHandler:null,uncaughtExceptionHandler:null,stdinDataHandler:null,stdinEndHandler:null,stdinErrorHandler:null,directory:".easbot",sdk:null,activeChannel:null,agent:null,acpConnection:null}),async s=>{let e=s.agent;e&&await e.stop().catch(()=>{}),dt(s),lt(s),s.agent=null,s.sdk=null,s.acpConnection=null;});async function W(){return ct.get()}function at(s){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=s.code;return e.includes(t??"")}function gn(s){if(s.handlersInstalled)return;let e=n=>{let r=n instanceof Error?n:new Error(utils.errorMeta(n).message);at(r)||Y.error("unhandled promise rejection",{error:utils.errorMeta(r)});},t=n=>{at(n)||(Y.error("uncaught exception",{error:utils.errorMeta(n)}),process.exit(1));};process.on("unhandledRejection",e),process.on("uncaughtException",t),s.unhandledRejectionHandler=e,s.uncaughtExceptionHandler=t,s.handlersInstalled=true;}function dt(s){s.handlersInstalled&&(s.unhandledRejectionHandler&&(process.off("unhandledRejection",s.unhandledRejectionHandler),s.unhandledRejectionHandler=null),s.uncaughtExceptionHandler&&(process.off("uncaughtException",s.uncaughtExceptionHandler),s.uncaughtExceptionHandler=null),s.handlersInstalled=false);}function lt(s){s.stdinDataHandler&&(process.stdin.off("data",s.stdinDataHandler),s.stdinDataHandler=null),s.stdinEndHandler&&(process.stdin.off("end",s.stdinEndHandler),s.stdinEndHandler=null),s.stdinErrorHandler&&(process.stdin.off("error",s.stdinErrorHandler),s.stdinErrorHandler=null);try{process.stdin.pause();}catch{}}async function mn(s){return s.instancePromise||(s.instancePromise=(async()=>{let e=chunk663BEBE4_cjs.f();(!e.directory||e.directory===process.cwd())&&chunk663BEBE4_cjs.d({directory:s.directory,worktree:s.directory}),Y.debug("instance bootstrap completed",{directory:s.directory});})()),s.instancePromise}async function fn(){try{chunk663BEBE4_cjs.e(),Y.debug("instance adapter reset");}catch(s){Y.debug("instance dispose skipped",{error:utils.errorMeta(s)});}}exports.x=void 0;(C=>{async function s(c,i){if(c.sdk)return c.sdk;let{getSdk:u}=await import('./interfaces-CGLEY6OS.cjs');return c.sdk=await u(),c.sdk}function e(c){switch(c){case chunkRGGMCKYA_cjs.b.STDIO:return "stdio";case chunkRGGMCKYA_cjs.b.HTTP:return "http";case chunkRGGMCKYA_cjs.b.WS:return "websocket";default:return "stdio"}}function t(){ct.clear();}C.resetState=t;async function n(c){let i=await W();if(i.initialized)return;if(i.initPromise)return i.initPromise;let u={directory:c?.directory??".easbot",initModels:c?.initModels??true,printLogs:c?.printLogs??false,logLevel:c?.logLevel??"INFO",channel:c?.channel??chunkRGGMCKYA_cjs.b.STDIO};if(i.directory=u.directory,await s(i,i.directory),i.activeChannel&&i.activeChannel!==u.channel)throw new utils.NameErrors.OperationFailedError({message:`Adapter already initialized with channel ${i.activeChannel}, cannot re-init with ${u.channel}`,operation:"adapter-init"});return i.activeChannel=u.channel,i.initPromise=(async()=>{try{gn(i);}catch(a){throw it("Failed to install unhandled exception handlers","handlers",a instanceof Error?a:void 0)}try{await mn(i);}catch(a){throw it("Failed to initialize instance","instance",a instanceof Error?a:void 0)}try{await chunk6VF3MZ6H_cjs.r.init();}catch(a){Y.warn("AcpCache init failed, falling back to lazy load",{error:utils.errorMeta(a)});}utils.ConfigFileWatcher.init(),chunkOQH5ALTQ_cjs.a.init(),i.initialized=true;})(),i.initPromise}C.init=n;async function r(){let c=await W();c.initialized&&(c.agent&&(await c.agent.stop().catch(()=>{}),c.agent=null),await rt(),dt(c),lt(c),await fn(),c.initialized=false,c.initPromise=null,c.instancePromise=null,c.activeChannel=null,c.sdk=null,c.agent=null,c.acpConnection=null);}C.destroy=r;async function o(){return (await W()).initialized}C.isInitialized=o;async function d(c){let i=await W();i.agent=c;}C.setAgent=d;async function p(){return (await W()).agent}C.getAgent=p;async function m(){let i=(await W()).agent?.getServerInstance();return i||null}C.getServer=m;async function h(){return (await W()).sdk}C.getSDK=h;async function b(){return (await W()).acpConnection}C.getACPConnection=b;async function w(){let c=await W(),i=!!c.agent?.getServerInstance();return {initialized:c.initialized,directory:c.directory,activeChannel:c.activeChannel,hasSDK:!!c.sdk,hasAgent:!!c.agent,hasACPConnection:!!c.acpConnection,hasServer:i}}C.getState=w;async function y(c){await n({channel:c.channel,directory:c.directory});let i=await W(),u=await s(i,i.directory);if(c.channel===chunkRGGMCKYA_cjs.b.STDIO)return x({directory:c.directory});if(i.agent?.getServerInstance()&&i.activeChannel&&i.activeChannel!==c.channel)throw new utils.NameErrors.OperationFailedError({message:`ACP service already started with channel ${i.activeChannel}, cannot switch to ${c.channel}`,operation:"adapter-switch-channel"});if(i.agent){let I=i.agent.getServerInstance();if(I)return {sdk:u,agent:i.agent,server:I}}let l=await ae.create({serviceMode:e(c.channel),acp:{sdk:u},acpServerConfig:c,channel:{type:c.channel,timeout:c.timeout}});await l.start();let g=l.getServerInstance();if(!g)throw new utils.NameErrors.OperationFailedError({message:"ACP server failed to start",operation:"acp-server-start"});return i.agent=l,i.activeChannel=c.channel,await ot(c),{sdk:u,agent:l,server:g}}C.ensureACPService=y;async function x(c){await n({channel:chunkRGGMCKYA_cjs.b.STDIO,directory:c.directory});let i=await W(),u=await s(i,i.directory);if(i.agent)return {sdk:u,agent:i.agent};let a=new WritableStream({write(f){return new Promise((v,S)=>{try{process.stdout.write(f)?v():process.stdout.once("drain",v);}catch(_){let k=_;k.code==="EPIPE"||k.code==="EIO"?S(new Error("stdout pipe broken")):S(_);}})}}),l=new ReadableStream({start(f){i.stdinDataHandler=v=>{try{f.enqueue(new Uint8Array(v));}catch{}},i.stdinEndHandler=()=>{try{f.close();}catch{}},i.stdinErrorHandler=v=>{try{f.error(v);}catch{}},process.stdin.on("data",i.stdinDataHandler),process.stdin.on("end",i.stdinEndHandler),process.stdin.on("error",i.stdinErrorHandler);}}),g=unstable.ndJsonStream(a,l),I=await ae.create({serviceMode:chunkRGGMCKYA_cjs.b.STDIO,acp:{sdk:u},channel:{type:chunkRGGMCKYA_cjs.b.STDIO,timeout:3e5},stdioStream:{stream:g}});return i.acpConnection=I.getPeer()??null,await I.start(),i.agent=I,i.activeChannel=chunkRGGMCKYA_cjs.b.STDIO,Y.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:u,agent:I}}C.ensureACPServiceStdio=x;})(exports.x||(exports.x={}));var zo=exports.x;
8
+ exports.a=G;exports.c=Ct;exports.d=pe;exports.e=we;exports.f=ge;exports.g=oe;exports.h=F;exports.i=He;exports.j=_t;exports.k=We;exports.l=fs;exports.m=ee;exports.n=Qe;exports.o=Ye;exports.p=Je;exports.q=Ks;exports.r=ae;exports.s=sn;exports.t=ot;exports.u=rt;exports.v=Ro;exports.w=it;exports.y=zo;