@easbot/agent 0.2.42 → 0.2.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/txt/command/builtin/loop.txt +10 -5
- package/dist/assets/txt/context/template/BOOT.txt +2 -0
- package/dist/assets/txt/scheduler/heartbeat.txt +18 -1
- package/dist/assets/txt/scheduler/scheduled.txt +17 -1
- package/dist/chunks/{acp-AJ7O6XNE.mjs → acp-OBY35HS7.mjs} +2 -2
- package/dist/chunks/adapter-loader-ZXPJJRRY.mjs +1 -0
- package/dist/chunks/{agent-SKRC54QG.mjs → agent-EJ64O3VC.mjs} +1 -1
- package/dist/chunks/{agent-VUPXBEWR.mjs → agent-WSRT77Z6.mjs} +1 -1
- package/dist/chunks/agent-service-registry-QA5V3B4G.mjs +1 -0
- package/dist/chunks/{app-EPNEAPMS.mjs → app-I6CHGBMN.mjs} +12 -12
- package/dist/chunks/{auth-34JK273T.mjs → auth-F3UJX6TK.mjs} +1 -1
- package/dist/chunks/bootstrap-O5UL3UT2.mjs +1 -0
- package/dist/chunks/build-program-LX6IAAHW.mjs +11 -0
- package/dist/chunks/bus-XKXFTFNZ.mjs +1 -0
- package/dist/chunks/{chunk-2YNYVTYT.mjs → chunk-3CQA7CJG.mjs} +1 -1
- package/dist/chunks/{chunk-BDS2JWYG.mjs → chunk-3UV6DBAA.mjs} +1 -1
- package/dist/chunks/{chunk-WGJIT5HU.mjs → chunk-4Q3JAZPL.mjs} +1 -1
- package/dist/chunks/{chunk-3472MC45.mjs → chunk-CDDE7L65.mjs} +1 -1
- package/dist/chunks/{chunk-JTVO3U27.mjs → chunk-EFJHO4OX.mjs} +1 -1
- package/dist/chunks/{chunk-EB3OP6TL.mjs → chunk-G63GWBVD.mjs} +1 -1
- package/dist/chunks/{chunk-J6VEDKPT.mjs → chunk-HIPEPY4E.mjs} +1 -1
- package/dist/chunks/{chunk-4OHDEBAX.mjs → chunk-LP2YYNMX.mjs} +1 -1
- package/dist/chunks/chunk-OSLGCE7R.mjs +1 -0
- package/dist/chunks/chunk-PT5TKWFJ.mjs +1051 -0
- package/dist/chunks/{chunk-UNBJ6Y7L.mjs → chunk-XQ3LMV3K.mjs} +2 -2
- package/dist/chunks/{chunk-PEMUENKB.mjs → chunk-ZH674M7Q.mjs} +1 -1
- package/dist/chunks/{command-CJGBEATT.mjs → command-34YNL5HZ.mjs} +1 -1
- package/dist/chunks/compaction-OCFEYJC4.mjs +1 -0
- package/dist/chunks/{config-YSZNIWZT.mjs → config-MLDSMYKU.mjs} +1 -1
- package/dist/chunks/{confirm-dialog-SJOXJWYU.mjs → confirm-dialog-PT62UY3W.mjs} +1 -1
- package/dist/chunks/{debug-GZCL57Q7.mjs → debug-GTUHAYVC.mjs} +3 -3
- package/dist/chunks/{export-4CIOZYMY.mjs → export-5BWFWBI3.mjs} +1 -1
- package/dist/chunks/file-P2YWB5Q7.mjs +1 -0
- package/dist/chunks/{gateway-D6XCB2OA.mjs → gateway-GFZFVEHP.mjs} +2 -2
- package/dist/chunks/{generate-NYQCTBY7.mjs → generate-FNIRYTGT.mjs} +1 -1
- package/dist/chunks/{github-IGWZXZRB.mjs → github-JPCEWX4N.mjs} +1 -1
- package/dist/chunks/global-HVRSDT3G.mjs +1 -0
- package/dist/chunks/{i18n-OMQXNLBR.mjs → i18n-4TNHSVRN.mjs} +1 -1
- package/dist/chunks/{import-TYN474UK.mjs → import-B5RTBC2W.mjs} +1 -1
- package/dist/chunks/installation-JDBMIGTK.mjs +1 -0
- package/dist/chunks/instance-5OB47GH5.mjs +1 -0
- package/dist/chunks/loader-GNE7KLKQ.mjs +1 -0
- package/dist/chunks/loader-J6SV3FLI.mjs +1 -0
- package/dist/chunks/lsp-QWPGRLGX.mjs +1 -0
- package/dist/chunks/{mcp-FYDYPGLE.mjs → mcp-5DZTVP6Z.mjs} +1 -1
- package/dist/chunks/mcp-KWZSND4L.mjs +1 -0
- package/dist/chunks/models-JIMJ74AN.mjs +1 -0
- package/dist/chunks/{pr-DQZIG2CT.mjs → pr-E7AEHZZT.mjs} +1 -1
- package/dist/chunks/preferences-KZ7TL4Q3.mjs +1 -0
- package/dist/chunks/project-3W6D3354.mjs +1 -0
- package/dist/chunks/prompt-7M7NMDG4.mjs +1 -0
- package/dist/chunks/provider-RGQTLMFK.mjs +1 -0
- package/dist/chunks/registry-AA7CYXUC.mjs +1 -0
- package/dist/chunks/revert-FOMRGDW5.mjs +1 -0
- package/dist/chunks/ripgrep-TBPFM3BV.mjs +1 -0
- package/dist/chunks/{run-EQ5GHPKF.mjs → run-MYXJU4RX.mjs} +1 -1
- package/dist/chunks/scheduler-YYOW743S.mjs +1 -0
- package/dist/chunks/server-SQMRITFT.mjs +1 -0
- package/dist/chunks/session-EPFSKATV.mjs +1 -0
- package/dist/chunks/session-FQ5O5XZY.mjs +1 -0
- package/dist/chunks/{session-R2LCLNAY.mjs → session-LWKQT4G7.mjs} +1 -1
- package/dist/chunks/{settings-panel-ZMAGAWRF.mjs → settings-panel-C32BQGOR.mjs} +1 -1
- package/dist/chunks/share-6NJ4W4CC.mjs +1 -0
- package/dist/chunks/snapshot-VO64Z4KV.mjs +1 -0
- package/dist/chunks/{stats-TREO4CFV.mjs → stats-6IILCYBN.mjs} +1 -1
- package/dist/chunks/storage-23DKEFPY.mjs +1 -0
- package/dist/chunks/{tui-FVQHBIJ7.mjs → tui-P4UKVVKY.mjs} +1 -1
- package/dist/chunks/{types-OIHWEQYC.mjs → types-2GDQRKMX.mjs} +1 -1
- package/dist/chunks/{types-GCXI5X7B.mjs → types-OCGSLJEP.mjs} +1 -1
- package/dist/chunks/{update-V3GTL4TX.mjs → update-NNMG3LC7.mjs} +1 -1
- package/dist/cli.mjs +2 -2
- package/package.json +13 -13
- package/dist/chunks/adapter-loader-VUS3UYMT.mjs +0 -1
- package/dist/chunks/agent-service-registry-DPO5SSXA.mjs +0 -1
- package/dist/chunks/bootstrap-3KXRWM6D.mjs +0 -1
- package/dist/chunks/build-program-2AR3LYQJ.mjs +0 -11
- package/dist/chunks/bus-QOWILU5Z.mjs +0 -1
- package/dist/chunks/chunk-2RSIOAZV.mjs +0 -1
- package/dist/chunks/chunk-XMIQEMED.mjs +0 -1051
- package/dist/chunks/compaction-R4RTVEDY.mjs +0 -1
- package/dist/chunks/file-G4WHJKUX.mjs +0 -1
- package/dist/chunks/global-5WFCDQ45.mjs +0 -1
- package/dist/chunks/installation-6S6OCY6F.mjs +0 -1
- package/dist/chunks/instance-YVRWMB6M.mjs +0 -1
- package/dist/chunks/loader-VV3FV5NS.mjs +0 -1
- package/dist/chunks/loader-XGUYA6ZM.mjs +0 -1
- package/dist/chunks/lsp-J7UR4JNX.mjs +0 -1
- package/dist/chunks/mcp-GEZSPY2W.mjs +0 -1
- package/dist/chunks/models-JNSS4QSZ.mjs +0 -1
- package/dist/chunks/preferences-QCM3RIAL.mjs +0 -1
- package/dist/chunks/project-53ZMRKRI.mjs +0 -1
- package/dist/chunks/prompt-XYHKPB7Q.mjs +0 -1
- package/dist/chunks/provider-2RFHZVX4.mjs +0 -1
- package/dist/chunks/registry-GGSZXBFC.mjs +0 -1
- package/dist/chunks/revert-7RBPZDWL.mjs +0 -1
- package/dist/chunks/ripgrep-U54LYBZO.mjs +0 -1
- package/dist/chunks/scheduler-3AYHIZGY.mjs +0 -1
- package/dist/chunks/server-ITUF2HX7.mjs +0 -1
- package/dist/chunks/session-5OU5P7UF.mjs +0 -1
- package/dist/chunks/session-XA4RMN7D.mjs +0 -1
- package/dist/chunks/share-45SYUA47.mjs +0 -1
- package/dist/chunks/snapshot-YC3DAH7Q.mjs +0 -1
- package/dist/chunks/storage-6F64537E.mjs +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {a as a$1,b as b$1}from'./chunk-CQVEAYYW.mjs';import {na,ta,va,ua,qa,ra,sa,Ka,oa,pa,za,Q,la}from'./chunk-
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-CQVEAYYW.mjs';import {na,ta,va,ua,qa,ra,sa,Ka,oa,pa,za,Q,la}from'./chunk-PT5TKWFJ.mjs';import {b as b$2}from'./chunk-4Q3JAZPL.mjs';import {c}from'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import {k as k$1,c as c$1}from'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import {i}from'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$2}from'./chunk-3UV6DBAA.mjs';import {b}from'./chunk-X6ISXWBN.mjs';import {Input,truncateToWidth,isKeyRelease,getKeybindings,Container,Text,Markdown,Editor,matchesKey,Key}from'@easbot/tui';import {randomUUID}from'crypto';import {loadTextFile,Shell,parseModelId,Filesystem}from'@easbot/utils';import {readdirSync,existsSync}from'fs';import zt from'path';import {pathToFileURL}from'url';import {SdkEventBus,SdkEventBridge,SdkEventType}from'@easbot/gateway';var $e=class extends Editor{constructor(t,n){super(t,n);b(this,"onEscape");b(this,"onCtrlC");b(this,"onCtrlD");b(this,"onCtrlG");b(this,"onCtrlL");b(this,"onCtrlO");b(this,"onCtrlP");b(this,"onCtrlT");b(this,"inputHandlerManager");}setInputHandlerManager(t){this.inputHandlerManager=t;}addToHistory(t){this.inputHandlerManager?.isHistoryBrowsing()||super.addToHistory(t);}handleInput(t){t.includes("\x1B")||t.includes("\r")||t.includes(`
|
|
2
2
|
`);let n=matchesKey(t,Key.up)||matchesKey(t,Key.down);if(n&&this.inputHandlerManager?this.inputHandlerManager.setHistoryBrowsing(true):this.inputHandlerManager&&!n&&(matchesKey(t,Key.ctrl("l"))||matchesKey(t,Key.ctrl("o"))||matchesKey(t,Key.ctrl("p"))||matchesKey(t,Key.ctrl("g"))||matchesKey(t,Key.ctrl("t"))||matchesKey(t,Key.escape)||matchesKey(t,Key.ctrl("c"))||matchesKey(t,Key.ctrl("d"))||this.inputHandlerManager.setHistoryBrowsing(false)),matchesKey(t,Key.ctrl("l"))&&this.onCtrlL){this.onCtrlL();return}if(matchesKey(t,Key.ctrl("o"))&&this.onCtrlO){this.onCtrlO();return}if(matchesKey(t,Key.ctrl("p"))&&this.onCtrlP){this.onCtrlP();return}if(matchesKey(t,Key.ctrl("g"))&&this.onCtrlG){this.onCtrlG();return}if(matchesKey(t,Key.ctrl("t"))&&this.onCtrlT){this.onCtrlT();return}if(matchesKey(t,Key.escape)){if(this.isShowingAutocomplete()){super.handleInput(t);return}if(this.onEscape){this.onEscape();return}}if(matchesKey(t,Key.ctrl("c"))&&this.onCtrlC){this.onCtrlC();return}if(matchesKey(t,Key.ctrl("d"))){this.getText().length===0&&this.onCtrlD&&this.onCtrlD();return}super.handleInput(t);}};var C={text:"#E8E3D5",dim:"#7B7F87",accent:"#F6C453",accentSoft:"#F2A65A",border:"#3C414B",userBg:"#2B2F36",userText:"#5A9F7A",userLabel:"#5A9F7A",systemText:"#9BA3B2",systemLabel:"#7B7F87",assistantLabel:"#B85C5C",subagentLabel:"#9B72CF",subagentBg:"#2A2535",toolPendingBg:"#1F2A2F",toolSuccessBg:"#1E2D23",toolErrorBg:"#2F1F1F",toolTitle:"#F6C453",toolOutput:"#E1DACB",quote:"#8CC8FF",quoteBorder:"#3B4D6B",code:"#F0C987",codeBorder:"#343A45",link:"#7DD3A5",error:"#F97066",success:"#7DD3A5"},I=s=>e=>`\x1B[38;2;${Lt(s)}m${e}\x1B[0m`,Ie=s=>e=>`\x1B[48;2;${Lt(s)}m${e}\x1B[0m`,ye=s=>`\x1B[1m${s}\x1B[0m`,nt=s=>`\x1B[3m${s}\x1B[0m`;function Lt(s){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);if(!e)return "255;255;255";let t=Number.parseInt(e[1]||"0",16),n=Number.parseInt(e[2]||"0",16),i=Number.parseInt(e[3]||"0",16);return `${t};${n};${i}`}var rs={selectedPrefix:s=>I(C.accent)(s),selectedText:s=>ye(I(C.accent)(s)),description:s=>I(C.dim)(s),scrollInfo:s=>I(C.dim)(s),noMatch:s=>I(C.dim)(s)},Z={fg:I(C.text),assistantText:s=>s,dim:I(C.dim),accent:I(C.accent),accentSoft:I(C.accentSoft),success:I(C.success),error:I(C.error),header:s=>ye(I(C.accent)(s)),system:I(C.systemText),userBg:Ie(C.userBg),userText:I(C.userText),userLabel:s=>I(C.userLabel)(s),systemLabel:s=>I(C.systemLabel)(s),assistantLabel:s=>I(C.assistantLabel)(s),subagentLabel:s=>I(C.subagentLabel)(s),subagentBg:Ie(C.subagentBg),subagent:s=>I(C.subagentLabel)(s),toolTitle:I(C.toolTitle),toolOutput:I(C.toolOutput),toolPendingBg:Ie(C.toolPendingBg),toolSuccessBg:Ie(C.toolSuccessBg),toolErrorBg:Ie(C.toolErrorBg),border:I(C.border),bold:ye,italic:nt,user:s=>I(C.userText)(s),assistant:s=>I(C.text)(s),code:I(C.code),quote:I(C.quote),link:I(C.link),tool:I(C.toolTitle),thinking:s=>nt(I(C.dim)(s)),warning:I(C.accentSoft),muted:I(C.dim),highlight:s=>ye(I(C.accent)(s))},os=rs;function as(s,e){let t=s.split(`
|
|
3
|
-
`);if(!e)return t.map(a=>I(C.code)(a));let n={keyword:I("#C586C0"),string:I("#CE9178"),comment:I("#6A9955"),number:I("#B5CEA8"),function:I("#DCDCAA"),type:I("#4EC9B0"),operator:I("#D4D4D4"),default:I(C.code)},i=e.toLowerCase();return i==="typescript"||i==="ts"||i==="javascript"||i==="js"?t.map(a=>ls(a,n)):i==="python"||i==="py"?t.map(a=>ds(a,n)):i==="bash"||i==="sh"||i==="shell"?t.map(a=>cs(a,n)):i==="json"?t.map(a=>us(a,n)):t.map(a=>n.default(a))}function ls(s,e){if(s.trim().startsWith("//"))return e.comment?.(s)??s;let t=/\b(const|let|var|function|async|await|return|if|else|for|while|class|interface|type|import|export|from|default|new|this|super|extends|implements)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"`])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\b\d+(\.\d+)?\b/g,i=>e.number?.(i)??i),n}function ds(s,e){if(s.trim().startsWith("#"))return e.comment?.(s)??s;let t=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|with|async|await|lambda|yield|pass|break|continue|None|True|False)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\b\d+(\.\d+)?\b/g,i=>e.number?.(i)??i),n}function cs(s,e){if(s.trim().startsWith("#"))return e.comment?.(s)??s;let t=/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|export|source|alias)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\$\{?[\w_]+\}?/g,i=>e.type?.(i)??i),n}function us(s,e){let t=s;return t=t.replace(/"([^"]+)":/g,(n,i)=>`${e.type?.(`"${i}"`)??`"${i}"`}: `),t=t.replace(/:\s*"([^"]+)"/g,(n,i)=>`: ${e.string?.(`"${i}"`)??`"${i}"`}`),t=t.replace(/:\s*(\d+(\.\d+)?)/g,(n,i)=>`: ${e.number?.(i)??i}`),t=t.replace(/:\s*(true|false|null)/g,(n,i)=>`: ${e.keyword?.(i)??i}`),t}var Ce={heading:s=>ye(I(C.accent)(s)),link:s=>I(C.link)(s),linkUrl:s=>I(C.dim)(s),code:s=>I(C.code)(s),codeBlock:s=>I(C.code)(s),codeBlockBorder:s=>I(C.codeBorder)(s),quote:s=>I(C.quote)(s),quoteBorder:s=>I(C.quoteBorder)(s),hr:s=>I(C.border)(s),listBullet:s=>I(C.accentSoft)(s),bold:ye,italic:nt,strikethrough:s=>`\x1B[9m${s}\x1B[0m`,underline:s=>`\x1B[4m${s}\x1B[0m`,highlightCode:as,codeBlockIndent:" "},_t={borderColor:s=>I(C.border)(s),selectList:os};var K=a.create({service:"cli-tui-chatlog"}),it=null;function gs(){if(it)return it;let s=i("tui.system.tool_executing",{vars:{tool:""}}).split(":")[0]?.trim()||"",e=i("tui.system.tool_completed",{vars:{tool:""}}).split(":")[0]?.trim()||"",t=i("tui.system.tool_failed",{vars:{tool:""}}).split(":")[0]?.trim()||"",n=[],i$1=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return s&&s!=="tui.system.tool_executing"&&n.push(new RegExp(i$1(s),"i")),e&&e!=="tui.system.tool_completed"&&n.push(new RegExp(i$1(e),"i")),t&&t!=="tui.system.tool_failed"&&n.push(new RegExp(i$1(t),"i")),n.push(/[⚙🔧]\s*(执行工具|Executing tool)/iu,/[✓✅]\s*(工具完成|工具执行完成|Tool completed|Tool execution completed)/iu,/[✗❌]\s*(工具失败|工具执行失败|Tool failed|Tool execution failed)/iu),it=n,n}var He=class extends Container{constructor(){super();b(this,"messages",[]);b(this,"maxMessages",1e3);b(this,"containerWidth",80);b(this,"getState");b(this,"cachedProtocolMetadata",null);b(this,"_cachedPrimaryAgents",null);}init(){this.addSystem(i("tui.system.welcome")),this.addSystem(i("tui.system.help_hint"));}setStateGetter(t){this.getState=t,this.loadProtocolMetadata();}async loadProtocolMetadata(){let t=this.getState?.();if(t?.sdk)try{let n=await t.sdk.app.context({});n.data?.protocolMetadata&&(this.cachedProtocolMetadata=n.data.protocolMetadata);}catch(n){K.debug("Failed to load protocol metadata",{error:n});}}setWidth(t){this.containerWidth=t;}addUser(t,n,i){this.addMessage("user",t,n,i);}addAssistant(t,n,i){this.addMessage("assistant",t,n,i);}addSystem(t,n,i){this.addMessage("system",t,n,i);}addMessage(t,n,i,a){if(K.debug("addMessage called",{type:t,content:n.substring(0,100),id:i,currentMessagesCount:this.messages.length}),i&&this.messages.findIndex(l=>l.id===i)!==-1){K.debug("Message with same ID already exists, skipping",{id:i});return}this.messages.push({type:t,content:n,timestamp:Date.now(),id:i,metadata:a}),K.debug("After push, messages count",{count:this.messages.length}),this.messages.length>this.maxMessages&&(this.messages=this.messages.slice(-this.maxMessages)),K.debug("Calling updateChildren"),this.updateChildren(),K.debug("updateChildren completed");}clear(){this.messages=[],this.updateChildren();}updateChildren(){let t=this.getState?.(),n=t?.toolsExpanded??false,i=t?.showThinking??false,a=t?.verboseLevel??"off",o=t?.messageLimit??50;K.debug("updateChildren called",{messagesCount:this.messages.length,childrenBeforeClear:this.children.length,toolsExpanded:n,showThinking:i,verboseLevel:a,messageLimit:o}),this.children=[],K.debug("Children cleared",{childrenAfterClear:this.children.length});let l=new Set,c=0,u=this.messages.slice(-o);K.debug("Applied message limit",{originalCount:this.messages.length,limitedCount:u.length,messageLimit:o});for(let d of u){if(d.id&&l.has(d.id)){K.debug("Skipping duplicate ID",{id:d.id});continue}if(!n&&this.shouldFilterToolMessage(d)){K.debug("Filtering tool message (tools collapsed)",{content:d.content.substring(0,50),metadata:d.metadata});continue}if(d.id&&!i&&this.shouldFilterThinkingMessage(d)){K.debug("Filtering thinking message (thinking mode off)",{content:d.content.substring(0,50),metadata:d.metadata});continue}if(d.id&&a==="off"&&this.shouldFilterBackgroundAgentMessage(d)){K.debug("Filtering background agent message (verbose off)",{content:d.content.substring(0,50),agent:d.metadata?.agent});continue}if(d.type==="assistant"&&this.shouldFilterAssistantMessage(d.content)){K.debug("Filtering assistant metadata",{content:d.content.substring(0,50)});continue}d.id&&l.add(d.id),K.debug("Rendering message",{type:d.type,content:d.content.substring(0,50),id:d.id,hasId:!!d.id,metadata:d.metadata}),this.renderMessage(d),c++;}K.debug("updateChildren completed",{childrenAfterRender:this.children.length,renderedCount:c}),this.invalidate();}shouldFilterSystemMessage(t){return gs().some(i=>i.test(t))}shouldFilterToolMessage(t){return t.metadata?.isTool===true?true:t.type==="system"?this.shouldFilterSystemMessage(t.content):false}shouldFilterThinkingMessage(t){return t.metadata?.isThinking===true}shouldFilterBackgroundAgentMessage(t){let n=t.metadata?.agent;if(!n)return false;let i=this.getState?.();if(!i?.sdk)return false;let a=async()=>{try{return ((await i.sdk.app.agents({})).data||[]).filter(c=>c.mode==="primary"&&c.hidden!==!0).map(c=>c.name)}catch{return []}};return this._cachedPrimaryAgents?!this._cachedPrimaryAgents.includes(n):(a().then(o=>{this._cachedPrimaryAgents=o,this.updateChildren();}),false)}shouldFilterAssistantMessage(t){return /^>\s+[\w-]+(\s+·\s+[\w-]+)?$/.test(t.trim())}renderMessage(t){if(!t.content||t.content.trim()===""){K.debug("Skipping empty message in render",{type:t.type,id:t.id});return}let n=new Date(t.timestamp).toLocaleTimeString();switch(t.type){case "user":{if(t.metadata?.isSubagentResult){let l=t.metadata.agent||"SubAgent",c=Z.subagentLabel(`[${n}] ${l}: `),u=new Text(c,1,0);this.addChild(u);let p=new Markdown(t.content,0,0,Ce).render(this.containerWidth-2);for(let M of p){let B=new Text(M,1,0);this.addChild(B);}break}let i$1=Z.userLabel(`[${n}] ${i("tui.chatlog.user_prefix")}: `),a=new Text(i$1,1,0);if(this.addChild(a),t.content.trim().startsWith("/")){let l=Z.accent(t.content),c=new Text(l,1,0);this.addChild(c);}else {let l=Z.userText(t.content),u=new Markdown(l,0,0,Ce).render(this.containerWidth-2);for(let d of u){let p=new Text(d,1,0);this.addChild(p);}}break}case "assistant":{let i$1=i("tui.chatlog.assistant_prefix");this.cachedProtocolMetadata?.name?i$1=this.cachedProtocolMetadata.name:t.metadata?.agent&&(i$1=t.metadata.agent);let a=Z.assistantLabel(`[${n}] ${i$1}: `),o=new Text(a,1,0);this.addChild(o);let c=new Markdown(t.content,0,0,Ce).render(this.containerWidth-2);for(let u of c){let d=new Text(u,1,0);this.addChild(d);}break}case "system":{let i$1=Z.systemLabel(`[${n}] ${i("tui.chatlog.system_prefix")}: `),a=new Text(i$1,1,0);this.addChild(a);let o=Z.system(t.content),c=new Markdown(o,0,0,Ce).render(this.containerWidth-2);for(let u of c){let d=new Text(u,1,0);this.addChild(d);}break}}}};var ps={q:"exit",quit:"exit",h:"help",s:"status",a:"agent",m:"model",sess:"session",skills:"skill",commands:"command",mcps:"mcp",models:"model",agents:"agent",sessions:"session",btw:"command"},hs=new Set(["btw","sync","abort","compact"]);function $t(s){let e=s.replace(/^\//,"").trim();if(!e)return {name:"",args:""};let[t="",...n]=e.split(/\s+/),i=t.toLowerCase();return hs.has(i)?{name:"command",args:e}:{name:ps[i]??i,args:n.join(" ").trim()}}var rt=[{name:"help",description:i("tui.command.help.description")},{name:"status",description:i("tui.command.status.description")},{name:"command",description:i("tui.command.command.description")},{name:"agent",description:i("tui.command.agent.description")},{name:"session",description:i("tui.command.session.description")},{name:"new",description:i("tui.command.new.description")},{name:"fork",description:i("tui.command.fork.description")},{name:"reset",description:i("tui.command.reset.description")},{name:"model",description:i("tui.command.model.description")},{name:"settings",description:i("tui.command.settings.description")},{name:"verbose",description:i("tui.command.verbose.description")},{name:"thinking",description:i("tui.command.thinking.description")},{name:"abort",description:i("tui.command.abort.description")},{name:"clear",description:i("tui.command.clear.description")},{name:"compact",description:i("tui.command.compact.description")},{name:"skill",description:i("tui.command.skill.description")},{name:"mcp",description:i("tui.command.mcp.description")},{name:"exit",description:i("tui.command.exit.description")}];async function Rt(s,e){let t=[...rt];if(s)try{let i=(await s.command.list({contextMode:e})).data||[],a=new Set(rt.map(o=>o.name));for(let o of i)a.has(o.name)||t.push({name:o.name,description:o.description||""});}catch(n){console.error("Failed to fetch dynamic commands:",n);}return t}function Ht(){return rt}function Ft(){let s=[];return s.push("# "+i("tui.help.title")),s.push(""),s.push("## "+i("tui.help.section.basic")),s.push("- `"+i("tui.help.command.help")+"`"),s.push("- `"+i("tui.help.command.status")+"`"),s.push("- `"+i("tui.help.command.command")+"`"),s.push(""),s.push("## "+i("tui.help.section.agent")),s.push("- `"+i("tui.help.command.agent")+"`"),s.push(""),s.push("## "+i("tui.help.section.session")),s.push("- `"+i("tui.help.command.session")+"`"),s.push("- `"+i("tui.help.command.new")+"`"),s.push("- `"+i("tui.help.command.fork")+"`"),s.push("- `"+i("tui.help.command.reset")+"`"),s.push(""),s.push("## "+i("tui.help.section.model")),s.push("- `"+i("tui.help.command.model")+"`"),s.push(""),s.push("## "+i("tui.help.section.settings")),s.push("- `"+i("tui.help.command.settings")+"`"),s.push("- `"+i("tui.help.command.verbose")+"`"),s.push("- `"+i("tui.help.command.thinking")+"`"),s.push(""),s.push("## "+i("tui.help.section.operations")),s.push("- `"+i("tui.help.command.abort")+"`"),s.push("- `"+i("tui.help.command.clear")+"`"),s.push("- `"+i("tui.help.command.compact")+"`"),s.push(""),s.push("## "+i("tui.help.section.skill")),s.push("- `"+i("tui.help.command.skill")+"`"),s.push("- `"+i("tui.help.command.mcp")+"`"),s.push(""),s.push("## "+i("tui.help.section.exit")),s.push("- `"+i("tui.help.command.exit")+"`"),s.push(""),s.push("## "+i("tui.help.section.local")),s.push("- `"+i("tui.help.command.local")+"`"),s.push(""),s.push("## "+i("tui.help.section.shortcuts")),s.push("- `"+i("tui.help.shortcut.ctrl_c")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_d")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_l")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_p")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_g")+"`"),s.push("- `"+i("tui.help.shortcut.esc")+"`"),s.join(`
|
|
4
|
-
`)}var fs=/[\s\-_./:#@]/;function Dt(s,e){return e===0||fs.test(s[e-1]??"")}function Bt(s,e){if(!e)return null;let t=s.toLowerCase(),n=e.toLowerCase(),i=t.length-n.length;if(i<0)return null;for(let a=0;a<=i;a++)if(t.startsWith(n,a)&&Dt(t,a))return a;return null}function ys(s,e){if(s.length===0)return 0;if(s.length>e.length)return null;let t=0,n=0,i=-1,a=0;for(let o=0;o<e.length&&t<s.length;o++)if(e[o]===s[t]){let l=Dt(e,o);i===o-1?(a++,n-=a*5):(a=0,i>=0&&(n+=(o-i-1)*2)),l&&(n-=10),n+=o*.1,i=o,t++;}return t<s.length?null:n}function Ut(s,e){let t=e.trim();if(!t)return s;let n=t.split(/\s+/).filter(a=>a.length>0);if(n.length===0)return s;let i=[];for(let a of s){let o=a.searchTextLower??"",l=0,c=true;for(let u of n){let d=ys(u,o);if(d!==null)l+=d;else {c=false;break}}c&&i.push({item:a,score:l});}return i.sort((a,o)=>a.score-o.score),i.map(a=>a.item)}var ws="\x1B",qt=new RegExp(`${ws}\\[[0-9;]*m`,"g"),X=class X{constructor(e,t,n){b(this,"items");b(this,"filteredItems");b(this,"selectedIndex",0);b(this,"maxVisible");b(this,"theme");b(this,"searchInput");b(this,"regexCache",new Map);b(this,"onSelect");b(this,"onCancel");b(this,"onSelectionChange");b(this,"compareByScore",(e,t)=>e.tier!==t.tier?e.tier-t.tier:e.score!==t.score?e.score-t.score:this.getItemLabel(e.item).localeCompare(this.getItemLabel(t.item)));this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.searchInput=new Input;}getCachedRegex(e){let t=this.regexCache.get(e);return t||(t=new RegExp(this.escapeRegex(e),"gi"),this.regexCache.set(e,t)),t}updateFilter(){let e=this.searchInput.getValue().trim();e?this.filteredItems=this.smartFilter(e):this.filteredItems=this.items,this.selectedIndex=0,this.notifySelectionChange();}smartFilter(e){let t=e.toLowerCase(),n=[],i=[];for(let o of this.items){let l=this.getItemLabel(o),c=o.description??"",u=a$1(l).toLowerCase(),d=a$1(c).toLowerCase(),p=u.indexOf(t);if(p!==-1){n.push({item:o,tier:0,score:p});continue}let M=Bt(u,t);if(M!==null){n.push({item:o,tier:1,score:M});continue}let B=d.indexOf(t);if(B!==-1){n.push({item:o,tier:2,score:B});continue}let T=o.searchText??"";i.push({item:o,searchTextLower:[l,c,T].map(y=>a$1(y)).filter(Boolean).join(" ").toLowerCase()});}n.sort(this.compareByScore);let a=Ut(i,t);return [...n.map(o=>o.item),...a.map(o=>o.item)]}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}getItemLabel(e){return e.label||e.value}splitAnsiParts(e){let t=[];qt.lastIndex=0;let n=0,i;for(;(i=qt.exec(e))!==null;)i.index>n&&t.push({text:e.slice(n,i.index),isAnsi:false}),t.push({text:i[0],isAnsi:true}),n=i.index+i[0].length;return n<e.length&&t.push({text:e.slice(n),isAnsi:false}),t}highlightMatch(e,t){let n=t.trim().split(/\s+/).map(o=>o.toLowerCase()).filter(o=>o.length>0);if(n.length===0)return e;let i=Array.from(new Set(n)).toSorted((o,l)=>l.length-o.length),a=this.splitAnsiParts(e);for(let o of i){let l=this.getCachedRegex(o),c=[];for(let u of a){if(u.isAnsi){c.push(u);continue}l.lastIndex=0;let d=u.text.replace(l,p=>this.theme.matchHighlight(p));if(d===u.text){c.push(u);continue}c.push(...this.splitAnsiParts(d));}a=c;}return a.map(o=>o.text).join("")}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1));}invalidate(){this.searchInput.invalidate();}render(e){let t=[],i=this.theme.searchPrompt("search: "),a=Math.max(1,e-b$1(i)),l=this.searchInput.render(a)[0]??"";t.push(`${i}${this.theme.searchInput(l)}`),t.push("");let c=this.searchInput.getValue().trim();if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matches")),t;let u=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),d=Math.min(u+this.maxVisible,this.filteredItems.length);for(let p=u;p<d;p++){let M=this.filteredItems[p];if(!M)continue;let B=p===this.selectedIndex;t.push(this.renderItemLine(M,B,e,c));}if(this.filteredItems.length>this.maxVisible){let p=`${this.selectedIndex+1}/${this.filteredItems.length}`;t.push(this.theme.scrollInfo(` ${p}`));}return t}renderItemLine(e,t,n,i){let a=t?"\u2192 ":" ",o=a.length,l=this.getItemLabel(e),c=e.description;if(c){let B=this.getDescriptionLayout(n,o);if(B){let T=truncateToWidth(l,B.maxValueWidth,""),y=this.highlightMatch(T,i),k=b$1(y),h=B.availableWidth-k-B.spacingWidth;if(h>=X.DESCRIPTION_MIN_WIDTH){let se=" ".repeat(B.spacingWidth),H=truncateToWidth(c,h,""),F=this.highlightMatch(H,i),x=t?F:this.theme.description(F),g=`${a}${y}${se}${x}`;return t?this.theme.selectedText(g):g}}}let u=n-o-2,d=truncateToWidth(l,u,""),p=this.highlightMatch(d,i),M=`${a}${p}`;return t?this.theme.selectedText(M):M}getDescriptionLayout(e,t){if(e<=X.DESCRIPTION_LAYOUT_MIN_WIDTH)return null;let n=Math.max(1,e-t-X.RIGHT_MARGIN_WIDTH),i=n-X.DESCRIPTION_MIN_WIDTH-X.DESCRIPTION_SPACING_WIDTH;return i<1?null:{availableWidth:n,maxValueWidth:i,spacingWidth:X.DESCRIPTION_SPACING_WIDTH}}handleInput(e){if(isKeyRelease(e))return;let t=getKeybindings(),n=!this.searchInput.getValue().trim();if(t.matches(e,"tui.select.up")||t.matches(e,"tui.editor.cursorUp")||n&&e==="k"){this.selectedIndex=Math.max(0,this.selectedIndex-1),this.notifySelectionChange();return}if(t.matches(e,"tui.select.down")||t.matches(e,"tui.editor.cursorDown")||n&&e==="j"){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+1),this.notifySelectionChange();return}if(t.matches(e,"tui.select.confirm")){let o=this.filteredItems[this.selectedIndex];o&&this.onSelect&&this.onSelect(o);return}if(t.matches(e,"tui.select.cancel")){this.onCancel&&this.onCancel();return}let i=this.searchInput.getValue();this.searchInput.handleInput(e);let a=this.searchInput.getValue();i!==a&&this.updateFilter();}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e);}getSelectedItem(){return this.filteredItems[this.selectedIndex]??null}};b(X,"DESCRIPTION_LAYOUT_MIN_WIDTH",40),b(X,"DESCRIPTION_MIN_WIDTH",12),b(X,"DESCRIPTION_SPACING_WIDTH",2),b(X,"RIGHT_MARGIN_WIDTH",2);var Fe=X;var ce=a.create({service:"cli-tui-selectors"}),Is={selectedPrefix:s=>`\x1B[36m${s}\x1B[0m`,selectedText:s=>`\x1B[1;36m${s}\x1B[0m`,description:s=>`\x1B[90m${s}\x1B[0m`,scrollInfo:s=>`\x1B[90m${s}\x1B[0m`,noMatch:s=>`\x1B[90m${s}\x1B[0m`,searchPrompt:s=>`\x1B[36m${s}\x1B[0m`,searchInput:s=>s,matchHighlight:s=>`\x1B[1;33m${s}\x1B[0m`};function ue(s,e){ce.debug("Creating searchable select list",{itemsCount:s.length,title:e.title});let t=e.maxVisible??10,n=new Fe(s,t,Is);return e.onSelect&&(n.onSelect=e.onSelect),e.onCancel&&(n.onCancel=e.onCancel),n}function De(s,e){ce.info("Creating model selector with data");let t=[];for(let[n,i]of Object.entries(s))if(i?.models)for(let[a,o]of Object.entries(i.models))t.push({label:`${i.name} - ${o.name}`,value:`${n}/${a}`,description:o.family||""});return ce.debug("Model list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.model.title"),placeholder:e.placeholder||i("tui.selector.model.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Be(s,e){ce.info("Creating session selector with data",{count:s.length});let t=s.map(n=>({label:n.title||n.id,value:n.id,description:`\u66F4\u65B0\u65F6\u95F4: ${n.time?.updated?new Date(n.time.updated).toLocaleString():"\u672A\u77E5"}`}));return ce.debug("Session list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.session.title"),placeholder:e.placeholder||i("tui.selector.session.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Ue(s,e){ce.info("Creating agent selector with data",{count:s.length});let t=s.map(n=>({label:n.name,value:n.name,description:n.description||(n.mode?`\u6A21\u5F0F: ${n.mode}`:"")}));return ce.debug("Agent list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.agent.title"),placeholder:e.placeholder||i("tui.selector.agent.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}var A=a.create({service:"cli-tui-command-handlers"});async function xs(s,e,t){let n=[];n.push("## "+i("tui.handler.status.title")),n.push(""),n.push("### "+i("tui.handler.status.system_info")),n.push("- **"+i("tui.handler.status.system")+"**: "+i("tui.handler.status.ok")),n.push("- **"+i("tui.handler.status.directory")+"**: `"+e+"`"),n.push(""),n.push("### "+i("tui.handler.status.global_paths")),n.push("- **home**: `"+a$2.Path.home+"`"),n.push("- **data**: `"+a$2.Path.data+"`"),n.push("- **bin**: `"+a$2.Path.bin+"`"),n.push("- **log**: `"+a$2.Path.log+"`"),n.push("- **cache**: `"+a$2.Path.cache+"`"),n.push("- **config**: `"+a$2.Path.config+"`"),n.push("- **state**: `"+a$2.Path.state+"`"),n.push(""),n.push("### "+i("tui.handler.status.session_info")),n.push("- **Agent**: "+(s.agent||i("tui.handler.status.not_set"))),n.push("- **Session**: "+(s.currentSessionKey||i("tui.handler.status.not_set"))),n.push("- **Model**: "+(s.sessionInfo.model||i("tui.handler.status.not_set"))),n.push(""),n.push("### Gateway");try{let i=t?.client,a=await c$1(),o=a.path||"",l=o.endsWith("/")?o.slice(0,-1):o,c=`ws://${a.hostname}:${a.port}${l}`;if(i){let u=i.getState();if(u==="connected")try{let d=await i.getStatus();n.push("- **Status**: connected"),n.push(`- **URL**: \`${c}\``),n.push(`- **Connections**: ${d.connections??0}`),n.push(`- **Sessions**: ${d.sessions??0}`),n.push(`- **Message Subscriptions**: ${d.messageSubscriptions??0}`),n.push(`- **Agent Subscriptions**: ${d.agentSubscriptions??0}`),d.agents&&n.push(`- **Agents**: ${d.agents.total??0} (healthy: ${d.agents.healthy??0}, unhealthy: ${d.agents.unhealthy??0})`);}catch{n.push("- **Status**: connected (status fetch failed)"),n.push(`- **URL**: \`${c}\``);}else n.push("- **Status**: "+u),n.push(`- **URL**: \`${c}\``);}else n.push("- **Status**: not initialized"),n.push(`- **URL**: \`${c}\``);}catch(i){A.error("Failed to get Gateway status",{error:String(i)}),n.push("- **Status**: error");}n.push("");try{let a=(await s.sdk.command.list({})).data||[],o=a.filter(u=>u.source==="skill"),l=a.filter(u=>u.source==="mcp"),c=a.filter(u=>u.source==="command");if(n.push("### "+i("tui.handler.status.skills")+" ("+o.length+")"),o.length>0){let u=o.map(d=>d.name).join(", ");n.push(u);}n.push("");try{let d=(await s.sdk.mcp.status({})).data||{},M=(await s.sdk.mcp.tools({})).data||{},B=Object.entries(d).filter(([,T])=>T.status==="connected");if(n.push("### "+i("tui.handler.status.mcp")+" ("+B.length+")"),B.length>0)for(let[T]of B){let y=M[T]||[];y.length>0?n.push("- **"+T+"** ("+y.length+"): "+y.join(", ")):n.push("- **"+T+"**");}n.push("");}catch(u){A.error("Failed to get MCP status",{error:u}),n.push("### "+i("tui.handler.status.mcp")+" (0)"),n.push("");}if(n.push("### "+i("tui.handler.status.commands")+" ("+c.length+")"),c.length>0){let u=c.map(d=>d.name).join(", ");n.push(u);}n.push(""),n.push("### "+i("tui.handler.status.services"));try{if(!s.sdk?.lsp)A.warn("SDK or LSP API is not initialized"),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let u=await s.sdk.lsp.status({});if(!u||typeof u!="object")A.warn("LSP status response is not a valid object",{response:u,responseType:typeof u}),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let d=Array.isArray(u.data)?u.data:[];if(n.push("- **LSP ("+d.length+")**: "),d.length>0){let p=d.filter(M=>M&&typeof M=="object").map(M=>M?.name||"unknown").join(", ");n.push(" "+p);}else n.push(" "+i("tui.handler.status.no_lsp"));}}}catch(u){A.error("Failed to get LSP status",{error:u}),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));}}catch(i$1){A.error("Failed to get command list for status",{error:i$1}),n.push(""),n.push("_"+i("tui.handler.status.error_loading")+"_");}return n.join(`
|
|
5
|
-
`)}function Ot(s,e){let{chatLog:t,tui:n,directory:i$1,openOverlay:a,closeOverlay:o,requestExit:l,setActivityStatus:c$1,updateFooter:u,refreshSessionInfo:d,loadHistory:p,setSession:M,refreshAgents:B,abortActive:T}=s,y=()=>{o();},k=async(H,F,x,g)=>{try{if(!F){A.warn("Cannot publish command event: no session ID",{name:H});return}await pa(e,za.Event.Executed,{name:H,sessionId:F,arguments:x,messageId:g}),A.debug("Command event published",{name:H,sessionId:F,messageId:g});}catch(f){A.error("Failed to publish command event",{name:H,sessionId:F,messageId:g,error:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0});}},ge=async(H,F)=>{let{name:x,args:g}=$t(H);if(x){try{switch(x){case "help":t.addSystem(Ft()),await k("help",e.currentSessionId||"",g||"",randomUUID());break;case "commands":case "command":case "cmds":case "cmd":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="command");if(b.length===0){t.addSystem(i("tui.handler.command.empty")),await k(x,e.currentSessionId||"",g||"",randomUUID());break}if(g){let v=g.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("command",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.command.not_found",{vars:{name:W}})),await k(x,e.currentSessionId||"",g,randomUUID());break}let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/command ${v.value} `):await se("command",v.value,e,t,c$1);},onCancel:y});a(E);}catch(f){A.error("Failed to handle command",{error:f}),t.addSystem(i("tui.handler.command.error",{vars:{error:String(f)}}));}await k(x,e.currentSessionId||"","",randomUUID());break}case "status":t.addSystem(await xs(e,i$1,s.gatewayManager)),await k("status",e.currentSessionId||"",g||"",randomUUID());break;case "agents":case "agent":if(g)e.agent=g,t.addSystem(i("tui.handler.agent.switched",{vars:{agentId:g}})),u(),await b$2(e),await k(x,e.currentSessionId||"",g,randomUUID());else {let L=(await ta(e)).filter(w=>w.mode==="primary"&&w.hidden!==!0),b=Ue(L,{onSelect:async w=>{e.agent=w.value,t.addSystem(i("tui.handler.agent.switched",{vars:{agentId:w.value}})),u(),y(),await b$2(e);},onCancel:y});a(b),await k(x,e.currentSessionId||"","",randomUUID());}break;case "sessions":case "session":if(g&&M)await M(g),u(),await k(x,e.currentSessionId||"",g,randomUUID());else {let f=await ua(e),L=Be(f,{onSelect:async b=>{M&&await M(b.value),u(),y();},onCancel:y});a(L),await k(x,e.currentSessionId||"","",randomUUID());}break;case "models":case "model":if(g)e.sessionInfo.model=g,t.addSystem(i("tui.handler.model.set",{vars:{model:g}})),u(),await b$2(e),await k(x,e.currentSessionId||"",g,randomUUID());else {let f=await va(e),L=De(f,{onSelect:async b=>{e.sessionInfo.model=b.value,t.addSystem(i("tui.handler.model.set",{vars:{model:b.value}})),u(),y(),await b$2(e);},onCancel:y});a(L),await k(x,e.currentSessionId||"","",randomUUID());}break;case "fork":{try{c$1(i("tui.handler.fork.begin"));let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,A.debug("Aborted running agent before forking session",{sessionId:f});}catch(L){A.warn("Failed to abort agent before forking, continuing anyway",{error:L});}if(t.clear(),t.init(),f){let b=(await e.sdk.session.fork({sessionId:f})).data;b&&(e.currentSessionId=b.id,e.currentSessionKey=b.title||b.slug||b.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e));}await oa(e,t),p&&await p(),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),c$1(i("tui.status.ready"));}catch(f){A.error("Failed to fork session",{error:f}),t.addSystem(i("tui.handler.fork.error",{vars:{error:String(f)}})),c$1(i("tui.status.error"));}await k("fork",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);break}case "new":{try{c$1(i("tui.handler.new.begin"));let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,A.debug("Aborted running agent before creating new session",{sessionId:f});}catch(E){A.warn("Failed to abort agent before creating new session, continuing anyway",{error:E});}t.clear(),t.init();let L=e.instanceContext.directory,w=(await e.sdk.session.create({directory:L})).data;w&&(e.currentSessionId=w.id,e.currentSessionKey=w.title||w.slug||w.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e)),await oa(e,t),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),c$1(i("tui.status.ready"));}catch(f){A.error("Failed to create new session",{error:f}),t.addSystem(i("tui.handler.new.error",{vars:{error:String(f)}})),c$1(i("tui.status.error"));}await k("new",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);break}case "reset":{try{let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,A.debug("Aborted running agent before reset",{sessionId:f});}catch(L){A.warn("Failed to abort agent before reset, continuing anyway",{error:L});}t.clear(),t.init(),t.addSystem(i("tui.handler.session.reset")),p&&await p(),await oa(e,t),u();}catch(f){A.error("Failed to reset session",{error:f}),t.addSystem(i("tui.handler.session.reset_error",{vars:{error:String(f)}}));}await k("reset",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);break}case "settings":{A.debug("Opening settings panel");let{createSettingsPanel:f}=await import('./settings-panel-ZMAGAWRF.mjs'),L=f({currentSettings:{thinkingLevel:e.thinkingLevel,showThinking:e.showThinking,verboseLevel:e.verboseLevel,messageLimit:e.messageLimit,toolsExpanded:e.toolsExpanded,localShellPermission:e.localShellPermission,contextMode:e.contextMode},onChange:(b,w)=>{switch(b){case "thinkingLevel":e.thinkingLevel=w,t.addSystem(i("tui.handler.thinking_level.set",{vars:{level:w}}));break;case "showThinking":e.showThinking=w==="true",A.debug("showThinking changed",{newValue:w,showThinking:e.showThinking}),t.addSystem(e.showThinking?i("tui.hint.show_thinking_on"):i("tui.hint.show_thinking_off"));break;case "verboseLevel":e.verboseLevel=w,t.addSystem(i("tui.handler.verbose_level.set",{vars:{level:w}}));break;case "messageLimit":e.messageLimit=Number.parseInt(w,10),t.addSystem(i("tui.handler.message_limit.set",{vars:{limit:w}}));break;case "toolsExpanded":e.toolsExpanded=w==="true",A.debug("toolsExpanded changed",{newValue:w,toolsExpanded:e.toolsExpanded}),t.addSystem(e.toolsExpanded?i("tui.hint.tools_expanded"):i("tui.hint.tools_collapsed"));break;case "localShellPermission":e.localShellPermission=w,A.debug("localShellPermission changed",{newValue:w,localShellPermission:e.localShellPermission}),t.addSystem(i("tui.shell.permission.updated",{vars:{permission:w}}));break;case "contextMode":{let E=w;e.contextMode=E,A.debug("contextMode changed",{newValue:w,contextMode:E}),t.addSystem(i("tui.handler.context_mode.set",{vars:{mode:E}})),e.currentSessionId&&e.sdk.session.contextMode.set({sessionId:e.currentSessionId,mode:E}).catch(v=>{A.error("Failed to update session contextMode",{error:v,sessionId:e.currentSessionId});});break}}b$2(e).then(async()=>{try{A.debug("Publishing HeaderRefresh event",{id:b,newValue:w}),await pa(e,c.StatusBarRefresh,{reason:`settings changed: ${b}`});}catch(E){A.error("Failed to publish HeaderRefresh event",{error:E});}}).catch(E=>{A.error("Failed to save TUI state after settings change",{error:E,id:b});});},onCancel:y});a(L),await k("settings",e.currentSessionId||"",g||"",randomUUID());break}case "verbose":if(!g){t.addSystem(i("tui.handler.verbose.usage")),await k(x,e.currentSessionId||"","",randomUUID());break}if(g!=="on"&&g!=="off"){t.addSystem(i("tui.handler.verbose.invalid",{vars:{value:g}})),await k(x,e.currentSessionId||"",g,randomUUID());break}e.verboseLevel=g,t.addSystem(i("tui.handler.verbose.set",{vars:{level:g}})),await b$2(e),await k(x,e.currentSessionId||"",g,randomUUID());break;case "thinking":if(!g){t.addSystem(i("tui.handler.thinking.usage")),await k(x,e.currentSessionId||"","",randomUUID());break}e.thinkingLevel=g,t.addSystem(i("tui.handler.thinking.set",{vars:{level:g}})),await b$2(e),await k("thinking",e.currentSessionId||"",g||"",randomUUID());break;case "clear":{A.debug("Opening clear confirmation dialog");let{createConfirmDialog:f}=await import('./confirm-dialog-SJOXJWYU.mjs'),L=f({message:i("tui.dialog.clear.message"),onConfirm:async()=>{try{c$1(i("tui.handler.clear.begin")),y();let b=e.currentSessionId;if(b&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:b}),e.activeChatRunId=null,A.debug("Aborted running agent before clearing session",{sessionId:b});}catch(v){A.warn("Failed to abort agent before clearing, continuing anyway",{error:v});}t.clear(),t.init(),b&&await e.sdk.session.delete({sessionId:b});let E=(await e.sdk.session.create({directory:e.instanceContext.directory})).data;E&&(e.currentSessionId=E.id,e.currentSessionKey=E.title||E.slug||E.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e)),await oa(e,t),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),t.addSystem(i("tui.handler.clear.success")),c$1(i("tui.status.ready"));}catch(b){A.error("Failed to clear chat history",{error:b}),t.addSystem(i("tui.handler.clear.error",{vars:{error:String(b)}})),c$1(i("tui.status.error"));}await k("clear",e.currentSessionId||"",g||"",randomUUID()),F.tui.requestRender(!0);},onCancel:()=>{t.addSystem(i("tui.clear.cancel")),y();}});a(L);break}case "skills":case "skill":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="skill");if(b.length===0){t.addSystem(i("tui.handler.skill.empty")),await k(x,e.currentSessionId||"",g||"",randomUUID());break}if(g){let v=g.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("skill",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.skill.not_found",{vars:{name:W}})),await k(x,e.currentSessionId||"",g,randomUUID());break}A.debug("Opening skill selector");let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/skill ${v.value} `):await se("skill",v.value,e,t,c$1);},onCancel:y});a(E),await k(x,e.currentSessionId||"","",randomUUID());}catch(f){A.error("Failed to handle skill",{error:f}),t.addSystem(i("tui.handler.skill.error",{vars:{error:String(f)}})),await k(x,e.currentSessionId||"",g||"",randomUUID());}break}case "mcps":case "mcp":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="mcp");if(b.length===0){t.addSystem(i("tui.handler.mcp.empty")),await k(x,e.currentSessionId||"",g||"",randomUUID());break}if(g){let v=g.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("mcp",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.mcp.not_found",{vars:{name:W}})),await k(x,e.currentSessionId||"",g,randomUUID());break}A.debug("Opening MCP prompt selector");let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/mcp ${v.value} `):await se("mcp",v.value,e,t,c$1);},onCancel:y});a(E);}catch(f){A.error("Failed to handle MCP prompt",{error:f}),t.addSystem(i("tui.handler.mcp.error",{vars:{error:String(f)}}));}await k(x,e.currentSessionId||"","",randomUUID());break}case "exit":case "quit":await k(x,e.currentSessionId||"",g||"",randomUUID()),l();break;default:A.debug("Unknown command, sending as message"),await h(H);break}}catch(f){let L=f instanceof Error?f.message:String(f);A.error("Command execution failed",{command:x,args:g,error:L,stack:f instanceof Error?f.stack:void 0}),t.addSystem(i("tui.handler.command.error",{vars:{command:x,error:L}}));}A.debug("handleCommand completed");}},h=async(H,F,x)=>{try{let g=randomUUID();if(e.activeChatRunId=g,c$1(i("tui.handler.send.sending")),!e.currentSessionId)throw new Error("No active session");let f;if(e.sessionInfo.model){let{provider:w,model:E}=parseModelId(e.sessionInfo.model);w&&E&&(f={providerId:w,modelId:E});}let L=[{type:"text",text:H}];if(F&&F.length>0)for(let w of F)L.push({type:"file",url:w.url,filename:w.filename,mime:w.mime});x&&L.push({type:"agent",name:x});let b=await e.sdk.session.prompt({sessionId:e.currentSessionId,parts:L,agent:e.agent||void 0,model:f,variant:e.thinkingLevel,contextMode:e.contextMode});if(b.data&&e.currentSessionId&&await k("message",e.currentSessionId,H,b.data.info?.id||randomUUID()),b.data){let w=b.data.parts?.filter(E=>E.type==="text")||[];for(let E of w)"text"in E&&E.text&&t.addAssistant(E.text,b.data.info?.id);}e.activeChatRunId=null,c$1("");}catch(g){e.activeChatRunId=null;let f=g instanceof Error?g.message:String(g),L=g instanceof Error?g.name:"Error";t.addSystem(i("tui.handler.send.error",{vars:{error:f}})),c$1(i("tui.handler.send.error_status")),A.error("Failed to send message",{error:f,errorName:L,sessionId:e.currentSessionId,hasModel:!!e.sessionInfo.model,stack:g instanceof Error?g.stack:void 0});}},se=async(H,F,x,g,f,L)=>{try{let b=H==="skill"?i("tui.handler.skill.executing"):H==="command"?i("tui.handler.command.executing"):i("tui.handler.mcp.executing");if(g.addSystem(b+`: ${F}`),f(i("tui.handler.executing",{vars:{command:F}})),!x.currentSessionId)throw new Error("No active session");let w;x.sessionInfo.model&&(w=x.sessionInfo.model);let E=L?[{type:"text",text:L}]:void 0,W=(await x.sdk.session.command({sessionId:x.currentSessionId,command:F,arguments:L??"",agent:x.agent||void 0,model:w,variant:x.thinkingLevel,contextMode:x.contextMode,parts:E})).data,Y=W?.metadata?.commandType;if(W?.success)Y==="local"&&g.addSystem(i("tui.handler.local.completed")+`: ${F}
|
|
3
|
+
`);if(!e)return t.map(a=>I(C.code)(a));let n={keyword:I("#C586C0"),string:I("#CE9178"),comment:I("#6A9955"),number:I("#B5CEA8"),function:I("#DCDCAA"),type:I("#4EC9B0"),operator:I("#D4D4D4"),default:I(C.code)},i=e.toLowerCase();return i==="typescript"||i==="ts"||i==="javascript"||i==="js"?t.map(a=>ls(a,n)):i==="python"||i==="py"?t.map(a=>ds(a,n)):i==="bash"||i==="sh"||i==="shell"?t.map(a=>cs(a,n)):i==="json"?t.map(a=>us(a,n)):t.map(a=>n.default(a))}function ls(s,e){if(s.trim().startsWith("//"))return e.comment?.(s)??s;let t=/\b(const|let|var|function|async|await|return|if|else|for|while|class|interface|type|import|export|from|default|new|this|super|extends|implements)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"`])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\b\d+(\.\d+)?\b/g,i=>e.number?.(i)??i),n}function ds(s,e){if(s.trim().startsWith("#"))return e.comment?.(s)??s;let t=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|with|async|await|lambda|yield|pass|break|continue|None|True|False)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\b\d+(\.\d+)?\b/g,i=>e.number?.(i)??i),n}function cs(s,e){if(s.trim().startsWith("#"))return e.comment?.(s)??s;let t=/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|export|source|alias)\b/g,n=s.replace(t,i=>e.keyword?.(i)??i);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,i=>e.string?.(i)??i),n=n.replace(/\$\{?[\w_]+\}?/g,i=>e.type?.(i)??i),n}function us(s,e){let t=s;return t=t.replace(/"([^"]+)":/g,(n,i)=>`${e.type?.(`"${i}"`)??`"${i}"`}: `),t=t.replace(/:\s*"([^"]+)"/g,(n,i)=>`: ${e.string?.(`"${i}"`)??`"${i}"`}`),t=t.replace(/:\s*(\d+(\.\d+)?)/g,(n,i)=>`: ${e.number?.(i)??i}`),t=t.replace(/:\s*(true|false|null)/g,(n,i)=>`: ${e.keyword?.(i)??i}`),t}var Ce={heading:s=>ye(I(C.accent)(s)),link:s=>I(C.link)(s),linkUrl:s=>I(C.dim)(s),code:s=>I(C.code)(s),codeBlock:s=>I(C.code)(s),codeBlockBorder:s=>I(C.codeBorder)(s),quote:s=>I(C.quote)(s),quoteBorder:s=>I(C.quoteBorder)(s),hr:s=>I(C.border)(s),listBullet:s=>I(C.accentSoft)(s),bold:ye,italic:nt,strikethrough:s=>`\x1B[9m${s}\x1B[0m`,underline:s=>`\x1B[4m${s}\x1B[0m`,highlightCode:as,codeBlockIndent:" "},_t={borderColor:s=>I(C.border)(s),selectList:os};var K=a.create({service:"cli-tui-chatlog"}),it=null;function gs(){if(it)return it;let s=i("tui.system.tool_executing",{vars:{tool:""}}).split(":")[0]?.trim()||"",e=i("tui.system.tool_completed",{vars:{tool:""}}).split(":")[0]?.trim()||"",t=i("tui.system.tool_failed",{vars:{tool:""}}).split(":")[0]?.trim()||"",n=[],i$1=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return s&&s!=="tui.system.tool_executing"&&n.push(new RegExp(i$1(s),"i")),e&&e!=="tui.system.tool_completed"&&n.push(new RegExp(i$1(e),"i")),t&&t!=="tui.system.tool_failed"&&n.push(new RegExp(i$1(t),"i")),n.push(/[⚙🔧]\s*(执行工具|Executing tool)/iu,/[✓✅]\s*(工具完成|工具执行完成|Tool completed|Tool execution completed)/iu,/[✗❌]\s*(工具失败|工具执行失败|Tool failed|Tool execution failed)/iu),it=n,n}var He=class extends Container{constructor(){super();b(this,"messages",[]);b(this,"containerWidth",80);b(this,"getState");b(this,"cachedProtocolMetadata",null);b(this,"_cachedPrimaryAgents",null);}get maxMessages(){return (this.getState?.()?.messageLimit??20)*2}init(){this.addSystem(i("tui.system.welcome")),this.addSystem(i("tui.system.help_hint"));}setStateGetter(t){this.getState=t,this.loadProtocolMetadata();}async loadProtocolMetadata(){let t=this.getState?.();if(t?.sdk)try{let n=await t.sdk.app.context({});n.data?.protocolMetadata&&(this.cachedProtocolMetadata=n.data.protocolMetadata);}catch(n){K.debug("Failed to load protocol metadata",{error:n});}}setWidth(t){this.containerWidth=t;}addUser(t,n,i){this.addMessage("user",t,n,i);}addAssistant(t,n,i){this.addMessage("assistant",t,n,i);}addSystem(t,n,i){this.addMessage("system",t,n,i);}addMessage(t,n,i,a){if(K.debug("addMessage called",{type:t,content:n.substring(0,100),id:i,currentMessagesCount:this.messages.length}),i&&this.messages.findIndex(l=>l.id===i)!==-1){K.debug("Message with same ID already exists, skipping",{id:i});return}this.messages.push({type:t,content:n,timestamp:Date.now(),id:i,metadata:a}),K.debug("After push, messages count",{count:this.messages.length}),this.messages.length>this.maxMessages&&(this.messages=this.messages.slice(-this.maxMessages)),K.debug("Calling updateChildren"),this.updateChildren(),K.debug("updateChildren completed");}clear(){this.messages=[],this.updateChildren();}updateChildren(){let t=this.getState?.(),n=t?.toolsExpanded??false,i=t?.showThinking??false,a=t?.verboseLevel??"off",o=t?.messageLimit??50;K.debug("updateChildren called",{messagesCount:this.messages.length,childrenBeforeClear:this.children.length,toolsExpanded:n,showThinking:i,verboseLevel:a,messageLimit:o}),this.children=[],K.debug("Children cleared",{childrenAfterClear:this.children.length});let l=new Set,c=0,u=this.messages.slice(-o);K.debug("Applied message limit",{originalCount:this.messages.length,limitedCount:u.length,messageLimit:o});for(let d of u){if(d.id&&l.has(d.id)){K.debug("Skipping duplicate ID",{id:d.id});continue}if(!n&&this.shouldFilterToolMessage(d)){K.debug("Filtering tool message (tools collapsed)",{content:d.content.substring(0,50),metadata:d.metadata});continue}if(d.id&&!i&&this.shouldFilterThinkingMessage(d)){K.debug("Filtering thinking message (thinking mode off)",{content:d.content.substring(0,50),metadata:d.metadata});continue}if(d.id&&a==="off"&&this.shouldFilterBackgroundAgentMessage(d)){K.debug("Filtering background agent message (verbose off)",{content:d.content.substring(0,50),agent:d.metadata?.agent});continue}if(d.type==="assistant"&&this.shouldFilterAssistantMessage(d.content)){K.debug("Filtering assistant metadata",{content:d.content.substring(0,50)});continue}d.id&&l.add(d.id),K.debug("Rendering message",{type:d.type,content:d.content.substring(0,50),id:d.id,hasId:!!d.id,metadata:d.metadata}),this.renderMessage(d),c++;}K.debug("updateChildren completed",{childrenAfterRender:this.children.length,renderedCount:c}),this.invalidate();}shouldFilterSystemMessage(t){return gs().some(i=>i.test(t))}shouldFilterToolMessage(t){return t.metadata?.isTool===true?true:t.type==="system"?this.shouldFilterSystemMessage(t.content):false}shouldFilterThinkingMessage(t){return t.metadata?.isThinking===true}shouldFilterBackgroundAgentMessage(t){let n=t.metadata?.agent;if(!n)return false;let i=this.getState?.();if(!i?.sdk)return false;let a=async()=>{try{return ((await i.sdk.app.agents({})).data||[]).filter(c=>c.mode==="primary"&&c.hidden!==!0).map(c=>c.name)}catch{return []}};return this._cachedPrimaryAgents?!this._cachedPrimaryAgents.includes(n):(a().then(o=>{this._cachedPrimaryAgents=o,this.updateChildren();}),false)}shouldFilterAssistantMessage(t){return /^>\s+[\w-]+(\s+·\s+[\w-]+)?$/.test(t.trim())}renderMessage(t){if(!t.content||t.content.trim()===""){K.debug("Skipping empty message in render",{type:t.type,id:t.id});return}let n=new Date(t.timestamp).toLocaleTimeString();switch(t.type){case "user":{if(t.metadata?.isSubagentResult){let l=t.metadata.agent||"SubAgent",c=Z.subagentLabel(`[${n}] ${l}: `),u=new Text(c,1,0);this.addChild(u);let g=new Markdown(t.content,0,0,Ce).render(this.containerWidth-2);for(let P of g){let B=new Text(P,1,0);this.addChild(B);}break}let i$1=Z.userLabel(`[${n}] ${i("tui.chatlog.user_prefix")}: `),a=new Text(i$1,1,0);if(this.addChild(a),t.content.trim().startsWith("/")){let l=Z.accent(t.content),c=new Text(l,1,0);this.addChild(c);}else {let l=Z.userText(t.content),u=new Markdown(l,0,0,Ce).render(this.containerWidth-2);for(let d of u){let g=new Text(d,1,0);this.addChild(g);}}break}case "assistant":{let i$1=i("tui.chatlog.assistant_prefix");this.cachedProtocolMetadata?.name?i$1=this.cachedProtocolMetadata.name:t.metadata?.agent&&(i$1=t.metadata.agent);let a=Z.assistantLabel(`[${n}] ${i$1}: `),o=new Text(a,1,0);this.addChild(o);let c=new Markdown(t.content,0,0,Ce).render(this.containerWidth-2);for(let u of c){let d=new Text(u,1,0);this.addChild(d);}break}case "system":{let i$1=Z.systemLabel(`[${n}] ${i("tui.chatlog.system_prefix")}: `),a=new Text(i$1,1,0);this.addChild(a);let o=Z.system(t.content),c=new Markdown(o,0,0,Ce).render(this.containerWidth-2);for(let u of c){let d=new Text(u,1,0);this.addChild(d);}break}}}};var ps={q:"exit",quit:"exit",h:"help",s:"status",a:"agent",m:"model",sess:"session",skills:"skill",commands:"command",mcps:"mcp",models:"model",agents:"agent",sessions:"session",btw:"command"},hs=new Set(["btw","sync","abort","compact"]);function $t(s){let e=s.replace(/^\//,"").trim();if(!e)return {name:"",args:""};let[t="",...n]=e.split(/\s+/),i=t.toLowerCase();return hs.has(i)?{name:"command",args:e}:{name:ps[i]??i,args:n.join(" ").trim()}}var rt=[{name:"help",description:i("tui.command.help.description")},{name:"status",description:i("tui.command.status.description")},{name:"command",description:i("tui.command.command.description")},{name:"agent",description:i("tui.command.agent.description")},{name:"session",description:i("tui.command.session.description")},{name:"new",description:i("tui.command.new.description")},{name:"fork",description:i("tui.command.fork.description")},{name:"reset",description:i("tui.command.reset.description")},{name:"model",description:i("tui.command.model.description")},{name:"settings",description:i("tui.command.settings.description")},{name:"verbose",description:i("tui.command.verbose.description")},{name:"thinking",description:i("tui.command.thinking.description")},{name:"abort",description:i("tui.command.abort.description")},{name:"clear",description:i("tui.command.clear.description")},{name:"compact",description:i("tui.command.compact.description")},{name:"skill",description:i("tui.command.skill.description")},{name:"mcp",description:i("tui.command.mcp.description")},{name:"exit",description:i("tui.command.exit.description")}];async function Rt(s,e){let t=[...rt];if(s)try{let i=(await s.command.list({contextMode:e})).data||[],a=new Set(rt.map(o=>o.name));for(let o of i)a.has(o.name)||t.push({name:o.name,description:o.description||""});}catch(n){console.error("Failed to fetch dynamic commands:",n);}return t}function Ht(){return rt}function Ft(){let s=[];return s.push("# "+i("tui.help.title")),s.push(""),s.push("## "+i("tui.help.section.basic")),s.push("- `"+i("tui.help.command.help")+"`"),s.push("- `"+i("tui.help.command.status")+"`"),s.push("- `"+i("tui.help.command.command")+"`"),s.push(""),s.push("## "+i("tui.help.section.agent")),s.push("- `"+i("tui.help.command.agent")+"`"),s.push(""),s.push("## "+i("tui.help.section.session")),s.push("- `"+i("tui.help.command.session")+"`"),s.push("- `"+i("tui.help.command.new")+"`"),s.push("- `"+i("tui.help.command.fork")+"`"),s.push("- `"+i("tui.help.command.reset")+"`"),s.push(""),s.push("## "+i("tui.help.section.model")),s.push("- `"+i("tui.help.command.model")+"`"),s.push(""),s.push("## "+i("tui.help.section.settings")),s.push("- `"+i("tui.help.command.settings")+"`"),s.push("- `"+i("tui.help.command.verbose")+"`"),s.push("- `"+i("tui.help.command.thinking")+"`"),s.push(""),s.push("## "+i("tui.help.section.operations")),s.push("- `"+i("tui.help.command.abort")+"`"),s.push("- `"+i("tui.help.command.clear")+"`"),s.push("- `"+i("tui.help.command.compact")+"`"),s.push(""),s.push("## "+i("tui.help.section.skill")),s.push("- `"+i("tui.help.command.skill")+"`"),s.push("- `"+i("tui.help.command.mcp")+"`"),s.push(""),s.push("## "+i("tui.help.section.exit")),s.push("- `"+i("tui.help.command.exit")+"`"),s.push(""),s.push("## "+i("tui.help.section.local")),s.push("- `"+i("tui.help.command.local")+"`"),s.push(""),s.push("## "+i("tui.help.section.shortcuts")),s.push("- `"+i("tui.help.shortcut.ctrl_c")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_d")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_l")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_p")+"`"),s.push("- `"+i("tui.help.shortcut.ctrl_g")+"`"),s.push("- `"+i("tui.help.shortcut.esc")+"`"),s.join(`
|
|
4
|
+
`)}var fs=/[\s\-_./:#@]/;function Dt(s,e){return e===0||fs.test(s[e-1]??"")}function Bt(s,e){if(!e)return null;let t=s.toLowerCase(),n=e.toLowerCase(),i=t.length-n.length;if(i<0)return null;for(let a=0;a<=i;a++)if(t.startsWith(n,a)&&Dt(t,a))return a;return null}function ys(s,e){if(s.length===0)return 0;if(s.length>e.length)return null;let t=0,n=0,i=-1,a=0;for(let o=0;o<e.length&&t<s.length;o++)if(e[o]===s[t]){let l=Dt(e,o);i===o-1?(a++,n-=a*5):(a=0,i>=0&&(n+=(o-i-1)*2)),l&&(n-=10),n+=o*.1,i=o,t++;}return t<s.length?null:n}function Ut(s,e){let t=e.trim();if(!t)return s;let n=t.split(/\s+/).filter(a=>a.length>0);if(n.length===0)return s;let i=[];for(let a of s){let o=a.searchTextLower??"",l=0,c=true;for(let u of n){let d=ys(u,o);if(d!==null)l+=d;else {c=false;break}}c&&i.push({item:a,score:l});}return i.sort((a,o)=>a.score-o.score),i.map(a=>a.item)}var ws="\x1B",qt=new RegExp(`${ws}\\[[0-9;]*m`,"g"),X=class X{constructor(e,t,n){b(this,"items");b(this,"filteredItems");b(this,"selectedIndex",0);b(this,"maxVisible");b(this,"theme");b(this,"searchInput");b(this,"regexCache",new Map);b(this,"onSelect");b(this,"onCancel");b(this,"onSelectionChange");b(this,"compareByScore",(e,t)=>e.tier!==t.tier?e.tier-t.tier:e.score!==t.score?e.score-t.score:this.getItemLabel(e.item).localeCompare(this.getItemLabel(t.item)));this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.searchInput=new Input;}getCachedRegex(e){let t=this.regexCache.get(e);return t||(t=new RegExp(this.escapeRegex(e),"gi"),this.regexCache.set(e,t)),t}updateFilter(){let e=this.searchInput.getValue().trim();e?this.filteredItems=this.smartFilter(e):this.filteredItems=this.items,this.selectedIndex=0,this.notifySelectionChange();}smartFilter(e){let t=e.toLowerCase(),n=[],i=[];for(let o of this.items){let l=this.getItemLabel(o),c=o.description??"",u=a$1(l).toLowerCase(),d=a$1(c).toLowerCase(),g=u.indexOf(t);if(g!==-1){n.push({item:o,tier:0,score:g});continue}let P=Bt(u,t);if(P!==null){n.push({item:o,tier:1,score:P});continue}let B=d.indexOf(t);if(B!==-1){n.push({item:o,tier:2,score:B});continue}let T=o.searchText??"";i.push({item:o,searchTextLower:[l,c,T].map(y=>a$1(y)).filter(Boolean).join(" ").toLowerCase()});}n.sort(this.compareByScore);let a=Ut(i,t);return [...n.map(o=>o.item),...a.map(o=>o.item)]}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}getItemLabel(e){return e.label||e.value}splitAnsiParts(e){let t=[];qt.lastIndex=0;let n=0,i;for(;(i=qt.exec(e))!==null;)i.index>n&&t.push({text:e.slice(n,i.index),isAnsi:false}),t.push({text:i[0],isAnsi:true}),n=i.index+i[0].length;return n<e.length&&t.push({text:e.slice(n),isAnsi:false}),t}highlightMatch(e,t){let n=t.trim().split(/\s+/).map(o=>o.toLowerCase()).filter(o=>o.length>0);if(n.length===0)return e;let i=Array.from(new Set(n)).toSorted((o,l)=>l.length-o.length),a=this.splitAnsiParts(e);for(let o of i){let l=this.getCachedRegex(o),c=[];for(let u of a){if(u.isAnsi){c.push(u);continue}l.lastIndex=0;let d=u.text.replace(l,g=>this.theme.matchHighlight(g));if(d===u.text){c.push(u);continue}c.push(...this.splitAnsiParts(d));}a=c;}return a.map(o=>o.text).join("")}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1));}invalidate(){this.searchInput.invalidate();}render(e){let t=[],i=this.theme.searchPrompt("search: "),a=Math.max(1,e-b$1(i)),l=this.searchInput.render(a)[0]??"";t.push(`${i}${this.theme.searchInput(l)}`),t.push("");let c=this.searchInput.getValue().trim();if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matches")),t;let u=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),d=Math.min(u+this.maxVisible,this.filteredItems.length);for(let g=u;g<d;g++){let P=this.filteredItems[g];if(!P)continue;let B=g===this.selectedIndex;t.push(this.renderItemLine(P,B,e,c));}if(this.filteredItems.length>this.maxVisible){let g=`${this.selectedIndex+1}/${this.filteredItems.length}`;t.push(this.theme.scrollInfo(` ${g}`));}return t}renderItemLine(e,t,n,i){let a=t?"\u2192 ":" ",o=a.length,l=this.getItemLabel(e),c=e.description;if(c){let B=this.getDescriptionLayout(n,o);if(B){let T=truncateToWidth(l,B.maxValueWidth,""),y=this.highlightMatch(T,i),A=b$1(y),h=B.availableWidth-A-B.spacingWidth;if(h>=X.DESCRIPTION_MIN_WIDTH){let se=" ".repeat(B.spacingWidth),H=truncateToWidth(c,h,""),F=this.highlightMatch(H,i),x=t?F:this.theme.description(F),p=`${a}${y}${se}${x}`;return t?this.theme.selectedText(p):p}}}let u=n-o-2,d=truncateToWidth(l,u,""),g=this.highlightMatch(d,i),P=`${a}${g}`;return t?this.theme.selectedText(P):P}getDescriptionLayout(e,t){if(e<=X.DESCRIPTION_LAYOUT_MIN_WIDTH)return null;let n=Math.max(1,e-t-X.RIGHT_MARGIN_WIDTH),i=n-X.DESCRIPTION_MIN_WIDTH-X.DESCRIPTION_SPACING_WIDTH;return i<1?null:{availableWidth:n,maxValueWidth:i,spacingWidth:X.DESCRIPTION_SPACING_WIDTH}}handleInput(e){if(isKeyRelease(e))return;let t=getKeybindings(),n=!this.searchInput.getValue().trim();if(t.matches(e,"tui.select.up")||t.matches(e,"tui.editor.cursorUp")||n&&e==="k"){this.selectedIndex=Math.max(0,this.selectedIndex-1),this.notifySelectionChange();return}if(t.matches(e,"tui.select.down")||t.matches(e,"tui.editor.cursorDown")||n&&e==="j"){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+1),this.notifySelectionChange();return}if(t.matches(e,"tui.select.confirm")){let o=this.filteredItems[this.selectedIndex];o&&this.onSelect&&this.onSelect(o);return}if(t.matches(e,"tui.select.cancel")){this.onCancel&&this.onCancel();return}let i=this.searchInput.getValue();this.searchInput.handleInput(e);let a=this.searchInput.getValue();i!==a&&this.updateFilter();}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e);}getSelectedItem(){return this.filteredItems[this.selectedIndex]??null}};b(X,"DESCRIPTION_LAYOUT_MIN_WIDTH",40),b(X,"DESCRIPTION_MIN_WIDTH",12),b(X,"DESCRIPTION_SPACING_WIDTH",2),b(X,"RIGHT_MARGIN_WIDTH",2);var Fe=X;var ce=a.create({service:"cli-tui-selectors"}),Is={selectedPrefix:s=>`\x1B[36m${s}\x1B[0m`,selectedText:s=>`\x1B[1;36m${s}\x1B[0m`,description:s=>`\x1B[90m${s}\x1B[0m`,scrollInfo:s=>`\x1B[90m${s}\x1B[0m`,noMatch:s=>`\x1B[90m${s}\x1B[0m`,searchPrompt:s=>`\x1B[36m${s}\x1B[0m`,searchInput:s=>s,matchHighlight:s=>`\x1B[1;33m${s}\x1B[0m`};function ue(s,e){ce.debug("Creating searchable select list",{itemsCount:s.length,title:e.title});let t=e.maxVisible??10,n=new Fe(s,t,Is);return e.onSelect&&(n.onSelect=e.onSelect),e.onCancel&&(n.onCancel=e.onCancel),n}function De(s,e){ce.info("Creating model selector with data");let t=[];for(let[n,i]of Object.entries(s))if(i?.models)for(let[a,o]of Object.entries(i.models))t.push({label:`${i.name} - ${o.name}`,value:`${n}/${a}`,description:o.family||""});return ce.debug("Model list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.model.title"),placeholder:e.placeholder||i("tui.selector.model.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Be(s,e){ce.info("Creating session selector with data",{count:s.length});let t=s.map(n=>({label:n.title||n.id,value:n.id,description:`\u66F4\u65B0\u65F6\u95F4: ${n.time?.updated?new Date(n.time.updated).toLocaleString():"\u672A\u77E5"}`}));return ce.debug("Session list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.session.title"),placeholder:e.placeholder||i("tui.selector.session.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Ue(s,e){ce.info("Creating agent selector with data",{count:s.length});let t=s.map(n=>({label:n.name,value:n.name,description:n.description||(n.mode?`\u6A21\u5F0F: ${n.mode}`:"")}));return ce.debug("Agent list loaded",{count:t.length}),ue(t,{title:e.title||i("tui.selector.agent.title"),placeholder:e.placeholder||i("tui.selector.agent.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}var k=a.create({service:"cli-tui-command-handlers"});async function xs(s,e,t){let n=[];n.push("## "+i("tui.handler.status.title")),n.push(""),n.push("### "+i("tui.handler.status.system_info")),n.push("- **"+i("tui.handler.status.system")+"**: "+i("tui.handler.status.ok")),n.push("- **"+i("tui.handler.status.directory")+"**: `"+e+"`"),n.push(""),n.push("### "+i("tui.handler.status.global_paths")),n.push("- **home**: `"+a$2.Path.home+"`"),n.push("- **data**: `"+a$2.Path.data+"`"),n.push("- **bin**: `"+a$2.Path.bin+"`"),n.push("- **log**: `"+a$2.Path.log+"`"),n.push("- **cache**: `"+a$2.Path.cache+"`"),n.push("- **config**: `"+a$2.Path.config+"`"),n.push("- **state**: `"+a$2.Path.state+"`"),n.push(""),n.push("### "+i("tui.handler.status.session_info")),n.push("- **Session**: "+(s.currentSessionKey||i("tui.handler.status.not_set"))),n.push("- **Session ID**: "+(s.currentSessionId||i("tui.handler.status.not_set"))),n.push(""),n.push("### "+i("tui.handler.status.preferences")),n.push("- **Thinking**: "+(s.thinkingLevel||"off")),n.push("- **Context Mode**: "+(s.contextMode||"general")),n.push("- **Verbose**: "+(s.verboseLevel||"off")),n.push("- **Message Limit**: "+(s.messageLimit||50)),n.push("- **Tools Expanded**: "+(s.toolsExpanded?"true":"false")),n.push("- **Local Shell**: "+(s.localShellPermission||"ask")),n.push("### Gateway");try{let i=t?.client,a=await c$1(),o=a.path||"",l=o.endsWith("/")?o.slice(0,-1):o,c=`ws://${a.hostname}:${a.port}${l}`;if(i){let u=i.getState();if(u==="connected")try{let d=await i.getStatus();if(n.push("- **Status**: connected"),n.push(`- **URL**: \`${c}\``),n.push(`- **Connections**: ${d.connections??0}`),n.push(`- **Sessions**: ${d.sessions??0}`),n.push(`- **Message Subscriptions**: ${d.messageSubscriptions??0}`),n.push(`- **Agent Subscriptions**: ${d.agentSubscriptions??0}`),d.agents&&n.push(`- **Agents**: ${d.agents.total??0} (healthy: ${d.agents.healthy??0}, unhealthy: ${d.agents.unhealthy??0})`),d.channels&&d.channels.length>0){let g=d.channels.map(P=>P.platform).join(", ");n.push(`- **Channels**: ${g}`);}}catch{n.push("- **Status**: connected (status fetch failed)"),n.push(`- **URL**: \`${c}\``);}else n.push("- **Status**: "+u),n.push(`- **URL**: \`${c}\``);}else n.push("- **Status**: not initialized"),n.push(`- **URL**: \`${c}\``);}catch(i){k.error("Failed to get Gateway status",{error:String(i)}),n.push("- **Status**: error");}n.push("");try{let a=(await s.sdk.command.list({})).data||[],o=a.filter(u=>u.source==="skill"),l=a.filter(u=>u.source==="mcp"),c=a.filter(u=>u.source==="command");if(n.push("### "+i("tui.handler.status.skills")+" ("+o.length+")"),o.length>0){let u=o.map(d=>d.name).join(", ");n.push(u);}n.push("");try{let d=(await s.sdk.mcp.status({})).data||{},P=(await s.sdk.mcp.tools({})).data||{},B=Object.entries(d).filter(([,T])=>T.status==="connected");if(n.push("### "+i("tui.handler.status.mcp")+" ("+B.length+")"),B.length>0)for(let[T]of B){let y=P[T]||[];y.length>0?n.push("- **"+T+"** ("+y.length+"): "+y.join(", ")):n.push("- **"+T+"**");}n.push("");}catch(u){k.error("Failed to get MCP status",{error:u}),n.push("### "+i("tui.handler.status.mcp")+" (0)"),n.push("");}if(n.push("### "+i("tui.handler.status.commands")+" ("+c.length+")"),c.length>0){let u=c.map(d=>d.name).join(", ");n.push(u);}n.push(""),n.push("### "+i("tui.handler.status.services"));try{if(!s.sdk?.lsp)k.warn("SDK or LSP API is not initialized"),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let u=await s.sdk.lsp.status({});if(!u||typeof u!="object")k.warn("LSP status response is not a valid object",{response:u,responseType:typeof u}),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let d=Array.isArray(u.data)?u.data:[];if(n.push("- **LSP ("+d.length+")**: "),d.length>0){let g=d.filter(P=>P&&typeof P=="object").map(P=>P?.name||"unknown").join(", ");n.push(" "+g);}else n.push(" "+i("tui.handler.status.no_lsp"));}}}catch(u){k.error("Failed to get LSP status",{error:u}),n.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));}}catch(i$1){k.error("Failed to get command list for status",{error:i$1}),n.push(""),n.push("_"+i("tui.handler.status.error_loading")+"_");}try{if(!s.sdk)n.push(""),n.push("### Scheduler"),n.push("- **Status**: not initialized"),n.push("- **Heartbeats**: 0/0"),n.push("- **Scheduled**: 0/0"),n.push("- **Commands**: 0/0");else if(!((await s.sdk.scheduler.initialized({})).data??!1))n.push(""),n.push("### Scheduler"),n.push("- **Status**: not initialized"),n.push("- **Heartbeats**: 0/0"),n.push("- **Scheduled**: 0/0"),n.push("- **Commands**: 0/0");else {let[o,l,c,u]=await Promise.all([s.sdk.scheduler.status({}),s.sdk.scheduler.heartbeats({}),s.sdk.scheduler.scheduled({}),s.sdk.scheduler.commands({})]);n.push(""),n.push("### Scheduler"),n.push("- **Status**: "+(o.data??"unknown")),n.push("- **Heartbeats**: "+l.data?.filter(d=>d.enabled).length+"/"+(l.data?.length??0)),n.push("- **Scheduled**: "+c.data?.filter(d=>d.enabled).length+"/"+(c.data?.length??0)),n.push("- **Commands**: "+u.data?.filter(d=>d.enabled).length+"/"+(u.data?.length??0));}}catch(i){k.error("Failed to get Scheduler status",{error:i}),n.push(""),n.push("### Scheduler"),n.push("- **Status**: error");}return n.join(`
|
|
5
|
+
`)}function Ot(s,e){let{chatLog:t,tui:n,directory:i$1,openOverlay:a,closeOverlay:o,requestExit:l,setActivityStatus:c$1,updateFooter:u,refreshSessionInfo:d,loadHistory:g,setSession:P,refreshAgents:B,abortActive:T}=s,y=()=>{o();},A=async(H,F,x,p)=>{try{if(!F){k.warn("Cannot publish command event: no session ID",{name:H});return}await pa(e,za.Event.Executed,{name:H,sessionId:F,arguments:x,messageId:p}),k.debug("Command event published",{name:H,sessionId:F,messageId:p});}catch(f){k.error("Failed to publish command event",{name:H,sessionId:F,messageId:p,error:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0});}},ge=async(H,F)=>{let{name:x,args:p}=$t(H);if(x){try{switch(x){case "help":t.addSystem(Ft()),await A("help",e.currentSessionId||"",p||"",randomUUID());break;case "commands":case "command":case "cmds":case "cmd":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="command");if(b.length===0){t.addSystem(i("tui.handler.command.empty")),await A(x,e.currentSessionId||"",p||"",randomUUID());break}if(p){let v=p.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("command",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.command.not_found",{vars:{name:W}})),await A(x,e.currentSessionId||"",p,randomUUID());break}let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/command ${v.value} `):await se("command",v.value,e,t,c$1);},onCancel:y});a(E);}catch(f){k.error("Failed to handle command",{error:f}),t.addSystem(i("tui.handler.command.error",{vars:{error:String(f)}}));}await A(x,e.currentSessionId||"","",randomUUID());break}case "status":t.addSystem(await xs(e,i$1,s.gatewayManager)),await A("status",e.currentSessionId||"",p||"",randomUUID());break;case "agents":case "agent":if(p)e.agent=p,t.addSystem(i("tui.handler.agent.switched",{vars:{agentId:p}})),u(),await b$2(e),await A(x,e.currentSessionId||"",p,randomUUID());else {let L=(await ta(e)).filter(w=>w.mode==="primary"&&w.hidden!==!0),b=Ue(L,{onSelect:async w=>{e.agent=w.value,t.addSystem(i("tui.handler.agent.switched",{vars:{agentId:w.value}})),u(),y(),await b$2(e);},onCancel:y});a(b),await A(x,e.currentSessionId||"","",randomUUID());}break;case "sessions":case "session":if(p&&P)await P(p),u(),await A(x,e.currentSessionId||"",p,randomUUID());else {let f=await ua(e),L=Be(f,{onSelect:async b=>{P&&await P(b.value),u(),y();},onCancel:y});a(L),await A(x,e.currentSessionId||"","",randomUUID());}break;case "models":case "model":if(p)e.sessionInfo.model=p,t.addSystem(i("tui.handler.model.set",{vars:{model:p}})),u(),await b$2(e),await A(x,e.currentSessionId||"",p,randomUUID());else {let f=await va(e),L=De(f,{onSelect:async b=>{e.sessionInfo.model=b.value,t.addSystem(i("tui.handler.model.set",{vars:{model:b.value}})),u(),y(),await b$2(e);},onCancel:y});a(L),await A(x,e.currentSessionId||"","",randomUUID());}break;case "fork":{try{c$1(i("tui.handler.fork.begin"));let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,k.debug("Aborted running agent before forking session",{sessionId:f});}catch(L){k.warn("Failed to abort agent before forking, continuing anyway",{error:L});}if(t.clear(),t.init(),f){let b=(await e.sdk.session.fork({sessionId:f})).data;b&&(e.currentSessionId=b.id,e.currentSessionKey=b.title||b.slug||b.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e));}await oa(e,t),g&&await g(),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),c$1(i("tui.status.ready"));}catch(f){k.error("Failed to fork session",{error:f}),t.addSystem(i("tui.handler.fork.error",{vars:{error:String(f)}})),c$1(i("tui.status.error"));}await A("fork",e.currentSessionId||"",p||"",randomUUID()),F.tui.requestRender(!0);break}case "new":{try{c$1(i("tui.handler.new.begin"));let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,k.debug("Aborted running agent before creating new session",{sessionId:f});}catch(E){k.warn("Failed to abort agent before creating new session, continuing anyway",{error:E});}t.clear(),t.init();let L=e.instanceContext.directory,w=(await e.sdk.session.create({directory:L})).data;w&&(e.currentSessionId=w.id,e.currentSessionKey=w.title||w.slug||w.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e)),await oa(e,t),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),c$1(i("tui.status.ready"));}catch(f){k.error("Failed to create new session",{error:f}),t.addSystem(i("tui.handler.new.error",{vars:{error:String(f)}})),c$1(i("tui.status.error"));}await A("new",e.currentSessionId||"",p||"",randomUUID()),F.tui.requestRender(!0);break}case "reset":{try{let f=e.currentSessionId;if(f&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:f}),e.activeChatRunId=null,k.debug("Aborted running agent before reset",{sessionId:f});}catch(L){k.warn("Failed to abort agent before reset, continuing anyway",{error:L});}t.clear(),t.init(),t.addSystem(i("tui.handler.session.reset")),g&&await g(),await oa(e,t),u();}catch(f){k.error("Failed to reset session",{error:f}),t.addSystem(i("tui.handler.session.reset_error",{vars:{error:String(f)}}));}await A("reset",e.currentSessionId||"",p||"",randomUUID()),F.tui.requestRender(!0);break}case "settings":{k.debug("Opening settings panel");let{createSettingsPanel:f}=await import('./settings-panel-C32BQGOR.mjs'),L=f({currentSettings:{thinkingLevel:e.thinkingLevel,showThinking:e.showThinking,verboseLevel:e.verboseLevel,messageLimit:e.messageLimit,toolsExpanded:e.toolsExpanded,localShellPermission:e.localShellPermission,contextMode:e.contextMode},onChange:(b,w)=>{switch(b){case "thinkingLevel":e.thinkingLevel=w,t.addSystem(i("tui.handler.thinking_level.set",{vars:{level:w}}));break;case "showThinking":e.showThinking=w==="true",k.debug("showThinking changed",{newValue:w,showThinking:e.showThinking}),t.addSystem(e.showThinking?i("tui.hint.show_thinking_on"):i("tui.hint.show_thinking_off"));break;case "verboseLevel":e.verboseLevel=w,t.addSystem(i("tui.handler.verbose_level.set",{vars:{level:w}}));break;case "messageLimit":e.messageLimit=Number.parseInt(w,10),t.addSystem(i("tui.handler.message_limit.set",{vars:{limit:w}}));break;case "toolsExpanded":e.toolsExpanded=w==="true",k.debug("toolsExpanded changed",{newValue:w,toolsExpanded:e.toolsExpanded}),t.addSystem(e.toolsExpanded?i("tui.hint.tools_expanded"):i("tui.hint.tools_collapsed"));break;case "localShellPermission":e.localShellPermission=w,k.debug("localShellPermission changed",{newValue:w,localShellPermission:e.localShellPermission}),t.addSystem(i("tui.shell.permission.updated",{vars:{permission:w}}));break;case "contextMode":{let E=w;e.contextMode=E,k.debug("contextMode changed",{newValue:w,contextMode:E}),t.addSystem(i("tui.handler.context_mode.set",{vars:{mode:E}})),e.currentSessionId&&e.sdk.session.contextMode.set({sessionId:e.currentSessionId,mode:E}).catch(v=>{k.error("Failed to update session contextMode",{error:v,sessionId:e.currentSessionId});});break}}b$2(e).then(async()=>{try{k.debug("Publishing HeaderRefresh event",{id:b,newValue:w}),await pa(e,c.StatusBarRefresh,{reason:`settings changed: ${b}`});}catch(E){k.error("Failed to publish HeaderRefresh event",{error:E});}}).catch(E=>{k.error("Failed to save TUI state after settings change",{error:E,id:b});});},onCancel:y});a(L),await A("settings",e.currentSessionId||"",p||"",randomUUID());break}case "verbose":if(!p){t.addSystem(i("tui.handler.verbose.usage")),await A(x,e.currentSessionId||"","",randomUUID());break}if(p!=="on"&&p!=="off"){t.addSystem(i("tui.handler.verbose.invalid",{vars:{value:p}})),await A(x,e.currentSessionId||"",p,randomUUID());break}e.verboseLevel=p,t.addSystem(i("tui.handler.verbose.set",{vars:{level:p}})),await b$2(e),await A(x,e.currentSessionId||"",p,randomUUID());break;case "thinking":if(!p){t.addSystem(i("tui.handler.thinking.usage")),await A(x,e.currentSessionId||"","",randomUUID());break}e.thinkingLevel=p,t.addSystem(i("tui.handler.thinking.set",{vars:{level:p}})),await b$2(e),await A("thinking",e.currentSessionId||"",p||"",randomUUID());break;case "clear":{k.debug("Opening clear confirmation dialog");let{createConfirmDialog:f}=await import('./confirm-dialog-PT62UY3W.mjs'),L=f({message:i("tui.dialog.clear.message"),onConfirm:async()=>{try{c$1(i("tui.handler.clear.begin")),y();let b=e.currentSessionId;if(b&&e.activeChatRunId)try{await e.sdk.session.abort({sessionId:b}),e.activeChatRunId=null,k.debug("Aborted running agent before clearing session",{sessionId:b});}catch(v){k.warn("Failed to abort agent before clearing, continuing anyway",{error:v});}t.clear(),t.init(),b&&await e.sdk.session.delete({sessionId:b});let E=(await e.sdk.session.create({directory:e.instanceContext.directory})).data;E&&(e.currentSessionId=E.id,e.currentSessionKey=E.title||E.slug||E.id,e.sessionInfo={model:e.sessionInfo.model},await b$2(e)),await oa(e,t),s.reconnectGateway&&e.currentSessionId&&await s.reconnectGateway(e.currentSessionId),u(),t.addSystem(i("tui.handler.clear.success")),c$1(i("tui.status.ready"));}catch(b){k.error("Failed to clear chat history",{error:b}),t.addSystem(i("tui.handler.clear.error",{vars:{error:String(b)}})),c$1(i("tui.status.error"));}await A("clear",e.currentSessionId||"",p||"",randomUUID()),F.tui.requestRender(!0);},onCancel:()=>{t.addSystem(i("tui.clear.cancel")),y();}});a(L);break}case "skills":case "skill":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="skill");if(b.length===0){t.addSystem(i("tui.handler.skill.empty")),await A(x,e.currentSessionId||"",p||"",randomUUID());break}if(p){let v=p.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("skill",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.skill.not_found",{vars:{name:W}})),await A(x,e.currentSessionId||"",p,randomUUID());break}k.debug("Opening skill selector");let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/skill ${v.value} `):await se("skill",v.value,e,t,c$1);},onCancel:y});a(E),await A(x,e.currentSessionId||"","",randomUUID());}catch(f){k.error("Failed to handle skill",{error:f}),t.addSystem(i("tui.handler.skill.error",{vars:{error:String(f)}})),await A(x,e.currentSessionId||"",p||"",randomUUID());}break}case "mcps":case "mcp":{try{let b=((await e.sdk.command.list({})).data||[]).filter(v=>v.source==="mcp");if(b.length===0){t.addSystem(i("tui.handler.mcp.empty")),await A(x,e.currentSessionId||"",p||"",randomUUID());break}if(p){let v=p.split(/\s+/),W=v[0],ae=v.slice(1).join(" ");b.some(ee=>ee.name===W)?await se("mcp",W,e,t,c$1,ae||void 0):t.addSystem(i("tui.handler.mcp.not_found",{vars:{name:W}})),await A(x,e.currentSessionId||"",p,randomUUID());break}k.debug("Opening MCP prompt selector");let w=b.map(v=>({label:v.name,description:v.description||"",value:v.name})),E=ue(w,{onSelect:async v=>{y(),s.setInputText?s.setInputText(`/mcp ${v.value} `):await se("mcp",v.value,e,t,c$1);},onCancel:y});a(E);}catch(f){k.error("Failed to handle MCP prompt",{error:f}),t.addSystem(i("tui.handler.mcp.error",{vars:{error:String(f)}}));}await A(x,e.currentSessionId||"","",randomUUID());break}case "exit":case "quit":await A(x,e.currentSessionId||"",p||"",randomUUID()),l();break;default:k.debug("Unknown command, sending as message"),await h(H);break}}catch(f){let L=f instanceof Error?f.message:String(f);k.error("Command execution failed",{command:x,args:p,error:L,stack:f instanceof Error?f.stack:void 0}),t.addSystem(i("tui.handler.command.error",{vars:{command:x,error:L}}));}k.debug("handleCommand completed");}},h=async(H,F,x)=>{try{let p=randomUUID();if(e.activeChatRunId=p,c$1(i("tui.handler.send.sending")),!e.currentSessionId)throw new Error("No active session");let f;if(e.sessionInfo.model){let{provider:w,model:E}=parseModelId(e.sessionInfo.model);w&&E&&(f={providerId:w,modelId:E});}let L=[{type:"text",text:H}];if(F&&F.length>0)for(let w of F)L.push({type:"file",url:w.url,filename:w.filename,mime:w.mime});x&&L.push({type:"agent",name:x});let b=await e.sdk.session.prompt({sessionId:e.currentSessionId,parts:L,agent:e.agent||void 0,model:f,variant:e.thinkingLevel,contextMode:e.contextMode});if(b.data&&e.currentSessionId&&await A("message",e.currentSessionId,H,b.data.info?.id||randomUUID()),b.data){let w=b.data.parts?.filter(E=>E.type==="text")||[];for(let E of w)"text"in E&&E.text&&t.addAssistant(E.text,b.data.info?.id);}e.activeChatRunId=null,c$1("");}catch(p){e.activeChatRunId=null;let f=p instanceof Error?p.message:String(p),L=p instanceof Error?p.name:"Error";t.addSystem(i("tui.handler.send.error",{vars:{error:f}})),c$1(i("tui.handler.send.error_status")),k.error("Failed to send message",{error:f,errorName:L,sessionId:e.currentSessionId,hasModel:!!e.sessionInfo.model,stack:p instanceof Error?p.stack:void 0});}},se=async(H,F,x,p,f,L)=>{try{let b=H==="skill"?i("tui.handler.skill.executing"):H==="command"?i("tui.handler.command.executing"):i("tui.handler.mcp.executing");if(p.addSystem(b+`: ${F}`),f(i("tui.handler.executing",{vars:{command:F}})),!x.currentSessionId)throw new Error("No active session");let w;x.sessionInfo.model&&(w=x.sessionInfo.model);let E=L?[{type:"text",text:L}]:void 0,W=(await x.sdk.session.command({sessionId:x.currentSessionId,command:F,arguments:L??"",agent:x.agent||void 0,model:w,variant:x.thinkingLevel,contextMode:x.contextMode,parts:E})).data,Y=W?.metadata?.commandType;if(W?.success)Y==="local"&&p.addSystem(i("tui.handler.local.completed")+`: ${F}
|
|
6
6
|
`+i("tui.handler.local.output")+`:
|
|
7
|
-
`+W.output);else {let ee=W?.error??"Command execution failed",q=H==="skill"?"tui.handler.skill.error":H==="command"?"tui.handler.command.error":"tui.handler.mcp.error";
|
|
8
|
-
${w}`),f(i("tui.status.error")),
|
|
7
|
+
`+W.output);else {let ee=W?.error??"Command execution failed",q=H==="skill"?"tui.handler.skill.error":H==="command"?"tui.handler.command.error":"tui.handler.mcp.error";p.addSystem(i(q,{vars:{command:F,error:ee}}));}f("");}catch(b){let w=b instanceof Error?b.message:String(b),E=b instanceof Error?b.name:"Error",v=H==="skill"?i("tui.handler.skill.error"):H==="command"?i("tui.handler.command.error"):i("tui.handler.mcp.error");p.addSystem(v+`: ${F}
|
|
8
|
+
${w}`),f(i("tui.status.error")),k.error("Failed to execute command",{type:H,name:F,error:w,errorName:E,sessionId:x.currentSessionId,stack:b instanceof Error?b.stack:void 0});}};return {handleCommand:ge,sendMessage:h,gatewayManager:s.gatewayManager}}var R=a.create({service:"cli-tui-events"});function Wt(s){return e=>{try{if(e.type==="message.updated"){As(s,e);return}if(e.type==="message.part.updated"){Ps(s,e);return}if(e.type==="session.status"){qs(s,e);return}if(e.type==="session.error"){Os(s,e);return}if(e.type==="agent.updated"){Ws(s,e);return}if(e.type==="session.updated"){Ns(s,e);return}if(e.type==="permission.asked"){Gs(s,e);return}if(e.type==="question.asked"){Qs(s,e);return}}catch(t){R.error("Event handling failed",{eventType:e.type,error:t instanceof Error?t.message:String(t)});}}}function As(s,e){if(e.type!=="message.updated")return;let{properties:t}=e,{info:n}=t,i=s.state?.currentSessionId||s.sessionId;if(!(i&&n.sessionId!==i)&&s.state&&"model"in n&&n.model){let a=`${n.model.providerId}/${n.model.modelId}`;s.state.sessionInfo.model=a,s.updateFooter&&s.updateFooter();}}function Ps(s,e){if(e.type!=="message.part.updated")return;let{properties:t}=e,{part:n}=t;if(!n){R.warn("Message part is undefined",{event:e,properties:t,propertiesType:typeof t,propertiesKeys:t?Object.keys(t):[]});return}let i=s.state?.currentSessionId||s.sessionId;i&&n.sessionId!==i||Ms(s,n);}function Ms(s,e){if(e.type==="tool"){Ds(s,e);return}if(e.type==="text"){if("time"in e&&e.time&&"end"in e.time&&e.time.end){Bs(s,e);return}if(!("time"in e)){Es(s,e);return}}if(e.type==="reasoning"&&"time"in e&&e.time&&"end"in e.time&&e.time.end){Us(s,e);return}if(e.type==="step-start"){Ls(s);return}if(e.type==="step-finish"){_s(s,e);return}if(e.type==="subtask-result"){$s(s,e);return}}function Es(s,e){let t=e.text?.trim();t&&s.chatLog.addUser(t,e.messageId);}function Ls(s){s.setActivityStatus(i("tui.status.executing_step"));}function _s(s,e){s.setActivityStatus(i("tui.status.step_completed")),s.state&&e.tokens&&Hs(s,e.tokens);}function $s(s,e){let t=Ka.formatSubtaskResultPart(e);s.chatLog.addUser(t,e.id,{agent:e.agent,isSubagentResult:true,subtaskResultPart:{taskId:e.taskId,source:e.source,agent:e.agent,status:e.status,result:e.result,error:e.error,duration:e.duration,rounds:e.rounds,time:e.time,metadata:e.metadata}});}async function Rs(s){let e=s.sessionInfo.model;if(!e)return null;let{provider:t,model:n}=parseModelId(e);if(!t||!n)return null;try{return ((await s.sdk.config.providers({})).data?.providers??[]).find(c=>c.id===t)?.models?.[n]?.limit?.context??null}catch(i){return R.warn("Failed to get context limit from model config",{error:i,providerId:t,modelId:n}),null}}function Hs(s,e){let t=e.input+e.output+e.reasoning+e.cache.read+e.cache.write;s.state.sessionInfo.totalTokens=t,s.state.sessionInfo.contextTokens||Rs(s.state).then(n=>{s.state.sessionInfo.contextTokens=n??2e5,s.updateFooter&&s.updateFooter();});}function Fs(s){let e=s.state?.status==="running"||s.state?.status==="completed"?s.state.input:void 0;if(!e)return;let t=e.filePath??e.filepath??e.path,n=e.title;return t?n=Filesystem.normalize(t):e.url&&(n=e.url),n}function Ds(s,e){if(!e.state){R.warn("Tool part missing state",{tool:e.tool,partType:e.type});return}let t=Fs(e),n=t?`${e.tool} ${t}`:e.tool;if(e.state.status==="running"&&(s.setActivityStatus(i("tui.status.executing_tool",{vars:{tool:e.tool}})),s.chatLog.addSystem(i("tui.system.tool_executing",{vars:{tool:n}}),e.id,{isTool:true,toolName:e.tool,toolCallId:e.callId,toolStatus:"executing",title:t})),e.state.status==="completed"&&(s.setActivityStatus(i("tui.status.tool_completed")),s.chatLog.addSystem(i("tui.system.tool_completed",{vars:{tool:n}}),e.id,{isTool:true,toolName:e.tool,toolCallId:e.callId,toolStatus:"completed",result:e.state.output,title:t}),s.state?.toolsExpanded&&s.state?.verboseLevel==="on"&&e.state.output)){let a=(typeof e.state.output=="string"?e.state.output:JSON.stringify(e.state.output,null,2)).trim();a&&s.chatLog.addSystem(`Tool output:
|
|
9
9
|
`+a);}e.state.status==="error"&&(s.setActivityStatus(i("tui.status.tool_failed")),s.chatLog.addSystem(i("tui.system.tool_failed",{vars:{tool:n}}),e.id,{isTool:true,toolName:e.tool,toolCallId:e.callId,toolStatus:"failed",error:e.state.error,title:t}));}function Bs(s,e){let t=e.text?.trim();t&&(s.chatLog.addAssistant(t,e.messageId),s.setActivityStatus(i("tui.status.receiving")));}function Us(s,e){let t=e.text?.trim();if(!t){R.warn("Reasoning part has no text, skipping",{partId:e.id});return}if(t=t.replace("[REDACTED]","").trim(),!t){R.warn("Reasoning part is redacted, skipping",{partId:e.id});return}if(t=t.trim(),!t){R.warn("Reasoning part has no content after cleanup",{partId:e.id});return}if(R.debug("Adding reasoning message to ChatLog",{textLength:t.length,partId:e.id,showThinking:s.state?.showThinking,hasTimeEnd:"time"in e&&e.time&&"end"in e.time?!!e.time.end:false}),s.chatLog.addSystem(i("tui.system.thinking",{vars:{text:t}}),e.id,{isThinking:true}),R.debug("Reasoning message added, requesting render"),s.state?.pendingQuestion){s.state.questionDisplayTimer&&(clearTimeout(s.state.questionDisplayTimer),s.state.questionDisplayTimer=null,R.debug("Question display fallback timer cleared (reasoning-end)"));let n=s.state.pendingQuestion;if(n.questions.length>0){let i=n.questions[0];i&&(R.debug("Show first question after reasoning-end",{header:i.header,question:i.question,optionCount:i.options?.length||0}),Nt(s,i,0,n.questions.length));}}}function qs(s,e){let{properties:t}=e,{sessionId:n,status:i$1}=t,a=s.state?.currentSessionId||s.sessionId;if(!(a&&n!==a)){if(R.debug("Session status",{status:i$1.type,sessionId:n}),i$1.type==="idle"){if(s.state){if(s.state.questionDisplayTimer&&(clearTimeout(s.state.questionDisplayTimer),s.state.questionDisplayTimer=null,R.debug("Question display fallback timer cleared (session idle)")),s.state.pendingQuestion){let o=s.state.pendingQuestion.id;R.debug("Rejecting pending question due to session idle",{questionId:o,sessionId:n}),s.state.pendingQuestion=null,s.chatLog.addSystem(i("tui.question.cancelled")),s.state.sdk.question.reject({requestId:o}).catch(l=>{R.error("Failed to reject question",{error:l});});}if(s.state.pendingPermission){let o=s.state.pendingPermission.sessionId,l=s.state.pendingPermission.id;R.debug("Rejecting pending permission due to session idle",{permissionId:l,sessionId:n}),s.state.pendingPermission=null,s.chatLog.addSystem(i("tui.permission.cancelled")),s.state.sdk.permission.respond({sessionId:o,permissionId:l,response:"reject"}).catch(c=>{R.error("Failed to reject permission",{error:c});});}}s.setActivityStatus(i("tui.status.ready"));}i$1.type==="running"&&s.setActivityStatus(i("tui.status.running")),i$1.type==="waiting"&&s.setActivityStatus(i("tui.status.waiting"));}}function Os(s,e){let{properties:t}=e,{sessionId:n,error:i$1}=t,a=s.state?.currentSessionId||s.sessionId;if(a&&n!==a)return;R.error("Session error",{error:i$1,sessionId:n});let o=String(i$1.name);"data"in i$1&&i$1.data&&"message"in i$1.data&&(o=String(i$1.data.message)),s.chatLog.addSystem(i("tui.system.error",{vars:{message:o}})),s.setActivityStatus(i("tui.status.error"));}function Ws(s,e){let{properties:t}=e,{agentId:n}=t;R.debug("Agent updated (backend event)",{agentId:n});}function Ns(s,e){let{properties:t}=e,{info:n}=t,i=s.state?.currentSessionId||s.sessionId;i&&n.id!==i||(R.debug("Session updated",{sessionId:n.id,title:n.title}),s.state&&(s.state.currentSessionKey=n.title||n.id,n.model&&(s.state.sessionInfo.model=`${n.model.providerId}/${n.model.modelId}`)),s.updateFooter&&s.updateFooter());}function Gs(s,e){let{properties:t}=e,n=t,i$1=s.state?.currentSessionId||s.sessionId;if(i$1&&n.sessionId!==i$1){R.debug("Ignore permission request from other session",{sessionId:n.sessionId,currentSessionId:i$1});return}R.debug("Received permission request",{permission:n.permission,patterns:n.patterns,sessionId:n.sessionId}),s.state&&(s.state.pendingPermission={id:n.id,sessionId:n.sessionId,permission:n.permission,patterns:n.patterns});let a=`
|
|
10
10
|
`+i("tui.permission.request_header")+`
|
|
11
11
|
`;a+=i("tui.permission.type",{vars:{type:n.permission}})+`
|
|
@@ -30,10 +30,10 @@ ${w}`),f(i("tui.status.error")),A.error("Failed to execute command",{type:H,name
|
|
|
30
30
|
`+i("tui.question.hint.custom_disabled_multiple")+`
|
|
31
31
|
`:l+=`
|
|
32
32
|
`+i("tui.question.hint.custom_disabled")+`
|
|
33
|
-
`;}R.debug("displayQuestion - final message",{messageLength:l.length,messagePreview:l.substring(0,100)}),s.chatLog.addSystem(l);}var J=a.create({service:"cli-tui-session-actions"});async function Gt(s){J.debug("Refreshing agent list");try{s.setActivityStatus(i("tui.session.loading_agents"));let n=((await s.sdk.app.agents({})).data||[]).map(i=>i.name);return J.info("Agent list loaded",{count:n.length}),s.setActivityStatus(i("tui.status.ready")),n}catch(e){return J.error("Failed to refresh agent list",{error:e}),s.chatLog.addSystem(i("tui.session.agents_failed",{vars:{error:String(e)}})),s.setActivityStatus(i("tui.status.error")),[]}}async function at(s,e){J.debug("Refreshing session info",{sessionId:e});try{s.setActivityStatus(i("tui.session.loading_info"));let n=(await s.sdk.session.get({sessionId:e})).data;return J.info("Session info loaded",{sessionId:e}),s.setActivityStatus(i("tui.status.ready")),n??null}catch(t){return J.error("Failed to refresh session info",{sessionId:e,error:t}),s.chatLog.addSystem(i("tui.session.info_failed",{vars:{error:String(t)}})),s.setActivityStatus(i("tui.status.error")),null}}async function qe(s,e,t){J.info("Loading history",{sessionId:e,limit:t});try{s.setActivityStatus(i("tui.session.loading_history"));let i$1=(await s.sdk.session.messages({sessionId:e,limit:t})).data||[];J.info("History loaded",{sessionId:e,count:i$1.length});for(let a=0;a<i$1.length;a++){let o=i$1[a],l=o?.info?.role;if(l==="user"){let u=(o?.parts?.filter(
|
|
34
|
-
`),d=o?.parts?.filter(
|
|
33
|
+
`;}R.debug("displayQuestion - final message",{messageLength:l.length,messagePreview:l.substring(0,100)}),s.chatLog.addSystem(l);}var J=a.create({service:"cli-tui-session-actions"});async function Gt(s){J.debug("Refreshing agent list");try{s.setActivityStatus(i("tui.session.loading_agents"));let n=((await s.sdk.app.agents({})).data||[]).map(i=>i.name);return J.info("Agent list loaded",{count:n.length}),s.setActivityStatus(i("tui.status.ready")),n}catch(e){return J.error("Failed to refresh agent list",{error:e}),s.chatLog.addSystem(i("tui.session.agents_failed",{vars:{error:String(e)}})),s.setActivityStatus(i("tui.status.error")),[]}}async function at(s,e){J.debug("Refreshing session info",{sessionId:e});try{s.setActivityStatus(i("tui.session.loading_info"));let n=(await s.sdk.session.get({sessionId:e})).data;return J.info("Session info loaded",{sessionId:e}),s.setActivityStatus(i("tui.status.ready")),n??null}catch(t){return J.error("Failed to refresh session info",{sessionId:e,error:t}),s.chatLog.addSystem(i("tui.session.info_failed",{vars:{error:String(t)}})),s.setActivityStatus(i("tui.status.error")),null}}async function qe(s,e,t){J.info("Loading history",{sessionId:e,limit:t});try{s.setActivityStatus(i("tui.session.loading_history"));let i$1=(await s.sdk.session.messages({sessionId:e,limit:t})).data||[];J.info("History loaded",{sessionId:e,count:i$1.length});for(let a=0;a<i$1.length;a++){let o=i$1[a],l=o?.info?.role;if(l==="user"){let u=(o?.parts?.filter(g=>g.type==="text")||[]).map(g=>("text"in g?g.text:"")||"").join(`
|
|
34
|
+
`),d=o?.parts?.filter(g=>g.type==="subtask-result")||[];for(let g of d)if("agent"in g&&"taskId"in g){let P=Ka.formatSubtaskResultPart(g);s.chatLog.addUser(P,o?.info?.id,{agent:g.agent||"SubAgent",isSubagentResult:!0,subtaskResultPart:{taskId:g.taskId,source:g.source,agent:g.agent,status:g.status,result:g.result,error:g.error,duration:g.duration,rounds:g.rounds,time:g.time,metadata:g.metadata}});}u&&s.chatLog.addUser(u,o?.info?.id,{agent:o?.info?.agent});}else if(l==="assistant"){let u=(o?.parts?.filter(d=>d.type==="text")||[]).map(d=>("text"in d?d.text:"")||"").join(`
|
|
35
35
|
`);u&&s.chatLog.addAssistant(u,o?.info?.id,{agent:o?.info?.agent});}else if(l==="system"){let u=(o?.parts?.filter(d=>d.type==="text")||[]).map(d=>("text"in d?d.text:"")||"").join(`
|
|
36
|
-
`);s.chatLog.addSystem(u,o?.info?.id,{agent:o?.info?.agent});}}return s.setActivityStatus(i("tui.status.ready")),i$1}catch(n){return J.error("Failed to load history",{sessionId:e,error:n}),s.chatLog.addSystem(i("tui.session.history_failed",{vars:{error:String(n)}})),s.setActivityStatus(i("tui.status.error")),[]}}async function Qt(s,e,t){J.debug("Switching session",{sessionId:e});try{t.currentSessionId=e,t.currentSessionKey=e,t.historyLoaded=!1;let n=await at(s,e);n&&(t.currentSessionKey=n.title||e,t.sessionInfo.model=n.model,t.sessionInfo.modelProvider=n.modelProvider);let{loadTuiState:i$1,saveTuiStateToStorage:a}=await import('./preferences-QCM3RIAL.mjs'),o=await i$1(e);t.toolsExpanded=o.toolsExpanded,t.showThinking=o.showThinking,t.thinkingLevel=o.thinkingLevel,t.verboseLevel=o.verboseLevel,t.messageLimit=o.messageLimit,t.localShellPermission=o.localShellPermission,o.model&&(t.sessionInfo.model=o.model),o.agent&&(t.agent=o.agent),J.debug("Session preferences loaded",{sessionId:e,model:t.sessionInfo.model,agent:t.agent,thinkingLevel:t.thinkingLevel}),await a(t),await qe(s,e,t.messageLimit),t.historyLoaded=!0,s.chatLog.addSystem(i("tui.session.switched",{vars:{sessionId:e}}));}catch(n){J.error("Failed to switch session",{sessionId:e,error:n}),s.chatLog.addSystem(i("tui.session.switch_failed",{vars:{error:String(n)}})),s.setActivityStatus(i("tui.status.error"));}}async function jt(s,e){J.debug("Aborting current run",{sessionId:e});try{s.setActivityStatus(i("tui.session.aborting"));let t=s.sdk.session.abort({sessionId:e}),n=new Promise((i$1,a)=>{setTimeout(()=>a(new Error(i("tui.abort.timeout"))),5e3);});await Promise.race([t,n]),s.chatLog.addSystem(i("tui.session.aborted")),s.setActivityStatus(i("tui.status.ready"));}catch(t){J.error("Failed to abort",{sessionId:e,error:t}),s.chatLog.addSystem(i("tui.session.abort_failed",{vars:{error:String(t)}})),s.setActivityStatus(i("tui.status.error"));}}function Kt(s,e){return {openOverlay:i=>{s.showOverlay(i);},closeOverlay:()=>{s.hasOverlay()&&s.hideOverlay(),s.setFocus(e);}}}var Oe=a.create({service:"tui-autocomplete"});function Vt(s){return new lt(s)}var lt=class{constructor(e){b(this,"basePath");b(this,"commands");b(this,"getAgents");this.basePath=e.basePath,this.commands=e.slashCommands,this.getAgents=e.getAgents;}updateCommands(e){this.commands=e;}setGetAgents(e){this.getAgents=e;}async getSuggestions(e,t,n,i){let o=(e[t]||"").slice(0,n),l=this.extractHashPrefix(o);if(l)return this.getFileSuggestions(l);let c=this.extractAtPrefix(o);return c?await this.getAgentSuggestions(c):o.startsWith("/")?this.getCommandSuggestions(o):null}applyCompletion(e,t,n,i,a){let o=e[t]||"",l=o.slice(0,n-a.length),c=o.slice(n);if(a.startsWith("#")){let u=i.label.endsWith("/"),d=u?i.value.replace(/\/$/,""):i.value,p=u?"":" ";return {lines:[...e.slice(0,t),l+d+p+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+d.length+p.length}}if(a.startsWith("@"))return {lines:[...e.slice(0,t),l+i.value+" "+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+i.value.length+1};if(a.startsWith("/")){let u="/"+i.value+" ";return {lines:[...e.slice(0,t),l+u+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+u.length}}return {lines:[...e.slice(0,t),l+i.value+" "+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+i.value.length+1}}async getCommandSuggestions(e){let t=e.indexOf(" ");if(t===-1){let c=e.slice(1),u=this.commands.filter(d=>d.name.toLowerCase().includes(c.toLowerCase())).map(d=>({value:d.name,label:d.name,description:d.description}));return u.length===0?null:{items:u.slice(0,50),prefix:e}}let n=e.slice(1,t),i=e.slice(t+1),a=this.commands.find(c=>c.name===n);if(!a?.getArgumentCompletions)return null;let o=a.getArgumentCompletions(i),l=o instanceof Promise?await o:o;return !l||l.length===0?null:{items:l.slice(0,50),prefix:i}}getFileSuggestions(e){let t=e.startsWith('#"')?e.slice(2):e.slice(1),n=e.startsWith('#"'),i=t.replace(/\\/g,"/");if(this.isDrivePath(i))return Oe.debug("Drive path, skip autocomplete",{normalizedPath:i}),null;let{targetPath:a,searchQuery:o}=this.parsePath(i),l=this.resolveBaseDir(a);try{let c;try{c=readdirSync(l,{withFileTypes:!0});}catch{return Oe.debug("Directory not found",{baseDir:l}),null}let u=[];for(let d of c){if(o&&!d.name.toLowerCase().includes(o.toLowerCase()))continue;let p=d.isDirectory(),M=a?`${a}${d.name}`:d.name;if(u.push({value:n?`#"${M}${p?"/":""}"`:`#${M}${p?"/":""}`,label:p?`${d.name}/`:d.name,description:M}),u.length>=50)break}return u.sort((d,p)=>{let M=d.label.endsWith("/"),B=p.label.endsWith("/");return M&&!B?-1:!M&&B?1:d.label.localeCompare(p.label)}),u.length===0?null:{items:u,prefix:e}}catch(c){return Oe.debug("File search failed",{error:c,targetPath:a}),null}}async getAgentSuggestions(e){if(!this.getAgents)return null;let t=e.slice(1);try{let i=(await this.getAgents()).filter(a=>a.hidden!==!0).filter(a=>a.name.toLowerCase().includes(t.toLowerCase())).map(a=>({value:`@${a.name}`,label:a.name,description:a.description}));return i.length===0?null:{items:i.slice(0,50),prefix:e}}catch(n){return Oe.debug("Agent search failed",{error:n,prefix:e}),null}}extractAtPrefix(e){let t=new Set([" "," ",'"',"'","="]);for(let n=e.length-1;n>=0;n--)if(t.has(e[n]??"")){let i=n+1;return e[i]==="@"?e.slice(i):null}return e.startsWith("@")?e:null}extractHashPrefix(e){let t=new Set([" "," ",'"',"'","="]);for(let n=e.length-1;n>=0;n--)if(t.has(e[n]??"")){let i=n+1;return e[i]==="#"?e.slice(i):null}return e.startsWith("#")?e:null}isDrivePath(e){return /^[A-Za-z]:[/\\]?$/.test(e)}parsePath(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?{targetPath:"",searchQuery:e}:{targetPath:e.slice(0,t+1),searchQuery:e.slice(t+1)}}resolveBaseDir(e){return e?zt.join(this.basePath,e):this.basePath}};function dt(s,e){let t=[],n=/(?<![\w`])#(\S+)/g,i;for(;(i=n.exec(s))!==null;){let a=i[1];if(!a)continue;let o=a.replace(/\\/g,"/"),l=Vs(o,e);existsSync(l)&&t.push({path:a,url:pathToFileURL(l).href,exists:true});}return {attachments:t,invalidPaths:[]}}function Vs(s,e){if(/^[A-Za-z]:[/\\]/.test(s))return s;let t=s.replace(/^[/\\]+/,"");return zt.join(e,t)}var G=a.create({service:"cli-tui-input-handlers"}),We=class{constructor(){b(this,"handlers",[]);b(this,"isBrowsingHistory",false);}register(e){this.handlers.push(e),G.debug("Register input handler",{name:e.name,total:this.handlers.length});}setHistoryBrowsing(e){this.isBrowsingHistory=e;}isHistoryBrowsing(){return this.isBrowsingHistory}async handle(e,t){let n=e.trim();if(n){this.isBrowsingHistory;for(let i of this.handlers)if(i.canHandle(n,t.state)){G.debug("Handle input with handler",{handler:i.name,input:n.substring(0,50)}),await i.handle(n,t);return}G.warn("No handler can process input",{input:n.substring(0,50)});}}getPrompt(e){for(let t of this.handlers)if(t.getPrompt&&t.canHandle("",e)){let n=t.getPrompt(e);if(n)return n}return "> "}},Ne=class{constructor(){b(this,"name","permission");}canHandle(e,t){return t.pendingPermission!==null}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=n.pendingPermission;if(!o)return;let l=e.toLowerCase().trim(),c;if(l==="y"||l==="yes")c="once";else if(l==="a"||l==="always")c="always";else if(l==="n"||l==="no"||l==="reject")c="reject";else {i$1.addSystem(i("tui.permission.invalid_input"));return}try{await ra(n,{requestId:o.id,reply:c}),n.pendingPermission=null;let u=c==="once"?i("tui.permission.once"):c==="always"?i("tui.permission.always"):i("tui.permission.reject");i$1.addSystem(i("tui.permission.replied",{vars:{reply:u}})),G.debug("Permission request replied",{requestId:o.id,reply:c});}catch(u){G.error("Failed to reply permission request",{error:u}),i$1.addSystem(i("tui.permission.error")),n.pendingPermission=null;}}getPrompt(e){return e.pendingPermission?i("tui.permission.prompt"):"> "}},Ge=class{constructor(){b(this,"name","question");}canHandle(e,t){return !(t.pendingQuestion===null||e.startsWith("/"))}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=n.pendingQuestion;if(!o){G.warn("QuestionInputHandler.handle - no pending question");return}G.debug("QuestionInputHandler.handle - processing input",{input:e.substring(0,50),currentIndex:o.currentQuestionIndex,totalQuestions:o.questions.length,requestId:o.id});let l=o.currentQuestionIndex,c=o.questions[l];if(!c){G.error("Current question does not exist",{currentIndex:l,totalQuestions:o.questions.length}),n.pendingQuestion=null;return}let u=this.parseAnswer(e,c);if(!u){G.debug("QuestionInputHandler.handle - invalid input",{input:e}),i$1.addSystem(i("tui.question.invalid_input"));return}if(G.debug("QuestionInputHandler.handle - answer parsed",{answer:u,answerLength:u.length}),o.collectedAnswers.push(u),o.currentQuestionIndex++,o.currentQuestionIndex<o.questions.length){G.debug("QuestionInputHandler.handle - showing next question",{nextIndex:o.currentQuestionIndex,totalQuestions:o.questions.length});let d=o.questions[o.currentQuestionIndex];d&&this.displayQuestion(d,o.currentQuestionIndex,o.questions.length,i$1);}else {G.debug("QuestionInputHandler.handle - all questions answered, calling API",{requestId:o.id,answerCount:o.collectedAnswers.length,answers:o.collectedAnswers});try{await sa(n,{requestId:o.id,answers:o.collectedAnswers}),n.pendingQuestion=null,i$1.addSystem(i("tui.question.completed",{vars:{count:o.collectedAnswers.length}})),G.debug("Question request completed",{requestId:o.id});}catch(d){G.error("Failed to reply question request",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,requestId:o.id,answers:o.collectedAnswers,errorType:d instanceof Error?d.constructor.name:typeof d});let p=d instanceof Error?d.message:String(d);i$1.addSystem(`${i("tui.question.error")}: ${p}`),n.pendingQuestion=null;}}}parseAnswer(e,t){let n=e.trim();if(!t.options||t.options.length===0)return [n];let i=n.match(/^(\d+(?:,\s*\d+)*)$/);if(i?.[1]){let o=i[1].split(",").map(l=>Number.parseInt(l.trim(),10)).filter(l=>l>0&&l<=t.options.length);if(o.length===0)return null;if(!t.multiple&&o.length>1){let l=o[0];if(l!==void 0){let c=t.options[l-1];if(c)return [c.label]}return null}return o.map(l=>{let c=t.options[l-1];return c?c.label:""}).filter(l=>l!=="")}return t.custom===false?null:[n]}displayQuestion(e,t,n,i$1){let a=`
|
|
36
|
+
`);s.chatLog.addSystem(u,o?.info?.id,{agent:o?.info?.agent});}}return s.setActivityStatus(i("tui.status.ready")),i$1}catch(n){return J.error("Failed to load history",{sessionId:e,error:n}),s.chatLog.addSystem(i("tui.session.history_failed",{vars:{error:String(n)}})),s.setActivityStatus(i("tui.status.error")),[]}}async function Qt(s,e,t){J.debug("Switching session",{sessionId:e});try{t.currentSessionId=e,t.currentSessionKey=e,t.historyLoaded=!1;let n=await at(s,e);n&&(t.currentSessionKey=n.title||e,t.sessionInfo.model=n.model,t.sessionInfo.modelProvider=n.modelProvider);let{loadTuiState:i$1,saveTuiStateToStorage:a}=await import('./preferences-KZ7TL4Q3.mjs'),o=await i$1(e);t.toolsExpanded=o.toolsExpanded,t.showThinking=o.showThinking,t.thinkingLevel=o.thinkingLevel,t.verboseLevel=o.verboseLevel,t.messageLimit=o.messageLimit,t.localShellPermission=o.localShellPermission,o.model&&(t.sessionInfo.model=o.model),o.agent&&(t.agent=o.agent),J.debug("Session preferences loaded",{sessionId:e,model:t.sessionInfo.model,agent:t.agent,thinkingLevel:t.thinkingLevel}),await a(t),await qe(s,e,t.messageLimit),t.historyLoaded=!0,s.chatLog.addSystem(i("tui.session.switched",{vars:{sessionId:e}}));}catch(n){J.error("Failed to switch session",{sessionId:e,error:n}),s.chatLog.addSystem(i("tui.session.switch_failed",{vars:{error:String(n)}})),s.setActivityStatus(i("tui.status.error"));}}async function jt(s,e){J.debug("Aborting current run",{sessionId:e});try{s.setActivityStatus(i("tui.session.aborting"));let t=s.sdk.session.abort({sessionId:e}),n=new Promise((i$1,a)=>{setTimeout(()=>a(new Error(i("tui.abort.timeout"))),5e3);});await Promise.race([t,n]),s.chatLog.addSystem(i("tui.session.aborted")),s.setActivityStatus(i("tui.status.ready"));}catch(t){J.error("Failed to abort",{sessionId:e,error:t}),s.chatLog.addSystem(i("tui.session.abort_failed",{vars:{error:String(t)}})),s.setActivityStatus(i("tui.status.error"));}}function Kt(s,e){return {openOverlay:i=>{s.showOverlay(i);},closeOverlay:()=>{s.hasOverlay()&&s.hideOverlay(),s.setFocus(e);}}}var Oe=a.create({service:"tui-autocomplete"});function Vt(s){return new lt(s)}var lt=class{constructor(e){b(this,"basePath");b(this,"commands");b(this,"getAgents");this.basePath=e.basePath,this.commands=e.slashCommands,this.getAgents=e.getAgents;}updateCommands(e){this.commands=e;}setGetAgents(e){this.getAgents=e;}async getSuggestions(e,t,n,i){let o=(e[t]||"").slice(0,n),l=this.extractHashPrefix(o);if(l)return this.getFileSuggestions(l);let c=this.extractAtPrefix(o);return c?await this.getAgentSuggestions(c):o.startsWith("/")?this.getCommandSuggestions(o):null}applyCompletion(e,t,n,i,a){let o=e[t]||"",l=o.slice(0,n-a.length),c=o.slice(n);if(a.startsWith("#")){let u=i.label.endsWith("/"),d=u?i.value.replace(/\/$/,""):i.value,g=u?"":" ";return {lines:[...e.slice(0,t),l+d+g+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+d.length+g.length}}if(a.startsWith("@"))return {lines:[...e.slice(0,t),l+i.value+" "+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+i.value.length+1};if(a.startsWith("/")){let u="/"+i.value+" ";return {lines:[...e.slice(0,t),l+u+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+u.length}}return {lines:[...e.slice(0,t),l+i.value+" "+c,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+i.value.length+1}}async getCommandSuggestions(e){let t=e.indexOf(" ");if(t===-1){let c=e.slice(1),u=this.commands.filter(d=>d.name.toLowerCase().includes(c.toLowerCase())).map(d=>({value:d.name,label:d.name,description:d.description}));return u.length===0?null:{items:u.slice(0,50),prefix:e}}let n=e.slice(1,t),i=e.slice(t+1),a=this.commands.find(c=>c.name===n);if(!a?.getArgumentCompletions)return null;let o=a.getArgumentCompletions(i),l=o instanceof Promise?await o:o;return !l||l.length===0?null:{items:l.slice(0,50),prefix:i}}getFileSuggestions(e){let t=e.startsWith('#"')?e.slice(2):e.slice(1),n=e.startsWith('#"'),i=t.replace(/\\/g,"/");if(this.isDrivePath(i))return Oe.debug("Drive path, skip autocomplete",{normalizedPath:i}),null;let{targetPath:a,searchQuery:o}=this.parsePath(i),l=this.resolveBaseDir(a);try{let c;try{c=readdirSync(l,{withFileTypes:!0});}catch{return Oe.debug("Directory not found",{baseDir:l}),null}let u=[];for(let d of c){if(o&&!d.name.toLowerCase().includes(o.toLowerCase()))continue;let g=d.isDirectory(),P=a?`${a}${d.name}`:d.name;if(u.push({value:n?`#"${P}${g?"/":""}"`:`#${P}${g?"/":""}`,label:g?`${d.name}/`:d.name,description:P}),u.length>=50)break}return u.sort((d,g)=>{let P=d.label.endsWith("/"),B=g.label.endsWith("/");return P&&!B?-1:!P&&B?1:d.label.localeCompare(g.label)}),u.length===0?null:{items:u,prefix:e}}catch(c){return Oe.debug("File search failed",{error:c,targetPath:a}),null}}async getAgentSuggestions(e){if(!this.getAgents)return null;let t=e.slice(1);try{let i=(await this.getAgents()).filter(a=>a.hidden!==!0).filter(a=>a.name.toLowerCase().includes(t.toLowerCase())).map(a=>({value:`@${a.name}`,label:a.name,description:a.description}));return i.length===0?null:{items:i.slice(0,50),prefix:e}}catch(n){return Oe.debug("Agent search failed",{error:n,prefix:e}),null}}extractAtPrefix(e){let t=new Set([" "," ",'"',"'","="]);for(let n=e.length-1;n>=0;n--)if(t.has(e[n]??"")){let i=n+1;return e[i]==="@"?e.slice(i):null}return e.startsWith("@")?e:null}extractHashPrefix(e){let t=new Set([" "," ",'"',"'","="]);for(let n=e.length-1;n>=0;n--)if(t.has(e[n]??"")){let i=n+1;return e[i]==="#"?e.slice(i):null}return e.startsWith("#")?e:null}isDrivePath(e){return /^[A-Za-z]:[/\\]?$/.test(e)}parsePath(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?{targetPath:"",searchQuery:e}:{targetPath:e.slice(0,t+1),searchQuery:e.slice(t+1)}}resolveBaseDir(e){return e?zt.join(this.basePath,e):this.basePath}};function dt(s,e){let t=[],n=/(?<![\w`])#(\S+)/g,i;for(;(i=n.exec(s))!==null;){let a=i[1];if(!a)continue;let o=a.replace(/\\/g,"/"),l=Vs(o,e);existsSync(l)&&t.push({path:a,url:pathToFileURL(l).href,exists:true});}return {attachments:t,invalidPaths:[]}}function Vs(s,e){if(/^[A-Za-z]:[/\\]/.test(s))return s;let t=s.replace(/^[/\\]+/,"");return zt.join(e,t)}var G=a.create({service:"cli-tui-input-handlers"}),We=class{constructor(){b(this,"handlers",[]);b(this,"isBrowsingHistory",false);}register(e){this.handlers.push(e),G.debug("Register input handler",{name:e.name,total:this.handlers.length});}setHistoryBrowsing(e){this.isBrowsingHistory=e;}isHistoryBrowsing(){return this.isBrowsingHistory}async handle(e,t){let n=e.trim();if(n){this.isBrowsingHistory;for(let i of this.handlers)if(i.canHandle(n,t.state)){G.debug("Handle input with handler",{handler:i.name,input:n.substring(0,50)}),await i.handle(n,t);return}G.warn("No handler can process input",{input:n.substring(0,50)});}}getPrompt(e){for(let t of this.handlers)if(t.getPrompt&&t.canHandle("",e)){let n=t.getPrompt(e);if(n)return n}return "> "}},Ne=class{constructor(){b(this,"name","permission");}canHandle(e,t){return t.pendingPermission!==null}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=n.pendingPermission;if(!o)return;let l=e.toLowerCase().trim(),c;if(l==="y"||l==="yes")c="once";else if(l==="a"||l==="always")c="always";else if(l==="n"||l==="no"||l==="reject")c="reject";else {i$1.addSystem(i("tui.permission.invalid_input"));return}try{await ra(n,{requestId:o.id,reply:c}),n.pendingPermission=null;let u=c==="once"?i("tui.permission.once"):c==="always"?i("tui.permission.always"):i("tui.permission.reject");i$1.addSystem(i("tui.permission.replied",{vars:{reply:u}})),G.debug("Permission request replied",{requestId:o.id,reply:c});}catch(u){G.error("Failed to reply permission request",{error:u}),i$1.addSystem(i("tui.permission.error")),n.pendingPermission=null;}}getPrompt(e){return e.pendingPermission?i("tui.permission.prompt"):"> "}},Ge=class{constructor(){b(this,"name","question");}canHandle(e,t){return !(t.pendingQuestion===null||e.startsWith("/"))}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=n.pendingQuestion;if(!o){G.warn("QuestionInputHandler.handle - no pending question");return}G.debug("QuestionInputHandler.handle - processing input",{input:e.substring(0,50),currentIndex:o.currentQuestionIndex,totalQuestions:o.questions.length,requestId:o.id});let l=o.currentQuestionIndex,c=o.questions[l];if(!c){G.error("Current question does not exist",{currentIndex:l,totalQuestions:o.questions.length}),n.pendingQuestion=null;return}let u=this.parseAnswer(e,c);if(!u){G.debug("QuestionInputHandler.handle - invalid input",{input:e}),i$1.addSystem(i("tui.question.invalid_input"));return}if(G.debug("QuestionInputHandler.handle - answer parsed",{answer:u,answerLength:u.length}),o.collectedAnswers.push(u),o.currentQuestionIndex++,o.currentQuestionIndex<o.questions.length){G.debug("QuestionInputHandler.handle - showing next question",{nextIndex:o.currentQuestionIndex,totalQuestions:o.questions.length});let d=o.questions[o.currentQuestionIndex];d&&this.displayQuestion(d,o.currentQuestionIndex,o.questions.length,i$1);}else {G.debug("QuestionInputHandler.handle - all questions answered, calling API",{requestId:o.id,answerCount:o.collectedAnswers.length,answers:o.collectedAnswers});try{await sa(n,{requestId:o.id,answers:o.collectedAnswers}),n.pendingQuestion=null,i$1.addSystem(i("tui.question.completed",{vars:{count:o.collectedAnswers.length}})),G.debug("Question request completed",{requestId:o.id});}catch(d){G.error("Failed to reply question request",{error:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,requestId:o.id,answers:o.collectedAnswers,errorType:d instanceof Error?d.constructor.name:typeof d});let g=d instanceof Error?d.message:String(d);i$1.addSystem(`${i("tui.question.error")}: ${g}`),n.pendingQuestion=null;}}}parseAnswer(e,t){let n=e.trim();if(!t.options||t.options.length===0)return [n];let i=n.match(/^(\d+(?:,\s*\d+)*)$/);if(i?.[1]){let o=i[1].split(",").map(l=>Number.parseInt(l.trim(),10)).filter(l=>l>0&&l<=t.options.length);if(o.length===0)return null;if(!t.multiple&&o.length>1){let l=o[0];if(l!==void 0){let c=t.options[l-1];if(c)return [c.label]}return null}return o.map(l=>{let c=t.options[l-1];return c?c.label:""}).filter(l=>l!=="")}return t.custom===false?null:[n]}displayQuestion(e,t,n,i$1){let a=`
|
|
37
37
|
${i("tui.question.header",{vars:{current:t+1,total:n}})}
|
|
38
38
|
`;if(a+=`${e.header}
|
|
39
39
|
`,a+=`${e.question}
|
|
@@ -50,9 +50,9 @@ ${i("tui.question.header",{vars:{current:t+1,total:n}})}
|
|
|
50
50
|
`+i("tui.question.hint.custom_disabled")+`
|
|
51
51
|
`;}i$1.addSystem(a);}getPrompt(e){let t=e.pendingQuestion;if(!t)return "> ";let n=t.currentQuestionIndex+1,i$1=t.questions.length;return i("tui.question.prompt",{vars:{current:n,total:i$1}})}},Qe=class{constructor(){b(this,"name","shell-permission");}canHandle(e,t){return t.pendingShellCommand!==null}async handle(e,t){let{state:n,chatLog:i$1,tui:a}=t,o=e.toLowerCase().trim();if(o==="y"||o==="yes"){n.localShellPermission="on",await b$2(n),i$1.addSystem(i("tui.shell.permission.updated",{vars:{permission:"on"}}));let l=n.pendingShellCommand;n.pendingShellCommand=null,await new xe().executeCommand(l,t);}else o==="n"||o==="no"?(n.localShellPermission="off",await b$2(n),i$1.addSystem(i("tui.shell.permission.updated",{vars:{permission:"off"}})),n.pendingShellCommand=null):i$1.addSystem(i("tui.shell.permission.invalid"));}getPrompt(e){return i("tui.shell.permission.prompt")}},xe=class{constructor(){b(this,"name","shell");}canHandle(e,t){return e.startsWith("!")}async handle(e,t){let{chatLog:n,tui:i$1,setActivityStatus:a,state:o}=t,l=e.slice(1).trim();if(!l){n.addSystem(i("tui.shell.empty"));return}switch(o.localShellPermission){case "on":await this.executeCommand(l,t);break;case "off":n.addSystem(i("tui.shell.permission.off"));break;case "ask":o.pendingShellCommand=l,n.addSystem(i("tui.shell.permission.ask"));break}}async executeCommand(e,t){let{chatLog:n,tui:i$1,setActivityStatus:a}=t;try{n.addSystem(`\u6B63\u5728\u6267\u884C Shell \u547D\u4EE4: ${e}`),a(i("tui.shell.executing",{vars:{command:e}})),G.debug("Executing shell command",{command:e});let o=await Shell.run(void 0,e,{cwd:process.cwd()}),l="";o.stdout?.trim()&&(l+=`
|
|
52
52
|
${o.stdout}`),o.stderr?.trim()&&(l+=`
|
|
53
|
-
${o.stderr}`),l&&n.addSystem(l),n.addSystem(i("tui.shell.success",{vars:{code:o.code}})),a(""),G.debug("Shell command executed successfully",{command:e,exitCode:o.code,stdoutLength:o.stdout?.length||0,stderrLength:o.stderr?.length||0});}catch(o){G.error("Failed to execute shell command",{command:e,error:o instanceof Error?o.message:String(o)});let l=o instanceof Error?o.message:String(o);n.addSystem(i("tui.shell.error",{vars:{error:l}})),a("");}}getPrompt(e){return "$ "}},je=class{constructor(){b(this,"name","command");}canHandle(e,t){return e.startsWith("/")}async handle(e,t){t.handleCommand?await t.handleCommand(e,t):G.warn("handleCommand is not defined");}getPrompt(e){return "> "}},Ke=class{constructor(){b(this,"name","normal");}canHandle(e,t){return true}async handle(e,t){t.sendMessage?await t.sendMessage(e):G.warn("sendMessage is not defined");}getPrompt(e){return "> "}},ze=class{constructor(){b(this,"name","at-mention");}canHandle(e,t){if(e.startsWith("/")||e.startsWith("!"))return false;let n=e.trimStart();return n.startsWith("@")||n.startsWith("#")}async handle(e,t){let{chatLog:n,sendMessage:i,state:a}=t,o=e.trimStart();if(o.startsWith("@")){let l=o.slice(1).split(/\s+/)[0];if(!l)return;let c=e.replace(/@\S+/g,"").trim(),d=dt(e,a.instanceContext.directory).attachments.map(
|
|
53
|
+
${o.stderr}`),l&&n.addSystem(l),n.addSystem(i("tui.shell.success",{vars:{code:o.code}})),a(""),G.debug("Shell command executed successfully",{command:e,exitCode:o.code,stdoutLength:o.stdout?.length||0,stderrLength:o.stderr?.length||0});}catch(o){G.error("Failed to execute shell command",{command:e,error:o instanceof Error?o.message:String(o)});let l=o instanceof Error?o.message:String(o);n.addSystem(i("tui.shell.error",{vars:{error:l}})),a("");}}getPrompt(e){return "$ "}},je=class{constructor(){b(this,"name","command");}canHandle(e,t){return e.startsWith("/")}async handle(e,t){t.handleCommand?await t.handleCommand(e,t):G.warn("handleCommand is not defined");}getPrompt(e){return "> "}},Ke=class{constructor(){b(this,"name","normal");}canHandle(e,t){return true}async handle(e,t){t.sendMessage?await t.sendMessage(e):G.warn("sendMessage is not defined");}getPrompt(e){return "> "}},ze=class{constructor(){b(this,"name","at-mention");}canHandle(e,t){if(e.startsWith("/")||e.startsWith("!"))return false;let n=e.trimStart();return n.startsWith("@")||n.startsWith("#")}async handle(e,t){let{chatLog:n,sendMessage:i,state:a}=t,o=e.trimStart();if(o.startsWith("@")){let l=o.slice(1).split(/\s+/)[0];if(!l)return;let c=e.replace(/@\S+/g,"").trim(),d=dt(e,a.instanceContext.directory).attachments.map(g=>({url:g.url,filename:g.path.split("/").pop()||g.path.split("\\").pop()||g.path,mime:"text/plain"}));i&&await i(c,d.length>0?d:void 0,l);return}if(o.startsWith("#")){let l=dt(e,a.instanceContext.directory);if(l.attachments.length===0)return;let c=e.replace(/#\S+/g,"").trim(),u=l.attachments.map(d=>({url:d.url,filename:d.path.split("/").pop()||d.path.split("\\").pop()||d.path,mime:"text/plain"}));i&&await i(c,u);return}}getPrompt(e){return "> "}};var Zs=loadTextFile("./banner.txt",import.meta.url),Xs=Zs();function Yt(){try{let s=Xs.replace("${Global.getVersion()}",a$2.getVersion());return s=s.replace("${t('tui.header.title')}",i("tui.header.title")),s}catch{return `EasBot v${a$2.getVersion()}
|
|
54
54
|
${i("tui.header.title")}
|
|
55
55
|
`}}var Ve=class{constructor(e){b(this,"log",a.create({service:"tui-gateway-message-handler"}));b(this,"config");b(this,"bridge");b(this,"eventBus");b(this,"bridgeStarted",false);this.config=e,this.eventBus=new SdkEventBus,this.bridge=new SdkEventBridge(e.state.sdk,this.eventBus);}async start(){if(!this.bridgeStarted){this.log.debug("Starting SdkEventBridge");try{await this.bridge.start(),this.bridgeStarted=!0,this.log.debug("SdkEventBridge started successfully");}catch(e){throw this.log.error("Failed to start SdkEventBridge",{error:String(e)}),e}}}async stop(){this.bridgeStarted&&(await this.bridge.stop(),this.bridgeStarted=false);}async sendMessage(e,t,n="output",i,a,o){let l=this.config.getGatewayClient();if(!l){this.log.warn("gatewayClient not available, skipping message send");return}await l.sendMessage(e,t,n,i,a,o??this.config.state.agent);}async handleMessage(e){if(!e?.id){this.log.warn("received incomplete message",{message:e});return}let t=e.metadata?.channel;if(!t?.chatId){this.log.warn("channelInfo missing chatId, cannot reply",{channelInfo:t});return}if(this.log.debug("Handling gateway message",{id:e.id,type:e.type,sessionId:e.sessionId,contentTypes:e.content.map(i=>i.type)}),e.type!=="input")return;let n=e.content.find(i=>i.type==="command");if(n){this.handleCommand(n,t,e.id,e.sessionId);return}this.handleTextMessage(e,t,e.id,e.sessionId);}async handleCommand(e,t,n,i$1){this.config.setActivityStatus?.(i("tui.handler.executing",{vars:{command:e.command}}));let a="prompt";try{a=((await this.config.state.sdk.command.list({})).data??[]).find(u=>u.name===e.command)?.commandType==="local"?"local":"prompt",this.log.debug("Command type determined",{command:e.command,commandType:a});}catch(o){this.log.warn("Failed to get command list, assuming prompt type",{error:String(o)});}try{if(a==="local"){await this.handleLocalCommand(e,t,n,i$1);return}await this.handlePromptCommand(e,t,n,i$1);}finally{this.config.setActivityStatus?.("");}}async handleLocalCommand(e,t,n,i){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for command"),await this.sendMessage(i,"Error: No active session","output",n,t);return}this.log.debug("Calling SDK command (local)",{command:e.command,arguments:e.arguments,sessionId:a});try{let o=await this.config.state.sdk.session.command({sessionId:a,command:e.command,arguments:e.arguments??"",agent:this.config.state.agent});if(o?.data?.success===!1){let c=o.data.error??"Command failed";this.log.debug("Command failed",{error:c}),await this.sendMessage(i,c,"output",n,t);return}let l=o?.data?.output??"";l&&(this.log.debug("Sending command result",{textLength:l.length}),await this.sendMessage(i,l,"output",n,t));}catch(o){this.log.error("SDK command error",{error:String(o)}),await this.sendMessage(i,`Command failed: ${String(o)}`,"output",n,t);}}async handlePromptCommand(e,t,n,i){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for prompt command"),await this.sendMessage(i,"Error: No active session","output",n,t);return}this.log.debug("Calling SDK command (prompt via events)",{command:e.command,arguments:e.arguments,sessionId:a});let o=this.eventBus.subscribeAll(l=>{if(l.type===SdkEventType.SDK_SESSION_UPDATE){let c=l.properties;if(c.sessionId!==a)return;this.log.debug("SDK_SESSION_UPDATE event received",{sessionId:c.sessionId,updateKeys:Object.keys(c.update),sessionUpdate:c.update.sessionUpdate});let u=this.assembleTextFromUpdate(c.update);u&&(this.log.debug("Sending prompt command result via event",{textLength:u.length}),this.sendMessage(i,u,"output",n,t));}});try{await this.config.state.sdk.session.command({sessionId:a,command:e.command,arguments:e.arguments??"",agent:this.config.state.agent});}catch(l){this.log.error("SDK command error",{error:String(l)}),await this.sendMessage(i,`Command failed: ${String(l)}`,"output",n,t);}finally{o();}}assembleTextFromUpdate(e){if(e.sessionUpdate==="agent_message_chunk"){let a=e.content;return a?.type==="text"&&a.text?a.text:""}let n=e.parts;return n?n.filter(a=>a.type==="text"&&a.time?.end).map(a=>a.text||"").join(`
|
|
56
|
-
`):""}async handleTextMessage(e,t,n,i$1){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for text message"),await this.sendMessage(i$1,"Error: No active session","output",n,t);return}let o=[];for(let T of e.content)if(T.type==="text"&&T.text)o.push({type:"text",text:T.text});else if(T.type==="image"){let y="";typeof T.image=="string"?y=T.image:T.image instanceof URL?y=T.image.toString():T.image instanceof Uint8Array&&(y=`data:${T.mime??"image/png"};base64,${Buffer.from(T.image).toString("base64")}`),y&&o.push({type:"file",url:y,mime:T.mime??"image/png"});}else if(T.type==="file"){let y="";typeof T.data=="string"?y=T.data:T.data instanceof URL?y=T.data.toString():T.data instanceof Uint8Array&&(y=`data:${T.mime??"application/octet-stream"};base64,${Buffer.from(T.data).toString("base64")}`),y&&o.push({type:"file",url:y,mime:T.mime??"application/octet-stream"});}if(o.length===0){this.log.debug("empty message (no text/file/image), skip");return}this.config.setActivityStatus?.(i("tui.status.sending"));let l=e.metadata?.system,{thinkingLevel:c,contextMode:u,sessionInfo:d}=this.config.state,
|
|
56
|
+
`):""}async handleTextMessage(e,t,n,i$1){let a=this.config.state.currentSessionId;if(!a){this.log.error("No current sessionId for text message"),await this.sendMessage(i$1,"Error: No active session","output",n,t);return}let o=[];for(let T of e.content)if(T.type==="text"&&T.text)o.push({type:"text",text:T.text});else if(T.type==="image"){let y="";typeof T.image=="string"?y=T.image:T.image instanceof URL?y=T.image.toString():T.image instanceof Uint8Array&&(y=`data:${T.mime??"image/png"};base64,${Buffer.from(T.image).toString("base64")}`),y&&o.push({type:"file",url:y,mime:T.mime??"image/png"});}else if(T.type==="file"){let y="";typeof T.data=="string"?y=T.data:T.data instanceof URL?y=T.data.toString():T.data instanceof Uint8Array&&(y=`data:${T.mime??"application/octet-stream"};base64,${Buffer.from(T.data).toString("base64")}`),y&&o.push({type:"file",url:y,mime:T.mime??"application/octet-stream"});}if(o.length===0){this.log.debug("empty message (no text/file/image), skip");return}this.config.setActivityStatus?.(i("tui.status.sending"));let l=e.metadata?.system,{thinkingLevel:c,contextMode:u,sessionInfo:d}=this.config.state,g=d.model?parseModelId(d.model):{provider:"",model:""},P=g.provider&&g.model?{providerId:g.provider,modelId:g.model}:void 0;this.log.debug("Calling SDK prompt via events",{partsCount:o.length,sessionId:a,model:P});let B=this.eventBus.subscribeAll(T=>{if(T.type===SdkEventType.SDK_SESSION_UPDATE){let y=T.properties;if(y.sessionId!==a)return;this.log.debug("SDK_SESSION_UPDATE event received",{sessionId:y.sessionId,updateKeys:Object.keys(y.update),sessionUpdate:y.update.sessionUpdate});let A=this.assembleTextFromUpdate(y.update);A&&(this.log.debug("Sending prompt result via event",{textLength:A.length}),this.sendMessage(i$1,A,"output",n,t));}});try{await this.config.state.sdk.session.prompt({sessionId:a,parts:o,agent:this.config.state.agent,...P?{model:P}:{},...c?{variant:c}:{},...u?{contextMode:u}:{},...l?{system:l}:{}});}catch(T){this.log.error("SDK prompt error",{error:String(T)}),this.sendMessage(i$1,`Error: ${String(T)}`,"output",n,t);}finally{B(),this.config.setActivityStatus?.("");}}},ct=class{constructor(e){b(this,"log");b(this,"client");b(this,"config");b(this,"connected",false);this.config=e,this.log=a.create({service:"tui-gateway-client"});let t=e.sessionId?`tui_${e.sessionId}`:"tui_default";this.client=new Q({url:e.gatewayUrl,type:"tui",id:t,heartbeat:{enabled:true,interval:6e4}}),this.client.onMessage(async n=>{if(!n){this.log.warn("received undefined message from gateway");return}this.log.debug("received message from gateway",{messageId:n.id,sessionId:n.sessionId,type:n.type}),e.onMessage&&await e.onMessage(n);}),this.client.onStateChange(async n=>{if(this.connected=n==="connected",e.onStateChange?.(n),n==="connected")try{let i=this.config.sessionId;i&&await this.client.subscribe(i);}catch(i){this.log.error("failed to subscribe",{error:String(i)});}});}async connect(){if(this.connected){this.log.warn("already connected");return}this.log.info("gateway client initialized, heartbeat will handle auto-reconnect",{url:this.config.gatewayUrl});}async disconnect(){this.connected&&(this.log.info("disconnecting from gateway"),this.config.sessionId&&await this.client.unsubscribe(this.config.sessionId),await this.client.disconnect(),this.connected=false,this.config.onStateChange?.("disconnected"),this.log.info("disconnected from gateway"));}async sendMessage(e,t,n="output",i,a,o){if(!this.connected)throw new Error("Not connected to gateway");if(!e)throw new Error("No gateway session ID available");await this.client.sendMessage(e,{content:[{type:"text",text:t}],channel:a?.platform,chatId:a?.chatId,userId:a?.userId,replyToMessageId:i,processorId:"tui",agent:o??"tui"}),this.log.debug("message sent via HTTP",{gatewaySessionId:e,type:n,replyToMessageId:i,hasChannelInfo:!!a,agent:o});}async subscribeMessage(e){if(!this.connected)throw new Error("Not connected to gateway");await this.client.subscribe(e),this.log.debug("subscribed to session",{sessionId:e});}async unsubscribeMessage(e){if(!this.connected)throw new Error("Not connected to gateway");await this.client.unsubscribe(e),this.log.debug("unsubscribed from session",{sessionId:e});}isConnected(){return this.connected}getClientId(){return this.client.getId()}getSubscribedSessions(){return this.client.getSubscriptions()}getState(){return this.client.getState()}async getStatus(){return this.client.getStatus()}generateId(){return `tui_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};function Zt(s){return new ct(s)}var me=a.create({service:"gateway-manager"}),ut=class{constructor(e){b(this,"config");b(this,"_client",null);b(this,"messageHandler",null);b(this,"connected",false);this.config=e;}get client(){return this._client}isConnected(){return this.connected}async connect(e){if(await this.disconnect(),!e){me.debug("No session ID, skipping gateway connection");return}me.debug("Connecting to gateway",{sessionId:e});try{this.messageHandler=new Ve({state:this.config.state,getGatewayClient:()=>this._client,setActivityStatus:this.config.setActivityStatus}),await this.messageHandler.start(),this._client=Zt({gatewayUrl:this.config.gatewayUrl,sessionId:e,onMessage:async t=>{this.messageHandler&&this.messageHandler.handleMessage(t);},onStateChange:t=>{me.debug("Gateway connection state changed",{state:t}),this.config.onConnectionChange?.(t==="connected");}}),await this._client.connect(),this.connected=!0,me.debug("Gateway connected successfully",{sessionId:e});}catch(t){throw me.error("Failed to connect to gateway",{sessionId:e,error:String(t)}),await this.disconnect(),t}}async disconnect(){if(!(!this.connected&&!this._client&&!this.messageHandler)){me.debug("Disconnecting from gateway");try{this._client&&await this._client.disconnect();}finally{this.messageHandler&&(await this.messageHandler.stop(),this.messageHandler=null),this._client=null,this.connected=false,this.config.onConnectionChange?.(false),me.debug("Gateway disconnected");}}}};function Xt(s){return new ut(s)}var D=a.create({service:"cli-tui-app"}),mt=null;function nn(s){mt=s;}function rn(){mt=null;}function pr(){return mt}async function hr(s,e){process.env.EASBOT_TUI_MODE="1";let t=new Container,n=new Container,i$1=Yt(),a=new Text(Z.header(i$1),1,0);n.addChild(a),t.addChild(n);let o=new He;t.addChild(o),o.setWidth(s.terminal.columns);let l=s.requestRender.bind(s);s.requestRender=(m=false)=>{o.setWidth(s.terminal.columns),l(m);};let c=new Container;t.addChild(c);let u=null,d=null,g=()=>{u&&d||(c.clear(),u=new Text("",1,0),d=new Text("",1,0),c.addChild(u),c.addChild(d));},P=new Container,B=new Text("",1,0);P.addChild(B),t.addChild(P);let T=new Container,y=new $e(s,_t);T.addChild(y),t.addChild(T);let A=Ht(),ge=Vt({basePath:e.directory||process.cwd(),slashCommands:A});y.setAutocompleteProvider(ge);let{state:h,unsubscribe:se}=await na({options:e,agent:e.agent,model:e.model,sessionId:e.sessionId},s,o,()=>{q();});D.debug("TUI state initialized",{agent:h.agent,model:h.sessionInfo.model,sessionId:h.currentSessionId}),o.init(),ge.setGetAgents(async()=>ta(h));try{A=await Rt(h.sdk,h.contextMode),ge.updateCommands?.(A),D.debug("Dynamic commands loaded with contextMode",{contextMode:h.contextMode,count:A.length});}catch(m){D.warn("Failed to load dynamic commands, using static commands only",{error:m});}o.setStateGetter(()=>h);let H=i("tui.status.idle"),F=i("tui.status.connection.local"),x="",p=null,f=H,L=new Set([i("tui.handler.send.sending"),i("tui.status.thinking"),i("tui.status.receiving"),i("tui.status.running"),i("tui.status.waiting"),i("tui.status.executing_step"),i("tui.status.sending"),i("tui.status.waiting_permission"),i("tui.status.waiting_answer"),i("tui.status.step_completed"),i("tui.status.tool_completed")]),b=m=>{if(L.has(m))return true;let M=i("tui.status.executing_tool",{vars:{tool:""}}).split(":")[0];if(m.startsWith(M))return true;let _=i("tui.handler.executing",{vars:{command:""}}).split(":")[0];return !!m.startsWith(_)},w=m=>{let M=Math.max(0,Math.floor((Date.now()-m)/1e3));if(M<60)return `${M}s`;let _=Math.floor(M/60),U=M%60;return `${_}m ${U}s`},v=()=>{if(g(),!u||!d)return;let m=b(H);f!==H&&(m?p=Date.now():p=null,f=H);let M=i("tui.status.label"),_=H;if(m&&p){let ns=w(p);_=`${_} \u2022 ${ns}`;}let U=`${M} ${_} | ${F}`;u.setText(Z.header(U));let le=h.showThinking?i("tui.system.on"):i("tui.system.off"),fe=h.toolsExpanded?i("tui.system.on"):i("tui.system.off"),be=[`ctrl+l: ${i("tui.keyhints.model")} | ctrl+g: ${i("tui.keyhints.agent")} | ctrl+p: ${i("tui.keyhints.session")} | ctrl+t: ${i("tui.keyhints.thinking")}(${le}) | ctrl+o: ${i("tui.keyhints.tools")}(${fe})`];x&&be.push(x);let et=be.join(" | ");d.setText(Z.header(et)),u.invalidate(),d.invalidate();},W=()=>{},Y=()=>{let m=h.agent||"unknown",M=h.sessionInfo.model||"unknown",_=h.currentSessionKey||"new",le=((fe,Pe)=>{if(!fe||fe===0)return "";let be=fe.toLocaleString();if(Pe&&Pe>0){let et=Math.round(fe/Pe*100);return ` | Tokens: ${be} (${et}%)`}return ` | Tokens: ${be}`})(h.sessionInfo.totalTokens,h.sessionInfo.contextTokens);B.setText(Z.dim(i("tui.footer.info",{vars:{agent:m,model:M,session:_,tokens:le}}))),B.invalidate();};v(),Y();let ee=false,q=()=>{ee||(ee=true,queueMicrotask(()=>{ee=false,s.requestRender();}));},gt=setInterval(()=>{p&&b(H)&&v(),Y(),q();},1e3),es=()=>{gt&&clearInterval(gt);},{openOverlay:Te,closeOverlay:re}=Kt(s,y),Je=()=>{h.currentSessionId&&(console.log(`
|
|
57
57
|
|
|
58
|
-
`),console.log(i("tui.exit.resume_hint",{vars:{sessionId:h.currentSessionId}})),console.log("")),s.stop(),e.onExit&&e.onExit(),process.exit(0);},Se=m=>{H=m||i("tui.status.idle"),v(),q();},Ze=(m,
|
|
58
|
+
`),console.log(i("tui.exit.resume_hint",{vars:{sessionId:h.currentSessionId}})),console.log("")),s.stop(),e.onExit&&e.onExit(),process.exit(0);},Se=m=>{H=m||i("tui.status.idle"),v(),q();},Ze=(m,M)=>{x=m,v(),q(),M&&M>0&&setTimeout(()=>{x="",v(),q();},M);},pe={tui:s,chatLog:o,setActivityStatus:Se,sdk:h.sdk},Ae=Ot({chatLog:o,tui:s,directory:e.directory||process.cwd(),openOverlay:Te,closeOverlay:re,requestExit:Je,setActivityStatus:Se,updateStatusBar:v,updateFooter:Y,refreshSessionInfo:async()=>{h.currentSessionId&&await at(pe,h.currentSessionId);},loadHistory:async()=>{h.currentSessionId&&await qe(pe,h.currentSessionId,h.messageLimit);},setSession:async m=>{o.clear(),await Qt(pe,m,h),v(),Y(),q();},refreshAgents:async()=>{await Gt(pe);},abortActive:async()=>{h.currentSessionId&&await jt(pe,h.currentSessionId);},setInputText:m=>{y.setText(m),q();},reconnectGateway:async m=>{await la(async()=>{ne&&(await ne.connect(m),pt.client=ne.client);},"TUI_RECONNECT_GATEWAY",{directory:e.directory});},gatewayManager:{client:null,isConnected:()=>ne?.isConnected()??false}},h),pt=Ae.gatewayManager,oe=new We;oe.register(new je),oe.register(new Ne),oe.register(new Ge),oe.register(new Qe),oe.register(new xe),oe.register(new ze),oe.register(new Ke),y.onSubmit=async m=>{let _=m.trim();if(y.setText(""),!_)return;y.addToHistory(_);let U={chatLog:o,tui:s,state:h,setActivityStatus:Se,updateStatusBar:v,updateFooter:Y,sendMessage:Ae.sendMessage,handleCommand:Ae.handleCommand};await oe.handle(_,U);};let Xe=0;y.onCtrlC=()=>{let m=y.getText(),M=Date.now();m.trim()?(y.setText(""),Ze(i("tui.hint.input_cleared"),3e3),Xe=M):M-Xe<=1e3?Je():(Ze(i("tui.hint.press_ctrlc_exit"),3e3),Xe=M);},y.onCtrlD=()=>{Je();},y.onEscape=()=>{s.hasOverlay()&&re();},y.onCtrlL=async()=>{try{let m=await va(h),M=De(m,{onSelect:async _=>{h.sessionInfo.model=_.value,o.addSystem(i("tui.handler.model.set",{vars:{model:_.value}})),re(),b$2(h).catch(U=>{D.error("Failed to save TUI state after model change",{error:U});}),Y(),q();},onCancel:()=>{re();}});Te(M);}catch(m){D.error("Failed to open model selector",{error:m}),o.addSystem(i("tui.selector.model.error",{vars:{error:String(m)}})),q();}},y.onCtrlP=async()=>{try{let m=await ua(h),M=Be(m,{onSelect:async _=>{h.currentSessionKey=_.value,o.addSystem(i("tui.handler.session.switched",{vars:{sessionKey:_.value}})),re(),Y(),q();},onCancel:()=>{re();}});Te(M);}catch(m){D.error("Failed to open session selector",{error:m}),o.addSystem(i("tui.selector.session.error",{vars:{error:String(m)}})),q();}},y.onCtrlG=async()=>{try{let M=(await ta(h)).filter(U=>U.mode==="primary"&&U.hidden!==!0),_=Ue(M,{onSelect:async U=>{h.agent=U.value,o.addSystem(i("tui.handler.agent.switched",{vars:{agentId:U.value}})),re(),b$2(h).catch(le=>{D.error("Failed to save TUI state after agent change",{error:le});}),Y(),q();},onCancel:()=>{re();}});Te(_);}catch(m){D.error("Failed to open agent selector",{error:m}),o.addSystem(i("tui.selector.agent.error",{vars:{error:String(m)}})),q();}},y.onCtrlT=()=>{h.showThinking=!h.showThinking,o.addSystem(i("tui.system.thinking_mode",{vars:{mode:h.showThinking?i("tui.system.on"):i("tui.system.off")}})),b$2(h).catch(m=>{D.error("Failed to save TUI state after Ctrl+T",{error:m});}),v(),q();},y.onCtrlO=()=>{h.toolsExpanded=!h.toolsExpanded;let m=i("tui.system.tools_output",{vars:{mode:h.toolsExpanded?i("tui.system.expanded"):i("tui.system.collapsed")}});o.addSystem(m),Ze(h.toolsExpanded?i("tui.hint.tools_expanded"):i("tui.hint.tools_collapsed"),2e3),b$2(h).catch(M=>{D.error("Failed to save TUI state after Ctrl+O",{error:M});}),v(),q();},s.setFocus(y);let ts={tui:s,chatLog:o,sessionId:h.currentSessionId,setActivityStatus:Se,updateStatusBar:v,updateFooter:Y,updateChatLog:W,state:h},ss=Wt(ts),{TuiEvent:he}=await import('./event-2JDHF3UV.mjs'),ht=()=>{},ft=()=>{},yt=()=>{},St=()=>{},bt=()=>{},vt=()=>{};ht=await qa(h,he.StatusBarRefresh,async m=>{D.debug("StatusBarRefresh event received",{reason:m.properties.reason}),v(),q();}),ft=await qa(h,he.FooterBarRefresh,async m=>{D.debug("FooterBarRefresh event received",{reason:m.properties.reason}),Y(),q();}),yt=await qa(h,he.ChatLogRefresh,async m=>{D.debug("ChatLogRefresh event received",{reason:m.properties.reason}),q();}),St=await qa(h,he.CommandExecute,async m=>{D.debug("TUI CommandExecute event received",{command:m.properties.command}),await Ae.handleCommand(m.properties.command,m.properties.inputHandlerContext);}),bt=await qa(h,he.PromptAppend,async m=>{D.debug("TUI PromptAppend event received",{text:m.properties.text});let M=y.getText();y.setText(M+m.properties.text),q();}),vt=await qa(h,he.ToastShow,async m=>{D.debug("TUI ToastShow event received",{message:m.properties.message});let{title:M,message:_,variant:U}=m.properties,le=U==="error"?"\u274C ":U==="warning"?"\u26A0\uFE0F ":U==="success"?"\u2705 ":"\u2139\uFE0F ";o.addSystem(`${le}${M?`[${M}] `:""}${_}`),q();}),nn((m,M)=>{let _=m instanceof Error?m.message:String(m),U=m instanceof Error?m.stack:void 0;D.error(`Global ${M} caught`,{type:M,message:_,stack:U,errorType:m instanceof Error?m.constructor.name:typeof m,fullError:m}),_.includes("No context found for instance")&&D.error("Instance context error detected",{currentSessionId:h.currentSessionId,instanceContext:h.instanceContext,stackTrace:U}),o.addSystem(i(`tui.error.global.${M}`,{vars:{error:_}})),q();});let wt=new AbortController,ne=null;return h.sdk.global.event({signal:wt.signal}).then(async({stream:m})=>{if(D.debug("SDK event subscription successful"),h.currentSessionId){let _=await k$1();_?(ne=Xt({gatewayUrl:_,state:h,setActivityStatus:Se,onConnectionChange:U=>{F=U?i("tui.status.connection.gateway_connected"):i("tui.status.connection.local"),v();}}),ne.connect(h.currentSessionId).then(()=>{pt.client=ne.client;})):D.debug("No gateway URL configured, skipping gateway client");}(async()=>{try{for await(let _ of m){let U=_.payload;ss(U);}}catch(_){D.debug("Event stream ended",{error:_});}})();let M=e.onExit;e.onExit=async()=>{D.debug("Unsubscribe events"),wt.abort(),se(),ht(),ft(),yt(),St(),bt(),vt(),es(),rn(),ne&&(await ne.disconnect(),ne=null,D.debug("Gateway manager disconnected")),delete process.env.EASBOT_TUI_MODE,D.debug("Cleared TUI mode environment variable"),M&&await M();};}).catch(m=>{D.error("SDK event subscription failed",{error:m});}),h.currentSessionId&&!h.historyLoaded&&(async()=>{try{await qe(pe,h.currentSessionId,h.messageLimit),h.historyLoaded=!0;}catch(m){D.error("Failed to auto-load history messages",{error:m});}})(),e.prompt&&setTimeout(()=>{y.setText(e.prompt),y.onSubmit?.(e.prompt);},100),D.debug("TUI app component created"),t}export{hr as createTuiApp,pr as getGlobalErrorHandler,nn as registerGlobalErrorHandler,rn as unregisterGlobalErrorHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-MYI75W3D.mjs';import'./chunk-CQVEAYYW.mjs';import'./chunk-FXOUIXIL.mjs';import {h,g,e,d}from'./chunk-M3K32WJV.mjs';import {i as i$1}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-MYI75W3D.mjs';import'./chunk-CQVEAYYW.mjs';import'./chunk-FXOUIXIL.mjs';import {h,g,e,d}from'./chunk-M3K32WJV.mjs';import {i as i$1}from'./chunk-XQ3LMV3K.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import'./chunk-X6ISXWBN.mjs';var i=a.create({service:"cli-command-auth"});function E(n,o){let e=n.command("auth").description(i$1("auth.command.description"));e.command("list").description(i$1("auth.command.list.description")).aliases(["ls"]).action(async()=>{i.debug("Listing credentials"),await v(o);}),e.command("login [provider]").description(i$1("auth.command.login.description")).option("--key <key>",i$1("auth.option.key")).action(async(t,g)=>{t?(i.debug("Logging in to provider",{provider:t}),await f(o,t,g.key)):(i.debug("Interactive login"),await y(o));}),e.command("logout <provider>").description(i$1("auth.command.logout.description")).action(async t=>{i.debug("Logging out from provider",{provider:t}),await b(o,t);});}async function v(n){try{let{data:o}=await n.sdk.config.providers({}),e=o?.providers||[];if(console.log(h(i$1("auth.list.title"))),console.log(""),e.length===0){console.log(g(i$1("auth.list.empty")));return}console.log(a$1({columns:[{key:"provider",header:i$1("auth.table.header.provider"),minWidth:20},{key:"type",header:i$1("auth.table.header.type"),minWidth:15}],rows:e.map(t=>({provider:t.name||t.id,type:"configured"})),width:process.stdout.columns||80,border:"unicode"})),i.debug("Credentials listed",{count:e.length});}catch(o){i.error("Failed to list credentials",{error:o instanceof Error?o.message:String(o)}),console.error(e(i$1("auth.list.error",{vars:{error:o instanceof Error?o.message:String(o)}}))),process.exit(1);}}async function f(n,o,e$1){try{e$1||(console.error(e(i$1("auth.login.key_required"))),console.log(g(i$1("auth.login.key_hint"))),process.exit(1)),console.log(h(i$1("auth.login.logging_in",{vars:{provider:o}}))),await n.sdk.auth.set({providerId:o,info:{type:"api",key:e$1}}),console.log(d(i$1("auth.login.success",{vars:{provider:o}}))),i.debug("Login successful",{provider:o});}catch(t){i.error("Login failed",{provider:o,error:t instanceof Error?t.message:String(t)}),console.error(e(i$1("auth.login.error",{vars:{error:t instanceof Error?t.message:String(t)}}))),process.exit(1);}}async function y(n){try{console.log(h(i$1("auth.interactive.title")));let{data:o}=await n.sdk.config.providers({}),e$1=o?.providers||[],t={easbot:0,anthropic:1,openai:2,google:3},g$1=e$1.sort((s,l)=>(t[s.id]??99)-(t[l.id]??99)).map(s=>({value:s.id,label:s.name||s.id,hint:s.id==="easbot"?"recommended":void 0}));console.log(""),console.log(g(i$1("auth.interactive.select_provider"))),console.log(a$1({columns:[{key:"index",header:"#",minWidth:4},{key:"provider",header:i$1("auth.table.header.provider"),minWidth:25},{key:"hint",header:i$1("auth.table.header.hint"),flex:!0}],rows:g$1.map((s,l)=>({index:`${l+1}`,provider:s.label,hint:s.hint||""})),width:process.stdout.columns||80,border:"unicode"})),console.log(""),console.log(g(i$1("auth.interactive.enter_number")));let h$1=g$1[0]?.value;h$1||(console.error(e(i$1("auth.interactive.no_providers"))),process.exit(1)),await f(n,h$1);}catch(o){i.error("Interactive login failed",{error:o instanceof Error?o.message:String(o)}),console.error(e(i$1("auth.login.error",{vars:{error:o instanceof Error?o.message:String(o)}}))),process.exit(1);}}async function b(n,o){try{console.log(h(i$1("auth.logout.logging_out",{vars:{provider:o}}))),await n.sdk.auth.remove({providerId:o}),console.log(d(i$1("auth.logout.success",{vars:{provider:o}}))),i.debug("Logout successful",{provider:o});}catch(e$1){i.error("Logout failed",{provider:o,error:e$1 instanceof Error?e$1.message:String(e$1)}),console.error(e(i$1("auth.logout.error",{vars:{error:e$1 instanceof Error?e$1.message:String(e$1)}}))),process.exit(1);}}export{E as registerAuthCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as bootstrap,b as bootstrapProgram}from'./chunk-ZH674M7Q.mjs';import'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-EFJHO4OX.mjs';import {a as a$1}from'./chunk-XPF2LJT2.mjs';import {Sa,xa,la}from'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import {i}from'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import {b as b$2}from'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.mjs';import'./chunk-X6ISXWBN.mjs';import {Command}from'commander';import'path';import k from'fs/promises';import {parse}from'jsonc-parser';var x="easbot",w="EASBot - Multi-Agent Collaboration Ecosystem CLI Tool",b="build",A=["main","ops","explorer"];var v=a.create({service:"cli-config"});async function G(t){try{let o=await k.readFile(t,"utf-8");return parse(o)||{}}catch(o){if(o&&typeof o=="object"&&"code"in o){if(o.code==="ENOENT")return {};v.warn("Failed to read config file",{filePath:t,error:o.code});}else v.error("Failed to parse config file",{filePath:t,error:o instanceof Error?o.message:String(o)});return {}}}function F(...t){let o={};for(let n of t)for(let[e,i]of Object.entries(n))i!==void 0&&(typeof i=="object"&&!Array.isArray(i)&&i!==null?o[e]={...o[e],...i}:o[e]=i);return o}function j(){return {server:{port:3e3,hostname:"localhost"},agent:{},model:{},permission:{}}}async function S(t={}){let{cwd:o=process.cwd(),customConfigPath:n}=t,e=j();if(t.sdk)try{let{data:i}=await t.sdk.config.get({});i&&(e=i);}catch{}if(n){let i=await G(n);Object.keys(i).length>0&&(e=F(e,i));}return e.directory=o,e}async function E(t={}){let o=t.cwd||process.cwd(),n=t.root||Sa.worktree,e=xa({directory:o}),i=await S({cwd:o,root:n,sdk:e,customConfigPath:t.customConfigPath});return {programVersion:b$2.getVersion(),channelOptions:["stdio","http","ws"],agentOptions:`${i.default_agent||b}|${A.join("|")}`,config:i,sdk:e}}var B=[{commands:[{name:"tui",description:"\u542F\u52A8 TUI \u754C\u9762",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./tui-P4UKVVKY.mjs')).registerTuiCommand(t,o);}},{commands:[{name:"run",description:"\u8FD0\u884C\u5355\u6B21\u5BF9\u8BDD",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./run-MYXJU4RX.mjs')).registerRunCommand(t,o);}},{commands:[{name:"generate",description:"\u751F\u6210 OpenAPI \u89C4\u8303",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./generate-FNIRYTGT.mjs')).registerGenerateCommand(t,o);}},{commands:[{name:"agent",description:"Agent \u7BA1\u7406\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./agent-EJ64O3VC.mjs')).registerAgentCommands(t,o);}},{commands:[{name:"session",description:"\u4F1A\u8BDD\u7BA1\u7406\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{let{registerSessionCommands:n}=await import('./session-LWKQT4G7.mjs');n(t,o);}},{commands:[{name:"mcp",description:"MCP \u670D\u52A1\u5668\u7BA1\u7406",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./mcp-5DZTVP6Z.mjs')).registerMcpCommands(t,o);}},{commands:[{name:"acp",description:"ACP Agent \u901A\u4FE1\u9002\u914D\u5668\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./acp-OBY35HS7.mjs')).registerAcpCommand(t,o);}},{commands:[{name:"debug",description:"\u8C03\u8BD5\u548C\u8BCA\u65AD\u5DE5\u5177",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./debug-GTUHAYVC.mjs')).registerDebugCommands(t,o);}},{commands:[{name:"gateway",description:"Gateway \u670D\u52A1\u7BA1\u7406\u547D\u4EE4",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./gateway-GFZFVEHP.mjs')).registerGatewayCommand(t,o);}},{commands:[{name:"auth",description:"Provider \u51ED\u636E\u7BA1\u7406",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./auth-F3UJX6TK.mjs')).registerAuthCommand(t,o);}},{commands:[{name:"export",description:"\u5BFC\u51FA\u4F1A\u8BDD\u6570\u636E",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./export-5BWFWBI3.mjs')).registerExportCommand(t,o);}},{commands:[{name:"github",description:"GitHub Agent \u7BA1\u7406",hasSubcommands:true}],register:async({program:t,ctx:o})=>{(await import('./github-JPCEWX4N.mjs')).registerGithubCommand(t,o);}},{commands:[{name:"import",description:"\u5BFC\u5165\u4F1A\u8BDD\u6570\u636E",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./import-B5RTBC2W.mjs')).registerImportCommand(t,o);}},{commands:[{name:"pr",description:"PR \u68C0\u51FA\u548C\u4F1A\u8BDD\u5BFC\u5165",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./pr-E7AEHZZT.mjs')).registerPrCommand(t,o);}},{commands:[{name:"stats",description:"Token \u4F7F\u7528\u91CF\u548C\u6210\u672C\u7EDF\u8BA1",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./stats-6IILCYBN.mjs')).registerStatsCommand(t,o);}},{commands:[{name:"update",description:"\u66F4\u65B0 Easbot CLI",hasSubcommands:false}],register:async({program:t,ctx:o})=>{(await import('./update-NNMG3LC7.mjs')).registerUpdateCommand(t,o);}}];async function H(t,o,n=process.argv){for(let e of B)await e.register({program:t,ctx:o,argv:n});}async function _(t,o,n=process.argv){await H(t,o,n);}function R(t,o){t.name(i("program.name")).description(i("program.description")),t.option("--cwd <directory>",i("program.option.cwd"),process.cwd()),t.option("--config <path>",i("program.option.config")),t.option("--print-logs",i("program.option.print_logs")),t.option("--log-level <level>",i("program.option.log_level"),"INFO"),t.option("--debug",i("program.option.debug")),t.helpOption("-h, --help",i("program.help.option")),t.helpCommand("help [command]",i("program.help.command")),t.configureHelp({sortSubcommands:true,sortOptions:true,optionTerm:n=>n.flags,subcommandTerm:n=>n.name()}),t.configureOutput({writeOut:n=>{process.stdout.write(L(n));},writeErr:n=>{process.stderr.write(L(n));},outputError:(n,e)=>{e(n);}}),t.addHelpText("afterAll",({command:n})=>n!==t?"":`
|
|
2
|
+
${i("program.help.examples")}:
|
|
3
|
+
easbot # ${i("help.example.tui")}
|
|
4
|
+
easbot tui --continue # ${i("help.example.tui_continue")}
|
|
5
|
+
easbot run --prompt "Hello" # ${i("help.example.run")}
|
|
6
|
+
easbot agent list # ${i("help.example.agent_list")}
|
|
7
|
+
easbot mcp list # ${i("help.example.mcp_list")}
|
|
8
|
+
easbot --help # ${i("help.example.help")}
|
|
9
|
+
|
|
10
|
+
${i("program.help.docs")}: https://easbot.dev/docs
|
|
11
|
+
`);}function L(t){return t.replace(/^Usage:/gm,"Usage:").replace(/^Options:/gm,"Options:").replace(/^Commands:/gm,"Commands:")}var p=a.create({service:"cli-preaction-hooks"}),I=false,O={tui:"tui",run:"run",acp:"acp",gateway:"gateway"},f=null;function N(t,o,n){t.hook("preAction",async(e,i)=>{M(i);let m=process.argv;if(U(m))return;let g=V(m);$(g)||z(o),f=g[0]??null,await W(f,n),await Y(f,n);});}function M(t){let o=t;for(;o.parent?.parent;)o=o.parent;let n=o.name();!n||n==="easbot"||(process.title=`easbot-${n}`);}function U(t){return t.some(o=>o==="-h"||o==="--help"||o==="-v"||o==="--version"||o==="help")}function V(t){let o=[];for(let n=2;n<t.length;n++){let e=t[n];if(e){if(e.startsWith("-"))break;o.push(e);}}return o}function $(t){if(process.env.EASBOT_HIDE_BANNER==="1"||process.env.EASBOT_HIDE_BANNER==="true")return true;let o=new Set(["completion","update"]),n=t[0];return n!==void 0&&o.has(n)}function z(t){I||(I=true,console.log(i("program.version.banner",{vars:{version:t}})));}async function W(t,o){try{t&&O[t]&&await la(async()=>{let{AgentServices:n}=await import('./agent-service-registry-QA5V3B4G.mjs'),e=O[t];n.init(e??""),p.debug("AgentServices initialized",{command:t,prefix:e});},"CLI_INIT_AGENT_SERVICES",{directory:o.config.directory});}catch(n){p.warn("Failed to initialize AgentServices",{error:String(n)});}}var X=new Set(["tui","gateway"]);async function Y(t,o){try{t&&X.has(t)&&await la(async()=>{let{Scheduler:n}=await import('./scheduler-YYOW743S.mjs');n.init(),p.debug("Scheduler initialized",{command:t});},"CLI_INIT_SCHEDULER",{directory:o.config.directory});}catch(n){p.warn("Failed to initialize Scheduler",{error:String(n)});}}var q=Symbol.for("easbot.cli.programContext");function T(t,o){t[q]=o;}var c=a.create({service:"cli-program"});async function Jo(t={}){c.debug("Initializing resource manager"),a$1.initialize();let o=new Command,n=await E({cwd:t.directory,root:void 0,customConfigPath:t.config_path});Object.assign(n.config,{print_logs:t.print_logs,log_level:t.log_level,debug:t.debug});let e=process.argv;return T(o,n),o.name(x).version(n.programVersion,"-V, --version",i("program.version.description")).description(w),R(o),N(o,n.programVersion,n),await Z(o,n),await _(o,n,e),await K(o),await Q(o),o}async function K(t){t.on("command:*",o=>{let n=o[0];console.error(i("program.error.unknown_command",{vars:{command:n}})),console.error(""),console.error(i("program.error.unknown_command_hint")),process.exit(1);});}async function Q(t){t.exitOverride(o=>{throw o.code==="commander.help"&&process.exit(0),o.code==="commander.version"&&process.exit(0),o.code==="commander.helpDisplayed"&&process.exit(0),o.code?.startsWith("commander.")&&(console.error(i("program.error.commander",{vars:{message:o.message}})),process.exit(1)),o});}async function Z(t,o){try{c.debug("Loading plugin system");let n=b$1(o),e=o.config.plugins,i={enabled:e&&typeof e=="object"&&"enabled"in e?e.enabled!==!1:!0,loadPaths:e&&typeof e=="object"&&"load"in e&&e.load&&typeof e.load=="object"&&"paths"in e.load&&Array.isArray(e.load.paths)?e.load.paths:[],allow:e&&typeof e=="object"&&"allow"in e&&Array.isArray(e.allow)?e.allow:[],deny:e&&typeof e=="object"&&"deny"in e&&Array.isArray(e.deny)?e.deny:[]};if(await n.loadAll(i),o._pluginCliRegistrations&&o._pluginCliRegistrations.length>0){c.debug("Registering plugin CLI commands",{count:o._pluginCliRegistrations.length});for(let m of o._pluginCliRegistrations)try{m.register({program:t,context:o}),c.debug("Plugin CLI commands registered",{pluginId:m.pluginId,commands:m.commands});}catch(g){c.error("Failed to register plugin CLI commands",{pluginId:m.pluginId,error:g});}}c.info("Plugin system loaded",{loadedPlugins:n.getLoadedPluginIds()});}catch(n){c.error("Failed to load plugin system",{error:n});}}export{Jo as buildProgram};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as Bus}from'./chunk-PT5TKWFJ.mjs';import'./chunk-4Q3JAZPL.mjs';import'./chunk-IJVW4VME.mjs';import'./chunk-CDDE7L65.mjs';import'./chunk-LGMGGNPW.mjs';import'./chunk-HIPEPY4E.mjs';import'./chunk-AAJAKVQY.mjs';import'./chunk-OSLGCE7R.mjs';import'./chunk-XQ3LMV3K.mjs';import'./chunk-LP2YYNMX.mjs';import'./chunk-G63GWBVD.mjs';import'./chunk-CJTCCLW4.mjs';import'./chunk-3CQA7CJG.mjs';import'./chunk-LFYBZHOI.mjs';import'./chunk-3UV6DBAA.mjs';import'./chunk-X6ISXWBN.mjs';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-3UV6DBAA.mjs';import {c,d}from'./chunk-X6ISXWBN.mjs';import o from'path';import a$2 from'fs/promises';import {NamedError,lazy,Filesystem,PKG,$,Lock}from'@easbot/utils';import E from'zod';import {glob}from'glob';var I;(v=>{let f=a.create({service:"storage"});v.NotFoundError=NamedError.create("NotFoundError",E.object({message:E.string()}));let O=[async i=>{let r=o.resolve(i,"../project");if(await Filesystem.isDir(r))for await(let n of new PKG.Glob("*").scan({cwd:r})){f.info(`migrating project ${n}`);let t=n,e=o.join(r,n),s="/";if(t!=="global"){let g=await glob("storage/session/message/*/*.json",{cwd:o.join(r,n),absolute:true});for(let c of g)if(s=(await a$2.readFile(c,"utf-8").then(m=>JSON.parse(m))).path?.root??"",s)break;if(!s||!await Filesystem.isDir(s))continue;let[u]=await $`git rev-list --max-parents=0 --all`.quiet().nothrow().cwd(s).text().then(c=>c.split(`
|
|
2
2
|
`).filter(Boolean).map(w=>w.trim()).toSorted());if(!u)continue;t=u,await PKG.write(o.join(i,"project",t+".json"),JSON.stringify({id:u,vcs:"git",worktree:s,time:{created:Date.now(),initialized:Date.now()}})),f.info(`migrating sessions for project ${t}`);for await(let c of new PKG.Glob("storage/session/info/*.json").scan({cwd:e,absolute:true})){let w=o.join(i,"session",t,o.basename(c));f.info("copying",{sessionFile:c,dest:w});let m=await a$2.readFile(c,"utf-8").then(p=>JSON.parse(p));await a$2.writeFile(w,JSON.stringify(m)),f.info(`migrating messages for session ${m.id}`);for await(let p of new PKG.Glob(`storage/session/message/${m.id}/*.json`).scan({cwd:e,absolute:true})){let J=o.join(i,"message",m.id,o.basename(p));f.info("copying",{msgFile:p,dest:J});let b=await a$2.readFile(p,"utf-8").then(j=>JSON.parse(j));await a$2.writeFile(J,JSON.stringify(b)),f.debug(`migrating parts for message ${b.id}`);for await(let j of new PKG.Glob(`storage/session/part/${m.id}/${b.id}/*.json`).scan({cwd:e,absolute:true})){let S=o.join(i,"part",b.id,o.basename(j)),P=await PKG.file(j).json();f.debug("copying",{partFile:j,dest:S}),await PKG.write(S,JSON.stringify(P));}}}}}},async i=>{for await(let r of new PKG.Glob("session/*/*.json").scan({cwd:i,absolute:true})){let n=await PKG.file(r).json();if(!n.providerId||!n.summary?.diffs)continue;let{diffs:t}=n.summary;await PKG.write(o.join(i,"session_diff",n.id+".json"),JSON.stringify(t)),await PKG.write(o.join(i,"session",n.providerId,n.id+".json"),JSON.stringify({...n,summary:{additions:t.reduce((e,s)=>e+s.additions,0),deletions:t.reduce((e,s)=>e+s.deletions,0)}}));}}],l=lazy(async()=>{let i=o.join(a$1.Path.data,"storage");await a$2.mkdir(i,{recursive:true});let r=o.join(i,"migration"),n=await a$2.readFile(r,"utf-8").then(t=>parseInt(t,10)).catch(()=>0);for(let t=n;t<O.length;t++){f.debug("running migration",{index:t});let e=O[t];e&&(await e(i).catch(()=>f.error("failed to run migration",{index:t})),await a$2.writeFile(r,(t+1).toString(),"utf-8"));}return {dir:i}});async function M(i){let r=await l().then(t=>t.dir),n=o.join(r,...i)+".json";return y(async()=>{await a$2.unlink(n).catch(()=>{});})}v.remove=M;function R(i){return l().then(r=>o.join(r.dir,...i))}v.dir=R;async function A(i){return a$2.rmdir(i).catch(()=>{})}v.rmdir=A;async function B(i){let r=await l().then(t=>t.dir),n=o.join(r,...i)+".json";return y(async()=>{var s=[];try{let t=c(s,await Lock.read(n));let e=await a$2.readFile(n,"utf-8");return JSON.parse(e)}catch(g){var u=g,c$1=true;}finally{d(s,u,c$1);}})}v.read=B;async function q(i,r){let n=await l().then(e=>e.dir),t=o.join(n,...i)+".json";return y(async()=>{var g=[];try{let e=c(g,await Lock.write(t));let s=await a$2.readFile(t,"utf-8").then(m=>JSON.parse(m));r(s);await a$2.writeFile(t,JSON.stringify(s,null,2),"utf-8");return s}catch(u){var c$1=u,w=true;}finally{d(g,c$1,w);}})}v.update=q;async function H(i,r){let n=await l().then(e=>e.dir),t=o.join(n,...i)+".json";return y(async()=>{var s=[];try{let e=c(s,await Lock.write(t));await a$2.mkdir(o.dirname(t),{recursive:!0});await a$2.writeFile(t,JSON.stringify(r,null,2),"utf-8");}catch(g){var u=g,c$1=true;}finally{d(s,u,c$1);}})}v.write=H;async function y(i){return i().catch(r=>{if(!(r instanceof Error))throw r;let n=r;throw n.code==="ENOENT"?new v.NotFoundError({message:`Resource not found: ${n.path}`}):r})}let D="**/*";async function K(i){let r=await l().then(n=>n.dir);try{let t=(await glob(D,{cwd:o.join(r,...i),nodir:!0})).map(e=>[...i,...e.slice(0,-5).split(o.sep)]);return t.sort(),t}catch{return []}}v.list=K;})(I||(I={}));export{I as a};
|