@memo-code/memo 0.6.0 → 0.6.31

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/index.js CHANGED
@@ -1,65 +1,69 @@
1
1
  #!/usr/bin/env node
2
- var gs=Object.create;var Bn=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var ys=Object.getOwnPropertyNames;var xs=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var Fn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ts=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ys(t))!vs.call(e,r)&&r!==n&&Bn(e,r,{get:()=>t[r],enumerable:!(o=hs(t,r))||o.enumerable});return e};var Vn=(e,t,n)=>(n=e!=null?gs(xs(e)):{},Ts(t||!e||!e.__esModule?Bn(n,"default",{value:e,enumerable:!0}):n,e));var eo=Fn((Hu,Qn)=>{"use strict";function Wn(e){return Array.isArray(e)?e:[e]}var Jt="",Kn=" ",Wt="\\",$s=/^\s+$/,Is=/(?:[^\\]|^)\\$/,Ls=/^\\!/,Os=/^\\#/,Ns=/\r?\n/g,Ds=/^\.*\/|^\.+$/,Kt="/",Xn="node-ignore";typeof Symbol<"u"&&(Xn=Symbol.for("node-ignore"));var Jn=Xn,Us=(e,t,n)=>Object.defineProperty(e,t,{value:n}),Hs=/([0-z])-([0-z])/g,Yn=()=>!1,js=e=>e.replace(Hs,(t,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?t:Jt),Bs=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Fs=[[/^\uFEFF/,()=>Jt],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Kn:Jt)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Kn}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return t+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Wt],[/\\\\/g,()=>Wt],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,o,r)=>t===Wt?`\\[${n}${Bs(o)}${r}`:r==="]"&&o.length%2===0?`[${js(n)}${o}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],qn=Object.create(null),Vs=(e,t)=>{let n=qn[e];return n||(n=Fs.reduce((o,[r,s])=>o.replace(r,s.bind(e)),e),qn[e]=n),t?new RegExp(n,"i"):new RegExp(n)},Yt=e=>typeof e=="string",Gs=e=>e&&Yt(e)&&!$s.test(e)&&!Is.test(e)&&e.indexOf("#")!==0,zs=e=>e.split(Ns),qt=class{constructor(t,n,o,r){this.origin=t,this.pattern=n,this.negative=o,this.regex=r}},Ws=(e,t)=>{let n=e,o=!1;e.indexOf("!")===0&&(o=!0,e=e.substr(1)),e=e.replace(Ls,"!").replace(Os,"#");let r=Vs(e,t);return new qt(n,e,o,r)},Ks=(e,t)=>{throw new t(e)},Te=(e,t,n)=>Yt(e)?e?Te.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),Zn=e=>Ds.test(e);Te.isNotRelative=Zn;Te.convert=e=>e;var Xt=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:o=!1}={}){Us(this,Jn,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(t){if(t&&t[Jn]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(Gs(t)){let n=Ws(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Wn(Yt(t)?zs(t):t).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(t){return this.add(t)}_testOne(t,n){let o=!1,r=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(r===i&&o!==r||i&&!o&&!r&&!n)return;s.regex.test(t)&&(o=!i,r=i)}),{ignored:o,unignored:r}}_test(t,n,o,r){let s=t&&Te.convert(t);return Te(s,t,this._allowRelativePaths?Yn:Ks),this._t(s,n,o,r)}_t(t,n,o,r){if(t in n)return n[t];if(r||(r=t.split(Kt)),r.pop(),!r.length)return n[t]=this._testOne(t,o);let s=this._t(r.join(Kt)+Kt,n,o,r);return n[t]=s.ignored?s:this._testOne(t,o)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return Wn(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},mt=e=>new Xt(e),Js=e=>Te(e&&Te.convert(e),e,Yn);mt.isPathValid=Js;mt.default=mt;Qn.exports=mt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Te.convert=e;let t=/^[a-z]:\//i;Te.isNotRelative=n=>t.test(n)||Zn(n)}});var Sr=Fn((Jd,It)=>{"use strict";function gr(e){return Array.isArray(e)?e:[e]}var $c=void 0,Sn="",dr=" ",Tn="\\",Ic=/^\s+$/,Lc=/(?:[^\\]|^)\\$/,Oc=/^\\!/,Nc=/^\\#/,Dc=/\r?\n/g,Uc=/^\.{0,2}\/|^\.{1,2}$/,Hc=/\/$/,ze="/",hr="node-ignore";typeof Symbol<"u"&&(hr=Symbol.for("node-ignore"));var yr=hr,We=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),jc=/([0-z])-([0-z])/g,xr=()=>!1,Bc=e=>e.replace(jc,(t,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?t:Sn),Fc=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Vc=[[/^\uFEFF/,()=>Sn],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?dr:Sn)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+dr}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return t+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Tn],[/\\\\/g,()=>Tn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,o,r)=>t===Tn?`\\[${n}${Fc(o)}${r}`:r==="]"&&o.length%2===0?`[${Bc(n)}${o}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],Gc=/(^|\\\/)?\\\*$/,et="regex",Rt="checkRegex",fr="_",zc={[et](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Rt](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Wc=e=>Vc.reduce((t,[n,o])=>t.replace(n,o.bind(e)),e),$t=e=>typeof e=="string",Kc=e=>e&&$t(e)&&!Ic.test(e)&&!Lc.test(e)&&e.indexOf("#")!==0,Jc=e=>e.split(Dc).filter(Boolean),_n=class{constructor(t,n,o,r,s,i){this.pattern=t,this.mark=n,this.negative=s,We(this,"body",o),We(this,"ignoreCase",r),We(this,"regexPrefix",i)}get regex(){let t=fr+et;return this[t]?this[t]:this._make(et,t)}get checkRegex(){let t=fr+Rt;return this[t]?this[t]:this._make(Rt,t)}_make(t,n){let o=this.regexPrefix.replace(Gc,zc[t]),r=this.ignoreCase?new RegExp(o,"i"):new RegExp(o);return We(this,n,r)}},qc=({pattern:e,mark:t},n)=>{let o=!1,r=e;r.indexOf("!")===0&&(o=!0,r=r.substr(1)),r=r.replace(Oc,"!").replace(Nc,"#");let s=Wc(r);return new _n(e,t,r,n,o,s)},kn=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[yr]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if($t(t)&&(t={pattern:t}),Kc(t.pattern)){let n=qc(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,gr($t(t)?Jc(t):t).forEach(this._add,this),this._added}test(t,n,o){let r=!1,s=!1,i;this._rules.forEach(c=>{let{negative:l}=c;s===l&&r!==s||l&&!r&&!s&&!n||!c[o].test(t)||(r=!l,s=l,i=l?$c:c)});let a={ignored:r,unignored:s};return i&&(a.rule=i),a}},Xc=(e,t)=>{throw new t(e)},be=(e,t,n)=>$t(e)?e?be.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),vr=e=>Uc.test(e);be.isNotRelative=vr;be.convert=e=>e;var bn=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:o=!1}={}){We(this,yr,!0),this._rules=new kn(n),this._strictPathCheck=!o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,o,r){let s=t&&be.convert(t);return be(s,t,this._strictPathCheck?Xc:xr),this._t(s,n,o,r)}checkIgnore(t){if(!Hc.test(t))return this.test(t);let n=t.split(ze).filter(Boolean);if(n.pop(),n.length){let o=this._t(n.join(ze)+ze,this._testCache,!0,n);if(o.ignored)return o}return this._rules.test(t,!1,Rt)}_t(t,n,o,r){if(t in n)return n[t];if(r||(r=t.split(ze).filter(Boolean)),r.pop(),!r.length)return n[t]=this._rules.test(t,o,et);let s=this._t(r.join(ze)+ze,n,o,r);return n[t]=s.ignored?s:this._rules.test(t,o,et)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return gr(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},wn=e=>new bn(e),Yc=e=>be(e&&be.convert(e),e,xr),Tr=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");be.convert=e;let t=/^[a-z]:\//i;be.isNotRelative=n=>t.test(n)||vr(n)};typeof process<"u"&&process.platform==="win32"&&Tr();It.exports=wn;wn.default=wn;It.exports.isPathValid=Yc;We(It.exports,Symbol.for("setupWindows"),Tr)});import{randomUUID as os}from"crypto";import{createInterface as xu}from"readline/promises";import{stdin as vu,stdout as Tu}from"process";import{render as Su}from"ink";import Ss from"os";import{readFile as _s}from"fs/promises";import{join as ks,dirname as bs}from"path";import{fileURLToPath as ws}from"url";var Cs=/{{\s*([\w.-]+)\s*}}/g;function Es(e,t){return e.replace(Cs,(n,o)=>t[o]??"")}function As(){try{return Ss.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function Gn(){let e=bs(ws(import.meta.url)),t=ks(e,"prompt.md"),n=await _s(t,"utf-8"),o={date:new Date().toISOString(),user:As(),pwd:process.cwd()};return Es(n,o)}import{appendFile as Ms,mkdir as Ps}from"fs/promises";import{dirname as Rs}from"path";var pt=class{constructor(t){this.filePath=t}ready=!1;async append(t){this.ready||(await Ps(Rs(this.filePath),{recursive:!0}),this.ready=!0),await Ms(this.filePath,`${JSON.stringify(t)}
3
- `,"utf8")}async flush(){return Promise.resolve()}};function zn(e){return{ts:new Date().toISOString(),sessionId:e.sessionId,turn:e.turn,step:e.step,type:e.type,content:e.content,role:e.role,meta:e.meta}}import{spawn as ci}from"child_process";import{z as tn}from"zod";function S(e,t=!1){return{content:[{type:"text",text:e}],isError:t}}var io=Vn(eo(),1);import{normalize as qs,resolve as ro,dirname as to,join as dt,relative as so,isAbsolute as Xs}from"path";import{homedir as Ys}from"os";import{existsSync as Qt,statSync as Zs}from"fs";import{readFile as Qs}from"fs/promises";function Y(e){return qs(ro(e))}function ei(e,t){let n=so(t,e);return n===""||!n.startsWith("..")&&!Xs(n)}function ti(){let e=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>Y(t)):[]}function ao(){let e=new Set;e.add(Y(process.cwd()));let t=process.env.MEMO_HOME?.trim()||dt(Ys(),".memo");e.add(Y(t));for(let n of ti())e.add(n);return Array.from(e)}function en(e){return ao().some(n=>ei(e,n))}function ft(e){if(en(e))return null;let t=ao();return`sandbox \u62D2\u7EDD\u5199\u5165: ${e} \u4E0D\u5728\u5141\u8BB8\u76EE\u5F55\u5185 (${t.join(", ")})`}var ni=["node_modules/",".git/","dist/","out/","build/","coverage/",".cache/",".idea/",".DS_Store",".next/",".turbo/",".pnpm/",".pnpm-store/","*.log","logs/","tmp/","temp/","vendor/"],no=100,Zt=1e4,oi="<system_hint>\u5F53\u524D\u67E5\u627E\u7ED3\u679C\u8FC7\u591A\uFF0C\u8BF7\u7EC6\u5316\u67E5\u627E\u8303\u56F4\uFF08\u7F29\u5C0F\u76EE\u5F55\u3001\u589E\u52A0\u66F4\u5177\u4F53\u7684 pattern/glob \u6216\u5173\u952E\u8BCD\uFF09\u3002</system_hint>",oo=new Map;function ri(e){return e.replace(/\\/g,"/")}function si(e){let t=ro(e);try{Zs(t).isFile()&&(t=to(t))}catch{t=process.cwd()}let n=t;for(;;){if(Qt(dt(t,".gitignore"))||Qt(dt(t,".git")))return t;let o=to(t);if(o===t)return n;t=o}}async function ii(e){let t=dt(e,".gitignore");return Qt(t)?(await Qs(t,"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")):[]}async function ai(e){let t=(0,io.default)();t.add(ni);let n=await ii(e);return n.length>0&&t.add(n),{root:e,ignores:o=>{let r=so(e,o);return!r||r.startsWith("..")?!1:t.ignores(ri(r))}}}async function gt(e){let t=si(e),n=oo.get(t);if(n)return n;let o=ai(t);return oo.set(t,o),o}function ht(e,t){let n=e.split(/\r?\n/),o=Math.max(t,n.length),r=n.slice(0,no).join(`
4
- `);return r.length>Zt&&(r=r.slice(0,Zt)),o>no||e.length>Zt?`${r}
5
-
6
- ${oi}`:r}var li=tn.object({command:tn.string().min(1,"command \u4E0D\u80FD\u4E3A\u7A7A"),timeout:tn.number().int("timeout \u5FC5\u987B\u662F\u6574\u6570\u6BEB\u79D2").positive("timeout \u5FC5\u987B\u5927\u4E8E 0").max(3600*1e3,"timeout \u4E0D\u80FD\u8D85\u8FC7 1 \u5C0F\u65F6").optional()}).strict(),co=4e3,lo=4e3;function uo(e,t){return e.length<=t?{value:e,truncated:!1}:{value:e.slice(0,t),truncated:!0}}function ui(e){return e.trim().replace(/^['"]|['"]$/g,"")}function pi(e){let t=e.split(/\s+/).map(ui).filter(Boolean),n=[];for(let o of t){if(!o.startsWith("/"))continue;let r=Y(o);en(r)||n.push(r)}return Array.from(new Set(n))}var po={name:"bash",description:"\u5728 shell \u4E2D\u6267\u884C\u547D\u4EE4\uFF0C\u8FD4\u56DE exit/stdout/stderr",inputSchema:li,execute:async({command:e,timeout:t})=>{let n=e.trim();if(!n)return S("bash \u9700\u8981\u8981\u6267\u884C\u7684\u547D\u4EE4",!0);let o=pi(n);if(o.length>0)return S(`sandbox \u62D2\u7EDD\u6267\u884C: \u547D\u4EE4\u5305\u542B\u8D8A\u754C\u7EDD\u5BF9\u8DEF\u5F84 (${o.join(", ")})`,!0);try{let r=ci("bash",["-lc",n],{env:process.env,stdio:["ignore","pipe","pipe"]}),s=_=>new Promise(k=>{if(!_)return k("");let d=[];_.setEncoding("utf8"),_.on("data",v=>d.push(v)),_.on("error",()=>k("")),_.on("end",()=>k(d.join("")))}),i=s(r.stdout),a=s(r.stderr),c,l=new Promise((_,k)=>{r.on("error",d=>k(d)),r.on("close",d=>_(typeof d=="number"?d:-1))}),u=t&&t>0?new Promise((_,k)=>{c=setTimeout(()=>{r.kill(),k(new Error(`bash \u8D85\u65F6 ${t}ms\uFF0C\u5DF2\u7EC8\u6B62\u8FDB\u7A0B`))},t)}):null,p=u?await Promise.race([l,u]):await l;c&&clearTimeout(c);let[h,y]=await Promise.all([i,a]),b=uo(h,co),x=uo(y,lo),w=b.truncated||x.truncated?`
7
- <system_hint>bash \u8F93\u51FA\u5DF2\u622A\u65AD\uFF08stdout_max=${co} chars, stderr_max=${lo} chars\uFF09\u3002\u8BF7\u7F29\u5C0F\u547D\u4EE4\u8F93\u51FA\u8303\u56F4\u3002</system_hint>`:"";return S(`exit=${p} stdout="${b.value}" stderr="${x.value}"${w}`)}catch(r){return S(`bash \u6267\u884C\u5931\u8D25: ${r.message}`,!0)}}};import{access as mi,readFile as di,writeFile as fi}from"fs/promises";import{z as ne}from"zod";var gi=ne.object({old_string:ne.string().min(1,"old_string \u4E0D\u80FD\u4E3A\u7A7A"),new_string:ne.string(),replace_all:ne.boolean().optional()}).strict(),hi=ne.object({file_path:ne.string().min(1),old_string:ne.string().optional(),new_string:ne.string().optional(),replace_all:ne.boolean().optional(),edits:ne.array(gi).min(1).optional()}).superRefine((e,t)=>{let n=!!(e.edits&&e.edits.length>0),o=typeof e.old_string=="string"||typeof e.new_string=="string";if(n&&o){t.addIssue({code:ne.ZodIssueCode.custom,message:"edits \u4E0E old_string/new_string \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528"});return}if(n)for(let r=0;r<(e.edits?.length??0);r++){let s=e.edits?.[r];s&&(s.old_string.trim()||t.addIssue({code:ne.ZodIssueCode.custom,message:"old_string \u4E0D\u80FD\u4E3A\u7A7A",path:["edits",r,"old_string"]}))}else{if(typeof e.old_string!="string"||typeof e.new_string!="string"){t.addIssue({code:ne.ZodIssueCode.custom,message:"\u5FC5\u987B\u63D0\u4F9B old_string/new_string\uFF0C\u6216\u4F7F\u7528 edits"});return}e.old_string.trim()||t.addIssue({code:ne.ZodIssueCode.custom,message:"old_string \u4E0D\u80FD\u4E3A\u7A7A",path:["old_string"]})}}).strict(),mo={name:"edit",description:"\u5728\u6587\u4EF6\u4E2D\u66FF\u6362\u6587\u672C\uFF0C\u652F\u6301 replace_all \u548C\u6279\u91CF edits",inputSchema:hi,execute:async e=>{let t=Y(e.file_path),n=ft(t);if(n)return S(n,!0);try{await mi(t);let o=await di(t,"utf8"),r=e.edits&&e.edits.length>0?e.edits:[{old_string:e.old_string??"",new_string:e.new_string??"",replace_all:e.replace_all}],s=o,i=0;for(let a=0;a<r.length;a++){let c=r[a];if(!c)continue;let l=c.old_string,u=c.replace_all??!1;if(!s.includes(l))return r.length===1?S("\u672A\u627E\u5230\u5F85\u66FF\u6362\u6587\u672C",!0):S(`\u7B2C ${a+1} \u5904\u66FF\u6362\u672A\u627E\u5230\u5F85\u66FF\u6362\u6587\u672C`,!0);if(u){let p=s.split(l),h=p.length-1;s=p.join(c.new_string),i+=h}else s=s.replace(l,c.new_string),i+=1}return s===o?S("\u672A\u68C0\u6D4B\u5230\u5185\u5BB9\u53D8\u5316"):(await fi(t,s,"utf8"),S(`\u66FF\u6362\u5B8C\u6210: file=${t} edits=${r.length} count=${i}`))}catch(o){return o.code==="ENOENT"?S(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`,!0):S(`edit \u5931\u8D25: ${o.message}`,!0)}}};import{z as fo}from"zod";var yi=fo.object({url:fo.string().min(1)}).strict(),go=1e4,Xe=512e3,nn=4e3,xi=new Set(["http:","https:","data:"]),vi=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Ti=/<\s*(br|hr)\s*\/?>/gi,Si=/<\s*li[^>]*>/gi,_i=/<[^>]+>/g,ki=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,bi=e=>e.replace(/&nbsp;/gi," ").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&amp;/gi,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(o,r)=>{try{let s=r.startsWith("x")||r.startsWith("X")?parseInt(r.slice(1),16):parseInt(r,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),wi=e=>{let o=e.replace(ki," ").replace(Si,"- ").replace(Ti,`
8
- `).replace(vi,`
9
- `).replace(_i," "),s=bi(o).replace(/\r/g,"").split(`
10
- `).map(a=>a.trim().replace(/[ \t]{2,}/g," "));return s.filter((a,c)=>a.length>0||c>0&&(s[c-1]?.length??0)>0).join(`
11
- `).trim()},Ci=e=>e.replace(/\s+/g," ").trim(),ho={name:"webfetch",description:"HTTP GET \u8BF7\u6C42\uFF0C\u8FD4\u56DE\u5904\u7406\u540E\u7684\u7EAF\u6587\u672C\u6B63\u6587\uFF08\u81EA\u52A8\u5265\u79BB HTML \u6807\u7B7E\uFF09",inputSchema:yi,execute:async e=>{let t;try{t=new URL(e.url)}catch{return S(`\u65E0\u6548 URL: ${e.url}`,!0)}if(!xi.has(t.protocol))return S(`\u4E0D\u652F\u6301\u7684\u534F\u8BAE: ${t.protocol}`,!0);let n=new AbortController,o=setTimeout(()=>n.abort(),go);try{let r=await globalThis.fetch(t,{signal:n.signal}),s=r.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>Xe)return S(`\u8BF7\u6C42\u88AB\u62D2\u7EDD: \u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${i} bytes\uFF09`,!0);let a=0,c="";if(r.body&&r.body.getReader){let w=r.body.getReader(),_=[];for(;;){let{done:v,value:E}=await w.read();if(v)break;if(E){if(a+=E.byteLength,a>Xe)return n.abort(),S(`\u8BF7\u6C42\u88AB\u4E2D\u6B62: \u54CD\u5E94\u4F53\u8D85\u8FC7 ${Xe} bytes`,!0);_.push(E)}}let k=new Uint8Array(a),d=0;for(let v of _)k.set(v,d),d+=v.byteLength;c=new TextDecoder().decode(k)}else if(c=await r.text(),a=new TextEncoder().encode(c).byteLength,a>Xe)return S(`\u8BF7\u6C42\u88AB\u62D2\u7EDD: \u54CD\u5E94\u4F53\u8D85\u8FC7 ${Xe} bytes`,!0);let l=r.headers.get("content-type")||"",u=/text\/html/i.test(l)||/^\s*<!doctype html/i.test(c)||/^\s*<html[\s>]/i.test(c),p=u?wi(c):c.trim(),h=Ci(p),y=h.length>nn?`${h.slice(0,nn)}...`:h,b=h.length>nn?" text_truncated=true":"",x=u?" source=html_stripped":"";return S(`status=${r.status} bytes=${a} text_chars=${h.length} text="${y}"${b}${x}`)}catch(r){return r.name==="AbortError"?S(`\u8BF7\u6C42\u8D85\u65F6\u6216\u88AB\u4E2D\u6B62\uFF08${go}ms\uFF09`,!0):S(`\u8BF7\u6C42\u5931\u8D25: ${r.message}`,!0)}finally{clearTimeout(o)}}};import{z as on}from"zod";import Ei from"fast-glob";var Ai=on.object({pattern:on.string().min(1),path:on.string().optional()}).strict(),Mi={name:"glob",description:"\u6309 glob \u6A21\u5F0F\u5339\u914D\u6587\u4EF6\uFF0C\u8FD4\u56DE\u7EDD\u5BF9\u8DEF\u5F84\u5217\u8868",inputSchema:Ai,execute:async e=>{let t=e.path?Y(e.path):process.cwd();try{let n=await gt(t),r=(await Ei(e.pattern,{cwd:t,absolute:!0,onlyFiles:!0})).filter(i=>!n.ignores(i));if(r.length===0)return S("\u672A\u627E\u5230\u5339\u914D\u6587\u4EF6");let s=r.join(`
12
- `);return S(ht(s,r.length))}catch(n){return S(`glob \u5931\u8D25: ${n.message}`,!0)}}},yo=Mi;import{spawn as Pi,spawnSync as Ri}from"child_process";import{z as Se}from"zod";import{isAbsolute as xo,resolve as vo}from"path";var $i=Se.object({pattern:Se.string().min(1),path:Se.string().optional(),output_mode:Se.enum(["content","files_with_matches","count"]).optional(),glob:Se.string().optional(),"-i":Se.boolean().optional(),"-A":Se.number().int().nonnegative().optional(),"-B":Se.number().int().nonnegative().optional(),"-C":Se.number().int().nonnegative().optional()}).strict(),To={name:"grep",description:"\u57FA\u4E8E ripgrep \u67E5\u627E\u6587\u672C\uFF0C\u652F\u6301\u8F93\u51FA\u5339\u914D\u5185\u5BB9\u3001\u6587\u4EF6\u5217\u8868\u6216\u8BA1\u6570",inputSchema:$i,execute:async e=>{let t=Ri("rg",["--version"],{stdio:"ignore"});if(t.error||t.status!==0)return S("rg \u672A\u5B89\u88C5\u6216\u4E0D\u5728 PATH",!0);let n=e.path?Y(e.path):process.cwd(),o=["--color","never"],r=e.output_mode??"content";r==="files_with_matches"?o.push("-l"):r==="count"?o.push("-c"):o.push("--line-number","--no-heading"),e["-i"]&&o.push("-i"),e.glob&&o.push("--glob",e.glob),e["-A"]!==void 0&&o.push("-A",String(e["-A"])),e["-B"]!==void 0&&o.push("-B",String(e["-B"])),e["-C"]!==void 0&&o.push("-C",String(e["-C"])),o.push(e.pattern,n);try{let s=await gt(n),i=Pi("rg",o,{stdio:["ignore","pipe","pipe"]}),a=x=>new Promise(w=>{if(!x)return w("");let _=[];x.setEncoding("utf8"),x.on("data",k=>_.push(k)),x.on("error",()=>w("")),x.on("end",()=>w(_.join("")))}),[c,l]=await Promise.all([a(i.stdout),a(i.stderr)]);if(await new Promise((x,w)=>{i.on("error",_=>w(_)),i.on("close",_=>x(typeof _=="number"?_:-1))})===2)return S(`grep \u5931\u8D25(exit=2): ${l||c}`,!0);let y=(c||l||"").split(/\r?\n/).map(x=>x.trimEnd()).filter(x=>x.length>0).filter(x=>{if(r==="files_with_matches"){let d=x.trim(),v=xo(d)?d:vo(n,d);return!s.ignores(v)}let w=x.indexOf(":");if(w===-1)return!0;let _=x.slice(0,w),k=xo(_)?_:vo(n,_);return!s.ignores(k)});if(y.length===0)return S("\u672A\u627E\u5230\u5339\u914D");let b=y.join(`
13
- `);return S(ht(b,y.length))}catch(s){return S(`grep \u6267\u884C\u5931\u8D25: ${s.message}`,!0)}}};import{mkdir as Ii,readFile as Li,writeFile as Oi,access as Ni}from"fs/promises";import{dirname as Di,join as So}from"path";import{homedir as Ui}from"os";import{z as _o}from"zod";var Hi=_o.object({fact:_o.string().min(1,"fact cannot be empty").max(120,"Please keep facts concise (\u2264120 characters)").describe('User-related identity traits or preferences, e.g., "User prefers Chinese responses", "User is a frontend engineer". Do not store project-specific technical details.')}).strict();function ji(){let e=process.env.MEMO_HOME?.trim()||So(Ui(),".memo");return So(e,"Agents.md")}function Bi(e){return e.replace(/\r?\n/g," ").replace(/\s+/g," ").trim()}function Fi(e,t){let o=t.map(r=>r.trim()).filter(Boolean).map(r=>`- ${r}`);return`${e}
14
-
15
- ${o.join(`
16
- `)}
17
- `}var ko={name:"save_memory",description:"Save user-related identity traits or preferences (e.g., language habits, tech preferences) for cross-session reuse. Do not save project-specific technical details or file structures.",inputSchema:Hi,execute:async e=>{let t=Bi(e.fact);if(!t)return S("fact cannot be empty",!0);let n=ji(),o=Di(n);try{await Ii(o,{recursive:!0});let r="## Memo Added Memories";try{let s=await(async()=>{try{return await Ni(n),await Li(n,"utf-8")}catch{return""}})(),[,i=""]=s.split(r),a=i.split(/\r?\n/).filter(u=>u.trim().startsWith("- ")).map(u=>u.replace(/^-+\s*/,"").trim());a.push(t);let c=a.slice(Math.max(0,a.length-50)),l=Fi(r,c);await Oi(n,l,"utf-8")}catch(s){console.warn(`Memory maintenance failed: ${s.message}`)}return S(`Memory saved to: ${n}`)}catch(r){return S(`Failed to write memory: ${r.message}`,!0)}}};import{z as _e}from"zod";var yt=10,pe=[],Vi=_e.object({type:_e.enum(["add","replace","update","remove"]),todos:_e.array(_e.object({content:_e.string().trim().min(1,"content \u4E0D\u80FD\u4E3A\u7A7A").max(200,"content \u6700\u957F 200 \u5B57\u7B26"),status:_e.enum(["pending","in_progress","completed"]).optional().default("pending"),id:_e.string().min(1,"id \u4E0D\u80FD\u4E3A\u7A7A").optional()})).optional(),ids:_e.array(_e.string().min(1,"id \u4E0D\u80FD\u4E3A\u7A7A")).optional()}).strict().refine(e=>{if(["add","replace","update"].includes(e.type)){if(!e.todos||e.todos.length===0)return!1;if(e.type==="update")return e.todos.every(t=>t.id)}return!(e.type==="remove"&&(!e.ids||e.ids.length===0))},{message:"add/replace/update \u9700\u8981 todos\uFF0Cremove \u9700\u8981 ids\uFF0Cupdate \u9700\u8981 id"});function xt(){return pe.map(e=>({...e}))}function Gi(e){switch(e.type){case"add":{let t=e.todos,n=yt-pe.length;if(t.length>n)return{error:`\u4EFB\u52A1\u4E0A\u9650 ${yt}\uFF0C\u5F53\u524D\u5269\u4F59 ${n} \u6761\u7A7A\u4F4D`};let o=t.map(r=>({id:crypto.randomUUID(),content:r.content,status:r.status}));return pe.push(...o),{added:o,tasks:xt()}}case"replace":{let t=e.todos;if(t.length>yt)return{error:`\u4EFB\u52A1\u4E0A\u9650 ${yt}`};pe.splice(0,pe.length);let n=t.map(o=>({id:crypto.randomUUID(),content:o.content,status:o.status}));return pe.push(...n),{replaced:!0,tasks:xt()}}case"update":{let t=e.todos,n=t.map(s=>s.id);if(new Set(n).size!==n.length)return{error:"\u66F4\u65B0\u5217\u8868\u5B58\u5728\u91CD\u590D id"};let r=new Map(pe.map(s=>[s.id,s]));for(let s of t){let i=r.get(s.id);if(!i)return{error:`\u672A\u627E\u5230\u4EFB\u52A1 id=${s.id}`};i.content=s.content,s.status&&(i.status=s.status)}return{updated:n,tasks:xt()}}case"remove":{let t=e.ids,n=pe.length,o=new Set(t),r=pe.filter(s=>!o.has(s.id));return r.length===n?{error:"\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u5220\u9664\u7684\u4EFB\u52A1 id"}:(pe.splice(0,pe.length,...r),{removed:t,tasks:xt()})}}}var bo={name:"todo",description:"\u7BA1\u7406\u5F85\u529E\u5217\u8868\uFF08add/update/remove/replace\uFF09\uFF0C\u6700\u591A 10 \u6761\uFF0C\u4E0D\u6301\u4E45\u5316",inputSchema:Vi,execute:async e=>{let t=Gi(e);if(t.error)return S(t.error,!0);let n={op:e.type,count:pe.length,tasks:t.tasks,added:t.added,updated:t.updated,removed:t.removed,replaced:!!t.replaced};return S(JSON.stringify(n))}};import{z as vt}from"zod";import{extname as zi}from"path";import{gzipSync as Wi}from"zlib";import{access as Ki,readFile as Ji}from"fs/promises";var wo=512e3,Co=2e6,qi=200,Eo=1e3,Xi=1024,rn=4e3,Yi=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg"]);function Zi(e){let t=zi(e).toLowerCase();return Yi.has(t)}function Qi(e){return Buffer.from(e).toString("base64")}function ea(e){try{let t=Wi(e,{level:6});if(t.byteLength<e.byteLength)return{data:new Uint8Array(t),encoding:"gzip+base64"}}catch{}return{data:e,encoding:"base64"}}function ta(e){let t=e.truncated?" truncated=true":"";return`image_base64 (encoding=${e.encoding} original_bytes=${e.originalBytes} payload_bytes=${e.payloadBytes} base64_length=${e.base64.length}${t}): ${e.base64}`}var na=vt.object({file_path:vt.string().min(1),offset:vt.number().int().positive().optional(),limit:vt.number().int().positive().optional()}).strict(),Ao={name:"read",description:"\u8BFB\u53D6\u6307\u5B9A\u6587\u4EF6\u5185\u5BB9\uFF0C\u53EF\u6309 offset/limit \u622A\u53D6\u5E76\u9644\u5E26\u884C\u53F7",inputSchema:na,execute:async e=>{let t=Y(e.file_path),n=e.offset??1,o=e.limit??qi,r=Math.min(o,Eo);try{await Ki(t);let s=await Ji(t),i=s.byteLength;if(Zi(t)){if(i>Co)return S(`\u56FE\u7247\u8FC7\u5927\uFF08${i} bytes\uFF09\uFF0C\u8D85\u8FC7\u9608\u503C ${Co} bytes\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6`,!0);let v=new Uint8Array(s),{data:E,encoding:B}=ea(v),I=Qi(E),ue=I.length>rn?`${I.slice(0,rn)}...`:I,M=I.length>rn;return S(ta({encoding:B,base64:ue,originalBytes:v.byteLength,payloadBytes:E.byteLength,truncated:M}))}if(i>wo)return S(`\u6587\u4EF6\u8FC7\u5927\uFF08${i} bytes\uFF09\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6\uFF0C\u9608\u503C ${wo} bytes`,!0);let c=new Uint8Array(s),l=Math.min(c.length,Xi);for(let v=0;v<l;v++)if(c[v]===0)return S("\u68C0\u6D4B\u5230\u4E8C\u8FDB\u5236\u5185\u5BB9\uFF0C\u5DF2\u62D2\u7EDD\u76F4\u63A5\u8BFB\u53D6",!0);let p=new TextDecoder().decode(c).split(/\r?\n/),h=Math.max(0,n-1),y=Math.min(p.length,h+r),x=p.slice(h,y).map((v,E)=>`${h+E+1}: ${v}`).join(`
18
- `),w=y<p.length,d=o!==r||w&&e.limit===void 0?`
19
- ... (truncated, showing ${r} lines; max=${Eo})`:"";return S(x+d)}catch(s){return S(`\u8BFB\u53D6\u5931\u8D25: ${s.message}`,!0)}}};import{z as sn}from"zod";import{dirname as oa}from"path";import{mkdir as ra,writeFile as sa}from"fs/promises";var ia=sn.object({file_path:sn.string().min(1),content:sn.any().optional()}).strict();function aa(e){if(e instanceof Uint8Array)return{data:e,info:`bytes=${e.byteLength}`};if(e instanceof ArrayBuffer){let n=new Uint8Array(e);return{data:n,info:`bytes=${n.byteLength}`}}if(typeof e=="string")return{data:e,info:`text_length=${e.length}`};let t=JSON.stringify(e??"",null,2);return{data:t,info:`json_length=${t.length}`}}var Mo={name:"write",description:"\u521B\u5EFA\u6216\u8986\u76D6\u6587\u4EF6\uFF0C\u4F20\u5165 file_path \u4E0E content",inputSchema:ia,execute:async e=>{let t=Y(e.file_path),n=ft(t);if(n)return S(n,!0);let{data:o,info:r}=aa(e.content);try{return await ra(oa(t),{recursive:!0}),await sa(t,o instanceof Uint8Array?o:String(o)),S(`\u5DF2\u5199\u5165 ${t} (overwrite, ${r})`)}catch(s){return S(`\u5199\u5165\u5931\u8D25: ${s.message}`,!0)}}};function ca(e){let t=e.toJSONSchema(),{$schema:n,...o}=t;return o}function la(e){return{name:e.name,description:e.description,source:"native",inputSchema:ca(e.inputSchema),validateInput:t=>{let n=e.inputSchema.safeParse(t);if(!n.success){let o=n.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${e.name} invalid input: ${o}`}}return{ok:!0,data:n.data}},execute:e.execute}}function Po(e){return e.map(la)}var ua={bash:po,read:Ao,write:Mo,edit:mo,glob:yo,grep:To,webfetch:ho,save_memory:ko,todo:bo},pa=Object.values(ua),Ro=Po(pa);import Na from"openai";import{encoding_for_model as ma,get_encoding as da}from"@dqbd/tiktoken";var $o="cl100k_base";function fa(e){let t=e?.trim()||$o;try{let n=()=>ma(t);return n().free(),{model:t,factory:n}}catch{let n=$o,o=()=>da(n);return o().free(),{model:n,factory:o}}}function Io(e){let{model:t,factory:n}=fa(e),o=n(),r=4,s=2,i=1,a=l=>l?o.encode(l).length:0;return{model:t,countText:a,countMessages:l=>{if(!l.length)return 0;let u=0;for(let p of l)u+=r,u+=a(p.content),p.name&&(u+=i);return u+=s,u},dispose:()=>o.free()}}import{mkdir as ga,writeFile as ha,readFile as ya,access as xa}from"fs/promises";import{homedir as Lo}from"os";import{dirname as va,join as Ie}from"path";import{randomUUID as tm}from"crypto";import{parse as Ta}from"toml";var Sa=Ie(Lo(),".memo"),_a="sessions",ka="Agents.md",je={current_provider:"deepseek",stream_output:!1,max_prompt_tokens:12e4,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function ba(e){return/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e)}function wa(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=[];for(let[n,o]of Object.entries(e)){if(!o)continue;let r=Array.isArray(o)?o:[o];for(let s of r){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),t.push(i)}}return t}function Oo(e){return e.startsWith("~")?Ie(Lo(),e.slice(1)):e}function Ca(e){let t=e.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let c=[`[[providers.${ba(i)}]]`,`name = ${JSON.stringify(i)}`,`env_api_key = ${JSON.stringify(String(s.env_api_key??""))}`,`model = ${JSON.stringify(String(s.model??""))}`];return s.base_url&&c.push(`base_url = ${JSON.stringify(String(s.base_url))}`),c.join(`
2
+ var As=Object.create;var zn=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var Ps=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,Is=Object.prototype.hasOwnProperty;var Gn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $s=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ps(e))!Is.call(t,r)&&r!==n&&zn(t,r,{get:()=>e[r],enumerable:!(o=Ms(e,r))||o.enumerable});return t};var Kn=(t,e,n)=>(n=t!=null?As(Rs(t)):{},$s(e||!t||!t.__esModule?zn(n,"default",{value:t,enumerable:!0}):n,t));var po=Gn((om,uo)=>{"use strict";function oo(t){return Array.isArray(t)?t:[t]}var nn="",ro=" ",en="\\",ai=/^\s+$/,li=/(?:[^\\]|^)\\$/,ci=/^\\!/,ui=/^\\#/,pi=/\r?\n/g,mi=/^\.*\/|^\.+$/,tn="/",ao="node-ignore";typeof Symbol<"u"&&(ao=Symbol.for("node-ignore"));var so=ao,di=(t,e,n)=>Object.defineProperty(t,e,{value:n}),fi=/([0-z])-([0-z])/g,lo=()=>!1,gi=t=>t.replace(fi,(e,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?e:nn),hi=t=>{let{length:e}=t;return t.slice(0,e-e%2)},yi=[[/^\uFEFF/,()=>nn],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?ro:nn)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+ro}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return e+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>en],[/\\\\/g,()=>en],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,o,r)=>e===en?`\\[${n}${hi(o)}${r}`:r==="]"&&o.length%2===0?`[${gi(n)}${o}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],io=Object.create(null),Ti=(t,e)=>{let n=io[t];return n||(n=yi.reduce((o,[r,s])=>o.replace(r,s.bind(t)),t),io[t]=n),e?new RegExp(n,"i"):new RegExp(n)},sn=t=>typeof t=="string",_i=t=>t&&sn(t)&&!ai.test(t)&&!li.test(t)&&t.indexOf("#")!==0,xi=t=>t.split(pi),on=class{constructor(e,n,o,r){this.origin=e,this.pattern=n,this.negative=o,this.regex=r}},Si=(t,e)=>{let n=t,o=!1;t.indexOf("!")===0&&(o=!0,t=t.substr(1)),t=t.replace(ci,"!").replace(ui,"#");let r=Ti(t,e);return new on(n,t,o,r)},vi=(t,e)=>{throw new e(t)},ke=(t,e,n)=>sn(t)?t?ke.isNotRelative(t)?n(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${e}\``,TypeError),co=t=>mi.test(t);ke.isNotRelative=co;ke.convert=t=>t;var rn=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:o=!1}={}){di(this,so,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[so]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(_i(e)){let n=Si(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,oo(sn(e)?xi(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,n){let o=!1,r=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(r===i&&o!==r||i&&!o&&!r&&!n)return;s.regex.test(e)&&(o=!i,r=i)}),{ignored:o,unignored:r}}_test(e,n,o,r){let s=e&&ke.convert(e);return ke(s,e,this._allowRelativePaths?lo:vi),this._t(s,n,o,r)}_t(e,n,o,r){if(e in n)return n[e];if(r||(r=e.split(tn)),r.pop(),!r.length)return n[e]=this._testOne(e,o);let s=this._t(r.join(tn)+tn,n,o,r);return n[e]=s.ignored?s:this._testOne(e,o)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return oo(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},wt=t=>new rn(t),Ci=t=>ke(t&&ke.convert(t),t,lo);wt.isPathValid=Ci;wt.default=wt;uo.exports=wt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");ke.convert=t;let e=/^[a-z]:\//i;ke.isNotRelative=n=>e.test(n)||co(n)}});var Lr=Gn((Mg,Dt)=>{"use strict";function Ar(t){return Array.isArray(t)?t:[t]}var wc=void 0,En="",kr=" ",wn="\\",Ec=/^\s+$/,kc=/(?:[^\\]|^)\\$/,bc=/^\\!/,Ac=/^\\#/,Mc=/\r?\n/g,Pc=/^\.{0,2}\/|^\.{1,2}$/,Rc=/\/$/,Je="/",Mr="node-ignore";typeof Symbol<"u"&&(Mr=Symbol.for("node-ignore"));var Pr=Mr,Ye=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),Ic=/([0-z])-([0-z])/g,Rr=()=>!1,$c=t=>t.replace(Ic,(e,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?e:En),Lc=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Oc=[[/^\uFEFF/,()=>En],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?kr:En)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+kr}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return e+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>wn],[/\\\\/g,()=>wn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,o,r)=>e===wn?`\\[${n}${Lc(o)}${r}`:r==="]"&&o.length%2===0?`[${$c(n)}${o}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],Nc=/(^|\\\/)?\\\*$/,pt="regex",Ot="checkRegex",br="_",Dc={[pt](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Ot](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Uc=t=>Oc.reduce((e,[n,o])=>e.replace(n,o.bind(t)),t),Nt=t=>typeof t=="string",Hc=t=>t&&Nt(t)&&!Ec.test(t)&&!kc.test(t)&&t.indexOf("#")!==0,Fc=t=>t.split(Mc).filter(Boolean),kn=class{constructor(e,n,o,r,s,i){this.pattern=e,this.mark=n,this.negative=s,Ye(this,"body",o),Ye(this,"ignoreCase",r),Ye(this,"regexPrefix",i)}get regex(){let e=br+pt;return this[e]?this[e]:this._make(pt,e)}get checkRegex(){let e=br+Ot;return this[e]?this[e]:this._make(Ot,e)}_make(e,n){let o=this.regexPrefix.replace(Nc,Dc[e]),r=this.ignoreCase?new RegExp(o,"i"):new RegExp(o);return Ye(this,n,r)}},jc=({pattern:t,mark:e},n)=>{let o=!1,r=t;r.indexOf("!")===0&&(o=!0,r=r.substr(1)),r=r.replace(bc,"!").replace(Ac,"#");let s=Uc(r);return new kn(t,e,r,n,o,s)},bn=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Pr]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Nt(e)&&(e={pattern:e}),Hc(e.pattern)){let n=jc(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,Ar(Nt(e)?Fc(e):e).forEach(this._add,this),this._added}test(e,n,o){let r=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&r!==s||c&&!r&&!s&&!n||!l[o].test(e)||(r=!c,s=c,i=c?wc:l)});let a={ignored:r,unignored:s};return i&&(a.rule=i),a}},Bc=(t,e)=>{throw new e(t)},Me=(t,e,n)=>Nt(t)?t?Me.isNotRelative(t)?n(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${e}\``,TypeError),Ir=t=>Pc.test(t);Me.isNotRelative=Ir;Me.convert=t=>t;var An=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:o=!1}={}){Ye(this,Pr,!0),this._rules=new bn(n),this._strictPathCheck=!o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,n,o,r){let s=e&&Me.convert(e);return Me(s,e,this._strictPathCheck?Bc:Rr),this._t(s,n,o,r)}checkIgnore(e){if(!Rc.test(e))return this.test(e);let n=e.split(Je).filter(Boolean);if(n.pop(),n.length){let o=this._t(n.join(Je)+Je,this._testCache,!0,n);if(o.ignored)return o}return this._rules.test(e,!1,Ot)}_t(e,n,o,r){if(e in n)return n[e];if(r||(r=e.split(Je).filter(Boolean)),r.pop(),!r.length)return n[e]=this._rules.test(e,o,pt);let s=this._t(r.join(Je)+Je,n,o,r);return n[e]=s.ignored?s:this._rules.test(e,o,pt)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Ar(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Mn=t=>new An(t),Wc=t=>Me(t&&Me.convert(t),t,Rr),$r=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Me.convert=t;let e=/^[a-z]:\//i;Me.isNotRelative=n=>e.test(n)||Ir(n)};typeof process<"u"&&process.platform==="win32"&&$r();Dt.exports=Mn;Mn.default=Mn;Dt.exports.isPathValid=Wc;Ye(Dt.exports,Symbol.for("setupWindows"),$r)});import{randomUUID as hs}from"crypto";import{createInterface as pp}from"readline/promises";import{stdin as mp,stdout as dp}from"process";import{render as fp}from"ink";import Ls from"os";import{readFile as Os}from"fs/promises";import{join as Ns,dirname as Ds}from"path";import{fileURLToPath as Us}from"url";var Hs=/{{\s*([\w.-]+)\s*}}/g;function Fs(t,e){return t.replace(Hs,(n,o)=>e[o]??"")}function js(){try{return Ls.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function qn(){let t=Ds(Us(import.meta.url)),e=Ns(t,"prompt.md"),n=await Os(e,"utf-8"),o={date:new Date().toISOString(),user:js(),pwd:process.cwd()};return Fs(n,o)}import{appendFile as Bs,mkdir as Ws}from"fs/promises";import{dirname as Vs}from"path";var Ct=class{constructor(e){this.filePath=e}ready=!1;async append(e){this.ready||(await Ws(Vs(this.filePath),{recursive:!0}),this.ready=!0),await Bs(this.filePath,`${JSON.stringify(e)}
3
+ `,"utf8")}async flush(){return Promise.resolve()}};function Xn(t){return{ts:new Date().toISOString(),sessionId:t.sessionId,turn:t.turn,step:t.step,type:t.type,content:t.content,role:t.role,meta:t.meta}}import{z as we}from"zod";function O(t){let{inputSchema:e,execute:n,...o}=t,r=e.toJSONSchema?.(),{$schema:s,...i}=r??{};return{...o,source:"native",inputSchema:i,validateInput:a=>{let l=e.safeParse(a);if(!l.success){let c=l.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${t.name} invalid input: ${c}`}}return{ok:!0,data:l.data}},execute:n}}function m(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}import{spawn as zs}from"child_process";import{EventEmitter as Gs}from"events";import{resolve as Ks}from"path";var qs=1e4,Xs=250,Js=2e3,Jn=64;function Ys(t){return Math.ceil(t.length/4)}function Zs(){return Math.random().toString(16).slice(2)||String(Date.now())}function Qs(t){let e=t.login,n=t.shell?.trim();if(process.platform==="win32"){let r=n||"powershell.exe";return r.toLowerCase().includes("powershell")?{file:r,args:["-NoProfile","-Command",t.cmd]}:{file:r,args:[e?"-lc":"-c",t.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[e?"-lc":"-c",t.cmd]}}function ei(t,e){let o=(typeof e=="number"&&e>0?Math.floor(e):Js)*4,r=Ys(t);return t.length<=o?{output:t,originalTokenCount:r}:{output:t.slice(0,o),originalTokenCount:r}}function ti(t){let e=[];return e.push(`Chunk ID: ${t.chunkId}`),e.push(`Wall time: ${t.wallTimeSeconds.toFixed(4)} seconds`),t.exitCode!==null?e.push(`Process exited with code ${t.exitCode}`):e.push(`Process running with session ID ${t.sessionId}`),e.push(`Original token count: ${t.originalTokenCount}`),e.push("Output:"),e.push(t.output),e.join(`
4
+ `)}function Yn(t,e){return typeof t!="number"||Number.isNaN(t)?e:t<0?0:Math.floor(t)}async function Zn(t,e){e<=0||t.exited||await Promise.race([new Promise(n=>{let o=setTimeout(()=>{s(),n()},e),r=()=>{clearTimeout(o),s(),n()},s=()=>{t.eventBus.off("exit",r)};t.eventBus.on("exit",r)})])}var Yt=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Jn)return;let e=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,o)=>n.startedAtMs-o.startedAtMs);for(let n of e){if(this.sessions.size<=Jn)break;this.sessions.delete(n.id)}}async start(e){let n=e.cmd.trim();if(!n)throw new Error("cmd must not be empty");let o=this.nextId++,r=Date.now(),s=Qs({cmd:n,shell:e.shell,login:e.login!==!1}),i=e.workdir?.trim()?Ks(process.cwd(),e.workdir.trim()):process.cwd(),a=zs(s.file,s.args,{cwd:i,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),l={id:o,output:"",readOffset:0,startedAtMs:r,exited:!1,exitCode:null,eventBus:new Gs,proc:a},c=(p,T)=>{let y=typeof T=="string"?T:T.toString("utf8");l.output+=p?`${p}${y}`:y,l.eventBus.emit("output")};a.stdout?.on("data",p=>c("",p)),a.stderr?.on("data",p=>c("",p)),a.on("error",p=>{l.output+=`
5
+ [exec error] ${p.message}`,l.eventBus.emit("output")}),a.on("close",p=>{l.exited=!0,l.exitCode=typeof p=="number"?p:-1,l.eventBus.emit("exit")}),this.sessions.set(o,l),this.cleanupSessions();let u=Yn(e.yield_time_ms,qs);return await Zn(l,u),this.buildResponseText(l,e.max_output_tokens)}async write(e){let n=this.sessions.get(e.session_id);if(!n)throw new Error(`session_id ${e.session_id} not found`);!n.exited&&e.chars&&e.chars.length>0&&n.proc.stdin?.write(e.chars);let o=Yn(e.yield_time_ms,Xs);return await Zn(n,o),this.buildResponseText(n,e.max_output_tokens)}buildResponseText(e,n){let o=e.output.slice(e.readOffset);e.readOffset=e.output.length;let r=ei(o,n),s={sessionId:e.id,chunkId:Zs(),wallTimeSeconds:(Date.now()-e.startedAtMs)/1e3,exitCode:e.exited?e.exitCode:null,output:r.output,originalTokenCount:r.originalTokenCount};return ti(s)}},Qn=new Yt;async function We(t){return Qn.start(t)}async function eo(t){return Qn.write(t)}var ni=we.object({command:we.array(we.string().min(1)).min(1,"command \u4E0D\u80FD\u4E3A\u7A7A"),workdir:we.string().optional(),timeout_ms:we.number().int().positive().optional(),sandbox_permissions:we.enum(["use_default","require_escalated"]).optional(),justification:we.string().optional(),prefix_rule:we.array(we.string().min(1)).optional()}).strict();function oi(t){return t.map(e=>/^[A-Za-z0-9_./:@%+-]+$/.test(e)?e:JSON.stringify(e)).join(" ")}var to=O({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:ni,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,timeout_ms:n})=>{try{let o=await We({cmd:oi(t),workdir:e,login:!1,yield_time_ms:n});return m(o)}catch(o){return m(`shell failed: ${o.message}`,!0)}}});import{z as Ee}from"zod";var ri=Ee.object({command:Ee.string().min(1,"command \u4E0D\u80FD\u4E3A\u7A7A"),workdir:Ee.string().optional(),login:Ee.boolean().optional(),timeout_ms:Ee.number().int().positive().optional(),sandbox_permissions:Ee.enum(["use_default","require_escalated"]).optional(),justification:Ee.string().optional(),prefix_rule:Ee.array(Ee.string().min(1)).optional()}).strict(),no=O({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:ri,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,login:n,timeout_ms:o})=>{try{let r=await We({cmd:t,workdir:e,login:n,yield_time_ms:o});return m(r)}catch(r){return m(`shell_command failed: ${r.message}`,!0)}}});import{z as me}from"zod";var si=me.object({cmd:me.string().min(1,"cmd \u4E0D\u80FD\u4E3A\u7A7A"),workdir:me.string().optional(),shell:me.string().optional(),login:me.boolean().optional(),tty:me.boolean().optional(),yield_time_ms:me.number().int().nonnegative().optional(),max_output_tokens:me.number().int().positive().optional(),sandbox_permissions:me.enum(["use_default","require_escalated"]).optional(),justification:me.string().optional(),prefix_rule:me.array(me.string().min(1)).optional()}).strict(),Zt=O({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:si,supportsParallelToolCalls:!0,isMutating:!0,execute:async t=>{try{let e=await We(t);return m(e)}catch(e){return m(`exec_command failed: ${e.message}`,!0)}}});import{z as tt}from"zod";var ii=tt.object({session_id:tt.number().int().positive(),chars:tt.string().optional(),yield_time_ms:tt.number().int().nonnegative().optional(),max_output_tokens:tt.number().int().positive().optional()}).strict(),Qt=O({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:ii,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await eo(t);return m(e)}catch(e){return m(`write_stdin failed: ${e.message}`,!0)}}});import{mkdir as go,readFile as Li,rm as ho,writeFile as an}from"fs/promises";import{dirname as yo}from"path";import{z as To}from"zod";var Pi=Kn(po(),1);import{normalize as wi,resolve as Ei,dirname as sm,join as ki,relative as bi,isAbsolute as Ai}from"path";import{homedir as Mi}from"os";import{existsSync as lm,statSync as cm}from"fs";import{readFile as pm}from"fs/promises";function de(t){return wi(Ei(t))}function Ri(t,e){let n=bi(e,t);return n===""||!n.startsWith("..")&&!Ai(n)}function Ii(){let t=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>de(e)):[]}function mo(){let t=new Set;t.add(de(process.cwd()));let e=process.env.MEMO_HOME?.trim()||ki(Mi(),".memo");t.add(de(e));for(let n of Ii())t.add(n);return Array.from(t)}function $i(t){return mo().some(n=>Ri(t,n))}function fo(t){if($i(t))return null;let e=mo();return`sandbox \u62D2\u7EDD\u5199\u5165: ${t} \u4E0D\u5728\u5141\u8BB8\u76EE\u5F55\u5185 (${e.join(", ")})`}var Oi=To.object({input:To.string().min(1,"patch input \u4E0D\u80FD\u4E3A\u7A7A")}).strict();function Ni(t){let e=t.replace(/\r/g,"").split(`
6
+ `);if(e[0]!=="*** Begin Patch")throw new Error("patch must start with *** Begin Patch");let n=[],o=1;for(;o<e.length;){let r=e[o]??"";if(r==="*** End Patch")break;if(!r){o+=1;continue}if(r.startsWith("*** Add File: ")){let s=r.slice(14).trim();if(!s)throw new Error("Add File requires a path");o+=1;let i=[];for(;o<e.length;){let a=e[o];if(a===void 0||a.startsWith("*** "))break;if(!a.startsWith("+"))throw new Error("Add File lines must start with +");i.push(a.slice(1)),o+=1}n.push({type:"add",file:s,lines:i});continue}if(r.startsWith("*** Delete File: ")){let s=r.slice(17).trim();if(!s)throw new Error("Delete File requires a path");n.push({type:"delete",file:s}),o+=1;continue}if(r.startsWith("*** Update File: ")){let s=r.slice(17).trim();if(!s)throw new Error("Update File requires a path");o+=1;let i,a=e[o];a&&a.startsWith("*** Move to: ")&&(i=a.slice(13).trim(),o+=1);let l=[],c=[];for(;o<e.length;){let u=e[o];if(u===void 0||u.startsWith("*** "))break;if(u.startsWith("@@")){c.length>0&&(l.push(c),c=[]),o+=1;continue}if(u==="*** End of File"){o+=1;continue}if(u.startsWith("+")||u.startsWith("-")||u.startsWith(" ")){c.push(u),o+=1;continue}throw new Error(`Unexpected patch line: ${u}`)}if(c.length>0&&l.push(c),l.length===0)throw new Error(`Update File ${s} has no hunks`);n.push({type:"update",file:s,moveTo:i,hunks:l});continue}throw new Error(`Unexpected patch marker: ${r}`)}if(n.length===0)throw new Error("patch contains no operations");return n}function Di(t,e){let n=e.filter(s=>s.startsWith(" ")||s.startsWith("-")).map(s=>s.slice(1)).join(`
7
+ `),o=e.filter(s=>s.startsWith(" ")||s.startsWith("+")).map(s=>s.slice(1)).join(`
8
+ `);if(!n){if(!o)return t;if(!t)return o;let s=t.endsWith(`
9
+ `)?"":`
10
+ `;return`${t}${s}${o}`}let r=t.indexOf(n);if(r<0)throw new Error("patch hunk context not found in target file");return`${t.slice(0,r)}${o}${t.slice(r+n.length)}`}function Et(t){let e=fo(t);if(e)throw new Error(e)}var _o=O({name:"apply_patch",description:"Apply a structured patch with Add/Update/Delete operations and hunk-based replacements.",inputSchema:Oi,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=Ni(t.input);for(let n of e){if(n.type==="add"){let s=de(n.file);Et(s),await go(yo(s),{recursive:!0}),await an(s,n.lines.join(`
11
+ `),"utf8");continue}if(n.type==="delete"){let s=de(n.file);Et(s),await ho(s);continue}let o=de(n.file);Et(o);let r=await Li(o,"utf8");for(let s of n.hunks)r=Di(r,s);if(n.moveTo){let s=de(n.moveTo);Et(s),await go(yo(s),{recursive:!0}),await an(s,r,"utf8"),s!==o&&await ho(o)}else await an(o,r,"utf8")}return m(`apply_patch succeeded (${e.length} operations)`)}catch(e){return m(`apply_patch failed: ${e.message}`,!0)}}});import{readFile as Ui}from"fs/promises";import{z as he}from"zod";var xo=500,So=200,Hi=he.object({file_path:he.string().min(1),offset:he.number().int().positive().optional(),limit:he.number().int().positive().optional(),mode:he.enum(["slice","indentation"]).optional(),indentation:he.object({anchor_line:he.number().int().positive().optional(),max_levels:he.number().int().nonnegative().optional(),include_siblings:he.boolean().optional(),include_header:he.boolean().optional(),max_lines:he.number().int().positive().optional()}).strict().optional()}).strict();function Fi(t){return t.length<=xo?t:t.slice(0,xo)}function ji(t){let e=0;for(let n of t)if(n===" ")e+=1;else if(n===" ")e+=4;else break;return e}function Bi(t){return t.split(/\r?\n/).map((n,o)=>({line:o+1,text:Fi(n),indent:ji(n)}))}function Wi(t){return t.map(e=>`L${e.line}: ${e.text}`).join(`
12
+ `)}function Vi(t,e,n){let o=e-1;if(o>=t.length)throw new Error("offset exceeds file length");return t.slice(o,o+n)}function zi(t,e){let n=e.offset??1,o=e.limit??So,r=e.indentation,s=r?.anchor_line??n;if(s<=0||s>t.length)throw new Error("anchor_line exceeds file length");let i=t[s-1];if(!i)throw new Error("anchor_line exceeds file length");let a=r?.max_levels??0,l=r?.include_siblings??!0,c=r?.include_header??!0,u=r?.max_lines??o,p=Math.max(1,Math.min(o,u)),T=a===0?0:Math.max(0,i.indent-a*4),y=s-1,S=s-1;for(;y-1>=0;){let h=t[y-1];if(!h)break;let P=/^\s*(#|\/\/|--)/.test(h.text),C=h.text.trim().length===0;if(h.indent<T||!l&&h.indent===T&&!P&&!C||!c&&(P||C)&&h.indent<i.indent||(y-=1,S-y+1>=p))break}for(;S+1<t.length&&S-y+1<p;){let h=t[S+1];if(!h||h.indent<T||!l&&h.indent===T)break;S+=1}return t.slice(y,S+1)}var vo=O({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Hi,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??1,n=t.limit??So;if(e<=0)return m("offset must be a 1-indexed line number",!0);if(n<=0)return m("limit must be greater than zero",!0);let o=t.file_path.trim();if(!o.startsWith("/"))return m("file_path must be an absolute path",!0);let r=de(o);try{let s=await Ui(r,"utf8"),i=Bi(s);if(i.length===0)return m("");let l=(t.mode??"slice")==="indentation"?zi(i,t):Vi(i,e,n);return m(Wi(l))}catch(s){return m(`read_file failed: ${s.message}`,!0)}}});import{readdir as Gi,lstat as Ki}from"fs/promises";import{join as qi}from"path";import{z as nt}from"zod";var Xi=1,Ji=25,Yi=2,Zi=nt.object({dir_path:nt.string().min(1),offset:nt.number().int().positive().optional(),limit:nt.number().int().positive().optional(),depth:nt.number().int().positive().optional()}).strict();function Qi(t){let e=" ".repeat(t.displayDepth*2),n="";t.kind==="dir"&&(n="/"),t.kind==="symlink"&&(n="@"),t.kind==="other"&&(n="?");let o=t.path.split("/"),r=o[o.length-1]??t.path;return`${e}${r}${n}`}var Co=O({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:Zi,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??Xi,n=t.limit??Ji,o=t.depth??Yi;if(e<=0)return m("offset must be a 1-indexed entry number",!0);if(n<=0)return m("limit must be greater than zero",!0);if(o<=0)return m("depth must be greater than zero",!0);let r=t.dir_path.trim();if(!r.startsWith("/"))return m("dir_path must be an absolute path",!0);let s=de(r);try{let i=[{absPath:s,depth:o,displayDepth:0}],a=[];for(;i.length>0;){let p=i.shift();if(!p)continue;let T=await Gi(p.absPath);T.sort((y,S)=>y.localeCompare(S));for(let y of T){let S=qi(p.absPath,y),h=await Ki(S),P=h.isSymbolicLink()?"symlink":h.isDirectory()?"dir":h.isFile()?"file":"other";a.push({path:S,displayDepth:p.displayDepth,kind:P}),P==="dir"&&p.depth>1&&i.push({absPath:S,depth:p.depth-1,displayDepth:p.displayDepth+1})}}if(a.length===0)return m(`Absolute path: ${s}`);let l=e-1;if(l>=a.length)return m("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),u=[`Absolute path: ${s}`,...c.map(Qi)];return l+n<a.length&&u.push(`More than ${n} entries found`),m(u.join(`
13
+ `))}catch(i){return m(`list_dir failed: ${i.message}`,!0)}}});import{spawn as ea}from"child_process";import{resolve as ta}from"path";import{z as ot}from"zod";var na=100,oa=2e3,ra=3e4,sa=ot.object({pattern:ot.string().min(1),include:ot.string().optional(),path:ot.string().optional(),limit:ot.number().int().positive().optional()}).strict();function ia(t){return new Promise((e,n)=>{let o=["--files-with-matches","--sortr=modified","--regexp",t.pattern,"--no-messages"];t.include?.trim()&&o.push("--glob",t.include.trim()),o.push("--",t.searchPath);let r=ea("rg",o,{cwd:t.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>s.push(l)),r.stderr?.on("data",l=>i.push(l));let a=setTimeout(()=>{r.kill("SIGTERM"),n(new Error("rg timed out after 30 seconds"))},ra);r.on("error",l=>{clearTimeout(a),n(l)}),r.on("close",l=>{clearTimeout(a),e({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var wo=O({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:sa,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.pattern.trim();if(!e)return m("pattern must not be empty",!0);let n=Math.min(t.limit??na,oa),o=t.path?.trim()?ta(process.cwd(),t.path.trim()):process.cwd();try{let r=await ia({pattern:e,include:t.include,searchPath:o,cwd:process.cwd(),limit:n});if(r.exitCode===1)return m("No matches found.");if(r.exitCode!==0)return m(`rg failed: ${r.stderr||r.stdout}`,!0);let s=r.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,n);return s.length===0?m("No matches found."):m(s.join(`
14
+ `))}catch(r){return m(`grep_files failed: ${r.message}`,!0)}}});import{z as be}from"zod";var Eo=null;function ln(t){Eo=t}function ko(){return Eo}var aa=be.object({server:be.string().optional(),cursor:be.string().optional()}).strict(),la=be.object({server:be.string().optional(),cursor:be.string().optional()}).strict(),ca=be.object({server:be.string().min(1),uri:be.string().min(1)}).strict();function cn(){let t=ko();if(!t)throw new Error("MCP pool is not initialized");return t}var bo=O({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:aa,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=cn();if(t?.trim()){let s=n.get(t.trim());if(!s)return m(`MCP server not found: ${t}`,!0);let i=await s.client.listResources(e?{cursor:e}:void 0);return m(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(e)return m("cursor is only supported when server is specified",!0);let o=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),r=[];for(let s of o){let i=await s.client.listResources();for(let a of i.resources)r.push({server:s.name,...a})}return m(JSON.stringify({resources:r},null,2))}catch(n){return m(`list_mcp_resources failed: ${n.message}`,!0)}}}),Ao=O({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:la,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=cn();if(t?.trim()){let s=n.get(t.trim());if(!s)return m(`MCP server not found: ${t}`,!0);let i=await s.client.listResourceTemplates(e?{cursor:e}:void 0);return m(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(e)return m("cursor is only supported when server is specified",!0);let o=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),r=[];for(let s of o){let i=await s.client.listResourceTemplates();for(let a of i.resourceTemplates)r.push({server:s.name,...a})}return m(JSON.stringify({resourceTemplates:r},null,2))}catch(n){return m(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Mo=O({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:ca,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let o=cn().get(t);if(!o)return m(`MCP server not found: ${t}`,!0);let r=await o.client.readResource({uri:e});return m(JSON.stringify({server:t,uri:e,...r},null,2))}catch(n){return m(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as Ve}from"zod";var ua=Ve.object({step:Ve.string().min(1),status:Ve.enum(["pending","in_progress","completed"])}).strict(),pa=Ve.object({explanation:Ve.string().optional(),plan:Ve.array(ua).min(1)}).strict(),Po=[],Ro=O({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:pa,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>e.filter(o=>o.status==="in_progress").length>1?m("At most one step can be in_progress at a time",!0):(Po=e,m(JSON.stringify({message:"Plan updated",explanation:t,plan:Po},null,2)))});import{readFile as ma}from"fs/promises";import{homedir as da}from"os";import{join as Io}from"path";import{z as $o}from"zod";var fa=$o.object({memory_id:$o.string().min(1)}).strict();function ga(){let t=process.env.MEMO_HOME?.trim()||Io(da(),".memo");return Io(t,"Agents.md")}var Lo=O({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:fa,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=ga(),n=await ma(e,"utf8");return m(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return m(`memory not found for memory_id=${t}`,!0)}}});import{z as Oo}from"zod";var ha=Oo.object({url:Oo.string().min(1)}).strict(),No=1e4,rt=512e3,un=4e3,ya=new Set(["http:","https:","data:"]),Ta=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,_a=/<\s*(br|hr)\s*\/?>/gi,xa=/<\s*li[^>]*>/gi,Sa=/<[^>]+>/g,va=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Ca=t=>t.replace(/&nbsp;/gi," ").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&amp;/gi,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(o,r)=>{try{let s=r.startsWith("x")||r.startsWith("X")?parseInt(r.slice(1),16):parseInt(r,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),wa=t=>{let o=t.replace(va," ").replace(xa,"- ").replace(_a,`
15
+ `).replace(Ta,`
16
+ `).replace(Sa," "),s=Ca(o).replace(/\r/g,"").split(`
17
+ `).map(a=>a.trim().replace(/[ \t]{2,}/g," "));return s.filter((a,l)=>a.length>0||l>0&&(s[l-1]?.length??0)>0).join(`
18
+ `).trim()},Ea=t=>t.replace(/\s+/g," ").trim(),Do=O({name:"webfetch",description:"HTTP GET \u8BF7\u6C42\uFF0C\u8FD4\u56DE\u5904\u7406\u540E\u7684\u7EAF\u6587\u672C\u6B63\u6587\uFF08\u81EA\u52A8\u5265\u79BB HTML \u6807\u7B7E\uFF09",inputSchema:ha,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return m(`\u65E0\u6548 URL: ${t.url}`,!0)}if(!ya.has(e.protocol))return m(`\u4E0D\u652F\u6301\u7684\u534F\u8BAE: ${e.protocol}`,!0);let n=new AbortController,o=setTimeout(()=>n.abort(),No);try{let r=await globalThis.fetch(e,{signal:n.signal}),s=r.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>rt)return m(`\u8BF7\u6C42\u88AB\u62D2\u7EDD: \u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${i} bytes\uFF09`,!0);let a=0,l="";if(r.body&&r.body.getReader){let P=r.body.getReader(),C=[];for(;;){let{done:A,value:M}=await P.read();if(A)break;if(M){if(a+=M.byteLength,a>rt)return n.abort(),m(`\u8BF7\u6C42\u88AB\u4E2D\u6B62: \u54CD\u5E94\u4F53\u8D85\u8FC7 ${rt} bytes`,!0);C.push(M)}}let x=new Uint8Array(a),b=0;for(let A of C)x.set(A,b),b+=A.byteLength;l=new TextDecoder().decode(x)}else if(l=await r.text(),a=new TextEncoder().encode(l).byteLength,a>rt)return m(`\u8BF7\u6C42\u88AB\u62D2\u7EDD: \u54CD\u5E94\u4F53\u8D85\u8FC7 ${rt} bytes`,!0);let c=r.headers.get("content-type")||"",u=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),p=u?wa(l):l.trim(),T=Ea(p),y=T.length>un?`${T.slice(0,un)}...`:T,S=T.length>un?" text_truncated=true":"",h=u?" source=html_stripped":"";return m(`status=${r.status} bytes=${a} text_chars=${T.length} text="${y}"${S}${h}`)}catch(r){return r.name==="AbortError"?m(`\u8BF7\u6C42\u8D85\u65F6\u6216\u88AB\u4E2D\u6B62\uFF08${No}ms\uFF09`,!0):m(`\u8BF7\u6C42\u5931\u8D25: ${r.message}`,!0)}finally{clearTimeout(o)}}});import{spawn as ka}from"child_process";import{existsSync as ba}from"fs";import{resolve as Aa}from"path";import{z as ne}from"zod";var Ma=3e4,Pa=1e4,Ra=3e5,Uo=4,Ia=1500,Ho=2e3,$e=new Map,$a=ne.object({message:ne.string().min(1),agent_type:ne.string().optional()}).strict(),La=ne.object({id:ne.string().min(1),message:ne.string().min(1),interrupt:ne.boolean().optional()}).strict(),Oa=ne.object({id:ne.string().min(1)}).strict(),Na=ne.object({ids:ne.array(ne.string().min(1)).min(1),timeout_ms:ne.number().int().positive().optional()}).strict(),Da=ne.object({id:ne.string().min(1)}).strict();function ze(){return new Date().toISOString()}function pn(t){return m(`agent not found: ${t}`,!0)}function Ua(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return Uo;let e=Number(t);return!Number.isFinite(e)||e<=0?Uo:Math.floor(e)}function Ha(){let t=0;for(let e of $e.values())e.running&&(t+=1);return t}function Fa(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=Aa(process.cwd(),"dist/index.js");return ba(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function ja(t){return t!=="running"}function Ba(t){return new Promise(e=>{setTimeout(e,t)})}function Wa(t){return t===void 0?Ma:t<=0?null:Math.max(Pa,Math.min(Ra,t))}function Va(t){return t.length<=Ho?t:`${t.slice(0,Ho)}
19
+ ...[truncated]`}function za(t,e){let n=[],o=t.trim(),r=e.trim();return o&&n.push(o),r&&n.push(`stderr:
20
+ ${r}`),Va(n.join(`
21
+
22
+ `))}async function Fo(t){let e=t.running;if(!e)return;e.interrupted=!0;let n=e.process;n.exitCode!==null||n.killed||await new Promise(o=>{let r=!1,s=()=>{r||(r=!0,clearTimeout(i),n.off("close",s),o())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},Ia);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function Ga(t){let e=$e.get(t);return e?e.status:"not_found"}function Ka(t){let e=$e.get(t);return e?{status:e.status,last_message:e.lastMessage,last_output:e.lastOutput,last_error:e.lastError,last_submission_id:e.lastSubmissionId,updated_at:e.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function qa(t){return{agent_id:t.id,status:t.status,created_at:t.createdAt,updated_at:t.updatedAt,last_message:t.lastMessage,last_submission_id:t.lastSubmissionId,has_last_output:!!t.lastOutput,has_last_error:!!t.lastError}}function Xa(t){let{record:e,submissionId:n,stdout:o,stderr:r,exitCode:s,interrupted:i}=t;if(!(!e.running||e.running.id!==n)&&(e.running=null,e.updatedAt=ze(),e.lastOutput=za(o,r)||null,e.lastError=null,e.status!=="closed")){if(i){e.status="errored",e.lastError="interrupted",e.statusBeforeClose="errored";return}if(s===0){e.status="completed",e.statusBeforeClose="completed";return}e.status="errored",e.lastError=`submission failed with exit code ${s}`,e.statusBeforeClose="errored"}}async function jo(t,e){let n=Ua();if(Ha()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let o=crypto.randomUUID(),r=Fa(),s=ka(r,{cwd:process.cwd(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],a=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",l=>i.push(l)),s.stderr?.on("data",l=>a.push(l)),s.on("error",l=>{a.push(`[spawn error] ${l.message}`)}),t.running={id:o,message:e,process:s,startedAt:ze(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=o,t.updatedAt=ze(),s.on("close",l=>{let c=typeof l=="number"?l:-1,u=!!(t.running?.id===o&&t.running.interrupted);Xa({record:t,submissionId:o,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:u})});try{s.stdin?.write(`${e.trim()}
23
+ `)}catch{}try{s.stdin?.end()}catch{}return o}var Bo=O({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:$a,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return m("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),o=ze(),r={id:n,createdAt:o,updatedAt:o,status:"running",statusBeforeClose:"completed",lastMessage:e,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};$e.set(n,r);try{let s=await jo(r,e);return m(JSON.stringify({...qa(r),submission_id:s},null,2))}catch(s){return $e.delete(n),m(`spawn_agent failed: ${s.message}`,!0)}}}),Wo=O({name:"send_input",description:"Send a message to an existing agent.",inputSchema:La,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let o=$e.get(t);if(!o)return pn(t);let r=e.trim();if(!r)return m("send_input failed: message must not be empty",!0);if(o.status==="closed")return m(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(o.running){if(!n)return m(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await Fo(o)}try{let s=await jo(o,r);return m(JSON.stringify({agent_id:o.id,status:o.status,submission_id:s},null,2))}catch(s){return m(`send_input failed: ${s.message}`,!0)}}}),Vo=O({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Oa,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=$e.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=ze()),m(JSON.stringify({agent_id:t,status:e.status},null,2))):pn(t)}}),zo=O({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Na,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=Wa(e);if(n===null)return m("wait failed: timeout_ms must be greater than zero",!0);let o=()=>{let i={},a={};for(let l of t){let c=Ga(l);ja(c)&&(i[l]=c,a[l]=Ka(l))}return{status:i,details:a}},r=o();if(Object.keys(r.status).length>0)return m(JSON.stringify({status:r.status,details:r.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await Ba(100),r=o(),Object.keys(r.status).length>0)return m(JSON.stringify({status:r.status,details:r.details,timed_out:!1},null,2));return m(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),Go=O({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Da,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=$e.get(t);return e?e.status==="closed"?m(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=ze(),await Fo(e),m(JSON.stringify({agent_id:t,status:"closed"},null,2))):pn(t)}});var mn={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_file:"read",list_dir:"read",grep_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},Ko=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]);var kt={read:0,write:1,execute:2},dn={read:t=>`${t} \u5C06\u8BFB\u53D6\u6587\u4EF6\u6216\u6570\u636E`,write:t=>`${t} \u5C06\u4FEE\u6539\u6216\u521B\u5EFA\u6587\u4EF6`,execute:t=>`${t} \u5C06\u6267\u884C\u7CFB\u7EDF\u547D\u4EE4`};function fn(t){let e={...mn,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let o=n.toLowerCase();return o.includes("exec")||o.includes("run")||o.includes("shell")||o.includes("command")||o.includes("stdin")?"execute":o.includes("write")||o.includes("patch")||o.includes("create")||o.includes("delete")||o.includes("modify")||o.includes("update")?"write":o.includes("read")||o.includes("get")||o.includes("fetch")||o.includes("search")||o.includes("list")||o.includes("find")?"read":"write"},compareRisk(n,o){return kt[n]-kt[o]},needsApproval(n,o){return o==="strict"?!0:n==="write"||n==="execute"}}}import{createHash as Ja}from"crypto";function bt(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>bt(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${bt(o)}`).join(",")}}`}function gn(t,e){let n=bt(e),o=`${t}:${n}`;return Ja("sha256").update(o).digest("hex").slice(0,16)}function hn(t){let{mode:e="auto",dangerous:n=!1,toolRiskLevels:o}=t||{},r=e==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=fn({customLevels:o}),i={session:new Set,once:new Set,denied:new Set};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(Ko.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,r))return{needApproval:!1,decision:"auto-execute"};let u=gn(a,l);return i.session.has(u)||i.once.has(u)?{needApproval:!1,decision:"auto-execute"}:i.denied.has(u)?{needApproval:!0,fingerprint:u,riskLevel:c,reason:"\u8BE5\u8BF7\u6C42\u5DF2\u88AB\u62D2\u7EDD",toolName:a,params:l}:{needApproval:!0,fingerprint:u,riskLevel:c,reason:dn[c](a),toolName:a,params:l}},recordDecision(a,l){switch(i.session.delete(a),i.once.delete(a),i.denied.delete(a),l){case"session":i.session.add(a);break;case"once":i.once.add(a);break;case"deny":i.denied.add(a);break}},isGranted(a){return i.session.has(a)||i.once.has(a)},clearOnceApprovals(){i.once.clear()},dispose(){i.session.clear(),i.once.clear(),i.denied.clear()}}}var qo=12e3;function Ya(){let t=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!t)return qo;let e=Number(t);return!Number.isFinite(e)||e<=0?qo:Math.floor(e)}function Za(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qa(t){let e=0;for(let n of t.content??[]){if(n.type==="text"){e+=n.text.length;continue}try{e+=JSON.stringify(n).length}catch{e+=100}}return e}function el(t,e,n){return`<system_hint type="tool_output_omitted" tool="${Za(t)}" reason="too_long" actual_chars="${e}" max_chars="${n}">\u5DE5\u5177\u8FD4\u56DE\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u81EA\u52A8\u7701\u7565\u3002\u8BF7\u7F29\u5C0F\u8303\u56F4\u6216\u589E\u52A0\u9650\u5236\u53C2\u6570\u540E\u91CD\u8BD5\u3002</system_hint>`}function tl(t,e){let n=Ya(),o=Qa(e);return o<=n?e:{content:[{type:"text",text:el(t,o,n)}],isError:!1}}function nl(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
24
+ `)}function ol(t,e){let n=e;if(typeof e=="string"){let o=e.trim();if(o)try{n=JSON.parse(o)}catch{n=o}else n={}}return typeof n!="object"||n===null?{ok:!1,error:`${t.name} invalid input: expected object`}:typeof t.validateInput=="function"?t.validateInput(n):{ok:!0,data:n}}function rl(t){let e=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return e.includes("sandbox")||e.includes("permission denied")||e.includes("operation not permitted")||e.includes("eacces")?"sandbox_denied":"execution_failed"}var yn=class{constructor(e){this.config=e;this.approvalManager=hn(e.approval)}approvalManager;async executeAction(e,n){let o=Date.now(),r=e.id??`${e.name}:${o}`,s=this.approvalManager.check(e.name,e.input);if(s.needApproval){let a={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(a);let l=n?.requestApproval?await n.requestApproval(a):"deny";if(this.approvalManager.recordDecision(s.fingerprint,l),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:l}),l==="deny")return{actionId:r,tool:e.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C: ${e.name}`,durationMs:Date.now()-o,rejected:!0}}let i=this.config.tools[e.name];if(!i)return{actionId:r,tool:e.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${e.name}`,durationMs:Date.now()-o};try{let a=ol(i,e.input);if(!a.ok)return{actionId:r,tool:e.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-o};let l=await i.execute(a.data),c=tl(e.name,l);return{actionId:r,tool:e.name,status:"success",success:!0,observation:nl(c)||"(no tool output)",durationMs:Date.now()-o}}catch(a){let l=rl(a);return{actionId:r,tool:e.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-o}}}async executeActions(e,n={}){let o=n.executionMode??"sequential",r=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(o==="parallel"){let l=await Promise.all(e.map(c=>this.executeAction(c,n)));if(r==="fail_fast"){let c=l.findIndex(u=>u.rejected);s=c>=0?l.slice(0,c+1):l}else s=l}else for(let l of e){let c=await this.executeAction(l,n);if(s.push(c),c.rejected&&r==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
25
+
26
+ `);return{results:s,combinedObservation:a,hasRejection:i,executionMode:o,failurePolicy:r}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function Xo(t){return new yn(t)}var At=class{tools=new Map;register(e){this.tools.set(e.name,e)}registerMany(e){for(let n of e)this.register(n)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,o]of this.tools)e[n]=o;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}};import{Client as sl}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as il}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as al}from"@modelcontextprotocol/sdk/client/stdio.js";function ll(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(o=>typeof o[1]=="string");return Object.fromEntries(n)}function Jo(){return new sl({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function cl(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function ul(t){let e={...t.http_headers??t.headers??{}};if(t.bearer_token_env_var){let n=process.env[t.bearer_token_env_var];n&&!e.Authorization&&(e.Authorization=`Bearer ${n}`)}return e}async function pl(t){let e=new URL(t.url),n=cl(ul(t));try{let o=Jo(),r=new il(e,{requestInit:n});return await o.connect(r),{client:o,transport:r}}catch(o){let r=`Failed to connect via streamable_http (${o.message})`,s=new Error(r);throw s.cause=o,s}}async function ml(t){if("url"in t)return pl(t);let e={command:t.command,args:t.args,env:ll(t.env),stderr:t.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new al(e),o=Jo();return await o.connect(n),{client:o,transport:n}}var Mt=class{connections=new Map;async connect(e,n){let o=this.connections.get(e);if(o)return o;let{client:r,transport:s}=await ml(n),i=await r.listTools(),a={name:e,client:r,transport:s,tools:(i.tools||[]).map(l=>({name:`${e}_${l.name}`,description:l.description||`Tool from ${e}: ${l.name}`,source:"mcp",serverName:e,originalName:l.name,inputSchema:l.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(e,a),a}get(e){return this.connections.get(e)}getAll(){return Array.from(this.connections.values())}getAllTools(){let e=[];for(let n of this.connections.values())for(let o of n.tools)e.push({name:o.name,description:o.description,serverName:o.serverName,originalName:o.originalName,inputSchema:o.inputSchema,client:n.client});return e}async closeAll(){let e=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(o){console.error(`[MCP] Error closing client ${n.name}:`,o)}});await Promise.all(e),this.connections.clear()}get size(){return this.connections.size}};var Pt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new Mt,ln(this.pool),this.shouldLog=process.env.MEMO_MCP_LOG==="1"||!(process.stdout.isTTY&&process.stdin.isTTY)}async loadServers(e){if(!e||Object.keys(e).length===0)return 0;let n=0;return await Promise.all(Object.entries(e).map(async([o,r])=>{try{let s=await this.pool.connect(o,r);for(let i of s.tools){let a={...i,execute:async l=>{let c=this.pool.get(i.serverName)?.client;if(!c)throw new Error(`MCP client for server '${i.serverName}' not found`);return c.callTool({name:i.originalName,arguments:l})}};this.tools.set(a.name,a)}n+=s.tools.length,this.shouldLog&&console.log(`[MCP] Connected to '${o}' with ${s.tools.length} tools`)}catch(s){this.shouldLog&&console.error(`[MCP] Failed to connect to server '${o}':`,s)}})),n}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,o]of this.tools)e[n]=o;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),ln(null)}getPool(){return this.pool}};var Rt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new At,this.mcpRegistry=new Pt}registerNativeTool(e){this.nativeRegistry.register(e)}registerNativeTools(e){for(let n of e)this.registerNativeTool(n)}async loadMcpServers(e){return this.mcpRegistry.loadServers(e)}getTool(e){return this.nativeRegistry.get(e)??this.mcpRegistry.get(e)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(e){return this.nativeRegistry.has(e)||this.mcpRegistry.has(e)}getToolCount(){let e=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:e,mcp:n,total:e+n}}async execute(e,n){let o=this.getTool(e);if(!o)throw new Error(`Tool '${e}' not found`);return o.execute(n)}generateToolDefinitions(){return this.getAllTools().map(e=>({name:e.name,description:e.description,input_schema:e.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let e=this.getAllTools();if(e.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let o=e.filter(s=>s.source==="native"),r=e.filter(s=>s.source==="mcp");if(o.length>0){n.push("### Built-in Tools"),n.push("");for(let s of o)n.push(this.formatToolDescription(s));n.push("")}if(r.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(r);for(let[i,a]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let l of a)n.push(this.formatToolDescription(l));n.push("")}}return n.join(`
27
+ `)}formatToolDescription(e){let n=[];return n.push(`#### ${e.name}`),n.push(`- **Description**: ${e.description}`),e.inputSchema&&Object.keys(e.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(e.inputSchema)}`),n.join(`
28
+ `)}groupByServer(e){let n={};for(let o of e)if(o.source==="mcp"){let r=o.serverName;n[r]||(n[r]=[]),n[r].push(o)}return n}getToolDescriptions(){return this.getAllTools().map(e=>({name:e.name,description:e.description,source:e.source,serverName:e.source==="mcp"?e.serverName:void 0,inputSchema:e.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};function dl(t){let e=process.env[t]?.trim();return e?new Set(e.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function fl(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=dl("MEMO_EXPERIMENTAL_TOOLS"),o=n.size===0,r=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return e==="shell"?t.push(to):e==="shell_command"?t.push(no):e==="unified_exec"?t.push(Zt,Qt):e!=="disabled"&&t.push(Zt,Qt),t.push(bo,Ao,Mo),t.push(Ro),t.push(_o),(o||n.has("grep_files"))&&t.push(wo),(o||n.has("read_file"))&&t.push(vo),(o||n.has("list_dir"))&&t.push(Co),s&&t.push(Lo),t.push(Do),r&&t.push(Bo,Wo,Vo,zo,Go),t}function gl(t){let e={};for(let n of t)e[n.name]=n;return e}var hl=gl(fl()),yl=Object.values(hl),Yo=yl;import $l from"openai";import{encoding_for_model as Tl,get_encoding as _l}from"@dqbd/tiktoken";var Zo="cl100k_base";function xl(t){let e=t?.trim()||Zo;try{let n=()=>Tl(e);return n().free(),{model:e,factory:n}}catch{let n=Zo,o=()=>_l(n);return o().free(),{model:n,factory:o}}}function Sl(t){return t.role==="assistant"&&t.tool_calls?.length?`${t.content}
29
+ ${JSON.stringify(t.tool_calls)}`:t.role==="tool"?`${t.content}
30
+ ${t.tool_call_id}
31
+ ${t.name??""}`:t.content}function Qo(t){let{model:e,factory:n}=xl(t),o=n(),r=4,s=2,i=1,a=c=>c?o.encode(c).length:0;return{model:e,countText:a,countMessages:c=>{if(!c.length)return 0;let u=0;for(let p of c)u+=r,u+=a(Sl(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>o.free()}}import{mkdir as vl,writeFile as Cl,readFile as wl,access as El}from"fs/promises";import{homedir as er}from"os";import{dirname as kl,join as it}from"path";import{randomUUID as pf}from"crypto";import{parse as bl}from"toml";var Al=it(er(),".memo"),Ml="sessions",st={current_provider:"deepseek",max_prompt_tokens:12e4,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function Pl(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function Rl(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=[];for(let[n,o]of Object.entries(t)){if(!o)continue;let r=Array.isArray(o)?o:[o];for(let s of r){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),e.push(i)}}return e}function tr(t){return t.startsWith("~")?it(er(),t.slice(1)):t}function Il(t){let e=t.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${Pl(i)}]]`,`name = ${JSON.stringify(i)}`,`env_api_key = ${JSON.stringify(String(s.env_api_key??""))}`,`model = ${JSON.stringify(String(s.model??""))}`];return s.base_url&&l.push(`base_url = ${JSON.stringify(String(s.base_url))}`),l.join(`
20
32
  `)}).filter(Boolean).join(`
21
33
 
22
- `),n="";e.mcp_servers&&Object.keys(e.mcp_servers).length>0&&(n=Object.entries(e.mcp_servers).map(([s,i])=>{if("url"in i){let y=[`[mcp_servers.${s}]`];y.push(`type = "${i.type??"streamable_http"}"`),y.push(`url = "${i.url}"`),"fallback_to_sse"in i&&i.fallback_to_sse!==void 0&&y.push(`fallback_to_sse = ${i.fallback_to_sse}`),i.bearer_token_env_var&&y.push(`bearer_token_env_var = ${JSON.stringify(i.bearer_token_env_var)}`);let b=i.http_headers??i.headers;if(b&&Object.keys(b).length>0){let x=Object.entries(b).map(([_,k])=>`${JSON.stringify(_)} = ${JSON.stringify(k)}`).join(", "),w=i.http_headers?"http_headers":"headers";y.push(`${w} = { ${x} }`)}return y.join(`
23
- `)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",c=i.type?`type = "${i.type}"
24
- `:"",l=i.stderr?`stderr = "${i.stderr}"
34
+ `),n="";t.mcp_servers&&Object.keys(t.mcp_servers).length>0&&(n=Object.entries(t.mcp_servers).map(([s,i])=>{if("url"in i){let y=[`[mcp_servers.${s}]`];y.push(`type = "${i.type??"streamable_http"}"`),y.push(`url = "${i.url}"`),i.bearer_token_env_var&&y.push(`bearer_token_env_var = ${JSON.stringify(i.bearer_token_env_var)}`);let S=i.http_headers??i.headers;if(S&&Object.keys(S).length>0){let h=Object.entries(S).map(([C,x])=>`${JSON.stringify(C)} = ${JSON.stringify(x)}`).join(", "),P=i.http_headers?"http_headers":"headers";y.push(`${P} = { ${h} }`)}return y.join(`
35
+ `)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",l=i.type?`type = "${i.type}"
36
+ `:"",c=i.stderr?`stderr = "${i.stderr}"
25
37
  `:"",u=`[mcp_servers.${s}]
26
- ${c}command = "${i.command}"
27
- ${l}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let h=p.map(([y,b])=>`${JSON.stringify(y)} = ${JSON.stringify(b)}`).join(`
38
+ ${l}command = "${i.command}"
39
+ ${c}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let T=p.map(([y,S])=>`${JSON.stringify(y)} = ${JSON.stringify(S)}`).join(`
28
40
  `);return`${u}
29
41
 
30
42
  [mcp_servers.${s}.env]
31
- ${h}`}).join(`
32
-
33
- `));let o=[`current_provider = "${e.current_provider}"`,`stream_output = ${e.stream_output??!1}`];return typeof e.max_prompt_tokens=="number"&&Number.isFinite(e.max_prompt_tokens)&&o.push(`max_prompt_tokens = ${Math.floor(e.max_prompt_tokens)}`),[o.join(`
34
- `),t,n].filter(Boolean).join(`
43
+ ${T}`}).join(`
35
44
 
36
- `)}async function ge(e,t){await ga(va(e),{recursive:!0}),await ha(e,Ca(t),"utf-8")}async function oe(){let e=process.env.MEMO_HOME?Oo(process.env.MEMO_HOME):Sa,t=Ie(e,"config.toml");try{await xa(t);let n=await ya(t,"utf-8"),o=Ta(n),r=wa(o.providers),s=typeof o.max_prompt_tokens=="number"&&Number.isFinite(o.max_prompt_tokens)&&o.max_prompt_tokens>0?Math.floor(o.max_prompt_tokens):void 0,i={current_provider:o.current_provider??je.current_provider,stream_output:o.stream_output??je.stream_output,max_prompt_tokens:s??je.max_prompt_tokens,providers:r,mcp_servers:o.mcp_servers??{}},a=!i.providers.length;return{config:a?je:i,home:e,configPath:t,needsSetup:a}}catch{return{config:je,home:e,configPath:t,needsSetup:!0}}}function Le(e,t){let n=t||e.current_provider,o=e.providers.find(r=>r.name===n);return o||(e.providers?.[0]??je.providers[0])}function Tt(e,t){let n=t.historyDir??Ie(e.home,_a);return Oo(n)}function No(e){return Ie(e.home,ka)}function Ea(e,t=100){return e.replace(/[\\/:\s]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t)||"root"}function Aa(e,t=180){let n=[],o=0;for(let r of e){let s=r.slice(0,Math.max(1,t-o-(n.length>0?1:0)));if(n.push(s),o+=s.length+(n.length>1?1:0),o>=t)break}return n}function Do(e,t){let n=new Date,o=String(n.getFullYear()),r=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),a=String(n.getMinutes()).padStart(2,"0"),c=String(n.getSeconds()).padStart(2,"0"),l=Uo(process.cwd()),u=`${o}-${r}-${s}_${i}${a}${c}_${t}.jsonl`;return Ie(e,l,u)}function Uo(e){let t=e.split(/[/\\]+/).map(o=>Ea(o));return Aa(t,180).join("-")||"root"}function Ho(e,t){return Ie(e,Uo(t))}var St=class{tools=new Map;register(t){this.tools.set(t.name,t)}registerMany(t){for(let n of t)this.register(n)}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,o]of this.tools)t[n]=o;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}};import{Client as Ma}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as jo}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as Pa}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Ra}from"@modelcontextprotocol/sdk/client/stdio.js";function _t(){return new Ma({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function $a(e){if(!(!e||Object.keys(e).length===0))return{headers:e}}function Ia(e){let t={...e.http_headers??e.headers??{}};if(e.bearer_token_env_var){let n=process.env[e.bearer_token_env_var];n&&!t.Authorization&&(t.Authorization=`Bearer ${n}`)}return t}async function La(e){let t=new URL(e.url),n=$a(Ia(e));if(e.type==="sse"){let r=_t(),s=new jo(t,{requestInit:n});return await r.connect(s),{client:r,transport:s}}let o=e.fallback_to_sse??!0;try{let r=_t(),s=new Pa(t,{requestInit:n});return await r.connect(s),{client:r,transport:s}}catch(r){if(!o)throw r;try{let s=_t(),i=new jo(t,{requestInit:n});return await s.connect(i),{client:s,transport:i}}catch(s){let i=`Failed to connect via streamable_http (${r.message}); SSE fallback failed (${s.message})`,a=new Error(i);throw a.cause={streamErr:r,sseErr:s},a}}}async function Oa(e){if("url"in e)return La(e);let t={command:e.command,args:e.args,env:e.env?{...process.env,...e.env}:void 0,stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new Ra(t),o=_t();return await o.connect(n),{client:o,transport:n}}var kt=class{connections=new Map;async connect(t,n){let o=this.connections.get(t);if(o)return o;let{client:r,transport:s}=await Oa(n),i=await r.listTools(),a={name:t,client:r,transport:s,tools:(i.tools||[]).map(c=>({name:`${t}_${c.name}`,description:c.description||`Tool from ${t}: ${c.name}`,source:"mcp",serverName:t,originalName:c.name,inputSchema:c.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(t,a),a}get(t){return this.connections.get(t)}getAll(){return Array.from(this.connections.values())}getAllTools(){let t=[];for(let n of this.connections.values())for(let o of n.tools)t.push({name:o.name,description:o.description,serverName:o.serverName,originalName:o.originalName,inputSchema:o.inputSchema,client:n.client});return t}async closeAll(){let t=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(o){console.error(`[MCP] Error closing client ${n.name}:`,o)}});await Promise.all(t),this.connections.clear()}get size(){return this.connections.size}};var bt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new kt,this.shouldLog=process.env.MEMO_MCP_LOG==="1"||!(process.stdout.isTTY&&process.stdin.isTTY)}async loadServers(t){if(!t||Object.keys(t).length===0)return 0;let n=0;return await Promise.all(Object.entries(t).map(async([o,r])=>{try{let s=await this.pool.connect(o,r);for(let i of s.tools){let a={...i,execute:async c=>{let l=this.pool.get(i.serverName)?.client;if(!l)throw new Error(`MCP client for server '${i.serverName}' not found`);return l.callTool({name:i.originalName,arguments:c})}};this.tools.set(a.name,a)}n+=s.tools.length,this.shouldLog&&console.log(`[MCP] Connected to '${o}' with ${s.tools.length} tools`)}catch(s){this.shouldLog&&console.error(`[MCP] Failed to connect to server '${o}':`,s)}})),n}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,o]of this.tools)t[n]=o;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear()}getPool(){return this.pool}};var wt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new St,this.mcpRegistry=new bt}registerNativeTool(t){this.nativeRegistry.register(t)}registerNativeTools(t){for(let n of t)this.registerNativeTool(n)}async loadMcpServers(t){return this.mcpRegistry.loadServers(t)}getTool(t){return this.nativeRegistry.get(t)??this.mcpRegistry.get(t)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(t){return this.nativeRegistry.has(t)||this.mcpRegistry.has(t)}getToolCount(){let t=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:t,mcp:n,total:t+n}}async execute(t,n){let o=this.getTool(t);if(!o)throw new Error(`Tool '${t}' not found`);return o.execute(n)}generateToolDefinitions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let t=this.getAllTools();if(t.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let o=t.filter(s=>s.source==="native"),r=t.filter(s=>s.source==="mcp");if(o.length>0){n.push("### Built-in Tools"),n.push("");for(let s of o)n.push(this.formatToolDescription(s));n.push("")}if(r.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(r);for(let[i,a]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let c of a)n.push(this.formatToolDescription(c));n.push("")}}return n.join(`
37
- `)}formatToolDescription(t){let n=[];return n.push(`#### ${t.name}`),n.push(`- **Description**: ${t.description}`),t.inputSchema&&Object.keys(t.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(t.inputSchema)}`),n.join(`
38
- `)}groupByServer(t){let n={};for(let o of t)if(o.source==="mcp"){let r=o.serverName;n[r]||(n[r]=[]),n[r].push(o)}return n}getToolDescriptions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,source:t.source,serverName:t.source==="mcp"?t.serverName:void 0,inputSchema:t.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};import{readFile as Da,access as Ua}from"fs/promises";function Ha(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}async function Bo(e,t,n){let o=await oe(),r=o.config,s=new wt;if(s.registerNativeTools(Ro),await s.loadMcpServers(r.mcp_servers),e.tools)for(let[y,b]of Object.entries(e.tools))s.registerNativeTool({name:y,description:b.description,source:"native",inputSchema:{type:"object"},execute:b.execute});let i=s.toRegistry(),a=async()=>{let y=await(e.loadPrompt??Gn)(),b=s.generateToolDescriptions();b&&(y+=`
45
+ `));let o=[`current_provider = "${t.current_provider}"`];return typeof t.max_prompt_tokens=="number"&&Number.isFinite(t.max_prompt_tokens)&&o.push(`max_prompt_tokens = ${Math.floor(t.max_prompt_tokens)}`),[o.join(`
46
+ `),e,n].filter(Boolean).join(`
39
47
 
40
- ${b}`);let x=No(o);try{await Ua(x);let w=(await Da(x,"utf-8")).trim();w&&(y+=`
48
+ `)}async function ye(t,e){await vl(kl(t),{recursive:!0}),await Cl(t,Il(e),"utf-8")}async function ie(){let t=process.env.MEMO_HOME?tr(process.env.MEMO_HOME):Al,e=it(t,"config.toml");try{await El(e);let n=await wl(e,"utf-8"),o=bl(n),r=Rl(o.providers),s=typeof o.max_prompt_tokens=="number"&&Number.isFinite(o.max_prompt_tokens)&&o.max_prompt_tokens>0?Math.floor(o.max_prompt_tokens):void 0,i={current_provider:o.current_provider??st.current_provider,max_prompt_tokens:s??st.max_prompt_tokens,providers:r,mcp_servers:o.mcp_servers??{}},a=!i.providers.length;return{config:a?st:i,home:t,configPath:e,needsSetup:a}}catch{return{config:st,home:t,configPath:e,needsSetup:!0}}}function Ue(t,e){let n=e||t.current_provider,o=t.providers.find(r=>r.name===n);return o||(t.providers?.[0]??st.providers[0])}function It(t,e){let n=e.historyDir??it(t.home,Ml);return tr(n)}function nr(t,e){let n=new Date,o=String(n.getFullYear()),r=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),a=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),c=`rollout-${o}-${r}-${s}T${i}-${a}-${l}-${e}.jsonl`;return it(t,o,r,s,c)}function Ll(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function Ol(t){return t.role==="assistant"?{role:"assistant",content:t.content,tool_calls:t.tool_calls?.map(e=>({id:e.id,type:e.type,function:{name:e.function.name,arguments:e.function.arguments}}))}:t.role==="tool"?{role:"tool",content:t.content,tool_call_id:t.tool_call_id}:{role:t.role,content:t.content}}async function or(t,e,n){let o=await ie(),r=o.config,s=new Rt;if(s.registerNativeTools(Yo),await s.loadMcpServers(r.mcp_servers),t.tools)for(let[T,y]of Object.entries(t.tools))s.registerNativeTool({name:T,description:y.description,source:"native",inputSchema:{type:"object"},execute:y.execute});let i=s.toRegistry(),a=async()=>{let T=await(t.loadPrompt??qn)(),y=s.generateToolDescriptions();return y&&(T+=`
41
49
 
42
- # Long-Term Memory
43
- ${w}`)}catch{}return y},c=s.generateToolDefinitions(),l=t.stream??r.stream_output??!1,u=Tt(o,t),p=Do(u,n),h=new pt(p);return{tools:i,dispose:async()=>{e.dispose&&await e.dispose(),await s.dispose()},callLLM:e.callLLM??(async(y,b,x)=>{let w=Le(r,t.providerName),_=process.env[w.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!_)throw new Error(`Missing env var ${w.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let k=new Na({apiKey:_,baseURL:w.base_url}),d=c.length>0?c.map(v=>({type:"function",function:{name:v.name,description:v.description,parameters:v.input_schema}})):void 0;if(l){let v=await k.chat.completions.create({model:w.model,messages:y,stream:!0},{signal:x?.signal}),E="";for await(let B of v){let I=B.choices?.[0]?.delta?.content;I&&(E+=I,b?.(I))}return{content:E,streamed:!0}}else{let v=await k.chat.completions.create({model:w.model,messages:y,tools:d,tool_choice:d?"auto":void 0},{signal:x?.signal}),E=v.choices?.[0]?.message;if(E?.tool_calls&&E.tool_calls.length>0){let I=[];E.content&&I.push({type:"text",text:E.content});for(let M of E.tool_calls)if(M.type==="function"){let C=Ha(M.function.arguments);C.ok?I.push({type:"tool_use",id:M.id,name:M.function.name,input:C.data}):I.push({type:"text",text:`[tool_use parse error] ${C.error}; raw: ${C.raw}`})}let ue=I.some(M=>M.type==="tool_use");return{content:I,stop_reason:ue?"tool_use":"end_turn",usage:{prompt:v.usage?.prompt_tokens??void 0,completion:v.usage?.completion_tokens??void 0,total:v.usage?.total_tokens??void 0}}}let B=E?.content;if(typeof B!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:B}],stop_reason:"end_turn",usage:{prompt:v.usage?.prompt_tokens??void 0,completion:v.usage?.completion_tokens??void 0,total:v.usage?.total_tokens??void 0}}}}),loadPrompt:a,historySinks:e.historySinks??[h],tokenCounter:e.tokenCounter??Io(t.tokenizerModel),historyFilePath:p}}import{jsonrepair as ja}from"jsonrepair";function an(e){try{return JSON.parse(e)}catch{try{let t=ja(e);return JSON.parse(t)}catch{return null}}}function Ba(e){let t=[],n=new Set,o=/```(?:json)?\s*([\s\S]*?)\s*```/g,r;for(;(r=o.exec(e))!==null;){let i=r[1]||"";if(!i)continue;let a=Fa(i);if(!(!a||n.has(a)))try{let c=an(a);if(c===null)continue;t.push({json:a,start:r.index,end:r.index+r[0].length,obj:c}),n.add(a)}catch{}}let s=Go(e);for(let{json:i,start:a,end:c}of s)if(!n.has(i)&&!(!i.includes('"tool"')&&!i.includes('"final"')))try{let l=an(i);if(l===null)continue;t.push({json:i,start:a,end:c,obj:l}),n.add(i)}catch{}return t}function Fa(e){return Go(e)[0]?.json??null}function Go(e){let t=[],n=0,o=-1,r=!1,s=!1;for(let i=0;i<e.length;i++){let a=e[i];if(s){s=!1;continue}if(a==="\\"&&r){s=!0;continue}if(a==='"'&&!r?r=!0:a==='"'&&r&&(r=!1),!r){if(a==="{")n===0&&(o=i),n++;else if(a==="}"&&(n--,n===0&&o!==-1)){let c=e.slice(o,i+1);t.push({json:c,start:o,end:i+1}),o=-1}}}return t}function Va(e){let t=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,o=e.replace(n,(r,s,i)=>{let a=(i??"").trim();return a&&t.push(a),a});return{thinkingParts:t,cleaned:o.trim()}}function cn(e){if(e.length===0)return;let t=e.join(`
44
- `),{thinkingParts:n,cleaned:o}=Va(t);return n.length>0?n.join(`
50
+ ${y}`),T},l=s.generateToolDefinitions(),c=It(o,e),u=nr(c,n),p=new Ct(u);return{tools:i,dispose:async()=>{t.dispose&&await t.dispose(),await s.dispose()},callLLM:t.callLLM??(async(T,y,S)=>{let h=Ue(r,e.providerName),P=process.env[h.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!P)throw new Error(`Missing env var ${h.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let C=new $l({apiKey:P,baseURL:h.base_url}),x=T.map(Ol),b=l.length>0?l.map(N=>({type:"function",function:{name:N.name,description:N.description,parameters:N.input_schema}})):void 0,A=await C.chat.completions.create({model:h.model,messages:x,tools:b,tool_choice:b?"auto":void 0},{signal:S?.signal}),M=A.choices?.[0]?.message;if(M?.tool_calls&&M.tool_calls.length>0){let N=[];M.content&&N.push({type:"text",text:M.content});for(let U of M.tool_calls)if(U.type==="function"){let B=Ll(U.function.arguments);B.ok?N.push({type:"tool_use",id:U.id,name:U.function.name,input:B.data}):N.push({type:"text",text:`[tool_use parse error] ${B.error}; raw: ${B.raw}`})}let _e=N.some(U=>U.type==="tool_use");return{content:N,stop_reason:_e?"tool_use":"end_turn",usage:{prompt:A.usage?.prompt_tokens??void 0,completion:A.usage?.completion_tokens??void 0,total:A.usage?.total_tokens??void 0}}}let w=M?.content;if(typeof w!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:w}],stop_reason:"end_turn",usage:{prompt:A.usage?.prompt_tokens??void 0,completion:A.usage?.completion_tokens??void 0,total:A.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:t.historySinks??[p],tokenCounter:t.tokenCounter??Qo(e.tokenizerModel),historyFilePath:u}}function Nl(t){let e=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,o=t.replace(n,(r,s,i)=>{let a=(i??"").trim();return a&&e.push(a),a});return{thinkingParts:e,cleaned:o.trim()}}function rr(t){if(t.length===0)return;let e=t.join(`
51
+ `),{thinkingParts:n,cleaned:o}=Nl(e);return n.length>0?n.join(`
45
52
 
46
- `):o||void 0}function Fo(e){return e!==null&&typeof e=="object"&&"tool"in e&&typeof e.tool=="string"}function Vo(e){return e!==null&&typeof e=="object"&&"final"in e&&typeof e.final=="string"}function zo(e){let t={},n=Ba(e);for(let{json:r,start:s,end:i,obj:a}of n){if(Fo(a)){t.action={tool:a.tool.trim(),input:a.input};let c=e.slice(0,s).trim(),l=e.slice(i).trim(),u=[];c&&u.push(c),l&&u.push(l);let p=cn(u);return p&&(t.thinking=p),t}if(Vo(a))return t.final=a.final,t}let o=e.trim();if(o.startsWith("{")&&o.endsWith("}")){let r=an(o);if(r&&Fo(r))return t.action={tool:r.tool,input:r.input},t;if(r&&Vo(r))return t.final=r.final,t}return e.trim()&&(t.final=e),t}import{randomUUID as Xo}from"crypto";function Ga(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[]}}function Wo(e,t){t&&(t.onTurnStart&&e.onTurnStart.push(t.onTurnStart),t.onAction&&e.onAction.push(t.onAction),t.onObservation&&e.onObservation.push(t.onObservation),t.onFinal&&e.onFinal.push(t.onFinal),t.onApprovalRequest&&e.onApprovalRequest.push(t.onApprovalRequest),t.onApprovalResponse&&e.onApprovalResponse.push(t.onApprovalResponse))}function Ko(e){let t=Ga();if(Wo(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)Wo(t,n);return t}async function Z(e,t,n){let o=e[t];if(o.length)for(let r of o)try{await r(n)}catch(s){console.warn(`Hook ${t} failed: ${s.message}`)}}function Be(e){return e.map(t=>({...t}))}var ln={read:"read",glob:"read",grep:"read",webfetch:"read",todo:"read",save_memory:"write",write:"write",edit:"write",bash:"execute"};var Ct={read:0,write:1,execute:2},un={read:e=>`${e} \u5C06\u8BFB\u53D6\u6587\u4EF6\u6216\u6570\u636E`,write:e=>`${e} \u5C06\u4FEE\u6539\u6216\u521B\u5EFA\u6587\u4EF6`,execute:e=>`${e} \u5C06\u6267\u884C\u7CFB\u7EDF\u547D\u4EE4`};function pn(e){let t={...ln,...e?.customLevels};return{getRiskLevel(n){if(n in t)return t[n];let o=n.toLowerCase();return o.includes("exec")||o.includes("run")||o.includes("shell")||o.includes("bash")||o.includes("command")?"execute":o.includes("write")||o.includes("edit")||o.includes("create")||o.includes("delete")||o.includes("modify")||o.includes("update")?"write":o.includes("read")||o.includes("get")||o.includes("fetch")||o.includes("search")||o.includes("list")||o.includes("find")?"read":"write"},compareRisk(n,o){return Ct[n]-Ct[o]},needsApproval(n,o){return o==="strict"?!0:n==="write"||n==="execute"}}}import{createHash as za}from"crypto";function Et(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>Et(n)).join(",")+"]":`{${Object.entries(e).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${Et(o)}`).join(",")}}`}function mn(e,t){let n=Et(t),o=`${e}:${n}`;return za("sha256").update(o).digest("hex").slice(0,16)}function dn(e){let{mode:t="auto",dangerous:n=!1,toolRiskLevels:o}=e||{};if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let r=pn({customLevels:o}),s={session:new Set,once:new Set,denied:new Set};return{get isDangerousMode(){return!1},getRiskLevel(i){return r.getRiskLevel(i)},check(i,a){let c=r.getRiskLevel(i);if(!r.needsApproval(c,t))return{needApproval:!1,decision:"auto-execute"};let l=mn(i,a);return s.session.has(l)||s.once.has(l)?{needApproval:!1,decision:"auto-execute"}:s.denied.has(l)?{needApproval:!0,fingerprint:l,riskLevel:c,reason:"\u8BE5\u8BF7\u6C42\u5DF2\u88AB\u62D2\u7EDD",toolName:i,params:a}:{needApproval:!0,fingerprint:l,riskLevel:c,reason:un[c](i),toolName:i,params:a}},recordDecision(i,a){switch(s.session.delete(i),s.once.delete(i),s.denied.delete(i),a){case"session":s.session.add(i);break;case"once":s.once.add(i);break;case"deny":s.denied.add(i);break}},isGranted(i){return s.session.has(i)||s.once.has(i)},clearOnceApprovals(){s.once.clear()},dispose(){s.session.clear(),s.once.clear(),s.denied.clear()}}}var Yo="interactive",Wa=12e4;function Jo(){return{prompt:0,completion:0,total:0}}function qo(e,t){if(!t)return;let n=t.prompt??0,o=t.completion??0,r=t.total??n+o;e.prompt+=n,e.completion+=o,e.total+=r}function Ka(e){if(typeof e=="string")return{textContent:e,toolUseBlocks:[]};if("content"in e&&typeof e.content=="string")return{textContent:e.content,toolUseBlocks:[],usage:"usage"in e?e.usage:void 0,streamed:"streamed"in e?e.streamed:void 0};if("content"in e&&Array.isArray(e.content)){let t=e.content.filter(o=>o.type==="text"),n=e.content.filter(o=>o.type==="tool_use");return{textContent:t.map(o=>o.text).join(`
47
- `),toolUseBlocks:n.map(o=>({id:o.id,name:o.name,input:o.input})),stopReason:"stop_reason"in e?e.stop_reason:void 0,usage:"usage"in e?e.usage:void 0}}return{textContent:"",toolUseBlocks:[]}}async function Ja(e,t){for(let n of t)try{await n.append(e)}catch(o){console.error(`Failed to write history event: ${o.message}`)}}function qa(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
48
- `)}function Xa(e,t){let n=t;if(typeof t=="string"){let o=t.trim();if(o)try{n=JSON.parse(o)}catch{n=o}else n={}}return typeof n!="object"||n===null?{ok:!1,error:`${e.name} invalid input: expected object`}:typeof e.validateInput=="function"?e.validateInput(n):{ok:!0,data:n}}function Ya(e){return e instanceof Error&&e.name==="AbortError"}function At(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>At(n)).join(",")}]`:`{${Object.entries(e).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${At(o)}`).join(",")}}`}var fn=class{constructor(t,n,o,r,s){this.deps=t;this.options=n;this.id=n.sessionId||Xo(),this.mode=n.mode||Yo,this.history=[{role:"system",content:o}],this.tokenCounter=r,this.sinks=t.historySinks??[],this.hooks=Ko(t),this.historyFilePath=s,this.approvalManager=dn({dangerous:n.dangerous??!1,mode:"auto"})}id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=Jo();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;approvalManager;async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(t,n){let o=`${t}:${At(n)}`;if(this.lastActionSignature===o?this.repeatedActionCount+=1:(this.lastActionSignature=o,this.repeatedActionCount=1),this.repeatedActionCount===3){let r=At(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${t}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${r}${r.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}async executeToolWithApproval(t,n,o,r){let s=this.approvalManager.check(t,n);if(!s.needApproval)return this.doExecuteTool(t,n);let i={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await Z(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:o,step:r,request:i});let a="deny";return this.deps.requestApproval?a=await this.deps.requestApproval(i):a="deny",this.approvalManager.recordDecision(s.fingerprint,a),await Z(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:o,step:r,fingerprint:s.fingerprint,decision:a}),a==="deny"?{success:!1,observation:`\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C: ${t}`,rejected:!0}:this.doExecuteTool(t,n)}async doExecuteTool(t,n){let o=this.deps.tools[t];if(!o)return{success:!1,observation:`Unknown tool: ${t}`};try{let r=Xa(o,n);if(!r.ok)return{success:!1,observation:r.error};let s=await o.execute(r.data);return{success:!0,observation:qa(s)||"(no tool output)"}}catch(r){return{success:!1,observation:`Tool execution failed: ${r.message}`}}}async runTurn(t){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let o=this.turnIndex,r=[],s=Jo(),i=Date.now(),a=this.options.maxPromptTokens??Wa;this.sessionStartEmitted||(await this.emitEvent("session_start",{meta:{mode:this.mode,tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a}}),this.sessionStartEmitted=!0),this.history.push({role:"user",content:t});try{let c=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:o,content:t,meta:{tokens:{prompt:c}}}),await Z(this.hooks,"onTurnStart",{sessionId:this.id,turn:o,input:t,promptTokens:c,history:Be(this.history)});let l="",u="ok",p;for(let h=0;;h++){let y=this.tokenCounter.countMessages(this.history);if(y>a){let C=`Context tokens (${y}) exceed the limit. Please shorten the input or restart the session.`,P=JSON.stringify({final:C});this.history.push({role:"assistant",content:P}),u="prompt_limit",l=C,p=C,await this.emitEvent("final",{turn:o,step:h,content:C,role:"assistant",meta:{tokens:{prompt:y}}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:C,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.options.warnPromptTokens&&y>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${y}`);let b="",x=[],w,_=!1,k;try{let C=await this.deps.callLLM(this.history,V=>this.deps.onAssistantStep?.(V,h),{signal:n.signal}),P=Ka(C);b=P.textContent,x=P.toolUseBlocks,k=P.stopReason,w=P.usage,_=!!P.streamed}catch(C){if(this.cancelling&&Ya(C)){u="cancelled",l="",p="Turn cancelled",await this.emitEvent("final",{turn:o,step:h,content:"",role:"assistant",meta:{cancelled:!0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:l,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}let P=`LLM call failed: ${C.message}`,V=JSON.stringify({final:P});this.history.push({role:"assistant",content:V}),u="error",l=P,p=P,await this.emitEvent("final",{turn:o,content:P,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:l,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}_||this.deps.onAssistantStep?.(b,h);let d;if(x.length>0){let C=x[0];if(C){let P=b?cn([b]):void 0;d={action:{tool:C.name,input:C.input},thinking:P}}else d={}}else b?d=zo(b):d={};let v=d.action?JSON.stringify({tool:d.action.tool,input:d.action.input}):d.final?JSON.stringify({final:d.final}):b;this.history.push({role:"assistant",content:v});let E=this.tokenCounter.countText(b),B=w?.prompt??y,I=w?.completion??E,ue=w?.total??B+I,M={prompt:B,completion:I,total:ue};if(qo(s,M),qo(this.sessionUsage,M),r.push({index:h,assistantText:b,parsed:d,tokenUsage:M}),await this.emitEvent("assistant",{turn:o,step:h,content:b,role:"assistant",meta:{tokens:M}}),x.length>1){for(let D of x)this.maybeWarnRepeatedAction(D.name,D.input);await this.emitEvent("action",{turn:o,step:h,meta:{tools:x.map(D=>D.name),parallel:!0,thinking:d.thinking,toolBlocks:x.map(D=>({name:D.name,input:D.input}))}});let C=x[0];C&&await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:h,action:{tool:C.name,input:C.input},parallelActions:x.map(D=>({tool:D.name,input:D.input})),thinking:d.thinking,history:Be(this.history)});let P=[],V=!1;for(let[D,re]of x.entries()){let se=await this.executeToolWithApproval(re.name,re.input,o,h);if(se.rejected){V=!0,P.push(`[${re.name}]: ${se.observation}`),await this.emitEvent("observation",{turn:o,step:h,content:se.observation,meta:{tool:re.name,index:D}});break}P.push(`[${re.name}]: ${se.observation}`),await this.emitEvent("observation",{turn:o,step:h,content:se.observation,meta:{tool:re.name,index:D}})}let ee=P.join(`
49
-
50
- `);this.history.push({role:"user",content:JSON.stringify({observation:ee})});let ye=r[r.length-1];if(ye&&(ye.observation=ee),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:h,tool:x.map(D=>D.name).join(", "),observation:ee,history:Be(this.history)}),V){u="cancelled",l="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:h,content:l,role:"assistant",meta:{rejected:!0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:l,status:u,tokenUsage:M,turnUsage:{...s},steps:r});break}continue}else if(d.action){this.maybeWarnRepeatedAction(d.action.tool,d.action.input),await this.emitEvent("action",{turn:o,step:h,meta:{tool:d.action.tool,input:d.action.input,thinking:d.thinking}}),await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:h,action:d.action,thinking:d.thinking,history:Be(this.history)});let C=await this.executeToolWithApproval(d.action.tool,d.action.input,o,h);if(C.rejected){u="cancelled",l="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:h,content:l,role:"assistant",meta:{rejected:!0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:l,status:u,tokenUsage:M,turnUsage:{...s},steps:r});break}let P=C.observation;this.history.push({role:"user",content:JSON.stringify({observation:P,tool:d.action.tool})});let V=r[r.length-1];V&&(V.observation=P),await this.emitEvent("observation",{turn:o,step:h,content:P,meta:{tool:d.action.tool}}),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:h,tool:d.action.tool,observation:P,history:Be(this.history)});continue}if(k==="end_turn"||d.final){this.resetActionRepetition(),l=d.final||b,d.final&&(d.final=l),await this.emitEvent("final",{turn:o,step:h,content:l,role:"assistant",meta:{tokens:M}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:l,status:u,tokenUsage:M,turnUsage:{...s},steps:r});break}this.resetActionRepetition();break}if(!l&&u!=="cancelled"){u==="ok"&&(u="error"),l="Unable to produce a final answer. Please retry or adjust the request.",p=l;let h=JSON.stringify({final:l});this.history.push({role:"assistant",content:h}),await this.emitEvent("final",{turn:o,content:l,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,finalText:l,status:u,errorMessage:p,turnUsage:{...s},steps:r})}return await this.emitEvent("turn_end",{turn:o,meta:{status:u,stepCount:r.length,durationMs:Date.now()-i,tokens:s}}),{finalText:l,steps:r,status:u,errorMessage:p,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.approvalManager.clearOnceApprovals()}}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async close(){if(this.closed)return;if(this.closed=!0,this.sessionStartEmitted||this.turnIndex>=0){await this.emitEvent("session_end",{meta:{durationMs:Date.now()-this.startedAt,tokens:this.sessionUsage}});for(let n of this.sinks)if(n.flush)try{await n.flush()}catch(o){console.error(`History flush failed: ${o.message}`)}}this.tokenCounter.dispose(),this.approvalManager.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(t,n){if(!this.sinks.length)return;let o=zn({sessionId:this.id,type:t,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Ja(o,this.sinks)}};async function Ye(e,t={}){let n=t.sessionId||Xo(),o=await Bo(e,{...t,sessionId:n},n),r=await o.loadPrompt(),s=new fn({...e,...o},{...t,sessionId:n,mode:t.mode??Yo},r,o.tokenCounter,o.historyFilePath);return await s.init(),s}import{useCallback as W,useEffect as jt,useMemo as In,useRef as it,useState as K}from"react";import{readFile as su}from"fs/promises";import"path";import{randomUUID as at}from"crypto";import{exec as iu}from"child_process";import{promisify as au}from"util";import{Box as Qr,useApp as cu,Text as lu}from"ink";import{Box as Zo,Text as Za}from"ink";import{memo as Qa}from"react";import{jsx as Qo,jsxs as ec}from"react/jsx-runtime";var er=Qa(function({contextPercent:t=0}){let n=t>0?` ${t.toFixed(1)}%`:" 0.0%";return Qo(Zo,{justifyContent:"flex-end",children:Qo(Zo,{marginTop:8,children:ec(Za,{color:"gray",children:["context:",n]})})})});import{Box as xe,Static as Cc,Text as le}from"ink";import{memo as Ec}from"react";import Ac from"os";import{Box as tc,Text as tr}from"ink";import{memo as nc}from"react";import{jsx as oc,jsxs as nr}from"react/jsx-runtime";var or=nc(function({message:t}){return nr(tc,{flexDirection:"column",gap:0,children:[nr(tr,{color:"cyan",children:["\u25CF ",t.title]}),oc(tr,{color:"gray",children:t.content})]})});import{Box as _c,Text as kc}from"ink";import{memo as bc}from"react";import{Box as Ze,Text as ce}from"ink";import{memo as fc}from"react";import{Box as gn,Text as G}from"ink";import{marked as rc}from"marked";import{useMemo as rr,memo as sc}from"react";import{jsx as Q,jsxs as Fe}from"react/jsx-runtime";var ic="#2b2b2b";function Mt(e){return e?[{type:"text",raw:e,text:e}]:[]}function ac(e,t,n){switch(e.type){case"text":return e.tokens&&e.tokens.length>0?ke(e.tokens,t,`${n}-text`):e.text;case"escape":return e.text;case"strong":return Q(G,{bold:!0,children:ke(e.tokens,t,`${n}-strong`)},n);case"em":return Q(G,{italic:!0,children:ke(e.tokens,t,`${n}-em`)},n);case"codespan":return Q(G,{color:t.codeColor,backgroundColor:ic,children:e.text},n);case"del":return Q(G,{strikethrough:!0,children:ke(e.tokens,t,`${n}-del`)},n);case"link":{let o=e.tokens&&e.tokens.length>0?ke(e.tokens,t,`${n}-link`):e.text,r=e.href&&e.text&&e.text!==e.href?` (${e.href})`:"";return Fe(G,{underline:!0,color:t.linkColor,children:[o,r]},n)}case"image":{let o=e.text||"image";return Fe(G,{color:t.linkColor,children:["[",o,"](",e.href,")"]},n)}case"br":return`
51
- `;case"checkbox":return e.checked?"[x]":"[ ]";case"html":return e.text;default:return"text"in e?e.text:e.raw}}function ke(e,t,n){return!e||e.length===0?[]:e.flatMap((o,r)=>{let s=`${n}-${r}`,i=ac(o,t,s);return Array.isArray(i)?i:[i]})}function cc(e){let t=e.tokens[0];return t?.type==="paragraph"||t?.type==="text"?t.tokens??Mt(t.text):e.tokens.length>0?e.tokens:Mt(e.text)}function lc(e){return e.split(`
52
- `).map(t=>t.length>0?` ${t}`:"").join(`
53
- `).trimEnd()}function uc(e){let t=e.header.map(r=>r.text).join(" | "),n=e.header.map(()=>"---").join(" | "),o=e.rows.map(r=>r.map(s=>s.text).join(" | "));return[t,n,...o].join(`
54
- `)}function pc(e){return e.type==="table"&&"header"in e&&"rows"in e&&"align"in e}function mc(e,t,n){switch(e.type){case"space":case"def":return null;case"heading":return Q(G,{bold:!0,color:t.textColor,children:ke(e.tokens,t,`${n}-heading`)},n);case"paragraph":{let o=e.tokens??Mt(e.text);return Q(G,{color:t.textColor,children:ke(o,t,`${n}-para`)},n)}case"text":{let o=e.tokens??Mt(e.text);return Q(G,{color:t.textColor,children:ke(o,t,`${n}-text`)},n)}case"code":{let o=lc(e.text);return Q(G,{color:t.codeColor,children:o},n)}case"list":{let o=typeof e.start=="number"?e.start:1;return Q(gn,{flexDirection:"column",children:e.items.map((r,s)=>{let i=e.ordered?`${o+s}.`:"-",a=r.task?r.checked?"[x] ":"[ ] ":"",c=cc(r);return Fe(gn,{children:[Fe(G,{color:t.textColor,children:[i," "]}),Fe(G,{color:t.textColor,children:[a,ke(c,t,`${n}-item-${s}`)]})]},`${n}-item-${s}`)})},n)}case"blockquote":return Fe(G,{color:"gray",dimColor:!0,children:["> ",e.text.trim()]},n);case"hr":return Q(G,{color:"gray",children:"---"},n);case"table":return pc(e)?Q(G,{color:t.textColor,children:uc(e)},n):Q(G,{color:t.textColor,children:"text"in e?e.text:e.raw},n);case"html":return Q(G,{color:t.textColor,children:e.text},n);default:return Q(G,{color:t.textColor,children:"text"in e?e.text:e.raw},n)}}function dc(e,t,n){return e.flatMap((o,r)=>{let s=mc(o,t,`${n}-${r}`);return s?[s]:[]})}var Ve=sc(function({text:t,tone:n="normal"}){let o=rr(()=>({textColor:n==="muted"?"gray":void 0,codeColor:n==="muted"?"gray":"cyan",linkColor:n==="muted"?"gray":"blue",muted:n==="muted"}),[n]),r=rr(()=>{let s=rc.lexer(t,{gfm:!0,breaks:!0});return dc(s,o,"markdown")},[t,o]);return Q(gn,{flexDirection:"column",gap:1,children:r})});import{Fragment as hn,jsx as J,jsxs as Ge}from"react/jsx-runtime";function sr(e){if(!e)return;if(typeof e=="string")return e.length>50?e.slice(0,47)+"...":e;if(typeof e!="object"||Array.isArray(e))return;let t=e,n=["file_path","path","file","filename","url","command","pattern","glob","query","content","cwd","dir"];for(let o of n)if(t[o]){let r=String(t[o]);return r.length>50?r.slice(0,47)+"...":r}for(let[o,r]of Object.entries(t))if(typeof r=="string"&&o!=="description")return r.length>50?r.slice(0,47)+"...":r}function gc(e,t){let n=e.step,o=t.step;return!(n.index!==o.index||n.assistantText!==o.assistantText||n.thinking!==o.thinking||n.action?.tool!==o.action?.tool||JSON.stringify(n.action?.input)!==JSON.stringify(o.action?.input)||JSON.stringify(n.parallelActions)!==JSON.stringify(o.parallelActions)||n.toolStatus!==o.toolStatus)}var ir=fc(function({step:t}){let n=t.action?.tool,o=t.action?.input,r=sr(o),s=t.parallelActions??[],i=s.length>1;return Ge(Ze,{flexDirection:"column",gap:0,children:[t.thinking&&Ge(Ze,{children:[J(ce,{color:"gray",children:"\u25CF "}),J(Ze,{flexDirection:"column",flexGrow:1,children:J(Ve,{text:t.thinking,tone:"muted"})})]}),i&&J(hn,{children:s.map((a,c)=>{let l=sr(a.input);return Ge(Ze,{children:[J(ce,{color:"green",children:"\u25CF "}),J(ce,{color:"gray",children:"Used "}),J(ce,{color:"cyan",children:a.tool}),l&&Ge(hn,{children:[J(ce,{color:"gray",children:" ("}),J(ce,{color:"cyan",children:l}),J(ce,{color:"gray",children:")"})]})]},c)})}),!i&&n&&Ge(Ze,{children:[J(ce,{color:"green",children:"\u25CF "}),J(ce,{color:"gray",children:"Used "}),J(ce,{color:"cyan",children:n}),r&&Ge(hn,{children:[J(ce,{color:"gray",children:" ("}),J(ce,{color:"cyan",children:r}),J(ce,{color:"gray",children:")"})]})]})]})},gc);import{Box as hc,Text as ar}from"ink";import{memo as yc}from"react";import{jsx as cr,jsxs as xc}from"react/jsx-runtime";var lr=yc(function({text:t}){return xc(hc,{paddingY:1,children:[cr(ar,{color:"gray",children:"\u203A "}),cr(ar,{color:"white",children:t})]})});import{Box as Qe,Text as Oe}from"ink";import{memo as yn,useMemo as vc}from"react";import{Fragment as Sc,jsx as me,jsxs as Pt}from"react/jsx-runtime";function Tc(e){let t=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,n=[],o,r=0,s=[];for(;(o=t.exec(e))!==null;){s.push({start:o.index,end:t.lastIndex});let a=o[2]?.trim();a&&n.push(a)}if(s.length===0)return{content:e,thinking:null};let i="";r=0;for(let{start:a,end:c}of s)i+=e.slice(r,a),r=c;return i+=e.slice(r),i=i.replace(/\n{3,}/g,`
53
+ `):o||void 0}import{randomUUID as cr}from"crypto";function Dl(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[]}}function sr(t,e){e&&(e.onTurnStart&&t.onTurnStart.push(e.onTurnStart),e.onAction&&t.onAction.push(e.onAction),e.onObservation&&t.onObservation.push(e.onObservation),e.onFinal&&t.onFinal.push(e.onFinal),e.onApprovalRequest&&t.onApprovalRequest.push(e.onApprovalRequest),e.onApprovalResponse&&t.onApprovalResponse.push(e.onApprovalResponse))}function ir(t){let e=Dl();if(sr(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)sr(e,n);return e}async function Z(t,e,n){let o=t[e];if(o.length)for(let r of o)try{await r(n)}catch(s){console.warn(`Hook ${e} failed: ${s.message}`)}}function Ge(t){return t.map(e=>e.role==="assistant"&&e.tool_calls?.length?{...e,tool_calls:e.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...e})}var ur="interactive",Ul=12e4;function ar(){return{prompt:0,completion:0,total:0}}function lr(t,e){if(!e)return;let n=e.prompt??0,o=e.completion??0,r=e.total??n+o;t.prompt+=n,t.completion+=o,t.total+=r}function Hl(t){let e=t.content.filter(o=>o.type==="text"),n=t.content.filter(o=>o.type==="tool_use");return{textContent:e.map(o=>o.text).join(`
54
+ `),toolUseBlocks:n.map(o=>({id:o.id,name:o.name,input:o.input})),stopReason:t.stop_reason,usage:t.usage}}async function Fl(t,e){for(let n of e)try{await n.append(t)}catch(o){console.error(`Failed to write history event: ${o.message}`)}}function jl(t){return t instanceof Error&&t.name==="AbortError"}function at(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(n=>at(n)).join(",")}]`:`{${Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${at(o)}`).join(",")}}`}function Bl(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:at(e.input)}}))}function Wl(t,e){let n=t.trim();if(!n)return null;let o=[n],r=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);r?.[1]&&o.push(r[1].trim());for(let s of o)if(!(!s.startsWith("{")||!s.endsWith("}")))try{let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,l=typeof a.tool=="string"?a.tool.trim():"";if(!l||!Object.prototype.hasOwnProperty.call(e,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}var Tn=class{constructor(e,n,o,r,s){this.deps=e;this.options=n;this.id=n.sessionId||cr(),this.mode=n.mode||ur,this.history=[{role:"system",content:o}],this.tokenCounter=r,this.sinks=e.historySinks??[],this.hooks=ir(e),this.historyFilePath=s,this.toolOrchestrator=Xo({tools:e.tools,approval:{dangerous:n.dangerous??!1,mode:"auto"}})}id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=ar();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(e,n){let o=`${e}:${at(n)}`;if(this.lastActionSignature===o?this.repeatedActionCount+=1:(this.lastActionSignature=o,this.repeatedActionCount=1),this.repeatedActionCount===3){let r=at(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${e}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${r}${r.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}buildToolApprovalHooks(e,n){return{onApprovalRequest:async o=>{await Z(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:e,step:n,request:o})},requestApproval:async o=>this.deps.requestApproval?this.deps.requestApproval(o):"deny",onApprovalResponse:async({fingerprint:o,decision:r})=>{await Z(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:e,step:n,fingerprint:o,decision:r})}}}async executeToolAction(e,n,o,r,s){return this.toolOrchestrator.executeAction({id:e,name:n,input:o},this.buildToolApprovalHooks(r,s))}async runTurn(e){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let o=this.turnIndex,r=[],s=ar(),i=Date.now(),a=this.options.maxPromptTokens??Ul;this.sessionStartEmitted||(await this.emitEvent("session_start",{meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a}}),this.sessionStartEmitted=!0),this.history.push({role:"user",content:e});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:o,content:e,meta:{tokens:{prompt:l}}}),await Z(this.hooks,"onTurnStart",{sessionId:this.id,turn:o,input:e,promptTokens:l,history:Ge(this.history)});let c="",u="ok",p,T=0,y=null,S=-1;for(let h=0;;h++){let P=this.tokenCounter.countMessages(this.history);if(P>a){let k=`Context tokens (${P}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:k}),u="prompt_limit",c=k,p=k,await this.emitEvent("final",{turn:o,step:h,content:k,role:"assistant",meta:{tokens:{prompt:P}}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:k,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.options.warnPromptTokens&&P>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${P}`);let C="",x=[],b,A;try{let k=await this.deps.callLLM(this.history,K=>this.deps.onAssistantStep?.(K,h),{signal:n.signal}),$=Hl(k);C=$.textContent,x=$.toolUseBlocks,A=$.stopReason,b=$.usage,C.trim().length>0&&(y=C,S=h)}catch(k){if(this.cancelling&&jl(k)){u="cancelled",c="",p="Turn cancelled",await this.emitEvent("final",{turn:o,step:h,content:"",role:"assistant",meta:{cancelled:!0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}let $=`LLM call failed: ${k.message}`;this.history.push({role:"assistant",content:$}),u="error",c=$,p=$,await this.emitEvent("final",{turn:o,content:$,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.deps.onAssistantStep?.(C,h);let M=x.length===0&&C?Wl(C,this.deps.tools):null,w,N=null;if(x.length>0){let k=x[0];if(k){let $=C?rr([C]):void 0;w={action:{tool:k.name,input:k.input},thinking:$},N={role:"assistant",content:C,tool_calls:Bl(x)}}else w={}}else C?(w={final:C},N={role:"assistant",content:C}):w={};let _e=this.tokenCounter.countText(C),U=b?.prompt??P,B=b?.completion??_e,re=b?.total??U+B,z={prompt:U,completion:B,total:re};if(lr(s,z),lr(this.sessionUsage,z),r.push({index:h,assistantText:C,parsed:w,tokenUsage:z}),await this.emitEvent("assistant",{turn:o,step:h,content:C,role:"assistant",meta:{tokens:z,protocol_violation:!!M,protocol_violation_count:M?T+1:T||void 0}}),M){T+=1;let k=`Model protocol error: returned plain-text tool JSON for "${M.tool}" ${T} times. Structured tool calls are required.`;u="error",c=k,p=k,this.history.push({role:"assistant",content:k}),await this.emitEvent("final",{turn:o,step:h,content:k,role:"assistant",meta:{error_type:"model_protocol_error",tool:M.tool,protocol_violation:!0,protocol_violation_count:T,tokens:z}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,errorMessage:p,tokenUsage:z,turnUsage:{...s},steps:r});break}if(N&&this.history.push(N),x.length>1){for(let E of x)this.maybeWarnRepeatedAction(E.name,E.input);await this.emitEvent("action",{turn:o,step:h,meta:{tools:x.map(E=>E.name),action_ids:x.map(E=>E.id),action_id:x[0]?.id,parallel:!0,phase:"dispatch",thinking:w.thinking,toolBlocks:x.map(E=>({id:E.id,name:E.name,input:E.input}))}});let k=x[0];k&&await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:h,action:{tool:k.name,input:k.input},parallelActions:x.map(E=>({tool:E.name,input:E.input})),thinking:w.thinking,history:Ge(this.history)});let $=x.every(E=>!!this.deps.tools[E.name]?.supportsParallelToolCalls),K=x.some(E=>!!this.deps.tools[E.name]?.isMutating),ue=$&&!K?"parallel":"sequential",pe=await this.toolOrchestrator.executeActions(x.map(E=>({id:E.id,name:E.name,input:E.input})),{...this.buildToolApprovalHooks(o,h),executionMode:ue,failurePolicy:"fail_fast"});for(let[E,F]of pe.results.entries())this.history.push({role:"tool",content:F.observation,tool_call_id:F.actionId,name:F.tool}),await this.emitEvent("observation",{turn:o,step:h,content:F.observation,meta:{tool:F.tool,index:E,action_id:F.actionId,phase:"result",status:F.status,error_type:F.errorType,duration_ms:F.durationMs,execution_mode:ue}});let xe=pe.combinedObservation,Ce=r[r.length-1];if(Ce&&(Ce.observation=xe),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:h,tool:x.map(E=>E.name).join(", "),observation:xe,history:Ge(this.history)}),pe.hasRejection){let E=pe.results.find(F=>F.rejected);u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:h,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:E?.actionId,error_type:E?.errorType??"approval_denied",duration_ms:E?.durationMs}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,tokenUsage:z,turnUsage:{...s},steps:r});break}continue}else if(w.action){this.maybeWarnRepeatedAction(w.action.tool,w.action.input);let k=x[0]?.id??`${o}:${h}:single:${w.action.tool}`;await this.emitEvent("action",{turn:o,step:h,meta:{tool:w.action.tool,input:w.action.input,action_id:k,phase:"dispatch",thinking:w.thinking}}),await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:h,action:w.action,thinking:w.thinking,history:Ge(this.history)});let $=await this.executeToolAction(k,w.action.tool,w.action.input,o,h);if($.rejected){u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:h,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:$.actionId,error_type:$.errorType??"approval_denied",duration_ms:$.durationMs}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,tokenUsage:z,turnUsage:{...s},steps:r});break}let K=$.observation;this.history.push({role:"tool",content:K,tool_call_id:$.actionId,name:w.action.tool});let ue=r[r.length-1];ue&&(ue.observation=K),await this.emitEvent("observation",{turn:o,step:h,content:K,meta:{tool:w.action.tool,action_id:$.actionId,phase:"result",status:$.status,error_type:$.errorType,duration_ms:$.durationMs}}),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:h,tool:w.action.tool,observation:K,history:Ge(this.history)});continue}if(A==="end_turn"||w.final){this.resetActionRepetition();let k=A==="end_turn"&&!w.final&&C.trim().length===0&&!!y&&S===h-1;c=k?y??"":w.final||C,w.final&&(w.final=c),await this.emitEvent("final",{turn:o,step:h,content:c,role:"assistant",meta:{tokens:z,fallback_from_previous_text:k||void 0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,tokenUsage:z,turnUsage:{...s},steps:r});break}this.resetActionRepetition();break}return!c&&u!=="cancelled"&&(u==="ok"&&(u="error"),c="Unable to produce a final answer. Please retry or adjust the request.",p=c,this.history.push({role:"assistant",content:c}),await this.emitEvent("final",{turn:o,content:c,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r})),await this.emitEvent("turn_end",{turn:o,meta:{status:u,stepCount:r.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:T||void 0}}),{finalText:c,steps:r,status:u,errorMessage:p,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async close(){if(this.closed)return;if(this.closed=!0,this.sessionStartEmitted||this.turnIndex>=0){await this.emitEvent("session_end",{meta:{durationMs:Date.now()-this.startedAt,tokens:this.sessionUsage}});for(let n of this.sinks)if(n.flush)try{await n.flush()}catch(o){console.error(`History flush failed: ${o.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(e,n){if(!this.sinks.length)return;let o=Xn({sessionId:this.id,type:e,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Fl(o,this.sinks)}};async function lt(t,e={}){let n=e.sessionId||cr(),o=await or(t,{...e,sessionId:n},n),r=await o.loadPrompt(),s=new Tn({...t,...o},{...e,sessionId:n,mode:e.mode??ur},r,o.tokenCounter,o.historyFilePath);return await s.init(),s}import{useCallback as J,useEffect as zt,useMemo as Dn,useRef as Tt,useState as Y}from"react";import{readFile as Zu}from"fs/promises";import"path";import{randomUUID as _t}from"crypto";import{exec as Qu}from"child_process";import{promisify as ep}from"util";import{Box as ms,useApp as tp,Text as np}from"ink";import{Box as pr,Text as Vl}from"ink";import{memo as zl}from"react";import{jsx as mr,jsxs as Gl}from"react/jsx-runtime";var dr=zl(function({contextPercent:e=0}){let n=e>0?` ${e.toFixed(1)}%`:" 0.0%";return mr(pr,{justifyContent:"flex-end",children:mr(pr,{marginTop:8,children:Gl(Vl,{color:"gray",children:["context:",n]})})})});import{Box as Se,Static as Tc,Text as ce}from"ink";import{memo as _c}from"react";import xc from"os";import{Box as Kl,Text as fr}from"ink";import{memo as ql}from"react";import{jsx as Xl,jsxs as gr}from"react/jsx-runtime";var hr=ql(function({message:e}){return gr(Kl,{flexDirection:"column",gap:0,children:[gr(fr,{color:"cyan",children:["\u25CF ",e.title]}),Xl(fr,{color:"gray",children:e.content})]})});import{Box as fc,Text as gc}from"ink";import{memo as hc}from"react";import{Box as ct,Text as le}from"ink";import{memo as ic}from"react";import{Box as _n,Text as q}from"ink";import{marked as Jl}from"marked";import{useMemo as yr,memo as Yl}from"react";import{jsx as oe,jsxs as Ke}from"react/jsx-runtime";var Zl="#2b2b2b";function $t(t){return t?[{type:"text",raw:t,text:t}]:[]}function Ql(t,e,n){switch(t.type){case"text":return t.tokens&&t.tokens.length>0?Ae(t.tokens,e,`${n}-text`):t.text;case"escape":return t.text;case"strong":return oe(q,{bold:!0,children:Ae(t.tokens,e,`${n}-strong`)},n);case"em":return oe(q,{italic:!0,children:Ae(t.tokens,e,`${n}-em`)},n);case"codespan":return oe(q,{color:e.codeColor,backgroundColor:Zl,children:t.text},n);case"del":return oe(q,{strikethrough:!0,children:Ae(t.tokens,e,`${n}-del`)},n);case"link":{let o=t.tokens&&t.tokens.length>0?Ae(t.tokens,e,`${n}-link`):t.text,r=t.href&&t.text&&t.text!==t.href?` (${t.href})`:"";return Ke(q,{underline:!0,color:e.linkColor,children:[o,r]},n)}case"image":{let o=t.text||"image";return Ke(q,{color:e.linkColor,children:["[",o,"](",t.href,")"]},n)}case"br":return`
55
+ `;case"checkbox":return t.checked?"[x]":"[ ]";case"html":return t.text;default:return"text"in t?t.text:t.raw}}function Ae(t,e,n){return!t||t.length===0?[]:t.flatMap((o,r)=>{let s=`${n}-${r}`,i=Ql(o,e,s);return Array.isArray(i)?i:[i]})}function ec(t){let e=t.tokens[0];return e?.type==="paragraph"||e?.type==="text"?e.tokens??$t(e.text):t.tokens.length>0?t.tokens:$t(t.text)}function tc(t){return t.split(`
56
+ `).map(e=>e.length>0?` ${e}`:"").join(`
57
+ `).trimEnd()}function nc(t){let e=t.header.map(r=>r.text).join(" | "),n=t.header.map(()=>"---").join(" | "),o=t.rows.map(r=>r.map(s=>s.text).join(" | "));return[e,n,...o].join(`
58
+ `)}function oc(t){return t.type==="table"&&"header"in t&&"rows"in t&&"align"in t}function rc(t,e,n){switch(t.type){case"space":case"def":return null;case"heading":return oe(q,{bold:!0,color:e.textColor,children:Ae(t.tokens,e,`${n}-heading`)},n);case"paragraph":{let o=t.tokens??$t(t.text);return oe(q,{color:e.textColor,children:Ae(o,e,`${n}-para`)},n)}case"text":{let o=t.tokens??$t(t.text);return oe(q,{color:e.textColor,children:Ae(o,e,`${n}-text`)},n)}case"code":{let o=tc(t.text);return oe(q,{color:e.codeColor,children:o},n)}case"list":{let o=typeof t.start=="number"?t.start:1;return oe(_n,{flexDirection:"column",children:t.items.map((r,s)=>{let i=t.ordered?`${o+s}.`:"-",a=r.task?r.checked?"[x] ":"[ ] ":"",l=ec(r);return Ke(_n,{children:[Ke(q,{color:e.textColor,children:[i," "]}),Ke(q,{color:e.textColor,children:[a,Ae(l,e,`${n}-item-${s}`)]})]},`${n}-item-${s}`)})},n)}case"blockquote":return Ke(q,{color:"gray",dimColor:!0,children:["> ",t.text.trim()]},n);case"hr":return oe(q,{color:"gray",children:"---"},n);case"table":return oc(t)?oe(q,{color:e.textColor,children:nc(t)},n):oe(q,{color:e.textColor,children:"text"in t?t.text:t.raw},n);case"html":return oe(q,{color:e.textColor,children:t.text},n);default:return oe(q,{color:e.textColor,children:"text"in t?t.text:t.raw},n)}}function sc(t,e,n){return t.flatMap((o,r)=>{let s=rc(o,e,`${n}-${r}`);return s?[s]:[]})}var qe=Yl(function({text:e,tone:n="normal"}){let o=yr(()=>({textColor:n==="muted"?"gray":void 0,codeColor:n==="muted"?"gray":"cyan",linkColor:n==="muted"?"gray":"blue",muted:n==="muted"}),[n]),r=yr(()=>{let s=Jl.lexer(e,{gfm:!0,breaks:!0});return sc(s,o,"markdown")},[e,o]);return oe(_n,{flexDirection:"column",gap:1,children:r})});import{Fragment as xn,jsx as Q,jsxs as Xe}from"react/jsx-runtime";function Tr(t){if(!t)return;if(typeof t=="string")return t.length>50?t.slice(0,47)+"...":t;if(typeof t!="object"||Array.isArray(t))return;let e=t,n=["cmd","dir_path","file_path","path","file","filename","url","command","pattern","include","query","content","cwd","dir"];for(let o of n)if(e[o]){let r=String(e[o]);return r.length>50?r.slice(0,47)+"...":r}for(let[o,r]of Object.entries(e))if(typeof r=="string"&&o!=="description")return r.length>50?r.slice(0,47)+"...":r}function ac(t,e){let n=t.step,o=e.step;return!(n.index!==o.index||n.assistantText!==o.assistantText||n.thinking!==o.thinking||n.action?.tool!==o.action?.tool||JSON.stringify(n.action?.input)!==JSON.stringify(o.action?.input)||JSON.stringify(n.parallelActions)!==JSON.stringify(o.parallelActions)||n.toolStatus!==o.toolStatus)}var _r=ic(function({step:e}){let n=e.action?.tool,o=e.action?.input,r=Tr(o),s=e.parallelActions??[],i=s.length>1;return Xe(ct,{flexDirection:"column",gap:0,children:[e.thinking&&Xe(ct,{children:[Q(le,{color:"gray",children:"\u25CF "}),Q(ct,{flexDirection:"column",flexGrow:1,children:Q(qe,{text:e.thinking,tone:"muted"})})]}),i&&Q(xn,{children:s.map((a,l)=>{let c=Tr(a.input);return Xe(ct,{children:[Q(le,{color:"green",children:"\u25CF "}),Q(le,{color:"gray",children:"Used "}),Q(le,{color:"cyan",children:a.tool}),c&&Xe(xn,{children:[Q(le,{color:"gray",children:" ("}),Q(le,{color:"cyan",children:c}),Q(le,{color:"gray",children:")"})]})]},l)})}),!i&&n&&Xe(ct,{children:[Q(le,{color:"green",children:"\u25CF "}),Q(le,{color:"gray",children:"Used "}),Q(le,{color:"cyan",children:n}),r&&Xe(xn,{children:[Q(le,{color:"gray",children:" ("}),Q(le,{color:"cyan",children:r}),Q(le,{color:"gray",children:")"})]})]})]})},ac);import{Box as lc,Text as xr}from"ink";import{memo as cc}from"react";import{jsx as Sr,jsxs as uc}from"react/jsx-runtime";var vr=cc(function({text:e}){return uc(lc,{paddingY:1,children:[Sr(xr,{color:"gray",children:"\u203A "}),Sr(xr,{color:"white",children:e})]})});import{Box as ut,Text as He}from"ink";import{memo as Sn,useMemo as pc}from"react";import{Fragment as dc,jsx as fe,jsxs as Lt}from"react/jsx-runtime";function mc(t){let e=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,n=[],o,r=0,s=[];for(;(o=e.exec(t))!==null;){s.push({start:o.index,end:e.lastIndex});let a=o[2]?.trim();a&&n.push(a)}if(s.length===0)return{content:t,thinking:null};let i="";r=0;for(let{start:a,end:l}of s)i+=t.slice(r,a),r=l;return i+=t.slice(r),i=i.replace(/\n{3,}/g,`
55
59
 
56
60
  `).trim(),{content:i,thinking:n.length>0?n.join(`
57
61
 
58
- `):null}}var ur=yn(function({text:t,isThinking:n=!1}){let{content:o,thinking:r}=vc(()=>Tc(t),[t]);return n?me(Qe,{flexDirection:"column",flexGrow:1,children:me(Ve,{text:t,tone:"muted"})}):Pt(Qe,{flexDirection:"column",flexGrow:1,gap:1,children:[r&&me(Qe,{flexDirection:"column",paddingLeft:2,children:me(Ve,{text:r,tone:"muted"})}),me(Ve,{text:o,tone:"normal"})]})}),Pd=yn(function({text:t}){return me(Qe,{children:Pt(Oe,{color:"gray",children:["\u2022 ",t]})})}),Rd=yn(function({toolName:t,fileName:n}){return Pt(Qe,{children:[me(Oe,{color:"green",children:"\u25CF "}),me(Oe,{color:"gray",children:"Used "}),me(Oe,{color:"cyan",children:t}),n&&Pt(Sc,{children:[me(Oe,{color:"gray",children:" ("}),me(Oe,{color:"cyan",children:n}),me(Oe,{color:"gray",children:")"})]})]})});import{jsx as xn,jsxs as pr}from"react/jsx-runtime";function wc(e,t){let n=e.turn,o=t.turn;if(n.index!==o.index||n.userInput!==o.userInput||n.finalText!==o.finalText||n.status!==o.status||n.steps.length!==o.steps.length||n.tokenUsage?.total!==o.tokenUsage?.total)return!1;for(let r=0;r<n.steps.length;r++){let s=n.steps[r],i=o.steps[r];if(!s||!i||s.assistantText!==i.assistantText||s.thinking!==i.thinking||s.action?.tool!==i.action?.tool)return!1}return!0}var vn=bc(function({turn:t}){let n=t.finalText?.trim()??"",o=n.length>0;return pr(_c,{flexDirection:"column",children:[xn(lr,{text:t.userInput}),t.steps.map(r=>xn(ir,{step:r},`step-${t.index}-${r.index}`)),o?xn(ur,{text:n,isThinking:!1}):null,t.status&&t.status!=="ok"?pr(kc,{color:"red",children:["Status: ",t.status]}):null]})},wc);import{jsx as q,jsxs as he}from"react/jsx-runtime";function Mc(e){let t=Ac.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Pc(e){return e.length>16?`${e.slice(0,8)}...${e.slice(-4)}`:e}function Rc(e,t){if(e.headerInfo?.sessionId!==t.headerInfo?.sessionId||e.headerInfo?.model!==t.headerInfo?.model||e.headerInfo?.providerName!==t.headerInfo?.providerName||e.headerInfo?.cwd!==t.headerInfo?.cwd||e.headerInfo?.version!==t.headerInfo?.version||e.headerInfo?.mcpNames?.length!==t.headerInfo?.mcpNames?.length)return!1;if(e.headerInfo?.mcpNames&&t.headerInfo?.mcpNames){let n=e.headerInfo.mcpNames,o=t.headerInfo.mcpNames;for(let r=0;r<n.length;r++)if(n[r]!==o[r])return!1}if(e.systemMessages.length!==t.systemMessages.length)return!1;for(let n=0;n<e.systemMessages.length;n++)if(e.systemMessages[n]?.id!==t.systemMessages[n]?.id)return!1;if(e.turns.length!==t.turns.length)return!1;for(let n=0;n<e.turns.length;n++)if(e.turns[n]!==t.turns[n])return!1;return!0}var mr=Ec(function({systemMessages:t,turns:n,headerInfo:o}){let r=n.length>0?n[n.length-1]:void 0,s=r&&(r.finalText||r.status&&r.status!=="ok"),i=s?n:n.slice(0,-1),a=s?void 0:r,c=[];o&&c.push({type:"header",data:o});let l=[];for(let u of t)l.push({sequence:u.sequence,item:{type:"system",data:u}});for(let u of i){let p=u.sequence??0;l.push({sequence:p,item:{type:"turn",data:u}})}l.sort((u,p)=>u.sequence-p.sequence);for(let u of l)c.push(u.item);return he(xe,{flexDirection:"column",gap:0,children:[q(Cc,{items:c,children:u=>{if(u.type==="header"&&u.data){let p=u.data;return he(xe,{borderStyle:"round",borderColor:"blueBright",paddingX:2,paddingY:1,flexDirection:"column",gap:1,children:[q(xe,{gap:1,alignItems:"center",children:he(xe,{flexDirection:"column",children:[q(le,{bold:!0,children:"Welcome to Memo Code CLI!"}),q(le,{color:"gray",children:"Send /help for help information."})]})}),he(xe,{flexDirection:"column",gap:0,children:[he(xe,{children:[q(le,{color:"gray",children:"Directory: "}),q(le,{color:"cyan",children:Mc(p.cwd)})]}),he(xe,{children:[q(le,{color:"gray",children:"Session: "}),q(le,{color:"cyan",children:Pc(p.sessionId)})]}),he(xe,{children:[q(le,{color:"gray",children:"Model: "}),q(le,{color:"cyan",children:p.model}),he(le,{color:"gray",children:[" ","(powered by ",p.providerName,")"]})]}),he(xe,{children:[q(le,{color:"gray",children:"Version: "}),he(le,{color:"cyan",children:["v",p.version]})]}),he(xe,{children:[q(le,{color:"gray",children:"MCP: "}),q(le,{color:"cyan",children:p.mcpNames.length>0?p.mcpNames.join(", "):"none"})]})]})]},"header")}return u.type==="system"?q(or,{message:u.data},u.data.id):u.type==="turn"?q(vn,{turn:u.data},`turn-${u.data.index}`):null}}),a&&q(vn,{turn:a},`turn-live-${a.index}`)]})},Rc);import{useCallback as Ur,useEffect as An,useMemo as Tl,useRef as Mn,useState as Ae}from"react";import{readFile as Sl,readdir as _l,stat as kl}from"fs/promises";import{basename as bl,join as wl,resolve as Hr}from"path";import{Box as Dt,Text as Ne,useInput as Cl}from"ink";var kr=Vn(Sr(),1);import{readFile as Zc,readdir as Qc}from"fs/promises";import{join as _r,relative as el,sep as tl}from"path";var nl=6,ol=2500,br=25,rl=[".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs","*.log"],Lt=new Map;function sl(e){return e.split(tl).join("/")}function il(e,t){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,respectGitIgnore:e.respectGitIgnore,ignoreGlobs:e.ignoreGlobs,gitignore:t})}function al(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):nl,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):ol,limit:typeof e.limit=="number"?Math.max(1,e.limit):br,respectGitIgnore:e.respectGitIgnore!==!1,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}async function cl(e,t){if(!t)return"";try{return await Zc(_r(e,".gitignore"),"utf8")}catch{}return""}async function ll(e,t){let n=await cl(t,e.respectGitIgnore),o=(0,kr.default)();o.add(rl),e.ignoreGlobs.length&&o.add(e.ignoreGlobs),n.trim()&&o.add(n);let r=il(e,n);return Object.assign(o,{__memoSignature:r})}async function ul(e,t,n){let o=[],r=t.maxEntries,s=async(i,a)=>{if(o.length>=r)return;let c;try{c=await Qc(i,{withFileTypes:!0})}catch{return}for(let l of c){if(o.length>=r)break;if(l.isSymbolicLink())continue;let u=_r(i,l.name),p=el(e,u);if(!p)continue;let h=sl(p);if(n.ignores(h))continue;let y=h.split("/").filter(Boolean),b=y.map(w=>w.toLowerCase()),x=l.isDirectory();if(o.push({path:h,pathLower:h.toLowerCase(),segments:y,segmentsLower:b,depth:a,isDir:x}),o.length>=r)break;x&&a<t.maxDepth&&await s(u,a+1)}};return await s(e,0),o.sort((i,a)=>i.path.localeCompare(a.path)),{entries:o,signature:n.__memoSignature}}async function pl(e,t){let n=al(t),o=await ll(n,e),r=o.__memoSignature,s=Lt.get(e);if(s&&s.signature===r)return s.pending?s.pending:s.entries;let i=ul(e,n,o).then(a=>(Lt.set(e,{entries:a.entries,signature:a.signature}),a.entries)).catch(a=>{throw Lt.delete(e),a});return Lt.set(e,{entries:[],signature:r,pending:i}),i}function ml(e){return e.depth+(e.isDir?-.2:.2)}function dl(e,t){if(!t.length)return ml(e);let n=e.depth,o=0;for(let r of t){let s=-1;for(let i=o;i<e.segmentsLower.length;i++){let a=e.segmentsLower[i];if(a.startsWith(r)){s=i,n+=(i-o)*1.5,n+=a.length-r.length;break}let c=a.indexOf(r);if(c!==-1){s=i,n+=(i-o)*2+c+2;break}}if(s===-1)return null;o=s+1}return e.isDir&&(n-=.5),n}function fl(e,t,n){let s=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(a=>a.toLowerCase()),i=[];for(let a of e){let c=dl(a,s);c!==null&&i.push({entry:a,score:c})}return i.sort((a,c)=>{let l=a.score-c.score;return l!==0?l:a.entry.path.localeCompare(c.entry.path)}),i.slice(0,n).map(({entry:a})=>({id:a.path,path:a.path,name:a.segments[a.segments.length-1]??a.path,parent:a.segments.length>1?a.segments.slice(0,-1).join("/"):void 0,isDir:a.isDir}))}async function wr(e){let t=await pl(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):br;return fl(t,e.query,n)}import{mkdir as Qd,readFile as ef,writeFile as tf}from"fs/promises";import{dirname as of}from"path";import{randomUUID as sf}from"crypto";import{Box as tt,Text as Ke}from"ink";import{jsx as we,jsxs as Er}from"react/jsx-runtime";var gl="#3a3a3a",Ot="#2b2b2b",Cr="#888888",hl="#666666";function Ar({items:e,activeIndex:t,loading:n}){return n?we(tt,{flexDirection:"column",paddingX:1,backgroundColor:Ot,children:we(Ke,{color:"gray",children:"Loading..."})}):e.length?we(tt,{flexDirection:"column",backgroundColor:Ot,children:e.map((o,r)=>{let s=r===t,i=s?gl:Ot;return o.kind==="slash"?Er(tt,{flexDirection:"row",gap:2,paddingX:1,backgroundColor:i,children:[we(Ke,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?we(Ke,{color:Cr,children:o.subtitle}):null]},o.id):Er(tt,{flexDirection:"row",gap:1,paddingX:1,backgroundColor:i,children:[we(Ke,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?we(Ke,{color:Cr,children:o.subtitle}):null]},o.id)})}):we(tt,{flexDirection:"column",paddingX:1,backgroundColor:Ot,children:we(Ke,{color:hl,children:"No matches"})})}var Cn=[{name:"help",description:"Show help and shortcuts"},{name:"exit",description:"Exit the session"},{name:"new",description:"Start a new session"},{name:"resume",description:"Resume session history"},{name:"models",description:"Select a model (from configured providers)"},{name:"context",description:"Set context length limit (80k/120k/150k/200k) (starts new session)"},{name:"mcp",description:"Show configured MCP servers"},{name:"init",description:"Generate AGENTS.md for current project"}],yl=Object.fromEntries(Cn.map(e=>[e.name,e.description]));function X(e){return yl[e]}function Mr(){let e=Cn.reduce((t,n)=>Math.max(t,n.name.length),0);return Cn.map(t=>` /${t.name.padEnd(e)} ${t.description}`)}var Pr={name:"new",description:X("new"),run:({closeSuggestions:e,setInputValue:t,clearScreen:n,showSystemMessage:o,newSession:r})=>{e(),t(""),n(),o("New Session","Starting a new session..."),r?.()}};var Rr={name:"exit",description:X("exit"),run:({closeSuggestions:e,exitApp:t})=>{e(),t()}};var $r={name:"resume",description:X("resume"),run:({closeSuggestions:e,setInputValue:t,showSystemMessage:n})=>{e(!1),t("resume "),n("Resume",'Type "resume" followed by keywords to filter and select from session history.')}};var Ir={name:"models",description:X("models"),run:({closeSuggestions:e,setInputValue:t,showSystemMessage:n,data:o})=>{e(!1);let{providers:r,providerName:s,model:i}=o;if(!r.length){n("Models",`No providers configured. Check ${o.configPath}`),t("");return}let a=r.map(c=>{let l=c.name===s&&c.model===i?" (current)":"",u=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${u}${l}`});t("/models "),n("Models",`Available models:
62
+ `):null}}var Cr=Sn(function({text:e,isThinking:n=!1}){let{content:o,thinking:r}=pc(()=>mc(e),[e]);return n?fe(ut,{flexDirection:"column",flexGrow:1,children:fe(qe,{text:e,tone:"muted"})}):Lt(ut,{flexDirection:"column",flexGrow:1,gap:1,children:[r&&fe(ut,{flexDirection:"column",paddingLeft:2,children:fe(qe,{text:r,tone:"muted"})}),fe(qe,{text:o,tone:"normal"})]})}),pg=Sn(function({text:e}){return fe(ut,{children:Lt(He,{color:"gray",children:["\u2022 ",e]})})}),mg=Sn(function({toolName:e,fileName:n}){return Lt(ut,{children:[fe(He,{color:"green",children:"\u25CF "}),fe(He,{color:"gray",children:"Used "}),fe(He,{color:"cyan",children:e}),n&&Lt(dc,{children:[fe(He,{color:"gray",children:" ("}),fe(He,{color:"cyan",children:n}),fe(He,{color:"gray",children:")"})]})]})});import{jsx as vn,jsxs as wr}from"react/jsx-runtime";function yc(t,e){let n=t.turn,o=e.turn;if(n.index!==o.index||n.userInput!==o.userInput||n.finalText!==o.finalText||n.status!==o.status||n.steps.length!==o.steps.length||n.tokenUsage?.total!==o.tokenUsage?.total)return!1;for(let r=0;r<n.steps.length;r++){let s=n.steps[r],i=o.steps[r];if(!s||!i||s.assistantText!==i.assistantText||s.thinking!==i.thinking||s.action?.tool!==i.action?.tool)return!1}return!0}var Cn=hc(function({turn:e}){let n=e.finalText?.trim()??"",o=n.length>0;return wr(fc,{flexDirection:"column",children:[vn(vr,{text:e.userInput}),e.steps.map(r=>vn(_r,{step:r},`step-${e.index}-${r.index}`)),o?vn(Cr,{text:n,isThinking:!1}):null,e.status&&e.status!=="ok"?wr(gc,{color:"red",children:["Status: ",e.status]}):null]})},yc);import{jsx as ee,jsxs as Te}from"react/jsx-runtime";function Sc(t){let e=xc.homedir();return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}function vc(t){return t.length>16?`${t.slice(0,8)}...${t.slice(-4)}`:t}function Cc(t,e){if(t.headerInfo?.sessionId!==e.headerInfo?.sessionId||t.headerInfo?.model!==e.headerInfo?.model||t.headerInfo?.providerName!==e.headerInfo?.providerName||t.headerInfo?.cwd!==e.headerInfo?.cwd||t.headerInfo?.version!==e.headerInfo?.version||t.headerInfo?.mcpNames?.length!==e.headerInfo?.mcpNames?.length)return!1;if(t.headerInfo?.mcpNames&&e.headerInfo?.mcpNames){let n=t.headerInfo.mcpNames,o=e.headerInfo.mcpNames;for(let r=0;r<n.length;r++)if(n[r]!==o[r])return!1}if(t.systemMessages.length!==e.systemMessages.length)return!1;for(let n=0;n<t.systemMessages.length;n++)if(t.systemMessages[n]?.id!==e.systemMessages[n]?.id)return!1;if(t.turns.length!==e.turns.length)return!1;for(let n=0;n<t.turns.length;n++)if(t.turns[n]!==e.turns[n])return!1;return!0}var Er=_c(function({systemMessages:e,turns:n,headerInfo:o}){let r=n.length>0?n[n.length-1]:void 0,s=r&&(r.finalText||r.status&&r.status!=="ok"),i=s?n:n.slice(0,-1),a=s?void 0:r,l=[];o&&l.push({type:"header",data:o});let c=[];for(let u of e)c.push({sequence:u.sequence,item:{type:"system",data:u}});for(let u of i){let p=u.sequence??0;c.push({sequence:p,item:{type:"turn",data:u}})}c.sort((u,p)=>u.sequence-p.sequence);for(let u of c)l.push(u.item);return Te(Se,{flexDirection:"column",gap:0,children:[ee(Tc,{items:l,children:u=>{if(u.type==="header"&&u.data){let p=u.data;return Te(Se,{borderStyle:"round",borderColor:"blueBright",paddingX:2,paddingY:1,flexDirection:"column",gap:1,children:[ee(Se,{gap:1,alignItems:"center",children:Te(Se,{flexDirection:"column",children:[ee(ce,{bold:!0,children:"Welcome to Memo Code CLI!"}),ee(ce,{color:"gray",children:"Send /help for help information."})]})}),Te(Se,{flexDirection:"column",gap:0,children:[Te(Se,{children:[ee(ce,{color:"gray",children:"Directory: "}),ee(ce,{color:"cyan",children:Sc(p.cwd)})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"Session: "}),ee(ce,{color:"cyan",children:vc(p.sessionId)})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"Model: "}),ee(ce,{color:"cyan",children:p.model}),Te(ce,{color:"gray",children:[" ","(powered by ",p.providerName,")"]})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"Version: "}),Te(ce,{color:"cyan",children:["v",p.version]})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"MCP: "}),ee(ce,{color:"cyan",children:p.mcpNames.length>0?p.mcpNames.join(", "):"none"})]})]})]},"header")}return u.type==="system"?ee(hr,{message:u.data},u.data.id):u.type==="turn"?ee(Cn,{turn:u.data},`turn-${u.data.index}`):null}}),a&&ee(Cn,{turn:a},`turn-live-${a.index}`)]})},Cc);import{useCallback as Yr,useEffect as In,useMemo as mu,useRef as $n,useState as Le}from"react";import{readFile as du,readdir as fu,stat as gu}from"fs/promises";import{basename as hu,join as jt,resolve as ft}from"path";import{Box as Bt,Text as Fe,useInput as yu}from"ink";var Nr=Kn(Lr(),1);import{readFile as Vc,readdir as zc}from"fs/promises";import{join as Or,relative as Gc,sep as Kc}from"path";var qc=6,Xc=2500,Dr=25,Jc=[".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs","*.log"],Ut=new Map;function Yc(t){return t.split(Kc).join("/")}function Zc(t,e){return JSON.stringify({maxDepth:t.maxDepth,maxEntries:t.maxEntries,respectGitIgnore:t.respectGitIgnore,ignoreGlobs:t.ignoreGlobs,gitignore:e})}function Qc(t){return{maxDepth:typeof t.maxDepth=="number"?Math.max(1,t.maxDepth):qc,maxEntries:typeof t.maxEntries=="number"?Math.max(100,t.maxEntries):Xc,limit:typeof t.limit=="number"?Math.max(1,t.limit):Dr,respectGitIgnore:t.respectGitIgnore!==!1,ignoreGlobs:t.ignoreGlobs?.length?t.ignoreGlobs:[]}}async function eu(t,e){if(!e)return"";try{return await Vc(Or(t,".gitignore"),"utf8")}catch{}return""}async function tu(t,e){let n=await eu(e,t.respectGitIgnore),o=(0,Nr.default)();o.add(Jc),t.ignoreGlobs.length&&o.add(t.ignoreGlobs),n.trim()&&o.add(n);let r=Zc(t,n);return Object.assign(o,{__memoSignature:r})}async function nu(t,e,n){let o=[],r=e.maxEntries,s=async(i,a)=>{if(o.length>=r)return;let l;try{l=await zc(i,{withFileTypes:!0})}catch{return}for(let c of l){if(o.length>=r)break;if(c.isSymbolicLink())continue;let u=Or(i,c.name),p=Gc(t,u);if(!p)continue;let T=Yc(p);if(n.ignores(T))continue;let y=T.split("/").filter(Boolean),S=y.map(P=>P.toLowerCase()),h=c.isDirectory();if(o.push({path:T,pathLower:T.toLowerCase(),segments:y,segmentsLower:S,depth:a,isDir:h}),o.length>=r)break;h&&a<e.maxDepth&&await s(u,a+1)}};return await s(t,0),o.sort((i,a)=>i.path.localeCompare(a.path)),{entries:o,signature:n.__memoSignature}}async function ou(t,e){let n=Qc(e),o=await tu(n,t),r=o.__memoSignature,s=Ut.get(t);if(s&&s.signature===r)return s.pending?s.pending:s.entries;let i=nu(t,n,o).then(a=>(Ut.set(t,{entries:a.entries,signature:a.signature}),a.entries)).catch(a=>{throw Ut.delete(t),a});return Ut.set(t,{entries:[],signature:r,pending:i}),i}function ru(t){return t.depth+(t.isDir?-.2:.2)}function su(t,e){if(!e.length)return ru(t);let n=t.depth,o=0;for(let r of e){let s=-1;for(let i=o;i<t.segmentsLower.length;i++){let a=t.segmentsLower[i];if(a.startsWith(r)){s=i,n+=(i-o)*1.5,n+=a.length-r.length;break}let l=a.indexOf(r);if(l!==-1){s=i,n+=(i-o)*2+l+2;break}}if(s===-1)return null;o=s+1}return t.isDir&&(n-=.5),n}function iu(t,e,n){let s=e.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(a=>a.toLowerCase()),i=[];for(let a of t){let l=su(a,s);l!==null&&i.push({entry:a,score:l})}return i.sort((a,l)=>{let c=a.score-l.score;return c!==0?c:a.entry.path.localeCompare(l.entry.path)}),i.slice(0,n).map(({entry:a})=>({id:a.path,path:a.path,name:a.segments[a.segments.length-1]??a.path,parent:a.segments.length>1?a.segments.slice(0,-1).join("/"):void 0,isDir:a.isDir}))}async function Ur(t){let e=await ou(t.cwd,t),n=typeof t.limit=="number"?Math.max(1,t.limit):Dr;return iu(e,t.query,n)}import{mkdir as Lg,readFile as Og,writeFile as Ng}from"fs/promises";import{dirname as Ug}from"path";import{randomUUID as Fg}from"crypto";import{Box as mt,Text as Ze}from"ink";import{jsx as Pe,jsxs as Fr}from"react/jsx-runtime";var au="#3a3a3a",Ht="#2b2b2b",Hr="#888888",lu="#666666";function jr({items:t,activeIndex:e,loading:n}){return n?Pe(mt,{flexDirection:"column",paddingX:1,backgroundColor:Ht,children:Pe(Ze,{color:"gray",children:"Loading..."})}):t.length?Pe(mt,{flexDirection:"column",backgroundColor:Ht,children:t.map((o,r)=>{let s=r===e,i=s?au:Ht;return o.kind==="slash"?Fr(mt,{flexDirection:"row",gap:2,paddingX:1,backgroundColor:i,children:[Pe(Ze,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?Pe(Ze,{color:Hr,children:o.subtitle}):null]},o.id):Fr(mt,{flexDirection:"row",gap:1,paddingX:1,backgroundColor:i,children:[Pe(Ze,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?Pe(Ze,{color:Hr,children:o.subtitle}):null]},o.id)})}):Pe(mt,{flexDirection:"column",paddingX:1,backgroundColor:Ht,children:Pe(Ze,{color:lu,children:"No matches"})})}var Pn=[{name:"help",description:"Show help and shortcuts"},{name:"exit",description:"Exit the session"},{name:"new",description:"Start a new session"},{name:"resume",description:"Resume session history"},{name:"models",description:"Select a model (from configured providers)"},{name:"context",description:"Set context length limit (80k/120k/150k/200k) (starts new session)"},{name:"mcp",description:"Show configured MCP servers"},{name:"init",description:"Generate AGENTS.md for current project"}],cu=Object.fromEntries(Pn.map(t=>[t.name,t.description]));function te(t){return cu[t]}function Br(){let t=Pn.reduce((e,n)=>Math.max(e,n.name.length),0);return Pn.map(e=>` /${e.name.padEnd(t)} ${e.description}`)}var Wr={name:"new",description:te("new"),run:({closeSuggestions:t,setInputValue:e,clearScreen:n,showSystemMessage:o,newSession:r})=>{t(),e(""),n(),o("New Session","Starting a new session..."),r?.()}};var Vr={name:"exit",description:te("exit"),run:({closeSuggestions:t,exitApp:e})=>{t(),e()}};var zr={name:"resume",description:te("resume"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n})=>{t(!1),e("resume "),n("Resume",'Type "resume" followed by keywords to filter and select from session history.')}};var Gr={name:"models",description:te("models"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n,data:o})=>{t(!1);let{providers:r,providerName:s,model:i}=o;if(!r.length){n("Models",`No providers configured. Check ${o.configPath}`),e("");return}let a=r.map(l=>{let c=l.name===s&&l.model===i?" (current)":"",u=l.base_url?` @ ${l.base_url}`:"";return`- ${l.name}: ${l.model}${u}${c}`});e("/models "),n("Models",`Available models:
59
63
  ${a.join(`
60
- `)}`)}};var xl=Mr().join(`
61
- `),Nt=`Available commands:
62
- ${xl}
64
+ `)}`)}};var uu=Br().join(`
65
+ `),Ft=`Available commands:
66
+ ${uu}
63
67
  exit Exit the session (no slash)
