@easbot/agent 0.2.39 → 0.2.40
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/chunks/{acp-DEC72N5Z.mjs → acp-SMAI7EJF.mjs} +2 -2
- package/dist/chunks/adapter-loader-X3GZRT3I.mjs +1 -0
- package/dist/chunks/{agent-FNDCT3LK.mjs → agent-BS6BU766.mjs} +1 -1
- package/dist/chunks/{agent-4RGZCCWP.mjs → agent-SXVN3QRB.mjs} +1 -1
- package/dist/chunks/app-4GCI3HZT.mjs +1 -0
- package/dist/chunks/bootstrap-SVDRDCAU.mjs +1 -0
- package/dist/chunks/{build-program-AADEFCFD.mjs → build-program-U2HDARWA.mjs} +1 -1
- package/dist/chunks/bus-SGXNL3LP.mjs +1 -0
- package/dist/chunks/{chunk-UOYFWTSY.mjs → chunk-3Q4UCILK.mjs} +1 -1
- package/dist/chunks/{chunk-7LTXB373.mjs → chunk-DJYON7M6.mjs} +2 -2
- package/dist/chunks/{chunk-SARDSKUQ.mjs → chunk-H45MZAM6.mjs} +1 -1
- package/dist/chunks/{chunk-OOI4D6ON.mjs → chunk-IXO5FAWI.mjs} +1 -1
- package/dist/chunks/{chunk-RK3Y4IMV.mjs → chunk-JII5HRIF.mjs} +1 -1
- package/dist/chunks/{chunk-IOMVCUO2.mjs → chunk-O2JOXYKG.mjs} +1 -1
- package/dist/chunks/{chunk-OMGK2WUC.mjs → chunk-VLDQ4LGX.mjs} +2 -2
- package/dist/chunks/{chunk-ONU6FQVM.mjs → chunk-XQXI2ZHB.mjs} +1 -1
- package/dist/chunks/{chunk-M7TI655U.mjs → chunk-YGFGAD5H.mjs} +17 -17
- package/dist/chunks/{chunk-IILYTWWL.mjs → chunk-ZFGVQIO5.mjs} +1 -1
- package/dist/chunks/{chunk-H47ICOJP.mjs → chunk-ZG2HQDXQ.mjs} +1 -1
- package/dist/chunks/{command-HXNWD64P.mjs → command-B7POR3LZ.mjs} +1 -1
- package/dist/chunks/compaction-4CV7NS2Z.mjs +1 -0
- package/dist/chunks/{config-7ZUIWRMI.mjs → config-JY4V5KGI.mjs} +1 -1
- package/dist/chunks/{debug-DHBLLGIZ.mjs → debug-LXNXB4VY.mjs} +3 -3
- package/dist/chunks/file-Q7BJ3BEC.mjs +1 -0
- package/dist/chunks/gateway-HTBKKYKV.mjs +16 -0
- package/dist/chunks/{generate-5SN5EG2R.mjs → generate-JBIFOTPV.mjs} +1 -1
- package/dist/chunks/{github-EYHQZRKW.mjs → github-XXJJ62IF.mjs} +1 -1
- package/dist/chunks/global-FDT3NNWD.mjs +1 -0
- package/dist/chunks/{import-RMNXXJJE.mjs → import-37R7O4NM.mjs} +1 -1
- package/dist/chunks/installation-WZEFRTPQ.mjs +1 -0
- package/dist/chunks/instance-AK3F7UK2.mjs +1 -0
- package/dist/chunks/loader-2FMNUQDJ.mjs +1 -0
- package/dist/chunks/loader-JWZHDUVM.mjs +1 -0
- package/dist/chunks/lsp-N672BWEP.mjs +1 -0
- package/dist/chunks/mcp-JIUYQ7QS.mjs +1 -0
- package/dist/chunks/{mcp-HO7BWSDW.mjs → mcp-X4FA7X53.mjs} +1 -1
- package/dist/chunks/models-OEA6XF6K.mjs +1 -0
- package/dist/chunks/{pr-HVGP5NLH.mjs → pr-WCMJT7VY.mjs} +1 -1
- package/dist/chunks/preferences-EUHOPNM3.mjs +1 -0
- package/dist/chunks/project-WTLNG2LH.mjs +1 -0
- package/dist/chunks/prompt-6OETS3YU.mjs +1 -0
- package/dist/chunks/provider-DC7XQTFP.mjs +1 -0
- package/dist/chunks/registry-ZXV6XNKB.mjs +1 -0
- package/dist/chunks/revert-PEILY52K.mjs +1 -0
- package/dist/chunks/ripgrep-4XTDDATX.mjs +1 -0
- package/dist/chunks/{run-SACOLR6C.mjs → run-PN7YADL6.mjs} +1 -1
- package/dist/chunks/scheduler-2U6D3A47.mjs +1 -0
- package/dist/chunks/server-23WY43I2.mjs +1 -0
- package/dist/chunks/session-2ZGF74EQ.mjs +1 -0
- package/dist/chunks/session-CQ3VGE4U.mjs +1 -0
- package/dist/chunks/{session-QWBUCCTA.mjs → session-FVNB4WZV.mjs} +1 -1
- package/dist/chunks/share-V2US2NJE.mjs +1 -0
- package/dist/chunks/snapshot-3CGXXTES.mjs +1 -0
- package/dist/chunks/storage-GQ3NTV5N.mjs +1 -0
- package/dist/chunks/{tui-AZ5VJAUO.mjs → tui-ABXWVS6I.mjs} +1 -1
- package/dist/chunks/tui-Y47JRG6G.mjs +1 -0
- package/dist/chunks/{types-XJNTBCTU.mjs → types-BFRURHUE.mjs} +1 -1
- package/dist/chunks/{update-GCCHHVAX.mjs → update-SO2ZPDG3.mjs} +1 -1
- package/dist/cli.mjs +2 -2
- package/package.json +13 -13
- package/dist/chunks/adapter-loader-XS6BWT6F.mjs +0 -1
- package/dist/chunks/app-I5FOXMDF.mjs +0 -1
- package/dist/chunks/bootstrap-OSZPS6EP.mjs +0 -1
- package/dist/chunks/bus-SCZARFCL.mjs +0 -1
- package/dist/chunks/compaction-OSH6YUUL.mjs +0 -1
- package/dist/chunks/file-C3SQUYVR.mjs +0 -1
- package/dist/chunks/gateway-YJNOYJAU.mjs +0 -16
- package/dist/chunks/global-FF4MKJCJ.mjs +0 -1
- package/dist/chunks/installation-NZGQ2ZXZ.mjs +0 -1
- package/dist/chunks/instance-ADSGDDDR.mjs +0 -1
- package/dist/chunks/loader-BFMEWP6S.mjs +0 -1
- package/dist/chunks/loader-NQMVER4S.mjs +0 -1
- package/dist/chunks/lsp-2SQQPXM7.mjs +0 -1
- package/dist/chunks/mcp-J3UIR35A.mjs +0 -1
- package/dist/chunks/models-UTUMURIZ.mjs +0 -1
- package/dist/chunks/preferences-ZNTUV4JW.mjs +0 -1
- package/dist/chunks/project-2D5PGMY4.mjs +0 -1
- package/dist/chunks/prompt-DWL63VVN.mjs +0 -1
- package/dist/chunks/provider-6LZMREKJ.mjs +0 -1
- package/dist/chunks/registry-QRMLBX6F.mjs +0 -1
- package/dist/chunks/revert-RLO2K6SP.mjs +0 -1
- package/dist/chunks/ripgrep-WPQB3RBY.mjs +0 -1
- package/dist/chunks/scheduler-W74P7BZY.mjs +0 -1
- package/dist/chunks/server-PSD2LV36.mjs +0 -1
- package/dist/chunks/session-3KHGGAUW.mjs +0 -1
- package/dist/chunks/session-UO6W6MN3.mjs +0 -1
- package/dist/chunks/share-SUJHB6OU.mjs +0 -1
- package/dist/chunks/snapshot-X6DLN3UT.mjs +0 -1
- package/dist/chunks/storage-IS4VGLPJ.mjs +0 -1
- package/dist/chunks/tui-TLXLQ6KA.mjs +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-CJTCCLW4.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$2}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-CJTCCLW4.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$2}from'./chunk-DJYON7M6.mjs';import D from'path';import {NamedError,$,Fetch,iife}from'@easbot/utils';import _ from'zod';function o(A){let T=process.env[A]?.toLowerCase();return T==="true"||T==="1"}function w(A,T){let B=process.env[A];if(B===void 0)return T;let m=Number(B);return Number.isNaN(m)?T:m}var i;(e=>{e.EASBOT_CONFIG=process.env.EASBOT_CONFIG,e.EASBOT_CONFIG_CONTENT=process.env.EASBOT_CONFIG_CONTENT,e.EASBOT_AUTO_SHARE=o("EASBOT_AUTO_SHARE"),e.EASBOT_DISABLE_AUTOUPDATE=o("EASBOT_DISABLE_AUTOUPDATE"),e.EASBOT_DISABLE_PRUNE=o("EASBOT_DISABLE_PRUNE"),e.EASBOT_DISABLE_TERMINAL_TITLE=o("EASBOT_DISABLE_TERMINAL_TITLE"),e.EASBOT_DISABLE_DEFAULT_PLUGINS=o("EASBOT_DISABLE_DEFAULT_PLUGINS"),e.EASBOT_DISABLE_LSP_DOWNLOAD=o("EASBOT_DISABLE_LSP_DOWNLOAD"),e.EASBOT_DISABLE_AUTOCOMPACT=o("EASBOT_DISABLE_AUTOCOMPACT"),e.EASBOT_DISABLE_MODELS_FETCH=o("EASBOT_DISABLE_MODELS_FETCH"),e.EASBOT_DISABLE_FILETIME_CHECK=o("EASBOT_DISABLE_FILETIME_CHECK"),e.EASBOT_ENABLE_EXPERIMENTAL_MODELS=o("EASBOT_ENABLE_EXPERIMENTAL_MODELS"),e.EASBOT_ENABLE_QUESTION_TOOL=o("EASBOT_ENABLE_QUESTION_TOOL"),e.EASBOT_DISABLE_EXTERNAL_SKILLS=o("EASBOT_DISABLE_EXTERNAL_SKILLS"),e.EASBOT_GIT_BASH_PATH=process.env.EASBOT_GIT_BASH_PATH,e.EASBOT_MODELS_URL=process.env.EASBOT_MODELS_URL,e.EASBOT_MODELS_PATH=process.env.EASBOT_MODELS_PATH,e.EASBOT_PERMISSION=process.env.EASBOT_PERMISSION,e.EASBOT_SERVER_USERNAME=process.env.EASBOT_SERVER_USERNAME,e.EASBOT_SERVER_PASSWORD=process.env.EASBOT_SERVER_PASSWORD,e.EASBOT_FAKE_VCS=process.env.EASBOT_FAKE_VCS,e.EASBOT_FILEWATCHER=o("EASBOT_FILEWATCHER"),e.EASBOT_ICON_DISCOVERY=o("EASBOT_ICON_DISCOVERY"),e.EASBOT_ENABLE_EXA=o("EASBOT_ENABLE_EXA"),e.EASBOT_BASH_DEFAULT_TIMEOUT_MS=O("EASBOT_BASH_DEFAULT_TIMEOUT_MS"),e.EASBOT_OUTPUT_TOKEN_MAX=O("EASBOT_OUTPUT_TOKEN_MAX"),e.EASBOT_OXFMT=o("EASBOT_OXFMT"),e.EASBOT_LSP_TY=o("EASBOT_LSP_TY"),e.EASBOT_LSP_TOOL=o("EASBOT_LSP_TOOL"),e.EASBOT_LSP_INIT_TIMEOUT=w("EASBOT_LSP_INIT_TIMEOUT",3e5),e.EASBOT_LSP_DIAGNOSTICS_TIMEOUT=w("EASBOT_LSP_DIAGNOSTICS_TIMEOUT",6e4),e.EASBOT_PLAN_MODE=o("EASBOT_PLAN_MODE"),e.EASBOT_MARKDOWN=o("EASBOT_MARKDOWN"),e.EASBOT_DISABLE_COMPACT=o("EASBOT_DISABLE_COMPACT"),e.EASBOT_DISABLE_AUTO_COMPACT=o("EASBOT_DISABLE_AUTO_COMPACT"),e.EASBOT_AUTOCOMPACT_PCT_OVERRIDE=O("EASBOT_AUTOCOMPACT_PCT_OVERRIDE"),e.EASBOT_AUTO_COMPACT_WINDOW=O("EASBOT_AUTO_COMPACT_WINDOW"),e.EASBOT_BLOCKING_LIMIT_OVERRIDE=O("EASBOT_BLOCKING_LIMIT_OVERRIDE"),e.EASBOT_MAX_CONTEXT_TOKENS=O("EASBOT_MAX_CONTEXT_TOKENS"),e.EASBOT_MAX_TOOL_USE_CONCURRENCY=O("EASBOT_MAX_TOOL_USE_CONCURRENCY");function O(y){let C=process.env[y];if(!C)return;let d=Number(C);return Number.isInteger(d)&&d>0?d:void 0}})(i||(i={}));Object.defineProperty(i,"EASBOT_DISABLE_PROJECT_CONFIG",{get(){return o("EASBOT_DISABLE_PROJECT_CONFIG")},enumerable:true,configurable:false});Object.defineProperty(i,"EASBOT_CONFIG_DIR",{get(){return process.env.EASBOT_CONFIG_DIR},enumerable:true,configurable:false});Object.defineProperty(i,"EASBOT_CLIENT",{get(){return process.env.EASBOT_CLIENT??"cli"},enumerable:true,configurable:false});var M;(S=>{let A=a.create({service:"installation"});S.Event={Updated:a$1.define("installation.updated",_.object({version:_.string()})),UpdateAvailable:a$1.define("installation.update-available",_.object({version:_.string()}))},S.Info=_.object({version:_.string(),latest:_.string()}).meta({ref:"InstallationInfo"});async function m(){return {version:I(),latest:await N()}}S.info=m;function P(){return a$2.isPreview()}S.isPreview=P;function R(){return a$2.isLocal()}S.isLocal=R;async function l(){if(process.execPath.includes(D.join(".easbot","bin"))||process.execPath.includes(D.join(".local","bin")))return "curl";let a=process.execPath.toLowerCase(),r=[{name:"npm",command:()=>$`npm list -g --depth=0`.throws(false).quiet().text()},{name:"yarn",command:()=>$`yarn global list`.throws(false).quiet().text()},{name:"pnpm",command:()=>$`pnpm list -g --depth=0`.throws(false).quiet().text()},{name:"bun",command:()=>$`bun pm ls -g`.throws(false).quiet().text()},{name:"brew",command:()=>$`brew list --formula easbot`.throws(false).quiet().text()},{name:"scoop",command:()=>$`scoop list easbot`.throws(false).quiet().text()},{name:"choco",command:()=>$`choco list --limit-output easbot`.throws(false).quiet().text()}];r.sort((t,s)=>{let E=a.includes(t.name),c=a.includes(s.name);return E&&!c?-1:!E&&c?1:0});for(let t of r){let s=await t.command(),E=(t.name==="brew"||t.name==="choco"||t.name==="scoop","easbot");if(s.includes(E))return t.name}return "unknown"}S.method=l,S.UpgradeFailedError=NamedError.create("UpgradeFailedError",_.object({stderr:_.string()}));async function f(){return (await $`brew list --formula anomalyco/tap/easbot`.throws(false).quiet().text()).includes("easbot")?"anomalyco/tap/easbot":((await $`brew list --formula easbot`.throws(false).quiet().text()).includes("easbot"),"easbot")}async function U(a,r){let t;switch(a){case "curl":t=$`curl -fsSL https://easbot.cn/install | bash`.env({...process.env,VERSION:r});break;case "npm":t=$`npm install -g easbot@${r}`;break;case "pnpm":t=$`pnpm install -g easbot@${r}`;break;case "bun":t=$`bun install -g easbot@${r}`;break;case "brew":{let E=await f();if(E.includes("/")){t=$`brew tap anomalyco/tap && cd "$(brew --repo anomalyco/tap)" && git pull --ff-only && brew upgrade ${E}`.env({HOMEBREW_NO_AUTO_UPDATE:"1",...process.env});break}t=$`brew upgrade ${E}`.env({HOMEBREW_NO_AUTO_UPDATE:"1",...process.env});break}case "choco":t=$`echo Y | choco upgrade easbot --version=${r}`;break;case "scoop":t=$`scoop install easbot@${r}`;break;default:throw new Error(`Unknown method: ${a}`)}let s=await t.quiet().throws(false);if(s.exitCode!==0){let E=a==="choco"?"not running from an elevated command shell":s.stderr.toString("utf8");throw new S.UpgradeFailedError({stderr:E})}A.info("upgraded",{method:a,target:r,stdout:s.stdout.toString(),stderr:s.stderr.toString()}),await $`${process.execPath} --version`.nothrow().quiet().text();}S.upgrade=U;function I(){return a$2.getVersion()}S.getVersion=I;function L(){return a$2.getChannel()}S.getChannel=L;function v(){return `easbot/${L()}/${I()}/${i.EASBOT_CLIENT}`}S.getUserAgent=v;async function N(a){let r=a||await l();if(r==="brew"){let t=await f();if(t.includes("/")){let s=await $`brew info --json=v2 ${t}`.quiet().text(),c=JSON.parse(s).formulae?.[0]?.versions?.stable;if(!c)throw new Error(`Could not detect version for tap formula: ${t}`);return c}return Fetch.get("https://formulae.brew.sh/api/formula/easbot.json").then(s=>{if(!s.ok)throw new Error(s.statusText);return s.data?.versions?.stable??"unknown"})}if(r==="npm"||r==="bun"||r==="pnpm"){let t=await iife(async()=>{let c=(await $`npm config get registry`.quiet().nothrow().text()).trim()||"https://registry.npmjs.org";return c.endsWith("/")?c.slice(0,-1):c}),s=L();return Fetch.get(`${t}/easbot/${s}`).then(E=>{if(!E.ok)throw new Error(E.statusText);return E.data?.version??"unknown"})}return r==="choco"?Fetch.get("https://community.chocolatey.org/api/v2/Packages?$filter=Id%20eq%20%27easbot%27%20and%20IsLatestVersion&$select=Version",{headers:{Accept:"application/json;odata=verbose"}}).then(t=>{if(!t.ok)throw new Error(t.statusText);return t.data?.d?.results?.[0]?.Version??"unknown"}):r==="scoop"?Fetch.get("https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/easbot.json",{headers:{Accept:"application/json"}}).then(t=>{if(!t.ok)throw new Error(t.statusText);return t.data?.version??"unknown"}):Fetch.get("https://api.github.com/repos/houjallen/easbot/releases/latest").then(t=>{if(!t.ok)throw new Error(t.statusText);return (t.data?.tag_name??"unknown").replace(/^v/,"")})}S.latest=N;})(M||(M={}));
|
|
2
2
|
export{i as a,M as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$1,b as b$1}from'./chunk-CQVEAYYW.mjs';import {oa,ta,va,ua,qa,ra,sa,Ka,pa,za}from'./chunk-
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-CQVEAYYW.mjs';import {oa,ta,va,ua,qa,ra,sa,Ka,pa,za}from'./chunk-YGFGAD5H.mjs';import {c}from'./chunk-CCRIJZBK.mjs';import {c as c$1}from'./chunk-ZBRXNYEM.mjs';import {b as b$2}from'./chunk-H45MZAM6.mjs';import {i}from'./chunk-UNBJ6Y7L.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$2}from'./chunk-DJYON7M6.mjs';import {b}from'./chunk-X6ISXWBN.mjs';import {Input,truncateToWidth,isKeyRelease,getKeybindings,Editor,matchesKey,Key,Container,Text,Markdown}from'@easbot/tui';import {loadTextFile,Shell,parseModelId,Fetch,Filesystem}from'@easbot/utils';import {randomUUID}from'crypto';import {readdirSync,existsSync}from'fs';import zt from'path';import {pathToFileURL}from'url';import {GatewayClient}from'@easbot/gateway';var Re=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 x={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`,Ce=s=>e=>`\x1B[48;2;${Lt(s)}m${e}\x1B[0m`,ve=s=>`\x1B[1m${s}\x1B[0m`,rt=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),r=Number.parseInt(e[3]||"0",16);return `${t};${n};${r}`}var ts={selectedPrefix:s=>I(x.accent)(s),selectedText:s=>ve(I(x.accent)(s)),description:s=>I(x.dim)(s),scrollInfo:s=>I(x.dim)(s),noMatch:s=>I(x.dim)(s)},ee={fg:I(x.text),assistantText:s=>s,dim:I(x.dim),accent:I(x.accent),accentSoft:I(x.accentSoft),success:I(x.success),error:I(x.error),header:s=>ve(I(x.accent)(s)),system:I(x.systemText),userBg:Ce(x.userBg),userText:I(x.userText),userLabel:s=>I(x.userLabel)(s),systemLabel:s=>I(x.systemLabel)(s),assistantLabel:s=>I(x.assistantLabel)(s),subagentLabel:s=>I(x.subagentLabel)(s),subagentBg:Ce(x.subagentBg),subagent:s=>I(x.subagentLabel)(s),toolTitle:I(x.toolTitle),toolOutput:I(x.toolOutput),toolPendingBg:Ce(x.toolPendingBg),toolSuccessBg:Ce(x.toolSuccessBg),toolErrorBg:Ce(x.toolErrorBg),border:I(x.border),bold:ve,italic:rt,user:s=>I(x.userText)(s),assistant:s=>I(x.text)(s),code:I(x.code),quote:I(x.quote),link:I(x.link),tool:I(x.toolTitle),thinking:s=>rt(I(x.dim)(s)),warning:I(x.accentSoft),muted:I(x.dim),highlight:s=>ve(I(x.accent)(s))},ss=ts;function ns(s,e){let t=s.split(`
|
|
3
3
|
`);if(!e)return t.map(a=>I(x.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(x.code)},r=e.toLowerCase();return r==="typescript"||r==="ts"||r==="javascript"||r==="js"?t.map(a=>is(a,n)):r==="python"||r==="py"?t.map(a=>rs(a,n)):r==="bash"||r==="sh"||r==="shell"?t.map(a=>os(a,n)):r==="json"?t.map(a=>as(a,n)):t.map(a=>n.default(a))}function is(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,r=>e.keyword?.(r)??r);return n=n.replace(/(['"`])(?:(?=(\\?))\2.)*?\1/g,r=>e.string?.(r)??r),n=n.replace(/\b\d+(\.\d+)?\b/g,r=>e.number?.(r)??r),n}function rs(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,r=>e.keyword?.(r)??r);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,r=>e.string?.(r)??r),n=n.replace(/\b\d+(\.\d+)?\b/g,r=>e.number?.(r)??r),n}function os(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,r=>e.keyword?.(r)??r);return n=n.replace(/(['"])(?:(?=(\\?))\2.)*?\1/g,r=>e.string?.(r)??r),n=n.replace(/\$\{?[\w_]+\}?/g,r=>e.type?.(r)??r),n}function as(s,e){let t=s;return t=t.replace(/"([^"]+)":/g,(n,r)=>`${e.type?.(`"${r}"`)??`"${r}"`}: `),t=t.replace(/:\s*"([^"]+)"/g,(n,r)=>`: ${e.string?.(`"${r}"`)??`"${r}"`}`),t=t.replace(/:\s*(\d+(\.\d+)?)/g,(n,r)=>`: ${e.number?.(r)??r}`),t=t.replace(/:\s*(true|false|null)/g,(n,r)=>`: ${e.keyword?.(r)??r}`),t}var xe={heading:s=>ve(I(x.accent)(s)),link:s=>I(x.link)(s),linkUrl:s=>I(x.dim)(s),code:s=>I(x.code)(s),codeBlock:s=>I(x.code)(s),codeBlockBorder:s=>I(x.codeBorder)(s),quote:s=>I(x.quote)(s),quoteBorder:s=>I(x.quoteBorder)(s),hr:s=>I(x.border)(s),listBullet:s=>I(x.accentSoft)(s),bold:ve,italic:rt,strikethrough:s=>`\x1B[9m${s}\x1B[0m`,underline:s=>`\x1B[4m${s}\x1B[0m`,highlightCode:ns,codeBlockIndent:" "},Mt={borderColor:s=>I(x.border)(s),selectList:ss};var z=a.create({service:"cli-tui-chatlog"}),ot=null;function ds(){if(ot)return ot;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=[],r=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return s&&s!=="tui.system.tool_executing"&&n.push(new RegExp(r(s),"i")),e&&e!=="tui.system.tool_completed"&&n.push(new RegExp(r(e),"i")),t&&t!=="tui.system.tool_failed"&&n.push(new RegExp(r(t),"i")),n.push(/[⚙🔧]\s*(执行工具|Executing tool)/iu,/[✓✅]\s*(工具完成|工具执行完成|Tool completed|Tool execution completed)/iu,/[✗❌]\s*(工具失败|工具执行失败|Tool failed|Tool execution failed)/iu),ot=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);}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){z.debug("Failed to load protocol metadata",{error:n});}}setWidth(t){this.containerWidth=t;}addUser(t,n,r){this.addMessage("user",t,n,r);}addAssistant(t,n,r){this.addMessage("assistant",t,n,r);}addSystem(t,n,r){this.addMessage("system",t,n,r);}addMessage(t,n,r,a){if(z.debug("addMessage called",{type:t,content:n.substring(0,100),id:r,currentMessagesCount:this.messages.length}),r&&this.messages.findIndex(l=>l.id===r)!==-1){z.debug("Message with same ID already exists, skipping",{id:r});return}this.messages.push({type:t,content:n,timestamp:Date.now(),id:r,metadata:a}),z.debug("After push, messages count",{count:this.messages.length}),this.messages.length>this.maxMessages&&(this.messages=this.messages.slice(-this.maxMessages)),z.debug("Calling updateChildren"),this.updateChildren(),z.debug("updateChildren completed");}clear(){this.messages=[],this.updateChildren();}updateChildren(){let t=this.getState?.(),n=t?.toolsExpanded??false,r=t?.showThinking??false,a=t?.verboseLevel??"off",o=t?.messageLimit??50;z.debug("updateChildren called",{messagesCount:this.messages.length,childrenBeforeClear:this.children.length,toolsExpanded:n,showThinking:r,verboseLevel:a,messageLimit:o}),this.children=[],z.debug("Children cleared",{childrenAfterClear:this.children.length});let l=new Set,d=0,u=this.messages.slice(-o);z.debug("Applied message limit",{originalCount:this.messages.length,limitedCount:u.length,messageLimit:o});for(let c of u){if(c.id&&l.has(c.id)){z.debug("Skipping duplicate ID",{id:c.id});continue}if(!n&&this.shouldFilterToolMessage(c)){z.debug("Filtering tool message (tools collapsed)",{content:c.content.substring(0,50),metadata:c.metadata});continue}if(c.id&&!r&&this.shouldFilterThinkingMessage(c)){z.debug("Filtering thinking message (thinking mode off)",{content:c.content.substring(0,50),metadata:c.metadata});continue}if(c.id&&a==="off"&&this.shouldFilterBackgroundAgentMessage(c)){z.debug("Filtering background agent message (verbose off)",{content:c.content.substring(0,50),agent:c.metadata?.agent});continue}if(c.type==="assistant"&&this.shouldFilterAssistantMessage(c.content)){z.debug("Filtering assistant metadata",{content:c.content.substring(0,50)});continue}c.id&&l.add(c.id),z.debug("Rendering message",{type:c.type,content:c.content.substring(0,50),id:c.id,hasId:!!c.id,metadata:c.metadata}),this.renderMessage(c),d++;}z.debug("updateChildren completed",{childrenAfterRender:this.children.length,renderedCount:d}),this.invalidate();}shouldFilterSystemMessage(t){return ds().some(r=>r.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 r=this.getState?.();if(!r?.sdk)return false;let a=async()=>{try{return ((await r.sdk.app.agents({})).data||[]).filter(d=>d.mode==="primary"&&d.hidden!==!0).map(d=>d.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){let n=new Date(t.timestamp).toLocaleTimeString();switch(t.type){case "user":{if(t.metadata?.isSubagentResult){let l=t.metadata.agent||"SubAgent",d=ee.subagentLabel(`[${n}] ${l}: `),u=new Text(d,1,0);this.addChild(u);let p=new Markdown(t.content,0,0,xe).render(this.containerWidth-2);for(let R of p){let H=new Text(R,1,0);this.addChild(H);}break}let r=ee.userLabel(`[${n}] ${i("tui.chatlog.user_prefix")}: `),a=new Text(r,1,0);if(this.addChild(a),t.content.trim().startsWith("/")){let l=ee.accent(t.content),d=new Text(l,1,0);this.addChild(d);}else {let l=ee.userText(t.content),u=new Markdown(l,0,0,xe).render(this.containerWidth-2);for(let c of u){let p=new Text(c,1,0);this.addChild(p);}}break}case "assistant":{let r=i("tui.chatlog.assistant_prefix");this.cachedProtocolMetadata?.name?r=this.cachedProtocolMetadata.name:t.metadata?.agent&&(r=t.metadata.agent);let a=ee.assistantLabel(`[${n}] ${r}: `),o=new Text(a,1,0);this.addChild(o);let d=new Markdown(t.content,0,0,xe).render(this.containerWidth-2);for(let u of d){let c=new Text(u,1,0);this.addChild(c);}break}case "system":{let r=ee.systemLabel(`[${n}] ${i("tui.chatlog.system_prefix")}: `),a=new Text(r,1,0);this.addChild(a);let o=ee.system(t.content),d=new Markdown(o,0,0,xe).render(this.containerWidth-2);for(let u of d){let c=new Text(u,1,0);this.addChild(c);}break}}}};var cs={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"},us=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+/),r=t.toLowerCase();return us.has(r)?{name:"command",args:e}:{name:cs[r]??r,args:n.join(" ").trim()}}var at=[{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=[...at];if(s)try{let r=(await s.command.list({contextMode:e})).data||[],a=new Set(at.map(o=>o.name));for(let o of r)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 $t(){return at}function Ht(){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
4
|
`)}var ms=/[\s\-_./:#@]/;function Ft(s,e){return e===0||ms.test(s[e-1]??"")}function Dt(s,e){if(!e)return null;let t=s.toLowerCase(),n=e.toLowerCase(),r=t.length-n.length;if(r<0)return null;for(let a=0;a<=r;a++)if(t.startsWith(n,a)&&Ft(t,a))return a;return null}function gs(s,e){if(s.length===0)return 0;if(s.length>e.length)return null;let t=0,n=0,r=-1,a=0;for(let o=0;o<e.length&&t<s.length;o++)if(e[o]===s[t]){let l=Ft(e,o);r===o-1?(a++,n-=a*5):(a=0,r>=0&&(n+=(o-r-1)*2)),l&&(n-=10),n+=o*.1,r=o,t++;}return t<s.length?null:n}function qt(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 r=[];for(let a of s){let o=a.searchTextLower??"",l=0,d=true;for(let u of n){let c=gs(u,o);if(c!==null)l+=c;else {d=false;break}}d&&r.push({item:a,score:l});}return r.sort((a,o)=>a.score-o.score),r.map(a=>a.item)}var ys="\x1B",Bt=new RegExp(`${ys}\\[[0-9;]*m`,"g"),se=class se{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=[],r=[];for(let o of this.items){let l=this.getItemLabel(o),d=o.description??"",u=a$1(l).toLowerCase(),c=a$1(d).toLowerCase(),p=u.indexOf(t);if(p!==-1){n.push({item:o,tier:0,score:p});continue}let R=Dt(u,t);if(R!==null){n.push({item:o,tier:1,score:R});continue}let H=c.indexOf(t);if(H!==-1){n.push({item:o,tier:2,score:H});continue}let ne=o.searchText??"";r.push({item:o,searchTextLower:[l,d,ne].map(A=>a$1(A)).filter(Boolean).join(" ").toLowerCase()});}n.sort(this.compareByScore);let a=qt(r,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=[];Bt.lastIndex=0;let n=0,r;for(;(r=Bt.exec(e))!==null;)r.index>n&&t.push({text:e.slice(n,r.index),isAnsi:false}),t.push({text:r[0],isAnsi:true}),n=r.index+r[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 r=Array.from(new Set(n)).toSorted((o,l)=>l.length-o.length),a=this.splitAnsiParts(e);for(let o of r){let l=this.getCachedRegex(o),d=[];for(let u of a){if(u.isAnsi){d.push(u);continue}l.lastIndex=0;let c=u.text.replace(l,p=>this.theme.matchHighlight(p));if(c===u.text){d.push(u);continue}d.push(...this.splitAnsiParts(c));}a=d;}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=[],r=this.theme.searchPrompt("search: "),a=Math.max(1,e-b$1(r)),l=this.searchInput.render(a)[0]??"";t.push(`${r}${this.theme.searchInput(l)}`),t.push("");let d=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)),c=Math.min(u+this.maxVisible,this.filteredItems.length);for(let p=u;p<c;p++){let R=this.filteredItems[p];if(!R)continue;let H=p===this.selectedIndex;t.push(this.renderItemLine(R,H,e,d));}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,r){let a=t?"\u2192 ":" ",o=a.length,l=this.getItemLabel(e),d=e.description;if(d){let H=this.getDescriptionLayout(n,o);if(H){let ne=truncateToWidth(l,H.maxValueWidth,""),A=this.highlightMatch(ne,r),M=b$1(A),h=H.availableWidth-M-H.spacingWidth;if(h>=se.DESCRIPTION_MIN_WIDTH){let re=" ".repeat(H.spacingWidth),F=truncateToWidth(d,h,""),w=this.highlightMatch(F,r),f=t?w:this.theme.description(w),g=`${a}${A}${re}${f}`;return t?this.theme.selectedText(g):g}}}let u=n-o-2,c=truncateToWidth(l,u,""),p=this.highlightMatch(c,r),R=`${a}${p}`;return t?this.theme.selectedText(R):R}getDescriptionLayout(e,t){if(e<=se.DESCRIPTION_LAYOUT_MIN_WIDTH)return null;let n=Math.max(1,e-t-se.RIGHT_MARGIN_WIDTH),r=n-se.DESCRIPTION_MIN_WIDTH-se.DESCRIPTION_SPACING_WIDTH;return r<1?null:{availableWidth:n,maxValueWidth:r,spacingWidth:se.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 r=this.searchInput.getValue();this.searchInput.handleInput(e);let a=this.searchInput.getValue();r!==a&&this.updateFilter();}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e);}getSelectedItem(){return this.filteredItems[this.selectedIndex]??null}};b(se,"DESCRIPTION_LAYOUT_MIN_WIDTH",40),b(se,"DESCRIPTION_MIN_WIDTH",12),b(se,"DESCRIPTION_SPACING_WIDTH",2),b(se,"RIGHT_MARGIN_WIDTH",2);var Fe=se;var ge=a.create({service:"cli-tui-selectors"}),Ss={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 pe(s,e){ge.debug("Creating searchable select list",{itemsCount:s.length,title:e.title});let t=e.maxVisible??10,n=new Fe(s,t,Ss);return e.onSelect&&(n.onSelect=e.onSelect),e.onCancel&&(n.onCancel=e.onCancel),n}function De(s,e){ge.info("Creating model selector with data");let t=[];for(let[n,r]of Object.entries(s))if(r?.models)for(let[a,o]of Object.entries(r.models))t.push({label:`${r.name} - ${o.name}`,value:`${n}/${a}`,description:o.family||""});return ge.debug("Model list loaded",{count:t.length}),pe(t,{title:e.title||i("tui.selector.model.title"),placeholder:e.placeholder||i("tui.selector.model.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function qe(s,e){ge.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 ge.debug("Session list loaded",{count:t.length}),pe(t,{title:e.title||i("tui.selector.session.title"),placeholder:e.placeholder||i("tui.selector.session.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}function Be(s,e){ge.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 ge.debug("Agent list loaded",{count:t.length}),pe(t,{title:e.title||i("tui.selector.agent.title"),placeholder:e.placeholder||i("tui.selector.agent.placeholder"),onSelect:e.onSelect,onCancel:e.onCancel})}var T=a.create({service:"cli-tui-command-handlers"});async function vs(s,e){let t=[];t.push("## "+i("tui.handler.status.title")),t.push(""),t.push("### "+i("tui.handler.status.system_info")),t.push("- **"+i("tui.handler.status.system")+"**: "+i("tui.handler.status.ok")),t.push("- **"+i("tui.handler.status.directory")+"**: `"+e+"`"),t.push(""),t.push("### "+i("tui.handler.status.global_paths")),t.push("- **home**: `"+a$2.Path.home+"`"),t.push("- **data**: `"+a$2.Path.data+"`"),t.push("- **bin**: `"+a$2.Path.bin+"`"),t.push("- **log**: `"+a$2.Path.log+"`"),t.push("- **cache**: `"+a$2.Path.cache+"`"),t.push("- **config**: `"+a$2.Path.config+"`"),t.push("- **state**: `"+a$2.Path.state+"`"),t.push(""),t.push("### "+i("tui.handler.status.session_info")),t.push("- **"+i("tui.handler.status.agent_label")+"**: "+(s.agent||i("tui.handler.status.not_set"))),t.push("- **"+i("tui.handler.status.session_label")+"**: "+(s.currentSessionKey||i("tui.handler.status.not_set"))),t.push("- **"+i("tui.handler.status.model_label")+"**: "+(s.sessionInfo.model||i("tui.handler.status.not_set"))),t.push("");try{let r=(await s.sdk.command.list({})).data||[],a=r.filter(d=>d.source==="skill"),o=r.filter(d=>d.source==="mcp"),l=r.filter(d=>d.source==="command");if(t.push("### "+i("tui.handler.status.skills")+" ("+a.length+")"),a.length>0){let d=a.map(u=>u.name).join(", ");t.push(d);}t.push("");try{let u=(await s.sdk.mcp.status({})).data||{},p=(await s.sdk.mcp.tools({})).data||{},R=Object.entries(u).filter(([,H])=>H.status==="connected");if(t.push("### "+i("tui.handler.status.mcp")+" ("+R.length+")"),R.length>0)for(let[H]of R){let ne=p[H]||[];ne.length>0?t.push("- **"+H+"** ("+ne.length+"): "+ne.join(", ")):t.push("- **"+H+"**");}t.push("");}catch(d){T.error("Failed to get MCP status",{error:d}),t.push("### "+i("tui.handler.status.mcp")+" (0)"),t.push("");}if(t.push("### "+i("tui.handler.status.commands")+" ("+l.length+")"),l.length>0){let d=l.map(u=>u.name).join(", ");t.push(d);}t.push(""),t.push("### "+i("tui.handler.status.services"));try{if(!s.sdk?.lsp)T.warn("SDK or LSP API is not initialized"),t.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let d=await s.sdk.lsp.status({});if(!d||typeof d!="object")T.warn("LSP status response is not a valid object",{response:d,responseType:typeof d}),t.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));else {let u=Array.isArray(d.data)?d.data:[];if(t.push("- **LSP ("+u.length+")**: "),u.length>0){let c=u.filter(p=>p&&typeof p=="object").map(p=>p?.name||"unknown").join(", ");t.push(" "+c);}else t.push(" "+i("tui.handler.status.no_lsp"));}}}catch(d){T.error("Failed to get LSP status",{error:d}),t.push("- **LSP**: "+i("tui.handler.status.error_loading_lsp"));}}catch(n){T.error("Failed to get command list for status",{error:n}),t.push(""),t.push("_"+i("tui.handler.status.error_loading")+"_");}return t.join(`
|
|
@@ -33,7 +33,7 @@ ${E}`),k(i("tui.status.error")),T.error("Failed to execute command",{type:F,name
|
|
|
33
33
|
`;}L.debug("displayQuestion - final message",{messageLength:l.length,messagePreview:l.substring(0,100)}),s.chatLog.addSystem(l);}var K=a.create({service:"cli-tui-session-actions"});async function Nt(s){K.info("Refreshing agent list");try{s.setActivityStatus(i("tui.session.loading_agents"));let n=((await s.sdk.app.agents({})).data||[]).map(r=>r.name);return K.info("Agent list loaded",{count:n.length}),s.setActivityStatus(i("tui.status.ready")),n}catch(e){return K.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 dt(s,e){K.info("Refreshing session info",{sessionId:e});try{s.setActivityStatus(i("tui.session.loading_info"));let n=(await s.sdk.session.get({sessionId:e})).data;return K.info("Session info loaded",{sessionId:e}),s.setActivityStatus(i("tui.status.ready")),n??null}catch(t){return K.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 Ue(s,e,t){K.info("Loading history",{sessionId:e,limit:t});try{s.setActivityStatus(i("tui.session.loading_history"));let r=(await s.sdk.session.messages({sessionId:e,limit:t})).data||[];K.info("History loaded",{sessionId:e,count:r.length});for(let a=0;a<r.length;a++){let o=r[a],l=o?.info?.role;if(l==="user"){let u=(o?.parts?.filter(p=>p.type==="text")||[]).map(p=>("text"in p?p.text:"")||"").join(`
|
|
34
34
|
`),c=o?.parts?.filter(p=>p.type==="subtask-result")||[];K.debug("loadHistory processing user message",{messageId:o?.info?.id,partCount:o?.parts?.length||0,subtaskPartCount:c.length});for(let p of c)if("agent"in p&&"taskId"in p){K.debug("loadHistory adding subtask-result",{messageId:o?.info?.id,agent:p.agent,taskId:p.taskId});let R=Ka.formatSubtaskResultPart(p);s.chatLog.addUser(R,o?.info?.id,{agent:p.agent||"SubAgent",isSubagentResult:!0,subtaskResultPart:{taskId:p.taskId,source:p.source,agent:p.agent,status:p.status,result:p.result,error:p.error,duration:p.duration,rounds:p.rounds,time:p.time,metadata:p.metadata}});}u&&s.chatLog.addUser(u,o?.info?.id,{agent:o?.info?.agent});}else if(l==="assistant"){let u=(o?.parts?.filter(c=>c.type==="text")||[]).map(c=>("text"in c?c.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(c=>c.type==="text")||[]).map(c=>("text"in c?c.text:"")||"").join(`
|
|
36
|
-
`);s.chatLog.addSystem(u,o?.info?.id,{agent:o?.info?.agent});}}return s.setActivityStatus(i("tui.status.ready")),r}catch(n){return K.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){K.info("Switching session",{sessionId:e});try{t.currentSessionId=e,t.currentSessionKey=e,t.historyLoaded=!1;let n=await dt(s,e);n&&(t.currentSessionKey=n.title||e,t.sessionInfo.model=n.model,t.sessionInfo.modelProvider=n.modelProvider);let{loadTuiState:r,saveTuiStateToStorage:a}=await import('./preferences-ZNTUV4JW.mjs'),o=await r(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),K.debug("Session preferences loaded",{sessionId:e,model:t.sessionInfo.model,agent:t.agent,thinkingLevel:t.thinkingLevel}),await a(t),await Ue(s,e,t.messageLimit),t.historyLoaded=!0,s.chatLog.addSystem(i("tui.session.switched",{vars:{sessionId:e}}));}catch(n){K.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 Gt(s,e){K.info("Aborting current run",{sessionId:e});try{s.setActivityStatus(i("tui.session.aborting"));let t=s.sdk.session.abort({sessionId:e}),n=new Promise((r,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){K.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 jt(s,e){return {openOverlay:r=>{s.showOverlay(r);},closeOverlay:()=>{s.hasOverlay()&&s.hideOverlay(),s.setFocus(e);}}}var Oe=a.create({service:"tui-autocomplete"});function Kt(s){return new ct(s)}var ct=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,r){let o=(e[t]||"").slice(0,n),l=this.extractHashPrefix(o);if(l)return this.getFileSuggestions(l);let d=this.extractAtPrefix(o);return d?await this.getAgentSuggestions(d):o.startsWith("/")?this.getCommandSuggestions(o):null}applyCompletion(e,t,n,r,a){let o=e[t]||"",l=o.slice(0,n-a.length),d=o.slice(n);if(a.startsWith("#")){let u=r.label.endsWith("/"),c=u?r.value.replace(/\/$/,""):r.value,p=u?"":" ";return {lines:[...e.slice(0,t),l+c+p+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+c.length+p.length}}if(a.startsWith("@"))return {lines:[...e.slice(0,t),l+r.value+" "+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+r.value.length+1};if(a.startsWith("/")){let u="/"+r.value+" ";return {lines:[...e.slice(0,t),l+u+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+u.length}}return {lines:[...e.slice(0,t),l+r.value+" "+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+r.value.length+1}}async getCommandSuggestions(e){let t=e.indexOf(" ");if(t===-1){let d=e.slice(1),u=this.commands.filter(c=>c.name.toLowerCase().includes(d.toLowerCase())).map(c=>({value:c.name,label:c.name,description:c.description}));return u.length===0?null:{items:u.slice(0,50),prefix:e}}let n=e.slice(1,t),r=e.slice(t+1),a=this.commands.find(d=>d.name===n);if(!a?.getArgumentCompletions)return null;let o=a.getArgumentCompletions(r),l=o instanceof Promise?await o:o;return !l||l.length===0?null:{items:l.slice(0,50),prefix:r}}getFileSuggestions(e){let t=e.startsWith('#"')?e.slice(2):e.slice(1),n=e.startsWith('#"'),r=t.replace(/\\/g,"/");if(this.isDrivePath(r))return Oe.debug("Drive path, skip autocomplete",{normalizedPath:r}),null;let{targetPath:a,searchQuery:o}=this.parsePath(r),l=this.resolveBaseDir(a);try{let d;try{d=readdirSync(l,{withFileTypes:!0});}catch{return Oe.debug("Directory not found",{baseDir:l}),null}let u=[];for(let c of d){if(o&&!c.name.toLowerCase().includes(o.toLowerCase()))continue;let p=c.isDirectory(),R=a?`${a}${c.name}`:c.name;if(u.push({value:n?`#"${R}${p?"/":""}"`:`#${R}${p?"/":""}`,label:p?`${c.name}/`:c.name,description:R}),u.length>=50)break}return u.sort((c,p)=>{let R=c.label.endsWith("/"),H=p.label.endsWith("/");return R&&!H?-1:!R&&H?1:c.label.localeCompare(p.label)}),u.length===0?null:{items:u,prefix:e}}catch(d){return Oe.debug("File search failed",{error:d,targetPath:a}),null}}async getAgentSuggestions(e){if(!this.getAgents)return null;let t=e.slice(1);try{let r=(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 r.length===0?null:{items:r.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 r=n+1;return e[r]==="@"?e.slice(r):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 r=n+1;return e[r]==="#"?e.slice(r):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 ut(s,e){let t=[],n=/(?<![\w`])#(\S+)/g,r;for(;(r=n.exec(s))!==null;){let a=r[1];if(!a)continue;let o=a.replace(/\\/g,"/"),l=js(o,e);existsSync(l)&&t.push({path:a,url:pathToFileURL(l).href,exists:true});}return {attachments:t,invalidPaths:[]}}function js(s,e){if(/^[A-Za-z]:[/\\]/.test(s))return s;let t=s.replace(/^[/\\]+/,"");return zt.join(e,t)}var U=a.create({service:"cli-tui-input-handlers"}),We=class{constructor(){b(this,"handlers",[]);b(this,"isBrowsingHistory",false);}register(e){this.handlers.push(e),U.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 r of this.handlers)if(r.canHandle(n,t.state)){U.debug("Handle input with handler",{handler:r.name,input:n.substring(0,50)}),await r.handle(n,t);return}U.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:r,tui:a}=t,o=n.pendingPermission;if(!o)return;let l=e.toLowerCase().trim(),d;if(l==="y"||l==="yes")d="once";else if(l==="a"||l==="always")d="always";else if(l==="n"||l==="no"||l==="reject")d="reject";else {r.addSystem(i("tui.permission.invalid_input"));return}try{await ra(n,{requestId:o.id,reply:d}),n.pendingPermission=null;let u=d==="once"?i("tui.permission.once"):d==="always"?i("tui.permission.always"):i("tui.permission.reject");r.addSystem(i("tui.permission.replied",{vars:{reply:u}})),U.info("Permission request replied",{requestId:o.id,reply:d});}catch(u){U.error("Failed to reply permission request",{error:u}),r.addSystem(i("tui.permission.error")),n.pendingPermission=null;}}getPrompt(e){return e.pendingPermission?i("tui.permission.prompt"):"> "}},Qe=class{constructor(){b(this,"name","question");}canHandle(e,t){return !(t.pendingQuestion===null||e.startsWith("/"))}async handle(e,t){let{state:n,chatLog:r,tui:a}=t,o=n.pendingQuestion;if(!o){U.warn("QuestionInputHandler.handle - no pending question");return}U.debug("QuestionInputHandler.handle - processing input",{input:e.substring(0,50),currentIndex:o.currentQuestionIndex,totalQuestions:o.questions.length,requestId:o.id});let l=o.currentQuestionIndex,d=o.questions[l];if(!d){U.error("Current question does not exist",{currentIndex:l,totalQuestions:o.questions.length}),n.pendingQuestion=null;return}let u=this.parseAnswer(e,d);if(!u){U.debug("QuestionInputHandler.handle - invalid input",{input:e}),r.addSystem(i("tui.question.invalid_input"));return}if(U.debug("QuestionInputHandler.handle - answer parsed",{answer:u,answerLength:u.length}),o.collectedAnswers.push(u),o.currentQuestionIndex++,o.currentQuestionIndex<o.questions.length){U.debug("QuestionInputHandler.handle - showing next question",{nextIndex:o.currentQuestionIndex,totalQuestions:o.questions.length});let c=o.questions[o.currentQuestionIndex];c&&this.displayQuestion(c,o.currentQuestionIndex,o.questions.length,r);}else {U.info("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,r.addSystem(i("tui.question.completed",{vars:{count:o.collectedAnswers.length}})),U.info("Question request completed",{requestId:o.id});}catch(c){U.error("Failed to reply question request",{error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0,requestId:o.id,answers:o.collectedAnswers,errorType:c instanceof Error?c.constructor.name:typeof c});let p=c instanceof Error?c.message:String(c);r.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 r=n.match(/^(\d+(?:,\s*\d+)*)$/);if(r?.[1]){let o=r[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 d=t.options[l-1];if(d)return [d.label]}return null}return o.map(l=>{let d=t.options[l-1];return d?d.label:""}).filter(l=>l!=="")}return t.custom===false?null:[n]}displayQuestion(e,t,n,r){let a=`
|
|
36
|
+
`);s.chatLog.addSystem(u,o?.info?.id,{agent:o?.info?.agent});}}return s.setActivityStatus(i("tui.status.ready")),r}catch(n){return K.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){K.info("Switching session",{sessionId:e});try{t.currentSessionId=e,t.currentSessionKey=e,t.historyLoaded=!1;let n=await dt(s,e);n&&(t.currentSessionKey=n.title||e,t.sessionInfo.model=n.model,t.sessionInfo.modelProvider=n.modelProvider);let{loadTuiState:r,saveTuiStateToStorage:a}=await import('./preferences-EUHOPNM3.mjs'),o=await r(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),K.debug("Session preferences loaded",{sessionId:e,model:t.sessionInfo.model,agent:t.agent,thinkingLevel:t.thinkingLevel}),await a(t),await Ue(s,e,t.messageLimit),t.historyLoaded=!0,s.chatLog.addSystem(i("tui.session.switched",{vars:{sessionId:e}}));}catch(n){K.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 Gt(s,e){K.info("Aborting current run",{sessionId:e});try{s.setActivityStatus(i("tui.session.aborting"));let t=s.sdk.session.abort({sessionId:e}),n=new Promise((r,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){K.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 jt(s,e){return {openOverlay:r=>{s.showOverlay(r);},closeOverlay:()=>{s.hasOverlay()&&s.hideOverlay(),s.setFocus(e);}}}var Oe=a.create({service:"tui-autocomplete"});function Kt(s){return new ct(s)}var ct=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,r){let o=(e[t]||"").slice(0,n),l=this.extractHashPrefix(o);if(l)return this.getFileSuggestions(l);let d=this.extractAtPrefix(o);return d?await this.getAgentSuggestions(d):o.startsWith("/")?this.getCommandSuggestions(o):null}applyCompletion(e,t,n,r,a){let o=e[t]||"",l=o.slice(0,n-a.length),d=o.slice(n);if(a.startsWith("#")){let u=r.label.endsWith("/"),c=u?r.value.replace(/\/$/,""):r.value,p=u?"":" ";return {lines:[...e.slice(0,t),l+c+p+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+c.length+p.length}}if(a.startsWith("@"))return {lines:[...e.slice(0,t),l+r.value+" "+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+r.value.length+1};if(a.startsWith("/")){let u="/"+r.value+" ";return {lines:[...e.slice(0,t),l+u+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+u.length}}return {lines:[...e.slice(0,t),l+r.value+" "+d,...e.slice(t+1)],cursorLine:t,cursorCol:l.length+r.value.length+1}}async getCommandSuggestions(e){let t=e.indexOf(" ");if(t===-1){let d=e.slice(1),u=this.commands.filter(c=>c.name.toLowerCase().includes(d.toLowerCase())).map(c=>({value:c.name,label:c.name,description:c.description}));return u.length===0?null:{items:u.slice(0,50),prefix:e}}let n=e.slice(1,t),r=e.slice(t+1),a=this.commands.find(d=>d.name===n);if(!a?.getArgumentCompletions)return null;let o=a.getArgumentCompletions(r),l=o instanceof Promise?await o:o;return !l||l.length===0?null:{items:l.slice(0,50),prefix:r}}getFileSuggestions(e){let t=e.startsWith('#"')?e.slice(2):e.slice(1),n=e.startsWith('#"'),r=t.replace(/\\/g,"/");if(this.isDrivePath(r))return Oe.debug("Drive path, skip autocomplete",{normalizedPath:r}),null;let{targetPath:a,searchQuery:o}=this.parsePath(r),l=this.resolveBaseDir(a);try{let d;try{d=readdirSync(l,{withFileTypes:!0});}catch{return Oe.debug("Directory not found",{baseDir:l}),null}let u=[];for(let c of d){if(o&&!c.name.toLowerCase().includes(o.toLowerCase()))continue;let p=c.isDirectory(),R=a?`${a}${c.name}`:c.name;if(u.push({value:n?`#"${R}${p?"/":""}"`:`#${R}${p?"/":""}`,label:p?`${c.name}/`:c.name,description:R}),u.length>=50)break}return u.sort((c,p)=>{let R=c.label.endsWith("/"),H=p.label.endsWith("/");return R&&!H?-1:!R&&H?1:c.label.localeCompare(p.label)}),u.length===0?null:{items:u,prefix:e}}catch(d){return Oe.debug("File search failed",{error:d,targetPath:a}),null}}async getAgentSuggestions(e){if(!this.getAgents)return null;let t=e.slice(1);try{let r=(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 r.length===0?null:{items:r.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 r=n+1;return e[r]==="@"?e.slice(r):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 r=n+1;return e[r]==="#"?e.slice(r):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 ut(s,e){let t=[],n=/(?<![\w`])#(\S+)/g,r;for(;(r=n.exec(s))!==null;){let a=r[1];if(!a)continue;let o=a.replace(/\\/g,"/"),l=js(o,e);existsSync(l)&&t.push({path:a,url:pathToFileURL(l).href,exists:true});}return {attachments:t,invalidPaths:[]}}function js(s,e){if(/^[A-Za-z]:[/\\]/.test(s))return s;let t=s.replace(/^[/\\]+/,"");return zt.join(e,t)}var U=a.create({service:"cli-tui-input-handlers"}),We=class{constructor(){b(this,"handlers",[]);b(this,"isBrowsingHistory",false);}register(e){this.handlers.push(e),U.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 r of this.handlers)if(r.canHandle(n,t.state)){U.debug("Handle input with handler",{handler:r.name,input:n.substring(0,50)}),await r.handle(n,t);return}U.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:r,tui:a}=t,o=n.pendingPermission;if(!o)return;let l=e.toLowerCase().trim(),d;if(l==="y"||l==="yes")d="once";else if(l==="a"||l==="always")d="always";else if(l==="n"||l==="no"||l==="reject")d="reject";else {r.addSystem(i("tui.permission.invalid_input"));return}try{await ra(n,{requestId:o.id,reply:d}),n.pendingPermission=null;let u=d==="once"?i("tui.permission.once"):d==="always"?i("tui.permission.always"):i("tui.permission.reject");r.addSystem(i("tui.permission.replied",{vars:{reply:u}})),U.info("Permission request replied",{requestId:o.id,reply:d});}catch(u){U.error("Failed to reply permission request",{error:u}),r.addSystem(i("tui.permission.error")),n.pendingPermission=null;}}getPrompt(e){return e.pendingPermission?i("tui.permission.prompt"):"> "}},Qe=class{constructor(){b(this,"name","question");}canHandle(e,t){return !(t.pendingQuestion===null||e.startsWith("/"))}async handle(e,t){let{state:n,chatLog:r,tui:a}=t,o=n.pendingQuestion;if(!o){U.warn("QuestionInputHandler.handle - no pending question");return}U.debug("QuestionInputHandler.handle - processing input",{input:e.substring(0,50),currentIndex:o.currentQuestionIndex,totalQuestions:o.questions.length,requestId:o.id});let l=o.currentQuestionIndex,d=o.questions[l];if(!d){U.error("Current question does not exist",{currentIndex:l,totalQuestions:o.questions.length}),n.pendingQuestion=null;return}let u=this.parseAnswer(e,d);if(!u){U.debug("QuestionInputHandler.handle - invalid input",{input:e}),r.addSystem(i("tui.question.invalid_input"));return}if(U.debug("QuestionInputHandler.handle - answer parsed",{answer:u,answerLength:u.length}),o.collectedAnswers.push(u),o.currentQuestionIndex++,o.currentQuestionIndex<o.questions.length){U.debug("QuestionInputHandler.handle - showing next question",{nextIndex:o.currentQuestionIndex,totalQuestions:o.questions.length});let c=o.questions[o.currentQuestionIndex];c&&this.displayQuestion(c,o.currentQuestionIndex,o.questions.length,r);}else {U.info("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,r.addSystem(i("tui.question.completed",{vars:{count:o.collectedAnswers.length}})),U.info("Question request completed",{requestId:o.id});}catch(c){U.error("Failed to reply question request",{error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0,requestId:o.id,answers:o.collectedAnswers,errorType:c instanceof Error?c.constructor.name:typeof c});let p=c instanceof Error?c.message:String(c);r.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 r=n.match(/^(\d+(?:,\s*\d+)*)$/);if(r?.[1]){let o=r[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 d=t.options[l-1];if(d)return [d.label]}return null}return o.map(l=>{let d=t.options[l-1];return d?d.label:""}).filter(l=>l!=="")}return t.custom===false?null:[n]}displayQuestion(e,t,n,r){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}
|
|
@@ -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-DJYON7M6.mjs';import E from'path';import j from'fs/promises';import t from'zod';import {NamedError,lazy,PKG,Filesystem,Fetch,Shell}from'@easbot/utils';import {ZipReader,BlobReader,BlobWriter}from'@zip.js/zip.js';var P;(c=>{let $=a.create({service:"ripgrep"}),A=t.object({elapsed:t.object({secs:t.number(),nanos:t.number(),human:t.string()}),searches:t.number(),searches_with_match:t.number(),bytes_searched:t.number(),bytes_printed:t.number(),matched_lines:t.number(),matches:t.number()}),S=t.object({type:t.literal("begin"),data:t.object({path:t.object({text:t.string()})})});c.Match=t.object({type:t.literal("match"),data:t.object({path:t.object({text:t.string()}),lines:t.object({text:t.string()}),line_number:t.number(),absolute_offset:t.number(),submatches:t.array(t.object({match:t.object({text:t.string()}),start:t.number(),end:t.number()}))})});let M=t.object({type:t.literal("end"),data:t.object({path:t.object({text:t.string()}),binary_offset:t.number().nullable(),stats:A})}),D=t.object({type:t.literal("summary"),data:t.object({elapsed_total:t.object({human:t.string(),nanos:t.number(),secs:t.number()}),stats:A})}),O=t.union([S,c.Match,M,D]),W={"arm64-darwin":{platform:"aarch64-apple-darwin",extension:"tar.gz"},"arm64-linux":{platform:"aarch64-unknown-linux-gnu",extension:"tar.gz"},"x64-darwin":{platform:"x86_64-apple-darwin",extension:"tar.gz"},"x64-linux":{platform:"x86_64-unknown-linux-musl",extension:"tar.gz"},"x64-win32":{platform:"x86_64-pc-windows-msvc",extension:"zip"}};c.ExtractionFailedError=NamedError.create("RipgrepExtractionFailedError",t.object({filepath:t.string(),stderr:t.string()})),c.UnsupportedPlatformError=NamedError.create("RipgrepUnsupportedPlatformError",t.object({platform:t.string()})),c.DownloadFailedError=NamedError.create("RipgrepDownloadFailedError",t.object({url:t.string(),status:t.number()}));let L=lazy(async()=>{let e=await PKG.which("rg");if(e){if((await j.stat(e).catch(()=>{}))?.isFile())return {filepath:Filesystem.resolve(e)};$.warn("bun.which returned invalid rg path",{filepath:e});}let l=Filesystem.resolve(E.join(a$1.Path.bin,"rg"+(process.platform==="win32"?".exe":"")));if(!await PKG.file(l).exists()){let i=`${process.arch}-${process.platform}`,f=W[i];if(!f)throw new c.UnsupportedPlatformError({platform:i});let r="14.1.1",b=`ripgrep-${r}-${f.platform}.${f.extension}`,p=`https://github.com/BurntSushi/ripgrep/releases/download/${r}/${b}`,m=await Fetch.get(p,{responseType:"arrayBuffer"});if(!m.ok)throw new c.DownloadFailedError({url:p,status:m.status});let u=m.data,n=E.join(a$1.Path.bin,b);if(await PKG.write(n,new Uint8Array(u)),f.extension==="tar.gz"){let o=["tar","-xzf",n,"--strip-components=1"];i.endsWith("-darwin")&&o.push("--include=*/rg"),i.endsWith("-linux")&&o.push("--wildcards","*/rg");let a=await Shell.run(void 0,o.join(" "),{cwd:a$1.Path.bin});if(a.code!==0)throw new c.ExtractionFailedError({filepath:l,stderr:a.stderr})}if(f.extension==="zip"){let a=await PKG.file(n).arrayBuffer(),d=new ZipReader(new BlobReader(new Blob([a]))),g=await d.getEntries(),w;for(let v of g)if(v.filename.endsWith("rg.exe")){w=v;break}if(!w)throw new c.ExtractionFailedError({filepath:n,stderr:"rg.exe not found in zip archive"});let x=await w.getData(new BlobWriter);if(!x)throw new c.ExtractionFailedError({filepath:n,stderr:"Failed to extract rg.exe from zip archive"});let C=await x.arrayBuffer();await PKG.write(l,new Uint8Array(C)),await d.close();}await j.unlink(n),i.endsWith("-win32")||await j.chmod(l,493);}return {filepath:l}});async function N(){let{filepath:e}=await L();return e}c.filepath=N;async function*H(e){e.signal?.throwIfAborted();let l=await N(),s=["--files","--glob=!.git/*"];if(e.follow&&s.push("--follow"),e.hidden!==false&&s.push("--hidden"),e.maxDepth!==void 0&&s.push(`--max-depth=${e.maxDepth}`),e.glob)for(let r of e.glob)s.push(`--glob=${r}`);if(!(await j.stat(e.cwd).catch(()=>{}))?.isDirectory())throw Object.assign(new Error(`No such file or directory: '${e.cwd}'`),{code:"ENOENT",errno:-2,path:e.cwd});let f=(await PKG.run([l,...s],{cwd:e.cwd})).stdout.trim().split(/\r?\n/).filter(Boolean);for(let r of f)e.signal?.throwIfAborted(),r&&(yield r);}c.files=H;async function Q(e){$.info("tree",e);let l=await Array.fromAsync(c.files({cwd:e.cwd,signal:e.signal}));function s(n,o){let a=n.children.get(o);if(a)return a;let d={name:o,children:new Map};return n.children.set(o,d),d}let i={children:new Map};for(let n of l){if(n.includes(".easbot"))continue;let o=n.split(E.sep);if(o.length<2)continue;let a=i;for(let d of o.slice(0,-1))a=s(a,d);}function f(n){let o=0;for(let a of n.children.values())o+=1+f(a);return o}let r=f(i),b=e.limit??r,p=[],m=[];for(let n of Array.from(i.children.values()).sort((o,a)=>o.name.localeCompare(a.name)))m.push({node:n,path:n.name});let u=0;for(let n=0;n<m.length&&u<b;n++){let o=m[n];if(!o)continue;let{node:a,path:d}=o;p.push(d),u++;for(let g of Array.from(a.children.values()).sort((w,x)=>w.name.localeCompare(x.name)))m.push({node:g,path:`${d}/${g.name}`});}return r>u&&p.push(`[${r-u} truncated]`),p.join(`
|
|
2
2
|
`)}c.tree=Q;async function R(e){let l=await N(),s=["--json","--hidden","--glob=!.git/*"];if(e.follow&&s.push("--follow"),e.glob)for(let r of e.glob)s.push(`--glob=${r}`);e.limit&&s.push(`--max-count=${e.limit}`),s.push("--"),s.push(e.pattern);let i=await PKG.run([l,...s],{cwd:e.cwd});return i.code!==0?[]:i.stdout.trim().split(/\r?\n/).filter(Boolean).map(r=>JSON.parse(r)).map(r=>O.parse(r)).filter(r=>r.type==="match").map(r=>r.data)}c.search=R;})(P||(P={}));export{P as a};
|