64
68
  $ Execute shell command (e.g. $ git status)
65
69
 
@@ -71,24 +75,24 @@ Shortcuts:
71
75
  Ctrl+L Start a new session
72
76
  Ctrl+C Exit
73
77
  exit Type in input to exit
74
- Esc Esc Cancel / Clear input`;var Lr={name:"help",description:X("help"),run:({closeSuggestions:e,setInputValue:t,showSystemMessage:n})=>{e(),t(""),n("Help",Nt)}};var Or={name:"context",description:X("context"),run:({closeSuggestions:e,setInputValue:t})=>{e(!1),t("/context ")}};function vl(e,t){let n=[];if(n.push(`- **${e}**`),"url"in t){n.push(` - Type: ${t.type??"streamable_http"}`),n.push(` - URL: ${t.url}`),t.bearer_token_env_var&&n.push(` - Bearer token env: ${t.bearer_token_env_var}`),t.type!=="sse"&&t.fallback_to_sse!==void 0&&n.push(` - Fallback to SSE: ${t.fallback_to_sse}`);let o=t.http_headers??t.headers;if(o&&Object.keys(o).length>0){let r=Object.entries(o).map(([s,i])=>`${s}=${i}`).join(", ");n.push(` - Headers: ${r}`)}}else if(n.push(` - Type: ${t.type??"stdio"}`),n.push(` - Command: ${t.command}`),t.args&&t.args.length>0&&n.push(` - Args: ${t.args.join(" ")}`),t.env&&Object.keys(t.env).length>0){let o=Object.entries(t.env).map(([r,s])=>`${r}=${s}`).join(", ");n.push(` - Env: ${o}`)}return n.join(`
75
- `)}var Nr={name:"mcp",description:X("mcp"),run:({closeSuggestions:e,setInputValue:t,showSystemMessage:n,data:o})=>{e();let{mcpServers:r,configPath:s}=o,i=Object.keys(r);if(i.length===0){n("MCP Servers",`No MCP servers configured.
76
-
77
- Add servers to ${s}`),t("");return}let a=[];a.push(`Total: ${i.length} server(s)
78
- `);for(let[c,l]of Object.entries(r))a.push(vl(c,l)),a.push("");t(""),n("MCP Servers",a.join(`
79
- `))}};var Dr={name:"init",description:X("init"),run:({closeSuggestions:e,setInputValue:t})=>{e(!1),t("/init")}};var En=[Lr,Rr,Pr,$r,Ir,Or,Nr,Dr];import{Fragment as jl,jsx as Me,jsxs as nt}from"react/jsx-runtime";var El=400;function jr({disabled:e,onSubmit:t,onExit:n,onClear:o,onNewSession:r,onCancelRun:s,onModelSelect:i,onSystemMessage:a,onSetContextLimit:c,history:l,cwd:u,sessionsDir:p,currentSessionFile:h,onHistorySelect:y,providers:b,configPath:x,providerName:w,model:_,contextLimit:k,mcpServers:d}){let[v,E]=Ae(""),[B,I]=Ae(null),[ue,M]=Ae(""),[C,P]=Ae("none"),[V,ee]=Ae([]),[ye,D]=Ae(0),[re,se]=Ae(!1),[Re,He]=Ae(!1),de=Mn(0),ie=Mn(0),H=Mn(""),Bt="\u203A ";An(()=>{H.current=v,He(!1)},[v]);let j=Tl(()=>Re||e?null:$l(v),[e,Re,v]),z=Ur((L=!0)=>{L&&He(!0),P("none"),ee([]),D(0),se(!1)},[]);An(()=>{e&&z(!1)},[e,z]),An(()=>{if(!j){P("none"),ee([]),D(0),se(!1);return}let L=!1,U=++de.current;return se(!0),(async()=>{try{if(j.type==="file"){let R=await wr({cwd:u,query:j.query,limit:8});if(L||U!==de.current)return;let N=R.map(g=>{let A=g.isDir?`${g.path}/`:g.path;return{id:g.id,title:A,kind:"file",value:A,meta:{isDir:g.isDir}}});P("file"),ee(N),D(g=>N.length?Math.min(g,N.length-1):0);return}if(j.type==="history"){let R=await Al({sessionsDir:p,cwd:u,keyword:j.keyword,activeSessionFile:h});if(L||U!==de.current)return;let N=R.map(Ul);P("history"),ee(N),D(g=>N.length?Math.min(g,N.length-1):0);return}if(j.type==="models"){let R=j.keyword.toLowerCase(),g=(b??[]).filter(A=>{let te=A.name?.toLowerCase()??"",fe=A.model?.toLowerCase()??"";return R?te.includes(R)||fe.includes(R):!0}).map(A=>({id:A.name,title:`${A.name}: ${A.model}`,subtitle:A.base_url??A.env_api_key??"",kind:"model",value:`/models ${A.name}`,meta:{provider:A}}));P("model"),ee(g),D(A=>g.length?Math.min(A,g.length-1):0);return}if(j.type==="context"){let N=[8e4,12e4,15e4,2e5].map(g=>({id:`${g}`,title:`${(g/1e3).toFixed(0)}k tokens`,subtitle:g===k?"Current":void 0,kind:"context",value:`/context ${(g/1e3).toFixed(0)}k`,meta:{contextValue:g}}));P("context"),ee(N),D(g=>N.length?Math.min(g,N.length-1):0);return}if(j.type==="slash"){let R=j.keyword.toLowerCase(),g=(R?En.filter(A=>A.matches?A.matches(R):A.name.startsWith(R)):En).map(A=>({id:A.name,title:`/${A.name}`,subtitle:A.description,kind:"slash",value:`/${A.name} `,meta:{slashCommand:A}}));P("slash"),ee(g),D(A=>g.length?Math.min(A,g.length-1):0);return}}catch{!L&&U===de.current&&ee([])}finally{!L&&U===de.current&&se(!1)}})(),()=>{L=!0}},[j,u,p,h,b,k]);let ct=Ur(L=>{if(L){if(C==="file"&&j?.type==="file"){let U=v.slice(0,j.tokenStart),R=v.slice(j.tokenStart+j.query.length),N=`${U}${L.value}${R}`;H.current=N,E(N),I(null),M(""),L.meta?.isDir||z();return}if(C==="history"){L.meta?.historyEntry&&y?.(L.meta.historyEntry),H.current=L.value,E(L.value),I(null),M(""),z();return}if(C==="model"&&L.meta?.provider){i?.(L.meta.provider),H.current="",E(""),I(null),M(""),z();return}if(C==="slash"&&L.meta?.slashCommand){L.meta.slashCommand.run({setInputValue:R=>{H.current=R,E(R),I(null),M("")},closeSuggestions:z,clearScreen:()=>{o()},newSession:()=>{r?.()},exitApp:()=>{n()},showSystemMessage:(R,N)=>{a?.(R,N)},switchModel:R=>{i?.(R)},setContextLimit:R=>{c?.(R)},loadHistory:R=>{y?.(R)},data:{configPath:x,providerName:w,model:_,contextLimit:k,providers:b,mcpServers:d}});return}if(C==="context"&&L.meta?.contextValue){let U=L.meta.contextValue;c?.(U),a?.("Context",`Context limit set to ${(U/1e3).toFixed(0)}k tokens`),H.current="",E(""),I(null),M(""),z();return}}},[z,o,n,i,a,c,y,C,j,v,x,w,_,k,b,d]);Cl((L,U)=>{if(U.ctrl&&L==="l"){H.current="",E(""),I(null),M(""),z(),o(),r?.();return}let R=C!=="none",N=R&&V.length>0;if(U.escape){let g=Date.now();if(g-ie.current<=El){ie.current=0,e?s():(H.current="",E(""),I(null),M(""),z());return}ie.current=g,R&&z();return}if(!e){if(U.upArrow){if(N){D(te=>te<=0?V.length-1:te-1);return}if(!l.length)return;if(B===null){M(H.current);let te=l.length-1;I(te);let fe=l[te]??"";H.current=fe,E(fe);return}let g=Math.max(0,B-1);I(g);let A=l[g]??"";H.current=A,E(A);return}if(U.downArrow){if(N){D(te=>(te+1)%V.length);return}if(B===null)return;let g=B+1;if(g>=l.length){I(null),H.current=ue,E(ue),M("");return}I(g);let A=l[g]??"";H.current=A,E(A);return}if(U.tab&&N){ct(V[ye]);return}if(U.return){if(N){ct(V[ye]);return}if(U.shift){let A=H.current+`
80
- `;H.current=A,E(A);return}let g=H.current.trim();g&&(t(g),H.current="",E(""),I(null),M(""),z(!1));return}if(U.backspace||U.delete){let g=H.current.slice(0,Math.max(0,H.current.length-1));H.current=g,E(g);return}if(L){let g=H.current+L;H.current=g,E(g)}}});let qe=v,lt=e?" ":"\u258A",$e=qe.split(`
81
- `),Ee=2,Ft=V.map(({value:L,meta:U,...R})=>R);return nt(Dt,{flexDirection:"column",gap:1,children:[nt(Dt,{flexDirection:"column",paddingY:1,children:[nt(Dt,{children:[Me(Ne,{color:"gray",children:Bt}),e?Me(Ne,{color:"gray",children:$e[0]}):nt(jl,{children:[Me(Ne,{color:"white",children:$e[0]}),$e.length===1&&Me(Ne,{color:"cyan",children:lt})]})]}),$e.slice(1).map((L,U)=>nt(Dt,{children:[Me(Ne,{color:"gray",children:" ".repeat(Ee)}),Me(Ne,{color:"white",children:L}),U===$e.length-2&&Me(Ne,{color:"cyan",children:lt})]},`line-${U}`))]}),C!=="none"?Me(Ar,{items:Ft,activeIndex:ye,loading:re}):null]})}async function Al(e){let t=Ho(e.sessionsDir,e.cwd),n;try{n=await _l(t,{withFileTypes:!0})}catch(l){return l?.code==="ENOENT"?[]:[]}let o=e.activeSessionFile?Hr(e.activeSessionFile):null,s=(await Promise.all(n.filter(l=>l.isFile()&&l.name.endsWith(".jsonl")).map(async l=>{let u=wl(t,l.name);if(o&&Hr(u)===o)return null;try{let p=await kl(u);return{path:u,mtimeMs:p.mtimeMs}}catch{return null}}))).filter(l=>!!l).sort((l,u)=>u.mtimeMs-l.mtimeMs),i=e.limit??10,a=e.keyword?.trim().toLowerCase(),c=[];for(let l of s){if(c.length>=i)break;let u=await Ml(l.path,e.cwd,l.mtimeMs);if(u&&!(a&&!u.input.toLowerCase().includes(a))&&(c.push(u),c.length>=i))break}return c}async function Ml(e,t,n){try{let o=await Sl(e,"utf8"),s=Pl(o)?.trim()||Rl(e);return{id:e,cwd:t,input:s,ts:n,sessionFile:e}}catch{return null}}function Pl(e){for(let t of e.split(`
82
- `)){let n=t.trim();if(!n)continue;let o;try{o=JSON.parse(n)}catch{continue}if(o&&typeof o=="object"&&o.type==="turn_start"){let r=typeof o.content=="string"?o.content.trim():"";if(r)return r}}return null}function Rl(e){return bl(e).replace(/\.jsonl$/i,"")}function $l(e){let t=Nl(e);if(t)return t;let n=Ol(e);if(n)return n;let o=Dl(e);if(o)return o;let r=Il(e);return r||Ll(e)}function Il(e){let t=e.lastIndexOf("@");if(t===-1)return null;if(t>0){let o=e[t-1];if(o&&!/\s/.test(o))return null}let n=e.slice(t+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:t+1}}function Ll(e){let t=e.trimStart(),n=e.length-t.length;if(t.length===0)return null;let o=t;if(o.startsWith("/")&&(o=o.slice(1)),!o.toLowerCase().startsWith("resume")||e.slice(0,n).trim().length>0)return null;let s=o.slice(6);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function Ol(e){let t=e.trimStart();if(!t.startsWith("/models"))return null;let n=t.slice(7);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim()}}function Nl(e){let t=e.trimStart();if(!t.startsWith("/context"))return null;let n=t.slice(8);return n&&!n.startsWith(" ")?null:{type:"context"}}function Dl(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1);return n.includes(" ")?null:/^[a-zA-Z]*$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:n.length===0?{type:"slash",keyword:""}:null}function Ul(e){return{id:e.id,title:e.input,subtitle:Hl(e.ts),kind:"history",badge:"HIS",value:e.input,meta:{historyEntry:e}}}function Hl(e){if(!e)return"";let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getFullYear()),o=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${r} ${s}:${i}`}import{Box as ot,Text as Pn,useInput as Bl}from"ink";import{useState as Fl,useCallback as Vl}from"react";import{jsx as rt,jsxs as Rn}from"react/jsx-runtime";function Gl(e){if(typeof e!="object"||e===null)return String(e);let t=Object.entries(e);if(t.length===0)return"";let[n,o]=t[0],r=typeof o=="string"?o:JSON.stringify(o);return`${r.slice(0,40)}${r.length>40?"...":""}`}function Br({request:e,onDecision:t}){let n=[{label:"Allow once",decision:"once"},{label:"Allow all session",decision:"session"},{label:"Reject this time",decision:"deny"}],[o,r]=Fl(0);Bl(Vl((i,a)=>{a.upArrow?r(c=>c>0?c-1:n.length-1):a.downArrow?r(c=>c<n.length-1?c+1:0):a.return&&t(n[o].decision)},[o,t,n]));let s=Gl(e.params);return Rn(ot,{borderStyle:"single",borderColor:"gray",paddingX:2,flexDirection:"column",children:[rt(ot,{children:rt(Pn,{bold:!0,children:"Tool Approval:"})}),rt(ot,{marginTop:1,children:Rn(Pn,{color:"cyan",children:[e.toolName,s?` (${s})`:""]})}),rt(ot,{flexDirection:"column",marginTop:1,children:n.map((i,a)=>rt(ot,{children:Rn(Pn,{color:o===a?"green":"gray",children:[o===a?"> ":" ",i.label]})},i.decision))})]})}import sg from"string-width";function Vr(e){if(!e)return"success";let t=e.toLowerCase();return t.includes("error")||t.includes("unknown")||t.includes("failed")?"error":"success"}var Fr={"gpt-4o-mini":128e3,"gpt-4o":128e3,"gpt-4":8192,"gpt-3.5":16384,"claude-3":2e5,claude:2e5,"deepseek-coder":64e3,"deepseek-chat":64e3,deepseek:64e3,"kimi-k2":2e5,kimi:2e5,default:12e4};function zl(e){let t=e.toLowerCase(),n=Object.entries(Fr).filter(([o])=>o!=="default");for(let[o,r]of n.sort((s,i)=>i[0].length-s[0].length))if(t.includes(o))return r;return Fr.default}function Gr(e,t){if(e==null)return 0;let n=typeof e=="number"?e:e.prompt??e.total??0;if(n<=0)return 0;let o=t&&t>0?t:zl("");return Math.min(100,n/o*100)}function zr(e){return e?`${e.total} tokens`:""}function Wr(e,t){let[n,...o]=e.trim().slice(1).split(/\s+/),r=(n??"").toLowerCase(),s=[8e4,12e4,15e4,2e5],i=a=>{if(!a)return null;let l=a.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!l)return null;let u=Number(l[1])*(l[2]?1e3:1);return Number.isFinite(u)?u:null};switch(r){case"exit":return{kind:"exit"};case"new":return{kind:"new"};case"help":return{kind:"message",title:"Help",content:Nt};case"config":return{kind:"message",title:"Config",content:`Config file: ${t.configPath}
83
- Current provider: ${t.providerName}
84
- Current model: ${t.model}`};case"resume":return{kind:"message",title:"Resume",content:'Type "resume" to filter and select from session history.'};case"context":{let p=i(o[0]),h=s.map(y=>`${y/1e3}k`).join(", ");return p===null?{kind:"message",title:"Context",content:`Current: ${(t.contextLimit/1e3).toFixed(0)}k
78
+ Esc Esc Cancel / Clear input`;var Kr={name:"help",description:te("help"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n})=>{t(),e(""),n("Help",Ft)}};var qr={name:"context",description:te("context"),run:({closeSuggestions:t,setInputValue:e})=>{t(!1),e("/context ")}};function pu(t,e){let n=[];if(n.push(`- **${t}**`),"url"in e){n.push(` - Type: ${e.type??"streamable_http"}`),n.push(` - URL: ${e.url}`),e.bearer_token_env_var&&n.push(` - Bearer token env: ${e.bearer_token_env_var}`);let o=e.http_headers??e.headers;if(o&&Object.keys(o).length>0){let r=Object.entries(o).map(([s,i])=>`${s}=${i}`).join(", ");n.push(` - Headers: ${r}`)}}else if(n.push(` - Type: ${e.type??"stdio"}`),n.push(` - Command: ${e.command}`),e.args&&e.args.length>0&&n.push(` - Args: ${e.args.join(" ")}`),e.env&&Object.keys(e.env).length>0){let o=Object.entries(e.env).map(([r,s])=>`${r}=${s}`).join(", ");n.push(` - Env: ${o}`)}return n.join(`
79
+ `)}var Xr={name:"mcp",description:te("mcp"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n,data:o})=>{t();let{mcpServers:r,configPath:s}=o,i=Object.keys(r);if(i.length===0){n("MCP Servers",`No MCP servers configured.
80
+
81
+ Add servers to ${s}`),e("");return}let a=[];a.push(`Total: ${i.length} server(s)
82
+ `);for(let[l,c]of Object.entries(r))a.push(pu(l,c)),a.push("");e(""),n("MCP Servers",a.join(`
83
+ `))}};var Jr={name:"init",description:te("init"),run:({closeSuggestions:t,setInputValue:e})=>{t(!1),e("/init")}};var Rn=[Kr,Vr,Wr,zr,Gr,qr,Xr,Jr];import{Fragment as $u,jsx as Oe,jsxs as dt}from"react/jsx-runtime";var Tu=400;function Qr({disabled:t,onSubmit:e,onExit:n,onClear:o,onNewSession:r,onCancelRun:s,onModelSelect:i,onSystemMessage:a,onSetContextLimit:l,history:c,cwd:u,sessionsDir:p,currentSessionFile:T,onHistorySelect:y,providers:S,configPath:h,providerName:P,model:C,contextLimit:x,mcpServers:b}){let[A,M]=Le(""),[w,N]=Le(null),[_e,U]=Le(""),[B,re]=Le("none"),[z,k]=Le([]),[$,K]=Le(0),[ue,pe]=Le(!1),[xe,Ce]=Le(!1),E=$n(0),F=$n(0),W=$n(""),Gt="\u203A ";In(()=>{W.current=A,Ce(!1)},[A]);let V=mu(()=>xe||t?null:Eu(A),[t,xe,A]),X=Yr((L=!0)=>{L&&Ce(!0),re("none"),k([]),K(0),pe(!1)},[]);In(()=>{t&&X(!1)},[t,X]),In(()=>{if(!V){re("none"),k([]),K(0),pe(!1);return}let L=!1,j=++E.current;return pe(!0),(async()=>{try{if(V.type==="file"){let R=await Ur({cwd:u,query:V.query,limit:8});if(L||j!==E.current)return;let H=R.map(g=>{let v=g.isDir?`${g.path}/`:g.path;return{id:g.id,title:v,kind:"file",value:v,meta:{isDir:g.isDir}}});re("file"),k(H),K(g=>H.length?Math.min(g,H.length-1):0);return}if(V.type==="history"){let R=await _u({sessionsDir:p,cwd:u,keyword:V.keyword,activeSessionFile:T});if(L||j!==E.current)return;let H=R.map(Ru);re("history"),k(H),K(g=>H.length?Math.min(g,H.length-1):0);return}if(V.type==="models"){let R=V.keyword.toLowerCase(),g=(S??[]).filter(v=>{let se=v.name?.toLowerCase()??"",ge=v.model?.toLowerCase()??"";return R?se.includes(R)||ge.includes(R):!0}).map(v=>({id:v.name,title:`${v.name}: ${v.model}`,subtitle:v.base_url??v.env_api_key??"",kind:"model",value:`/models ${v.name}`,meta:{provider:v}}));re("model"),k(g),K(v=>g.length?Math.min(v,g.length-1):0);return}if(V.type==="context"){let H=[8e4,12e4,15e4,2e5].map(g=>({id:`${g}`,title:`${(g/1e3).toFixed(0)}k tokens`,subtitle:g===x?"Current":void 0,kind:"context",value:`/context ${(g/1e3).toFixed(0)}k`,meta:{contextValue:g}}));re("context"),k(H),K(g=>H.length?Math.min(g,H.length-1):0);return}if(V.type==="slash"){let R=V.keyword.toLowerCase(),g=(R?Rn.filter(v=>v.matches?v.matches(R):v.name.startsWith(R)):Rn).map(v=>({id:v.name,title:`/${v.name}`,subtitle:v.description,kind:"slash",value:`/${v.name} `,meta:{slashCommand:v}}));re("slash"),k(g),K(v=>g.length?Math.min(v,g.length-1):0);return}}catch{!L&&j===E.current&&k([])}finally{!L&&j===E.current&&pe(!1)}})(),()=>{L=!0}},[V,u,p,T,S,x]);let xt=Yr(L=>{if(L){if(B==="file"&&V?.type==="file"){let j=A.slice(0,V.tokenStart),R=A.slice(V.tokenStart+V.query.length),H=`${j}${L.value}${R}`;W.current=H,M(H),N(null),U(""),L.meta?.isDir||X();return}if(B==="history"){L.meta?.historyEntry&&y?.(L.meta.historyEntry),W.current=L.value,M(L.value),N(null),U(""),X();return}if(B==="model"&&L.meta?.provider){i?.(L.meta.provider),W.current="",M(""),N(null),U(""),X();return}if(B==="slash"&&L.meta?.slashCommand){L.meta.slashCommand.run({setInputValue:R=>{W.current=R,M(R),N(null),U("")},closeSuggestions:X,clearScreen:()=>{o()},newSession:()=>{r?.()},exitApp:()=>{n()},showSystemMessage:(R,H)=>{a?.(R,H)},switchModel:R=>{i?.(R)},setContextLimit:R=>{l?.(R)},loadHistory:R=>{y?.(R)},data:{configPath:h,providerName:P,model:C,contextLimit:x,providers:S,mcpServers:b}});return}if(B==="context"&&L.meta?.contextValue){let j=L.meta.contextValue;l?.(j),a?.("Context",`Context limit set to ${(j/1e3).toFixed(0)}k tokens`),W.current="",M(""),N(null),U(""),X();return}}},[X,o,n,i,a,l,y,B,V,A,h,P,C,x,S,b]);yu((L,j)=>{if(j.ctrl&&L==="l"){W.current="",M(""),N(null),U(""),X(),o(),r?.();return}let R=B!=="none",H=R&&z.length>0;if(j.escape){let g=Date.now();if(g-F.current<=Tu){F.current=0,t?s():(W.current="",M(""),N(null),U(""),X());return}F.current=g,R&&X();return}if(!t){if(j.upArrow){if(H){K(se=>se<=0?z.length-1:se-1);return}if(!c.length)return;if(w===null){U(W.current);let se=c.length-1;N(se);let ge=c[se]??"";W.current=ge,M(ge);return}let g=Math.max(0,w-1);N(g);let v=c[g]??"";W.current=v,M(v);return}if(j.downArrow){if(H){K(se=>(se+1)%z.length);return}if(w===null)return;let g=w+1;if(g>=c.length){N(null),W.current=_e,M(_e),U("");return}N(g);let v=c[g]??"";W.current=v,M(v);return}if(j.tab&&H){xt(z[$]);return}if(j.return){if(H){xt(z[$]);return}if(j.shift){let v=W.current+`
84
+ `;W.current=v,M(v);return}let g=W.current.trim();g&&(e(g),W.current="",M(""),N(null),U(""),X(!1));return}if(j.backspace||j.delete){let g=W.current.slice(0,Math.max(0,W.current.length-1));W.current=g,M(g);return}if(L){let g=W.current+L;W.current=g,M(g)}}});let et=A,St=t?" ":"\u258A",De=et.split(`
85
+ `),Ie=2,Kt=z.map(({value:L,meta:j,...R})=>R);return dt(Bt,{flexDirection:"column",gap:1,children:[dt(Bt,{flexDirection:"column",paddingY:1,children:[dt(Bt,{children:[Oe(Fe,{color:"gray",children:Gt}),t?Oe(Fe,{color:"gray",children:De[0]}):dt($u,{children:[Oe(Fe,{color:"white",children:De[0]}),De.length===1&&Oe(Fe,{color:"cyan",children:St})]})]}),De.slice(1).map((L,j)=>dt(Bt,{children:[Oe(Fe,{color:"gray",children:" ".repeat(Ie)}),Oe(Fe,{color:"white",children:L}),j===De.length-2&&Oe(Fe,{color:"cyan",children:St})]},`line-${j}`))]}),B!=="none"?Oe(jr,{items:Kt,activeIndex:$,loading:ue}):null]})}async function _u(t){let e=t.activeSessionFile?ft(t.activeSessionFile):null,r=(await wu(t.sessionsDir)).filter(l=>!e||ft(l.path)!==e).filter((l,c,u)=>u.findIndex(p=>ft(p.path)===ft(l.path))===c).sort((l,c)=>c.mtimeMs-l.mtimeMs),s=t.limit??10,i=t.keyword?.trim().toLowerCase(),a=[];for(let l of r){if(a.length>=s)break;let c=await xu(l.path,t.cwd,l.mtimeMs);if(c&&!(i&&!c.input.toLowerCase().includes(i))&&(a.push(c),a.length>=s))break}return a}async function xu(t,e,n){try{let o=await du(t,"utf8"),{firstPrompt:r,sessionCwd:s}=Su(o);if(!Cu(e,s))return null;let i=r?.trim()||vu(t);return{id:t,cwd:e,input:i,ts:n,sessionFile:t}}catch{return null}}function Su(t){let e=null,n=null;for(let o of t.split(`
86
+ `)){let r=o.trim();if(!r)continue;let s;try{s=JSON.parse(r)}catch{continue}if(!(!s||typeof s!="object")){if(s.type==="session_start"&&!n){let i=s.meta?.cwd;typeof i=="string"&&i.trim()&&(n=i);continue}if(s.type==="turn_start"&&!e){let i=typeof s.content=="string"?s.content.trim():"";i&&(e=i)}}}return{firstPrompt:e,sessionCwd:n}}function vu(t){return hu(t).replace(/\.jsonl$/i,"")}function Zr(t){let e=ft(t);return process.platform==="win32"?e.toLowerCase():e}function Cu(t,e){return e?Zr(t)===Zr(e):!1}async function wu(t){let e=async s=>{try{return await fu(s,{withFileTypes:!0})}catch{return[]}},n=(await e(t)).filter(s=>s.isDirectory()&&/^\d{4}$/.test(s.name)),o=[];for(let s of n){let i=jt(t,s.name),a=(await e(i)).filter(l=>l.isDirectory()&&/^\d{2}$/.test(l.name));for(let l of a){let c=jt(i,l.name),u=(await e(c)).filter(p=>p.isDirectory()&&/^\d{2}$/.test(p.name));for(let p of u){let T=jt(c,p.name),y=(await e(T)).filter(S=>S.isFile()&&S.name.endsWith(".jsonl"));for(let S of y)o.push(jt(T,S.name))}}}return(await Promise.all(o.map(async s=>{try{let i=await gu(s);return{path:s,mtimeMs:i.mtimeMs}}catch{return null}}))).filter(s=>!!s)}function Eu(t){let e=Mu(t);if(e)return e;let n=Au(t);if(n)return n;let o=Pu(t);if(o)return o;let r=ku(t);return r||bu(t)}function ku(t){let e=t.lastIndexOf("@");if(e===-1)return null;if(e>0){let o=t[e-1];if(o&&!/\s/.test(o))return null}let n=t.slice(e+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:e+1}}function bu(t){let e=t.trimStart(),n=t.length-e.length;if(e.length===0)return null;let o=e;if(o.startsWith("/")&&(o=o.slice(1)),!o.toLowerCase().startsWith("resume")||t.slice(0,n).trim().length>0)return null;let s=o.slice(6);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function Au(t){let e=t.trimStart();if(!e.startsWith("/models"))return null;let n=e.slice(7);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim()}}function Mu(t){let e=t.trimStart();if(!e.startsWith("/context"))return null;let n=e.slice(8);return n&&!n.startsWith(" ")?null:{type:"context"}}function Pu(t){let e=t.trimStart();if(!e.startsWith("/"))return null;let n=e.slice(1);return n.includes(" ")?null:/^[a-zA-Z]*$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:n.length===0?{type:"slash",keyword:""}:null}function Ru(t){return{id:t.id,title:t.input,subtitle:Iu(t.ts),kind:"history",badge:"HIS",value:t.input,meta:{historyEntry:t}}}function Iu(t){if(!t)return"";let e=new Date(t);if(Number.isNaN(e.getTime()))return"";let n=String(e.getFullYear()),o=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");return`${n}-${o}-${r} ${s}:${i}`}import{Box as gt,Text as Ln,useInput as Lu}from"ink";import{useState as Ou,useCallback as Nu}from"react";import{jsx as ht,jsxs as On}from"react/jsx-runtime";function Du(t){if(typeof t!="object"||t===null)return String(t);let e=Object.entries(t);if(e.length===0)return"";let[n,o]=e[0],r=typeof o=="string"?o:JSON.stringify(o);return`${r.slice(0,40)}${r.length>40?"...":""}`}function es({request:t,onDecision:e}){let n=[{label:"Allow once",decision:"once"},{label:"Allow all session",decision:"session"},{label:"Reject this time",decision:"deny"}],[o,r]=Ou(0);Lu(Nu((i,a)=>{a.upArrow?r(l=>l>0?l-1:n.length-1):a.downArrow?r(l=>l<n.length-1?l+1:0):a.return&&e(n[o].decision)},[o,e,n]));let s=Du(t.params);return On(gt,{borderStyle:"single",borderColor:"gray",paddingX:2,flexDirection:"column",children:[ht(gt,{children:ht(Ln,{bold:!0,children:"Tool Approval:"})}),ht(gt,{marginTop:1,children:On(Ln,{color:"cyan",children:[t.toolName,s?` (${s})`:""]})}),ht(gt,{flexDirection:"column",marginTop:1,children:n.map((i,a)=>ht(gt,{children:On(Ln,{color:o===a?"green":"gray",children:[o===a?"> ":" ",i.label]})},i.decision))})]})}import Hh from"string-width";function ns(t){if(!t)return"success";let e=t.toLowerCase();return e.includes("error")||e.includes("unknown")||e.includes("failed")?"error":"success"}var ts={"gpt-4o-mini":128e3,"gpt-4o":128e3,"gpt-4":8192,"gpt-3.5":16384,"claude-3":2e5,claude:2e5,"deepseek-coder":64e3,"deepseek-chat":64e3,deepseek:64e3,"kimi-k2":2e5,kimi:2e5,default:12e4};function Uu(t){let e=t.toLowerCase(),n=Object.entries(ts).filter(([o])=>o!=="default");for(let[o,r]of n.sort((s,i)=>i[0].length-s[0].length))if(e.includes(o))return r;return ts.default}function os(t,e){if(t==null)return 0;let n=typeof t=="number"?t:t.prompt??t.total??0;if(n<=0)return 0;let o=e&&e>0?e:Uu("");return Math.min(100,n/o*100)}function rs(t){return t?`${t.total} tokens`:""}function ss(t,e){let[n,...o]=t.trim().slice(1).split(/\s+/),r=(n??"").toLowerCase(),s=[8e4,12e4,15e4,2e5],i=a=>{if(!a)return null;let c=a.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!c)return null;let u=Number(c[1])*(c[2]?1e3:1);return Number.isFinite(u)?u:null};switch(r){case"exit":return{kind:"exit"};case"new":return{kind:"new"};case"help":return{kind:"message",title:"Help",content:Ft};case"config":return{kind:"message",title:"Config",content:`Config file: ${e.configPath}
87
+ Current provider: ${e.providerName}
88
+ Current model: ${e.model}`};case"resume":return{kind:"message",title:"Resume",content:'Type "resume" to filter and select from session history.'};case"context":{let p=i(o[0]),T=s.map(y=>`${y/1e3}k`).join(", ");return p===null?{kind:"message",title:"Context",content:`Current: ${(e.contextLimit/1e3).toFixed(0)}k
85
89
  Usage: /context <length> (starts new session)
86
- Choices: ${h}`}:s.includes(p)?{kind:"set_context_limit",limit:p}:{kind:"message",title:"Context",content:`Unsupported length: ${p}. Pick one of: ${h}`}}case"init":return{kind:"init_agents_md"};case"$":{let p=o.join(" ").trim();return p?{kind:"shell_command",command:p}:{kind:"message",title:"Shell Command",content:"Usage: $ <command> (e.g. $ git status)"}}case"models":if(!t.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${t.configPath}`};let a=o.join(" ").trim(),c=t.providers.find(p=>p.name===a)??t.providers.find(p=>p.model===a);if(c)return{kind:"switch_model",provider:c};let l=t.providers.map(p=>{let h=p.base_url?` @ ${p.base_url}`:"";return`- ${p.name}: ${p.model}${h}`});return{kind:"message",title:"Models",content:`${a?`Not found: ${a}, `:""}Available models:
87
- ${l.join(`
88
- `)}`};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${e}
89
- Type /help for available commands.`}}}import{dirname as Ut,join as Jr,resolve as Wl}from"path";import{statSync as Kl,existsSync as qr,readFileSync as Jl}from"fs";import{readFile as ql}from"fs/promises";import{get as Xl}from"https";import{fileURLToPath as Yl}from"url";function Kr(e){let t=e.trim().replace(/^v/i,""),[n="",o]=t.split("-",2),r=n.split(".").map(s=>Number(s));return r.length<3||r.some(s=>!Number.isFinite(s))?null:{major:r[0]??0,minor:r[1]??0,patch:r[2]??0,prerelease:o??null}}function Zl(e,t){let n=Kr(e),o=Kr(t);return!n||!o?!1:n.major!==o.major?n.major>o.major:n.minor!==o.minor?n.minor>o.minor:n.patch!==o.patch?n.patch>o.patch:n.prerelease&&!o.prerelease?!1:!n.prerelease&&o.prerelease?!0:n.prerelease&&o.prerelease?n.prerelease>o.prerelease:!1}function Xr(){try{let t=Yl(import.meta.url);return Ut(t)}catch{}let e=Wl(process.argv[1]??process.cwd());try{return Kl(e).isFile()?Ut(e):e}catch{return process.cwd()}}async function Ql(e){let t=Jr(e,"package.json");if(!qr(t))return null;let n=await ql(t,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}function eu(e){let t=Jr(e,"package.json");if(!qr(t))return null;try{let n=Jl(t,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}catch{return null}}async function tu(){let e=Xr();for(;;){let t=await Ql(e);if(t&&t.name==="@memo-code/memo")return t;let n=Ut(e);if(n===e)break;e=n}return null}function Ht(){let e=Xr();for(;;){let t=eu(e);if(t&&t.name==="@memo-code/memo")return t;let n=Ut(e);if(n===e)break;e=n}return null}async function nu(e,t=1500){let o=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(r=>{let s=Xl(o,{timeout:t},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),r(null);return}let a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{try{let c=JSON.parse(Buffer.concat(a).toString("utf8"));r(c.version??null)}catch{r(null)}})});s.on("timeout",()=>{s.destroy(),r(null)}),s.on("error",()=>r(null))})}async function Yr(){let e=await tu();if(!e)return null;let t=await nu(e.name);return!t||!Zl(t,e.version)?null:{current:e.version,latest:t}}import{Box as Je,Text as ve,useInput as ou}from"ink";import{useCallback as $n,useMemo as ru,useState as st}from"react";import{jsx as Ce,jsxs as De}from"react/jsx-runtime";var Pe=[{key:"name",label:"Provider name",hint:"Used in /model and config",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Memo reads this env var at runtime",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",hint:"Provider model ID",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",hint:"Leave default unless you have a custom endpoint",defaultValue:"https://api.deepseek.com"}];function Zr({configPath:e,onComplete:t,onExit:n}){let[o,r]=st(0),[s,i]=st(""),[a,c]=st({}),[l,u]=st(!1),[p,h]=st(null),y=Pe[o]??Pe[0],b=s||a[y.key]||"",x=$n(async k=>{u(!0),h(null);try{let d=k.name||Pe[0].defaultValue,v=k.envKey||Pe[1].defaultValue,E=k.model||Pe[2].defaultValue,B=k.baseUrl||Pe[3].defaultValue;await ge(e,{current_provider:d,providers:[{name:d,env_api_key:v,model:E,base_url:B||void 0}]}),t()}catch(d){h(d.message),u(!1)}},[e,t]),w=$n(async()=>{let d=s.trim()||y.defaultValue,v={...a,[y.key]:d};if(c(v),i(""),o<Pe.length-1){r(o+1);return}await x(v)},[y.defaultValue,y.key,o,s,a,x]);ou($n((k,d)=>{if(!l){if(d.ctrl&&k==="c"){n();return}if(d.return){w();return}if(d.backspace||d.delete){i(v=>v.slice(0,-1));return}k&&i(v=>v+k)}},[w,n,l]));let _=ru(()=>`Step ${o+1}/${Pe.length}`,[o]);return De(Je,{flexDirection:"column",children:[De(Je,{flexDirection:"column",marginBottom:1,children:[Ce(ve,{bold:!0,children:"Memo setup"}),Ce(ve,{color:"gray",children:"No provider config found. Create one to continue."}),De(ve,{color:"gray",children:["Config path: ",e]})]}),De(Je,{flexDirection:"column",marginBottom:1,children:[Ce(ve,{color:"cyan",children:_}),De(ve,{children:[y.label," (default: ",y.defaultValue,")"]}),y.hint?Ce(ve,{color:"gray",children:y.hint}):null]}),De(Je,{children:[Ce(ve,{children:"> "}),Ce(ve,{children:b})]}),Ce(Je,{marginTop:1,children:Ce(ve,{color:"gray",children:"Press Enter to continue. Ctrl+C to exit."})}),p?Ce(Je,{marginTop:1,children:De(ve,{color:"red",children:["Failed to write config: ",p]})}):null]})}import{jsx as Ue,jsxs as du}from"react/jsx-runtime";var uu=au(iu);function pu(e){return{index:e,userInput:"",steps:[]}}function es({sessionOptions:e,providerName:t,model:n,configPath:o,mcpServers:r,cwd:s,sessionsDir:i,providers:a,dangerous:c=!1,needsSetup:l=!1}){let{exit:u}=cu(),[p,h]=K(t),[y,b]=K(n),[x,w]=K(a),[_,k]=K({...e,providerName:t}),[d,v]=K(null),[E,B]=K([]),[I,ue]=K([]),[M,C]=K(!1),P=it(null),V=it(null),[ee,ye]=K([]),[D,re]=K(null),[se,Re]=K([]),[He,de]=K(null),ie=it(null),[H,Bt]=K(null),j=it(0),[z,ct]=K(e.maxPromptTokens??12e4),[qe,lt]=K(l),[$e,Ee]=K(0),Ft=In(()=>Ht(),[]),[L,U]=K(null),R=it(null),N=W(()=>(j.current+=1,j.current),[]),g=W((m,f)=>{let T=`${Date.now()}-${Math.random().toString(16).slice(2)}`,$=N();ue(O=>[...O,{id:T,title:m,content:f,sequence:$}])},[N]),A=W((m,f)=>{B(T=>{let $=[...T],O=$.findIndex(ae=>ae.index===m);O===-1&&($.push(pu(m)),O=$.length-1);let F=$[O];return F&&($[O]=f(F)),$})},[]),te=In(()=>({onAssistantStep:(m,f)=>{let T=P.current;T&&A(T,$=>{let O=$.steps.slice();for(;O.length<=f;)O.push({index:O.length,assistantText:""});let F=O[f];if(!F)return $;let ae={...F,assistantText:F.assistantText+m};return O[f]=ae,{...$,steps:O}})},requestApproval:c?void 0:m=>new Promise(f=>{U(m),R.current=f}),hooks:{onTurnStart:({turn:m,input:f,promptTokens:T})=>{P.current=m;let $=V.current;$&&(V.current=null);let O=$??f;T&&T>0&&Ee(T),A(m,F=>({...F,index:m,userInput:O,steps:[],startedAt:Date.now(),contextPromptTokens:T??F.contextPromptTokens}))},onAction:({turn:m,step:f,action:T,thinking:$,parallelActions:O})=>{A(m,F=>{let ae=F.steps.slice();for(;ae.length<=f;)ae.push({index:ae.length,assistantText:""});let ut=ae[f];return ut?(ae[f]={...ut,action:T,thinking:$,toolStatus:"executing",parallelActions:O&&O.length>1?O:void 0},{...F,steps:ae}):F})},onObservation:({turn:m,step:f,observation:T})=>{A(m,$=>{let O=$.steps.slice();for(;O.length<=f;)O.push({index:O.length,assistantText:""});let F=O[f];return F?(O[f]={...F,observation:T,toolStatus:Vr(T)},{...$,steps:O}):$})},onFinal:({turn:m,finalText:f,status:T,turnUsage:$,tokenUsage:O})=>{A(m,F=>{let ae=F.startedAt??Date.now(),ut=Math.max(0,Date.now()-ae),ds=O?.prompt??F.contextPromptTokens,fs=F.sequence??N();return{...F,finalText:f,status:T,tokenUsage:$,contextPromptTokens:ds,startedAt:ae,durationMs:ut,sequence:fs}}),C(!1)}}}),[A,c,N]);jt(()=>{let m=!1;return(async()=>{if(qe)return;let f=ie.current;f&&await f.close();let T=await Ye(te,_);if(m){await T.close();return}ie.current=T,v(T),re(T.historyFilePath??null)})(),()=>{m=!0}},[te,_,qe]),jt(()=>{let m=!1;return(async()=>{let f=await Yr();m||!f||g("Update",`Update available: v${f.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{m=!0}},[g]),jt(()=>()=>{ie.current&&ie.current.close()},[]);let fe=W(async()=>{ie.current&&await ie.current.close(),Bt("Bye!"),setTimeout(()=>{u()},300)},[u]),Nn=W(()=>{B([]),ue([]),Re([]),de(null),Ee(0),j.current=0},[]),Dn=W(async()=>{B([]),ue([]),Re([]),de(null),Ee(0),j.current=0;let m=at(),f={..._,sessionId:m};ie.current&&await ie.current.close();let T=await Ye(te,f);ie.current=T,v(T),re(T.historyFilePath??null),k(f),g("New Session","Started a new session with fresh context.")},[te,_,g]),Un=W(async m=>{try{let f=await oe(),T={...f.config,max_prompt_tokens:m};await ge(f.configPath,T)}catch(f){g("Failed to save config",`Failed to save context limit: ${f.message}`)}},[g]),Vt=W(m=>{ct(m),Ee(0),k(f=>({...f,maxPromptTokens:m,sessionId:at()})),g("Context length",`Context limit set to ${(m/1e3).toFixed(0)}k tokens (new session started)`),Un(m)},[g,Un]),ss=W(async m=>{if(!m.sessionFile){g("History","This entry has no context file to load.");return}try{let f=await su(m.sessionFile,"utf8"),T=mu(f);Re(T.turns),de(T.messages),C(!1),B([]),v(null),re(null),Ee(0),P.current=null,j.current=Math.max(j.current,T.maxSequence),k($=>({...$,sessionId:at()})),g("History loaded",T.summary||m.input)}catch(f){g("Failed to load history",`Unable to read ${m.sessionFile}: ${f.message}`)}},[g]),Hn=W(async m=>{try{let f=await oe(),T={...f.config,current_provider:m};await ge(f.configPath,T)}catch(f){g("Failed to save config",`Failed to save model selection: ${f.message}`)}},[g]),is=W(()=>{M&&d?.cancelCurrentTurn?.()},[M,d]),Gt=W(async m=>{if(m.name===p&&m.model===y){g("Model switch",`Already using ${m.name} (${m.model})`);return}if(M){g("Model switch","Currently running. Press Esc Esc to cancel before switching models.");return}B([]),Re([]),de(null),Ee(0),P.current=null,v(null),re(null),h(m.name),b(m.model),k(f=>({...f,sessionId:at(),providerName:m.name})),await Hn(m.name),g("Model switch",`Switched to ${m.name} (${m.model})`)},[g,M,y,p,Hn]),zt=W(async m=>{if(!m.trim()){g("Shell Command","Usage: $ <command> (e.g. $ git status)");return}C(!0);try{let{stdout:f,stderr:T}=await uu(m,{cwd:s,maxBuffer:5242880}),$=[f?.trim(),T?.trim()].filter(Boolean).join(`
90
- `);g("Shell Result",$||"(no output)")}catch(f){let T=f,O=[T.stdout?.trim(),T.stderr?.trim(),T.message].filter(Boolean).join(`
91
- `);g("Shell Error",O||"Command failed")}finally{C(!1)}},[g,s]),jn=W(async m=>{let f=Wr(m,{configPath:o,providerName:p,model:y,mcpServers:r,providers:x,contextLimit:z});if(f.kind==="exit"){await fe();return}if(f.kind==="new"){await Dn();return}if(f.kind==="switch_model"){await Gt(f.provider);return}if(f.kind==="set_context_limit"){Vt(f.limit);return}if(f.kind==="init_agents_md"){g("Init","Analyzing project structure and generating AGENTS.md...");let T=`Please analyze the current project and create an AGENTS.md file at the project root.
90
+ Choices: ${T}`}:s.includes(p)?{kind:"set_context_limit",limit:p}:{kind:"message",title:"Context",content:`Unsupported length: ${p}. Pick one of: ${T}`}}case"init":return{kind:"init_agents_md"};case"$":{let p=o.join(" ").trim();return p?{kind:"shell_command",command:p}:{kind:"message",title:"Shell Command",content:"Usage: $ <command> (e.g. $ git status)"}}case"models":if(!e.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${e.configPath}`};let a=o.join(" ").trim(),l=e.providers.find(p=>p.name===a)??e.providers.find(p=>p.model===a);if(l)return{kind:"switch_model",provider:l};let c=e.providers.map(p=>{let T=p.base_url?` @ ${p.base_url}`:"";return`- ${p.name}: ${p.model}${T}`});return{kind:"message",title:"Models",content:`${a?`Not found: ${a}, `:""}Available models:
91
+ ${c.join(`
92
+ `)}`};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${t}
93
+ Type /help for available commands.`}}}import{dirname as Wt,join as as,resolve as Hu}from"path";import{statSync as Fu,existsSync as ls,readFileSync as ju}from"fs";import{readFile as Bu}from"fs/promises";import{get as Wu}from"https";import{fileURLToPath as Vu}from"url";function is(t){let e=t.trim().replace(/^v/i,""),[n="",o]=e.split("-",2),r=n.split(".").map(s=>Number(s));return r.length<3||r.some(s=>!Number.isFinite(s))?null:{major:r[0]??0,minor:r[1]??0,patch:r[2]??0,prerelease:o??null}}function zu(t,e){let n=is(t),o=is(e);return!n||!o?!1:n.major!==o.major?n.major>o.major:n.minor!==o.minor?n.minor>o.minor:n.patch!==o.patch?n.patch>o.patch:n.prerelease&&!o.prerelease?!1:!n.prerelease&&o.prerelease?!0:n.prerelease&&o.prerelease?n.prerelease>o.prerelease:!1}function cs(){try{let e=Vu(import.meta.url);return Wt(e)}catch{}let t=Hu(process.argv[1]??process.cwd());try{return Fu(t).isFile()?Wt(t):t}catch{return process.cwd()}}async function Gu(t){let e=as(t,"package.json");if(!ls(e))return null;let n=await Bu(e,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}function Ku(t){let e=as(t,"package.json");if(!ls(e))return null;try{let n=ju(e,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}catch{return null}}async function qu(){let t=cs();for(;;){let e=await Gu(t);if(e&&e.name==="@memo-code/memo")return e;let n=Wt(t);if(n===t)break;t=n}return null}function Vt(){let t=cs();for(;;){let e=Ku(t);if(e&&e.name==="@memo-code/memo")return e;let n=Wt(t);if(n===t)break;t=n}return null}async function Xu(t,e=1500){let o=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(r=>{let s=Wu(o,{timeout:e},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),r(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));r(l.version??null)}catch{r(null)}})});s.on("timeout",()=>{s.destroy(),r(null)}),s.on("error",()=>r(null))})}async function us(){let t=await qu();if(!t)return null;let e=await Xu(t.name);return!e||!zu(e,t.version)?null:{current:t.version,latest:e}}import{Box as Qe,Text as ve,useInput as Ju}from"ink";import{useCallback as Nn,useMemo as Yu,useState as yt}from"react";import{jsx as Re,jsxs as je}from"react/jsx-runtime";var Ne=[{key:"name",label:"Provider name",hint:"Used in /model and config",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Memo reads this env var at runtime",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",hint:"Provider model ID",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",hint:"Leave default unless you have a custom endpoint",defaultValue:"https://api.deepseek.com"}];function ps({configPath:t,onComplete:e,onExit:n}){let[o,r]=yt(0),[s,i]=yt(""),[a,l]=yt({}),[c,u]=yt(!1),[p,T]=yt(null),y=Ne[o]??Ne[0],S=s||a[y.key]||"",h=Nn(async x=>{u(!0),T(null);try{let b=x.name||Ne[0].defaultValue,A=x.envKey||Ne[1].defaultValue,M=x.model||Ne[2].defaultValue,w=x.baseUrl||Ne[3].defaultValue;await ye(t,{current_provider:b,providers:[{name:b,env_api_key:A,model:M,base_url:w||void 0}]}),e()}catch(b){T(b.message),u(!1)}},[t,e]),P=Nn(async()=>{let b=s.trim()||y.defaultValue,A={...a,[y.key]:b};if(l(A),i(""),o<Ne.length-1){r(o+1);return}await h(A)},[y.defaultValue,y.key,o,s,a,h]);Ju(Nn((x,b)=>{if(!c){if(b.ctrl&&x==="c"){n();return}if(b.return){P();return}if(b.backspace||b.delete){i(A=>A.slice(0,-1));return}x&&i(A=>A+x)}},[P,n,c]));let C=Yu(()=>`Step ${o+1}/${Ne.length}`,[o]);return je(Qe,{flexDirection:"column",children:[je(Qe,{flexDirection:"column",marginBottom:1,children:[Re(ve,{bold:!0,children:"Memo setup"}),Re(ve,{color:"gray",children:"No provider config found. Create one to continue."}),je(ve,{color:"gray",children:["Config path: ",t]})]}),je(Qe,{flexDirection:"column",marginBottom:1,children:[Re(ve,{color:"cyan",children:C}),je(ve,{children:[y.label," (default: ",y.defaultValue,")"]}),y.hint?Re(ve,{color:"gray",children:y.hint}):null]}),je(Qe,{children:[Re(ve,{children:"> "}),Re(ve,{children:S})]}),Re(Qe,{marginTop:1,children:Re(ve,{color:"gray",children:"Press Enter to continue. Ctrl+C to exit."})}),p?Re(Qe,{marginTop:1,children:je(ve,{color:"red",children:["Failed to write config: ",p]})}):null]})}import{jsx as Be,jsxs as ip}from"react/jsx-runtime";var op=ep(Qu);function rp(t){return{index:t,userInput:"",steps:[]}}function ds({sessionOptions:t,providerName:e,model:n,configPath:o,mcpServers:r,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:u}=tp(),[p,T]=Y(e),[y,S]=Y(n),[h,P]=Y(a),[C,x]=Y({...t,providerName:e}),[b,A]=Y(null),[M,w]=Y([]),[N,_e]=Y([]),[U,B]=Y(!1),re=Tt(null),z=Tt(null),[k,$]=Y([]),[K,ue]=Y(null),[pe,xe]=Y([]),[Ce,E]=Y(null),F=Tt(null),[W,Gt]=Y(null),V=Tt(0),[X,xt]=Y(t.maxPromptTokens??12e4),[et,St]=Y(c),[De,Ie]=Y(0),Kt=Dn(()=>Vt(),[]),[L,j]=Y(null),R=Tt(null),H=J(()=>(V.current+=1,V.current),[]),g=J((d,f)=>{let _=`${Date.now()}-${Math.random().toString(16).slice(2)}`,I=H();_e(D=>[...D,{id:_,title:d,content:f,sequence:I}])},[H]),v=J((d,f)=>{w(_=>{let I=[..._],D=I.findIndex(ae=>ae.index===d);D===-1&&(I.push(rp(d)),D=I.length-1);let G=I[D];return G&&(I[D]=f(G)),I})},[]),se=Dn(()=>({onAssistantStep:(d,f)=>{let _=re.current;_&&v(_,I=>{let D=I.steps.slice();for(;D.length<=f;)D.push({index:D.length,assistantText:""});let G=D[f];if(!G)return I;let ae={...G,assistantText:G.assistantText+d};return D[f]=ae,{...I,steps:D}})},requestApproval:l?void 0:d=>new Promise(f=>{j(d),R.current=f}),hooks:{onTurnStart:({turn:d,input:f,promptTokens:_})=>{re.current=d;let I=z.current;I&&(z.current=null);let D=I??f;_&&_>0&&Ie(_),v(d,G=>({...G,index:d,userInput:D,steps:[],startedAt:Date.now(),contextPromptTokens:_??G.contextPromptTokens}))},onAction:({turn:d,step:f,action:_,thinking:I,parallelActions:D})=>{v(d,G=>{let ae=G.steps.slice();for(;ae.length<=f;)ae.push({index:ae.length,assistantText:""});let vt=ae[f];return vt?(ae[f]={...vt,action:_,thinking:I,toolStatus:"executing",parallelActions:D&&D.length>1?D:void 0},{...G,steps:ae}):G})},onObservation:({turn:d,step:f,observation:_})=>{v(d,I=>{let D=I.steps.slice();for(;D.length<=f;)D.push({index:D.length,assistantText:""});let G=D[f];return G?(D[f]={...G,observation:_,toolStatus:ns(_)},{...I,steps:D}):I})},onFinal:({turn:d,finalText:f,status:_,turnUsage:I,tokenUsage:D})=>{v(d,G=>{let ae=G.startedAt??Date.now(),vt=Math.max(0,Date.now()-ae),ks=D?.prompt??G.contextPromptTokens,bs=G.sequence??H();return{...G,finalText:f,status:_,tokenUsage:I,contextPromptTokens:ks,startedAt:ae,durationMs:vt,sequence:bs}}),B(!1)}}}),[v,l,H]);zt(()=>{let d=!1;return(async()=>{if(et)return;let f=F.current;f&&await f.close();let _=await lt(se,C);if(d){await _.close();return}F.current=_,A(_),ue(_.historyFilePath??null)})(),()=>{d=!0}},[se,C,et]),zt(()=>{let d=!1;return(async()=>{let f=await us();d||!f||g("Update",`Update available: v${f.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{d=!0}},[g]),zt(()=>()=>{F.current&&F.current.close()},[]);let ge=J(async()=>{F.current&&await F.current.close(),Gt("Bye!"),setTimeout(()=>{u()},300)},[u]),Fn=J(()=>{w([]),_e([]),xe([]),E(null),Ie(0),V.current=0},[]),jn=J(async()=>{w([]),_e([]),xe([]),E(null),Ie(0),V.current=0;let d=_t(),f={...C,sessionId:d};F.current&&await F.current.close();let _=await lt(se,f);F.current=_,A(_),ue(_.historyFilePath??null),x(f),g("New Session","Started a new session with fresh context.")},[se,C,g]),Bn=J(async d=>{try{let f=await ie(),_={...f.config,max_prompt_tokens:d};await ye(f.configPath,_)}catch(f){g("Failed to save config",`Failed to save context limit: ${f.message}`)}},[g]),qt=J(d=>{xt(d),Ie(0),x(f=>({...f,maxPromptTokens:d,sessionId:_t()})),g("Context length",`Context limit set to ${(d/1e3).toFixed(0)}k tokens (new session started)`),Bn(d)},[g,Bn]),Ts=J(async d=>{if(!d.sessionFile){g("History","This entry has no context file to load.");return}try{let f=await Zu(d.sessionFile,"utf8"),_=sp(f);xe(_.turns),E(_.messages),B(!1),w([]),A(null),ue(null),Ie(0),re.current=null,V.current=Math.max(V.current,_.maxSequence),x(I=>({...I,sessionId:_t()})),g("History loaded",_.summary||d.input)}catch(f){g("Failed to load history",`Unable to read ${d.sessionFile}: ${f.message}`)}},[g]),Wn=J(async d=>{try{let f=await ie(),_={...f.config,current_provider:d};await ye(f.configPath,_)}catch(f){g("Failed to save config",`Failed to save model selection: ${f.message}`)}},[g]),_s=J(()=>{U&&b?.cancelCurrentTurn?.()},[U,b]),Xt=J(async d=>{if(d.name===p&&d.model===y){g("Model switch",`Already using ${d.name} (${d.model})`);return}if(U){g("Model switch","Currently running. Press Esc Esc to cancel before switching models.");return}w([]),xe([]),E(null),Ie(0),re.current=null,A(null),ue(null),T(d.name),S(d.model),x(f=>({...f,sessionId:_t(),providerName:d.name})),await Wn(d.name),g("Model switch",`Switched to ${d.name} (${d.model})`)},[g,U,y,p,Wn]),Jt=J(async d=>{if(!d.trim()){g("Shell Command","Usage: $ <command> (e.g. $ git status)");return}B(!0);try{let{stdout:f,stderr:_}=await op(d,{cwd:s,maxBuffer:5242880}),I=[f?.trim(),_?.trim()].filter(Boolean).join(`
94
+ `);g("Shell Result",I||"(no output)")}catch(f){let _=f,D=[_.stdout?.trim(),_.stderr?.trim(),_.message].filter(Boolean).join(`
95
+ `);g("Shell Error",D||"Command failed")}finally{B(!1)}},[g,s]),Vn=J(async d=>{let f=ss(d,{configPath:o,providerName:p,model:y,mcpServers:r,providers:h,contextLimit:X});if(f.kind==="exit"){await ge();return}if(f.kind==="new"){await jn();return}if(f.kind==="switch_model"){await Xt(f.provider);return}if(f.kind==="set_context_limit"){qt(f.limit);return}if(f.kind==="init_agents_md"){g("Init","Analyzing project structure and generating AGENTS.md...");let _=`Please analyze the current project and create an AGENTS.md file at the project root.
92
96
 
93
97
  The AGENTS.md should include:
94
98
  1. Project name and brief description
@@ -99,15 +103,15 @@ The AGENTS.md should include:
99
103
  6. Any project-specific notes for AI assistants
100
104
 
101
105
  Steps:
102
- 1. First explore the project structure using glob and bash tools
106
+ 1. First explore the project structure using list_dir and exec_command tools
103
107
  2. Read key configuration files (package.json, tsconfig.json, etc.)
104
108
  3. Understand the tech stack and conventions
105
- 4. Create the AGENTS.md file using the write tool
109
+ 4. Create the AGENTS.md file using apply_patch
106
110
 
107
- Make the AGENTS.md concise but informative, following best practices for AI agent guidelines.`;if(ye($=>[...$,"/init"]),!d){g("Error","Session not initialized");return}C(!0);try{V.current="/init (generate AGENTS.md)",await d.runTurn(T)}catch{C(!1)}return}if(f.kind==="shell_command"){await zt(f.command);return}g(f.title,f.content)},[g,Vt,o,Nn,fe,Gt,r,y,p,z,x,zt]),as=W(async()=>{try{let m=await oe(),f=Le(m.config);w(m.config.providers),h(f.name),b(f.model),k(T=>({...T,sessionId:at(),providerName:f.name})),lt(!1),g("Setup",`Config saved to ${m.configPath}`)}catch(m){g("Setup",`Failed to reload config: ${m.message}`)}},[g]);jt(()=>{if(!d||!He?.length)return;let m=d.history[0];m&&(d.history.splice(0,d.history.length,m,...He),de(null))},[He,d]);let cs=W(async m=>{if(m.trim().toLowerCase()==="exit"){await fe();return}if(!d||M)return;let f=m.trim();if(f.startsWith("$")){let T=f.slice(1).trim();ye($=>[...$,m]),await zt(T);return}if(m.startsWith("/")){await jn(m);return}ye(T=>[...T,m]),C(!0);try{await d.runTurn(m)}catch{C(!1)}},[M,jn,fe,d]),ls=E[E.length-1],Au=zr(ls?.tokenUsage),us=Gr($e,z),ps=In(()=>[...se,...E],[se,E]),ms=W(m=>{let f=R.current;f&&(f(m),R.current=null),U(null)},[]);if(H){let m=H.split(`
108
- `);return Ue(Qr,{flexDirection:"column",children:m.map((f,T)=>Ue(lu,{color:"green",children:f},T))})}return qe?Ue(Zr,{configPath:o,onComplete:as,onExit:fe}):du(Qr,{flexDirection:"column",children:[Ue(mr,{systemMessages:I,turns:ps,headerInfo:{providerName:p,model:y,cwd:s,sessionId:_.sessionId??"unknown",mcpNames:Object.keys(r??{}).sort(),version:Ft?.version??"unknown"}}),Ue(jr,{disabled:!d||M||!!L,onSubmit:cs,onExit:fe,onClear:Nn,onNewSession:Dn,onCancelRun:is,onHistorySelect:ss,onModelSelect:Gt,onSystemMessage:g,onSetContextLimit:m=>{Vt(m)},history:ee,cwd:s,sessionsDir:i,currentSessionFile:D??void 0,providers:x,configPath:o,providerName:p,model:y,contextLimit:z,mcpServers:r}),L&&Ue(Br,{request:L,onDecision:ms}),Ue(er,{contextPercent:us})]})}function mu(e){let t=[],n=[],o=[],r=e.split(`
109
- `).map(c=>c.trim()).filter(Boolean),s=null,i=0,a=0;for(let c of r){let l;try{l=JSON.parse(c)}catch{continue}if(!(!l||typeof l!="object")){if(l.type==="turn_start"){let u=typeof l.content=="string"?l.content:"";s={index:-(i+1),userInput:u,steps:[],status:"ok",sequence:a+=1},n.push(s),u&&(t.push({role:"user",content:u}),o.push(`User: ${u}`)),i+=1;continue}if(l.type==="assistant"){let u=typeof l.content=="string"?l.content:"";if(u&&(t.push({role:"assistant",content:u}),o.push(`Assistant: ${u}`),s)){let p={index:s.steps.length,assistantText:u};s.steps=[...s.steps,p],s.finalText=u}continue}if(l.type==="action"&&s){let u=l.meta;if(u&&typeof u=="object"){let p=typeof u.tool=="string"?u.tool:"",h=u.input,y=typeof u.thinking=="string"?u.thinking:"",x=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(_=>{let k=typeof _?.name=="string"?_.name:"";return k?{tool:k,input:_?.input}:null}).filter(Boolean),w=s.steps[s.steps.length-1];w&&(x.length>1?(w.action=x[0],w.parallelActions=x):p&&(w.action={tool:p,input:h}),y&&(w.thinking=y))}continue}if(l.type==="observation"&&s){let u=typeof l.content=="string"?l.content:"",p=s.steps[s.steps.length-1];p&&(p.observation=u);continue}}}return{summary:o.join(`
110
- `),messages:t,turns:n,maxSequence:a}}var fu=`
111
+ Make the AGENTS.md concise but informative, following best practices for AI agent guidelines.`;if($(I=>[...I,"/init"]),!b){g("Error","Session not initialized");return}B(!0);try{z.current="/init (generate AGENTS.md)",await b.runTurn(_)}catch{B(!1)}return}if(f.kind==="shell_command"){await Jt(f.command);return}g(f.title,f.content)},[g,qt,o,Fn,ge,Xt,r,y,p,X,h,Jt]),xs=J(async()=>{try{let d=await ie(),f=Ue(d.config);P(d.config.providers),T(f.name),S(f.model),x(_=>({..._,sessionId:_t(),providerName:f.name})),St(!1),g("Setup",`Config saved to ${d.configPath}`)}catch(d){g("Setup",`Failed to reload config: ${d.message}`)}},[g]);zt(()=>{if(!b||!Ce?.length)return;let d=b.history[0];d&&(b.history.splice(0,b.history.length,d,...Ce),E(null))},[Ce,b]);let Ss=J(async d=>{if(d.trim().toLowerCase()==="exit"){await ge();return}if(!b||U)return;let f=d.trim();if(f.startsWith("$")){let _=f.slice(1).trim();$(I=>[...I,d]),await Jt(_);return}if(d.startsWith("/")){await Vn(d);return}$(_=>[..._,d]),B(!0);try{await b.runTurn(d)}catch{B(!1)}},[U,Vn,ge,b]),vs=M[M.length-1],Sp=rs(vs?.tokenUsage),Cs=os(De,X),ws=Dn(()=>[...pe,...M],[pe,M]),Es=J(d=>{let f=R.current;f&&(f(d),R.current=null),j(null)},[]);if(W){let d=W.split(`
112
+ `);return Be(ms,{flexDirection:"column",children:d.map((f,_)=>Be(np,{color:"green",children:f},_))})}return et?Be(ps,{configPath:o,onComplete:xs,onExit:ge}):ip(ms,{flexDirection:"column",children:[Be(Er,{systemMessages:N,turns:ws,headerInfo:{providerName:p,model:y,cwd:s,sessionId:C.sessionId??"unknown",mcpNames:Object.keys(r??{}).sort(),version:Kt?.version??"unknown"}}),Be(Qr,{disabled:!b||U||!!L,onSubmit:Ss,onExit:ge,onClear:Fn,onNewSession:jn,onCancelRun:_s,onHistorySelect:Ts,onModelSelect:Xt,onSystemMessage:g,onSetContextLimit:d=>{qt(d)},history:k,cwd:s,sessionsDir:i,currentSessionFile:K??void 0,providers:h,configPath:o,providerName:p,model:y,contextLimit:X,mcpServers:r}),L&&Be(es,{request:L,onDecision:Es}),Be(dr,{contextPercent:Cs})]})}function sp(t){let e=[],n=[],o=[],r=t.split(`
113
+ `).map(l=>l.trim()).filter(Boolean),s=null,i=0,a=0;for(let l of r){let c;try{c=JSON.parse(l)}catch{continue}if(!(!c||typeof c!="object")){if(c.type==="turn_start"){let u=typeof c.content=="string"?c.content:"";s={index:-(i+1),userInput:u,steps:[],status:"ok",sequence:a+=1},n.push(s),u&&(e.push({role:"user",content:u}),o.push(`User: ${u}`)),i+=1;continue}if(c.type==="assistant"){let u=typeof c.content=="string"?c.content:"";if(u&&(e.push({role:"assistant",content:u}),o.push(`Assistant: ${u}`),s)){let p={index:s.steps.length,assistantText:u};s.steps=[...s.steps,p],s.finalText=u}continue}if(c.type==="action"&&s){let u=c.meta;if(u&&typeof u=="object"){let p=typeof u.tool=="string"?u.tool:"",T=u.input,y=typeof u.thinking=="string"?u.thinking:"",h=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(C=>{let x=typeof C?.name=="string"?C.name:"";return x?{tool:x,input:C?.input}:null}).filter(Boolean),P=s.steps[s.steps.length-1];P&&(h.length>1?(P.action=h[0],P.parallelActions=h):p&&(P.action={tool:p,input:T}),y&&(P.thinking=y))}continue}if(c.type==="observation"&&s){let u=typeof c.content=="string"?c.content:"",p=s.steps[s.steps.length-1];p&&(p.observation=u);continue}}}return{summary:o.join(`
114
+ `),messages:e,turns:n,maxSequence:a}}var ap=`
111
115
  Usage:
112
116
  memo mcp list [--json]
113
117
  memo mcp get <name> [--json]
@@ -116,14 +120,14 @@ Usage:
116
120
  memo mcp remove <name>
117
121
  memo mcp login <name> [--scopes scope1,scope2]
118
122
  memo mcp logout <name>
119
- `;function Ln(){console.log(fu.trim())}function gu(e){let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),o=e.slice(t+1);return n?{key:n,value:o}:null}function ts(e,t){let n=[];if(n.push(`${e}`),"url"in t){n.push(` type: ${t.type??"streamable_http"}`),n.push(` url: ${t.url}`),t.bearer_token_env_var&&n.push(` bearer_token_env_var: ${t.bearer_token_env_var}`);let o=t.http_headers??t.headers;o&&Object.keys(o).length>0&&n.push(` headers: ${Object.entries(o).map(([r,s])=>`${r}=${s}`).join(", ")}`)}else n.push(` type: ${t.type??"stdio"}`),n.push(` command: ${t.command}`),t.args&&t.args.length>0&&n.push(` args: ${t.args.join(" ")}`),t.env&&Object.keys(t.env).length>0&&n.push(` env: ${Object.entries(t.env).map(([o,r])=>`${o}=${r}`).join(", ")}`);return n.join(`
120
- `)}function hu(e){let t=e.shift();if(!t)return{error:"Missing server name."};let n,o,r={},s=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(a){if(a==="--"){s=e.slice(i+1);break}if(a==="--url"){let c=e[i+1];if(!c)return{error:"Missing value for --url."};n=c,i+=1;continue}if(a==="--bearer-token-env-var"){let c=e[i+1];if(!c)return{error:"Missing value for --bearer-token-env-var."};o=c,i+=1;continue}if(a==="--env"){let c=e[i+1];if(!c)return{error:"Missing value for --env (KEY=VALUE)."};let l=gu(c);if(!l)return{error:"Invalid --env format. Use KEY=VALUE."};r[l.key]=l.value,i+=1;continue}return a==="--help"||a==="-h"?{error:""}:{error:`Unknown option: ${a}`}}}return n?s.length>0?{error:"Use either --url or a stdio command, not both."}:Object.keys(r).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:t,url:n,bearerTokenEnvVar:o}}:o?{error:"--bearer-token-env-var is only supported with HTTP servers."}:s.length===0?{error:"Missing stdio command. Use `-- <command...>`."}:{options:{name:t,command:s[0],args:s.slice(1),env:Object.keys(r).length>0?r:void 0}}}function yu(e){let[t,...n]=e;return!t||t==="--help"||t==="-h"||t==="help"?{command:"help",rest:[]}:{command:t,rest:n}}function On(e,t=[]){let n=new Set(t);for(let o=0;o<e.length;o+=1){let r=e[o];if(r){if(r.startsWith("--")){n.has(r)&&(o+=1);continue}return r}}return null}async function ns(e){let{command:t,rest:n}=yu(e);if(t==="help"){Ln();return}if(t==="list"){let o=n.includes("--json"),s=(await oe()).config.mcp_servers??{};if(o){console.log(JSON.stringify(s,null,2));return}let i=Object.keys(s);if(i.length===0){console.log('No MCP servers configured. Add one with "memo mcp add".');return}console.log(`MCP servers (${i.length}):`);for(let a of i){let c=s[a];c&&console.log(ts(a,c))}return}if(t==="get"){let o=n.includes("--json"),r=On(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let i=(await oe()).config.mcp_servers?.[r];if(!i){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(o){console.log(JSON.stringify(i,null,2));return}console.log(ts(r,i));return}if(t==="add"){let o=hu(n);if(o.error!==void 0){o.error&&(console.error(o.error),process.exitCode=1),Ln();return}let r=o.options;if(!r)return;if(r.url)try{new URL(r.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await oe(),i={...s.config.mcp_servers??{}};if(i[r.name]){console.error(`MCP server "${r.name}" already exists.`),process.exitCode=1;return}let a;r.url?a={type:"streamable_http",url:r.url,...r.bearerTokenEnvVar?{bearer_token_env_var:r.bearerTokenEnvVar}:{}}:a={command:r.command,args:r.args&&r.args.length>0?r.args:void 0,env:r.env},i[r.name]=a,await ge(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${r.name}".`);return}if(t==="remove"){let o=On(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let r=await oe(),s={...r.config.mcp_servers??{}};if(!s[o]){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}delete s[o],await ge(r.configPath,{...r.config,mcp_servers:s}),console.log(`Removed MCP server "${o}".`);return}if(t==="login"||t==="logout"){let o=On(n,["--scopes"]);if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=(await oe()).config.mcp_servers?.[o];if(!s){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth login/logout only applies to streamable HTTP servers."),process.exitCode=1;return}console.error("OAuth login/logout is not supported in memo yet. Configure a bearer token env var instead."),process.exitCode=1;return}console.error(`Unknown subcommand: ${t}`),Ln(),process.exitCode=1}import{jsx as Eu}from"react/jsx-runtime";function _u(e){let t={once:!1,dangerous:!1,showVersion:!1},n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r!==void 0){if(r==="--version"||r==="-v"){t.showVersion=!0;continue}if(r==="--once"){t.once=!0;continue}if(r==="--dangerous"||r==="-d"){t.dangerous=!0;continue}n.push(r)}}return{question:n.join(" "),options:t}}async function rs(e){let t=await oe();if(!t.needsSetup)return t;let n=t.config.providers[0],r=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&r)return await ge(t.configPath,t.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${t.configPath}`),{...t,needsSetup:!1};if(e==="tui")return t;let s=xu({input:vu,output:Tu}),i=async(a,c)=>(await s.question(a)).trim()||c;try{console.log("No provider config found. Please answer the prompts:");let a=await i("Provider name [deepseek]: ","deepseek"),c=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),l=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),p={current_provider:a,providers:[{name:a,env_api_key:c,model:l,base_url:u||void 0}]};return await ge(t.configPath,p),console.log(`Config written to ${t.configPath}
121
- `),{...t,config:p,needsSetup:!1}}finally{s.close()}}async function ku(e){let t=await rs("plain"),n=Le(t.config),r={sessionId:os(),mode:"once",stream:t.config.stream_output??!1,maxPromptTokens:t.config.max_prompt_tokens,dangerous:e.options.dangerous};e.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={onAssistantStep:c=>{process.stdout.write(c)},requestApproval:e.options.dangerous?void 0:c=>(console.log(`
122
- [approval required] ${c.toolName}: ${c.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:c})=>{console.log(`
123
- [tool] ${c.tool}`),c.input!==void 0&&console.log(`[input] ${JSON.stringify(c.input)}`)},onObservation:()=>{}}},i=await Ye(s,r),a=e.question;if(!a&&!process.stdin.isTTY&&(a=await Cu()),!a&&e.options.once&&(a="Give me a quick self-introduction."),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
124
- `);let c=await i.runTurn(a);t.config.stream_output||console.log(`
125
- ${c.finalText}`),console.log(`
126
- [tokens] prompt=${c.tokenUsage.prompt} completion=${c.tokenUsage.completion} total=${c.tokenUsage.total}`),console.log(`
127
- provider=${n.name} model=${n.model}`)}catch(c){console.error(`Run failed: ${c.message}`)}finally{await i.close()}}async function bu(e){let t=await rs("tui"),n=Le(t.config),r={sessionId:os(),mode:"interactive",stream:t.config.stream_output??!1,maxPromptTokens:t.config.max_prompt_tokens,dangerous:e.options.dangerous},s=Tt(t,r);e.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
128
- `)),await Su(Eu(es,{sessionOptions:r,providerName:n.name,model:n.model,configPath:t.configPath,mcpServers:t.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:s,providers:t.config.providers,dangerous:e.options.dangerous,needsSetup:t.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function wu(){let e=process.argv.slice(2);if(e[0]==="mcp"||e[0]==="--"&&e[1]==="mcp"){let o=e[0]==="--"?2:1;await ns(e.slice(o));return}let t=_u(e);if(t.options.showVersion){let r=Ht()?.version??"unknown";console.log(r);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)||t.options.once){await ku(t);return}await bu(t)}wu();async function Cu(){return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim())}),process.stdin.resume()})}
123
+ `;function Un(){console.log(ap.trim())}function lp(t){let e=t.indexOf("=");if(e<=0)return null;let n=t.slice(0,e).trim(),o=t.slice(e+1);return n?{key:n,value:o}:null}function fs(t,e){let n=[];if(n.push(`${t}`),"url"in e){n.push(` type: ${e.type??"streamable_http"}`),n.push(` url: ${e.url}`),e.bearer_token_env_var&&n.push(` bearer_token_env_var: ${e.bearer_token_env_var}`);let o=e.http_headers??e.headers;o&&Object.keys(o).length>0&&n.push(` headers: ${Object.entries(o).map(([r,s])=>`${r}=${s}`).join(", ")}`)}else n.push(` type: ${e.type??"stdio"}`),n.push(` command: ${e.command}`),e.args&&e.args.length>0&&n.push(` args: ${e.args.join(" ")}`),e.env&&Object.keys(e.env).length>0&&n.push(` env: ${Object.entries(e.env).map(([o,r])=>`${o}=${r}`).join(", ")}`);return n.join(`
124
+ `)}function cp(t){let e=t.shift();if(!e)return{error:"Missing server name."};let n,o,r={},s=[];for(let i=0;i<t.length;i+=1){let a=t[i];if(a){if(a==="--"){s=t.slice(i+1);break}if(a==="--url"){let l=t[i+1];if(!l)return{error:"Missing value for --url."};n=l,i+=1;continue}if(a==="--bearer-token-env-var"){let l=t[i+1];if(!l)return{error:"Missing value for --bearer-token-env-var."};o=l,i+=1;continue}if(a==="--env"){let l=t[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=lp(l);if(!c)return{error:"Invalid --env format. Use KEY=VALUE."};r[c.key]=c.value,i+=1;continue}return a==="--help"||a==="-h"?{error:""}:{error:`Unknown option: ${a}`}}}return n?s.length>0?{error:"Use either --url or a stdio command, not both."}:Object.keys(r).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:e,url:n,bearerTokenEnvVar:o}}:o?{error:"--bearer-token-env-var is only supported with HTTP servers."}:s.length===0?{error:"Missing stdio command. Use `-- <command...>`."}:{options:{name:e,command:s[0],args:s.slice(1),env:Object.keys(r).length>0?r:void 0}}}function up(t){let[e,...n]=t;return!e||e==="--help"||e==="-h"||e==="help"?{command:"help",rest:[]}:{command:e,rest:n}}function Hn(t,e=[]){let n=new Set(e);for(let o=0;o<t.length;o+=1){let r=t[o];if(r){if(r.startsWith("--")){n.has(r)&&(o+=1);continue}return r}}return null}async function gs(t){let{command:e,rest:n}=up(t);if(e==="help"){Un();return}if(e==="list"){let o=n.includes("--json"),s=(await ie()).config.mcp_servers??{};if(o){console.log(JSON.stringify(s,null,2));return}let i=Object.keys(s);if(i.length===0){console.log('No MCP servers configured. Add one with "memo mcp add".');return}console.log(`MCP servers (${i.length}):`);for(let a of i){let l=s[a];l&&console.log(fs(a,l))}return}if(e==="get"){let o=n.includes("--json"),r=Hn(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let i=(await ie()).config.mcp_servers?.[r];if(!i){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(o){console.log(JSON.stringify(i,null,2));return}console.log(fs(r,i));return}if(e==="add"){let o=cp(n);if(o.error!==void 0){o.error&&(console.error(o.error),process.exitCode=1),Un();return}let r=o.options;if(!r)return;if(r.url)try{new URL(r.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await ie(),i={...s.config.mcp_servers??{}};if(i[r.name]){console.error(`MCP server "${r.name}" already exists.`),process.exitCode=1;return}let a;r.url?a={type:"streamable_http",url:r.url,...r.bearerTokenEnvVar?{bearer_token_env_var:r.bearerTokenEnvVar}:{}}:a={command:r.command,args:r.args&&r.args.length>0?r.args:void 0,env:r.env},i[r.name]=a,await ye(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${r.name}".`);return}if(e==="remove"){let o=Hn(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let r=await ie(),s={...r.config.mcp_servers??{}};if(!s[o]){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}delete s[o],await ye(r.configPath,{...r.config,mcp_servers:s}),console.log(`Removed MCP server "${o}".`);return}if(e==="login"||e==="logout"){let o=Hn(n,["--scopes"]);if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=(await ie()).config.mcp_servers?.[o];if(!s){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth login/logout only applies to streamable HTTP servers."),process.exitCode=1;return}console.error("OAuth login/logout is not supported in memo yet. Configure a bearer token env var instead."),process.exitCode=1;return}console.error(`Unknown subcommand: ${e}`),Un(),process.exitCode=1}import{jsx as xp}from"react/jsx-runtime";function gp(t){let e={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let o=0;o<t.length;o++){let r=t[o];if(r!==void 0){if(r==="--version"||r==="-v"){e.showVersion=!0;continue}if(r==="--once"){e.removedOnceFlag=!0;continue}if(r==="--dangerous"||r==="-d"){e.dangerous=!0;continue}n.push(r)}}return{question:n.join(" "),options:e}}async function ys(t){let e=await ie();if(!e.needsSetup)return e;let n=e.config.providers[0],r=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&r)return await ye(e.configPath,e.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${e.configPath}`),{...e,needsSetup:!1};if(t==="tui")return e;let s=pp({input:mp,output:dp}),i=async(a,l)=>(await s.question(a)).trim()||l;try{console.log("No provider config found. Please answer the prompts:");let a=await i("Provider name [deepseek]: ","deepseek"),l=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),c=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),p={current_provider:a,providers:[{name:a,env_api_key:l,model:c,base_url:u||void 0}]};return await ye(e.configPath,p),console.log(`Config written to ${e.configPath}
125
+ `),{...e,config:p,needsSetup:!1}}finally{s.close()}}async function hp(t){let e=await ys("plain"),n=Ue(e.config),r={sessionId:hs(),mode:"interactive",maxPromptTokens:e.config.max_prompt_tokens,dangerous:t.options.dangerous};t.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={requestApproval:t.options.dangerous?void 0:l=>(console.log(`
126
+ [approval required] ${l.toolName}: ${l.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:l})=>{console.log(`
127
+ [tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await lt(s,r),a=t.question;if(!a&&!process.stdin.isTTY&&(a=await _p()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
128
+ `);let l=await i.runTurn(a);console.log(`
129
+ ${l.finalText}`),console.log(`
130
+ [tokens] prompt=${l.tokenUsage.prompt} completion=${l.tokenUsage.completion} total=${l.tokenUsage.total}`),console.log(`
131
+ provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function yp(t){let e=await ys("tui"),n=Ue(e.config),r={sessionId:hs(),mode:"interactive",maxPromptTokens:e.config.max_prompt_tokens,dangerous:t.options.dangerous},s=It(e,r);t.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
132
+ `)),await fp(xp(ds,{sessionOptions:r,providerName:n.name,model:n.model,configPath:e.configPath,mcpServers:e.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:s,providers:e.config.providers,dangerous:t.options.dangerous,needsSetup:e.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function Tp(){let t=process.argv.slice(2);if(t[0]==="mcp"||t[0]==="--"&&t[1]==="mcp"){let o=t[0]==="--"?2:1;await gs(t.slice(o));return}let e=gp(t);if(e.options.removedOnceFlag){console.error("`--once` has been removed. Use `memo` (interactive) or pipe input to `memo`."),process.exitCode=1;return}if(e.options.showVersion){let r=Vt()?.version??"unknown";console.log(r);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await hp(e);return}await yp(e)}Tp();async function _p(){return new Promise(t=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n}),process.stdin.on("end",()=>{t(e.trim())}),process.stdin.resume()})}
129
133
  //# sourceMappingURL=index.js.map