@memo-code/memo 0.7.1 → 0.7.3

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,102 +1,103 @@
1
1
  #!/usr/bin/env node
2
- var pi=Object.create;var hr=Object.defineProperty;var di=Object.getOwnPropertyDescriptor;var mi=Object.getOwnPropertyNames;var fi=Object.getPrototypeOf,gi=Object.prototype.hasOwnProperty;var hi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var yi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mi(t))!gi.call(e,o)&&o!==n&&hr(e,o,{get:()=>t[o],enumerable:!(r=di(t,o))||r.enumerable});return e};var Ti=(e,t,n)=>(n=e!=null?pi(fi(e)):{},yi(t||!e||!e.__esModule?hr(n,"default",{value:e,enumerable:!0}):n,e));var Br=hi((fm,Fr)=>{"use strict";function Or(e){return Array.isArray(e)?e:[e]}var In="",Lr=" ",kn="\\",fa=/^\s+$/,ga=/(?:[^\\]|^)\\$/,ha=/^\\!/,ya=/^\\#/,Ta=/\r?\n/g,_a=/^\.*\/|^\.+$/,Pn="/",Dr="node-ignore";typeof Symbol<"u"&&(Dr=Symbol.for("node-ignore"));var Nr=Dr,Sa=(e,t,n)=>Object.defineProperty(e,t,{value:n}),va=/([0-z])-([0-z])/g,Ur=()=>!1,xa=e=>e.replace(va,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:In),Ca=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ba=[[/^\uFEFF/,()=>In],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Lr:In)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Lr}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>kn],[/\\\\/g,()=>kn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===kn?`\\[${n}${Ca(r)}${o}`:o==="]"&&r.length%2===0?`[${xa(n)}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],$r=Object.create(null),Ea=(e,t)=>{let n=$r[e];return n||(n=ba.reduce((r,[o,s])=>r.replace(o,s.bind(e)),e),$r[e]=n),t?new RegExp(n,"i"):new RegExp(n)},Ln=e=>typeof e=="string",Aa=e=>e&&Ln(e)&&!fa.test(e)&&!ga.test(e)&&e.indexOf("#")!==0,wa=e=>e.split(Ta),Rn=class{constructor(t,n,r,o){this.origin=t,this.pattern=n,this.negative=r,this.regex=o}},Ma=(e,t)=>{let n=e,r=!1;e.indexOf("!")===0&&(r=!0,e=e.substr(1)),e=e.replace(ha,"!").replace(ya,"#");let o=Ea(e,t);return new Rn(n,e,r,o)},ka=(e,t)=>{throw new t(e)},De=(e,t,n)=>Ln(e)?e?De.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),Hr=e=>_a.test(e);De.isNotRelative=Hr;De.convert=e=>e;var On=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){Sa(this,Nr,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(t){if(t&&t[Nr]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(Aa(t)){let n=Ma(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Or(Ln(t)?wa(t):t).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(t){return this.add(t)}_testOne(t,n){let r=!1,o=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(o===i&&r!==o||i&&!r&&!o&&!n)return;s.regex.test(t)&&(r=!i,o=i)}),{ignored:r,unignored:o}}_test(t,n,r,o){let s=t&&De.convert(t);return De(s,t,this._allowRelativePaths?Ur:ka),this._t(s,n,r,o)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(Pn)),o.pop(),!o.length)return n[t]=this._testOne(t,r);let s=this._t(o.join(Pn)+Pn,n,r,o);return n[t]=s.ignored?s:this._testOne(t,r)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return Or(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},Wt=e=>new On(e),Pa=e=>De(e&&De.convert(e),e,Ur);Wt.isPathValid=Pa;Wt.default=Wt;Fr.exports=Wt;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,"/");De.convert=e;let t=/^[a-z]:\//i;De.isNotRelative=n=>t.test(n)||Hr(n)}});import{randomUUID as ii}from"crypto";import{createInterface as Sd}from"readline/promises";import{stdin as vd,stdout as xd}from"process";import{render as Cd}from"ink";import _i from"os";import{readFile as yr}from"fs/promises";import{join as Tr,dirname as Si}from"path";import{fileURLToPath as vi}from"url";var xi=/{{\s*([\w.-]+)\s*}}/g;function Ci(e,t){return e.replace(xi,(n,r)=>t[r]??"")}function bi(){try{return _i.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function Ei(e){let t=Tr(e,"AGENTS.md");try{let n=await yr(t,"utf-8");return n.trim()?{path:t,content:n}:null}catch{return null}}function Ai(e,t){return`${e}
2
+ var pa=Object.create;var Kr=Object.defineProperty;var da=Object.getOwnPropertyDescriptor;var ma=Object.getOwnPropertyNames;var fa=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty;var Vr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ha=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ma(e))!ga.call(t,o)&&o!==n&&Kr(t,o,{get:()=>e[o],enumerable:!(r=da(e,o))||r.enumerable});return t};var Xr=(t,e,n)=>(n=t!=null?pa(fa(t)):{},ha(e||!t||!t.__esModule?Kr(n,"default",{value:t,enumerable:!0}):n,t));var vo=Vr((_g,To)=>{"use strict";function mo(t){return Array.isArray(t)?t:[t]}var jn="",fo=" ",Hn="\\",dl=/^\s+$/,ml=/(?:[^\\]|^)\\$/,fl=/^\\!/,gl=/^\\#/,hl=/\r?\n/g,yl=/^\.*\/|^\.+$/,Bn="/",yo="node-ignore";typeof Symbol<"u"&&(yo=Symbol.for("node-ignore"));var go=yo,_l=(t,e,n)=>Object.defineProperty(t,e,{value:n}),Sl=/([0-z])-([0-z])/g,_o=()=>!1,Tl=t=>t.replace(Sl,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:jn),vl=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Cl=[[/^\uFEFF/,()=>jn],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?fo:jn)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+fo}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return e+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Hn],[/\\\\/g,()=>Hn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Hn?`\\[${n}${vl(r)}${o}`:o==="]"&&r.length%2===0?`[${Tl(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],ho=Object.create(null),xl=(t,e)=>{let n=ho[t];return n||(n=Cl.reduce((r,[o,s])=>r.replace(o,s.bind(t)),t),ho[t]=n),e?new RegExp(n,"i"):new RegExp(n)},zn=t=>typeof t=="string",bl=t=>t&&zn(t)&&!dl.test(t)&&!ml.test(t)&&t.indexOf("#")!==0,El=t=>t.split(hl),Wn=class{constructor(e,n,r,o){this.origin=e,this.pattern=n,this.negative=r,this.regex=o}},Ml=(t,e)=>{let n=t,r=!1;t.indexOf("!")===0&&(r=!0,t=t.substr(1)),t=t.replace(fl,"!").replace(gl,"#");let o=xl(t,e);return new Wn(n,t,r,o)},wl=(t,e)=>{throw new e(t)},$e=(t,e,n)=>zn(t)?t?$e.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),So=t=>yl.test(t);$e.isNotRelative=So;$e.convert=t=>t;var Gn=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){_l(this,go,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[go]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(bl(e)){let n=Ml(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,mo(zn(e)?El(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,n){let r=!1,o=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(o===i&&r!==o||i&&!r&&!o&&!n)return;s.regex.test(e)&&(r=!i,o=i)}),{ignored:r,unignored:o}}_test(e,n,r,o){let s=e&&$e.convert(e);return $e(s,e,this._allowRelativePaths?_o:wl),this._t(s,n,r,o)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(Bn)),o.pop(),!o.length)return n[e]=this._testOne(e,r);let s=this._t(o.join(Bn)+Bn,n,r,o);return n[e]=s.ignored?s:this._testOne(e,r)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return mo(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Vt=t=>new Gn(t),Al=t=>$e(t&&$e.convert(t),t,_o);Vt.isPathValid=Al;Vt.default=Vt;To.exports=Vt;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,"/");$e.convert=t;let e=/^[a-z]:\//i;$e.isNotRelative=n=>e.test(n)||So(n)}});var mi=Vr((U_,hn)=>{"use strict";function ai(t){return Array.isArray(t)?t:[t]}var Kp=void 0,br="",si=" ",xr="\\",Vp=/^\s+$/,Xp=/(?:[^\\]|^)\\$/,Jp=/^\\!/,Yp=/^\\#/,Zp=/\r?\n/g,Qp=/^\.{0,2}\/|^\.{1,2}$/,ed=/\/$/,yt="/",li="node-ignore";typeof Symbol<"u"&&(li=Symbol.for("node-ignore"));var ci=li,_t=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),td=/([0-z])-([0-z])/g,ui=()=>!1,nd=t=>t.replace(td,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:br),rd=t=>{let{length:e}=t;return t.slice(0,e-e%2)},od=[[/^\uFEFF/,()=>br],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?si:br)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+si}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return e+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>xr],[/\\\\/g,()=>xr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===xr?`\\[${n}${rd(r)}${o}`:o==="]"&&r.length%2===0?`[${nd(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],sd=/(^|\\\/)?\\\*$/,$t="regex",fn="checkRegex",ii="_",id={[$t](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[fn](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ad=t=>od.reduce((e,[n,r])=>e.replace(n,r.bind(t)),t),gn=t=>typeof t=="string",ld=t=>t&&gn(t)&&!Vp.test(t)&&!Xp.test(t)&&t.indexOf("#")!==0,cd=t=>t.split(Zp).filter(Boolean),Er=class{constructor(e,n,r,o,s,i){this.pattern=e,this.mark=n,this.negative=s,_t(this,"body",r),_t(this,"ignoreCase",o),_t(this,"regexPrefix",i)}get regex(){let e=ii+$t;return this[e]?this[e]:this._make($t,e)}get checkRegex(){let e=ii+fn;return this[e]?this[e]:this._make(fn,e)}_make(e,n){let r=this.regexPrefix.replace(sd,id[e]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return _t(this,n,o)}},ud=({pattern:t,mark:e},n)=>{let r=!1,o=t;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Jp,"!").replace(Yp,"#");let s=ad(o);return new Er(t,e,o,n,r,s)},Mr=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[ci]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(gn(e)&&(e={pattern:e}),ld(e.pattern)){let n=ud(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,ai(gn(e)?cd(e):e).forEach(this._add,this),this._added}test(e,n,r){let o=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&o!==s||c&&!o&&!s&&!n||!l[r].test(e)||(o=!c,s=c,i=c?Kp:l)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},pd=(t,e)=>{throw new e(t)},He=(t,e,n)=>gn(t)?t?He.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),pi=t=>Qp.test(t);He.isNotRelative=pi;He.convert=t=>t;var wr=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){_t(this,ci,!0),this._rules=new Mr(n),this._strictPathCheck=!r,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,r,o){let s=e&&He.convert(e);return He(s,e,this._strictPathCheck?pd:ui),this._t(s,n,r,o)}checkIgnore(e){if(!ed.test(e))return this.test(e);let n=e.split(yt).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(yt)+yt,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(e,!1,fn)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(yt).filter(Boolean)),o.pop(),!o.length)return n[e]=this._rules.test(e,r,$t);let s=this._t(o.join(yt)+yt,n,r,o);return n[e]=s.ignored?s:this._rules.test(e,r,$t)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return ai(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Ar=t=>new wr(t),dd=t=>He(t&&He.convert(t),t,ui),di=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");He.convert=t;let e=/^[a-z]:\//i;He.isNotRelative=n=>e.test(n)||pi(n)};typeof process<"u"&&process.platform==="win32"&&di();hn.exports=Ar;Ar.default=Ar;hn.exports.isPathValid=dd;_t(hn.exports,Symbol.for("setupWindows"),di)});import{randomUUID as aa}from"crypto";import{createInterface as bf}from"readline/promises";import{stdin as Ef,stdout as Mf}from"process";import{render as wf}from"ink";import ya from"os";import{readFile as Jr}from"fs/promises";import{join as Yr,dirname as _a}from"path";import{fileURLToPath as Sa}from"url";var Ta=/{{\s*([\w.-]+)\s*}}/g;function va(t,e){return t.replace(Ta,(n,r)=>e[r]??"")}function Ca(){try{return ya.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function xa(t){let e=Yr(t,"AGENTS.md");try{let n=await Jr(e,"utf-8");return n.trim()?{path:e,content:n}:null}catch{return null}}function ba(t,e){return`${t}
3
3
 
4
4
  ## Project AGENTS.md (Startup Root)
5
- Loaded from: ${t.path}
5
+ Loaded from: ${e.path}
6
6
 
7
- ${t.content}`}async function _r(e={}){let t=e.cwd??process.cwd(),n=Si(vi(import.meta.url)),r=Tr(n,"prompt.md"),o=await yr(r,"utf-8"),s={date:new Date().toISOString(),user:bi(),pwd:t},i=Ci(o,s),a=await Ei(t);return a?Ai(i,a):i}import{appendFile as wi,mkdir as Mi}from"fs/promises";import{dirname as ki}from"path";var Ft=class{constructor(t){this.filePath=t}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=Mi(ki(this.filePath),{recursive:!0}).then(()=>{})),this.ensureDirPromise}async append(t){if(this.closed)throw new Error("History sink is closed");return this.writeQueue=this.writeQueue.then(async()=>{await this.ensureDirectory(),await wi(this.filePath,`${JSON.stringify(t)}
8
- `,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function Sr(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{z as Ne}from"zod";function N(e){let{inputSchema:t,execute:n,...r}=e,o=t.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,source:"native",inputSchema:i,validateInput:a=>{let l=t.safeParse(a);if(!l.success){let c=l.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${e.name} invalid input: ${c}`}}return{ok:!0,data:l.data}},execute:n}}function f(e,t=!1){return{content:[{type:"text",text:e}],isError:t}}import{spawn as Ji}from"child_process";import{EventEmitter as Yi}from"events";import{resolve as Zi}from"path";import{posix as Pi}from"path";var vr=220,xr=4096,Ii=/^\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)$/i,Ri=/(?:^|[\s(])(?:\d?>>?|>>|>\||&>)\s*\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)(?:\s|$)/i,Oi=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Li=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function xn(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ni(e){let t=e.replace(/\s+/g," ").trim();return t.length>vr?`${t.slice(0,vr)}\u2026`:t}function Cr(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return(t.split(/[\\/]/).at(-1)??t).toLowerCase()}function $i(e){let t=null,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){n=!1;continue}if(o==="\\"&&t!=="'"){n=!0;continue}if(t){o===t&&(t=null);continue}if(o==='"'||o==="'"){t=o;continue}if(o==="#")return e.slice(0,r)}return e}function Di(e){let t=[],n="",r=null,o=!1,s=()=>{let i=$i(n).trim();i&&t.push(i),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){n+=a,o=!0;continue}if(r){n+=a,a===r&&(r=null);continue}if(a==='"'||a==="'"){r=a,n+=a;continue}if(a===";"||a===`
9
- `){s();continue}if(a==="&"){e[i+1]==="&"&&(i+=1),s();continue}if(a==="|"){e[i+1]==="|"&&(i+=1),s();continue}n+=a}return s(),t}function Ui(e){let t=[],n="",r=null,o=!1,s=()=>{n&&t.push(n),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){o=!0;continue}if(r){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(/\s/.test(a)){s();continue}n+=a}return s(),t}function br(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function Hi(e,t){let n=t;for(;n<e.length;){let r=Cr(e[n]??"");if(r==="sudo"){for(n+=1;n<e.length;){let o=e[n]??"";if(!o.startsWith("-"))break;n+=1,Oi.has(o)&&n<e.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<e.length;){let o=e[n]??"";if(o.startsWith("-")||br(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function Fi(e){let t=Ui(e);if(t.length===0)return null;let n=0;for(;n<t.length&&br(t[n]??"");)n+=1;if(n=Hi(t,n),n>=t.length)return null;let r=Cr(t[n]??"");return r?{raw:e,commandName:r,args:t.slice(n+1)}:null}function Cn(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return Ii.test(t)}function Bi(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.toLowerCase();return n==="/"||n==="/*"||n==="/.*"||n==="~"||n==="~/"||n==="~/*"||n==="$home"||n==="$home/"||n==="$home/*"||n==="${home}"||n==="${home}/"||n==="${home}/*"?!0:t.startsWith("/")&&!/[*?[\]{}$]/.test(t)?Pi.normalize(t)==="/":!1}function Wi(e){return e.startsWith("-")&&e!=="-"}function ji(e){if(e.commandName!=="rm")return null;let t=!1,n=0;for(;n<e.args.length;){let o=e.args[n]??"";if(o==="--"){n+=1;break}if(!Wi(o))break;if(o==="--recursive"){t=!0,n+=1;continue}if(o.startsWith("--")){n+=1;continue}let s=o.slice(1);(s.includes("r")||s.includes("R"))&&(t=!0),n+=1}if(!t)return null;let r=e.args.slice(n);for(let o of r)if(Bi(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:e.raw};return null}function zi(e){return e.commandName==="mkfs"||e.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:e.raw}:null}function qi(e){if(e.commandName!=="dd")return null;for(let t=0;t<e.args.length;t+=1){let n=e.args[t]??"",r=n.indexOf("=");if(r<=0)continue;let o=n.slice(0,r).toLowerCase(),s=n.slice(r+1);if(o==="of"&&Cn(s))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}for(let t=0;t<e.args.length-1;t+=1){let n=(e.args[t]??"").toLowerCase(),r=e.args[t+1]??"";if(n==="of"&&Cn(r))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}return null}function Gi(e){return!Li.has(e.commandName)||!e.args.some(t=>Cn(t))?null:{ruleId:"disk_mutation_block_device",matchedSegment:e.raw}}function Ki(e){return Ri.test(e)?{ruleId:"redirect_block_device",matchedSegment:e}:null}function Vi(e){for(let t of Di(e)){let n=Fi(t);if(n){let o=ji(n);if(o)return o;let s=zi(n);if(s)return s;let i=qi(n);if(i)return i;let a=Gi(n);if(a)return a}let r=Ki(t);if(r)return r}return null}function Xi(e,t){let n=Ni(e.command),r=typeof e.sessionId=="number"?` session_id="${e.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${xn(e.toolName)}" reason="dangerous_command" policy="blacklist" rule="${xn(t.ruleId)}"${r} command="${xn(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function bn(e){let t=Vi(e.command);return t?{blocked:!0,xml:Xi(e,t),match:t}:{blocked:!1}}function Er(e){let n=e.replace(/\r\n/g,`
7
+ ${e.content}`}async function Zr(t={}){let e=t.cwd??process.cwd(),n=_a(Sa(import.meta.url)),r=Yr(n,"prompt.md"),o=await Jr(r,"utf-8"),s={date:new Date().toISOString(),user:Ca(),pwd:e},i=va(o,s),a=await xa(e);return a?ba(i,a):i}import{appendFile as Ea,mkdir as Ma}from"fs/promises";import{dirname as wa}from"path";var qt=class{constructor(e){this.filePath=e}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=Ma(wa(this.filePath),{recursive:!0}).then(()=>{})),this.ensureDirPromise}async append(e){if(this.closed)throw new Error("History sink is closed");return this.writeQueue=this.writeQueue.then(async()=>{await this.ensureDirectory(),await Ea(this.filePath,`${JSON.stringify(e)}
8
+ `,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function Qr(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 Le}from"zod";function N(t){let{inputSchema:e,execute:n,...r}=t,o=e.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,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 d(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}import{spawn as Va}from"child_process";import{EventEmitter as Xa}from"events";import{resolve as Ja}from"path";import{posix as Aa}from"path";var eo=220,to=4096,Pa=/^\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)$/i,ka=/(?:^|[\s(])(?:\d?>>?|>>|>\||&>)\s*\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)(?:\s|$)/i,Ra=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Ia=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function On(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Oa(t){let e=t.replace(/\s+/g," ").trim();return e.length>eo?`${e.slice(0,eo)}\u2026`:e}function no(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return(e.split(/[\\/]/).at(-1)??e).toLowerCase()}function La(t){let e=null,n=!1;for(let r=0;r<t.length;r+=1){let o=t[r];if(n){n=!1;continue}if(o==="\\"&&e!=="'"){n=!0;continue}if(e){o===e&&(e=null);continue}if(o==='"'||o==="'"){e=o;continue}if(o==="#")return t.slice(0,r)}return t}function Na(t){let e=[],n="",r=null,o=!1,s=()=>{let i=La(n).trim();i&&e.push(i),n=""};for(let i=0;i<t.length;i+=1){let a=t[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){n+=a,o=!0;continue}if(r){n+=a,a===r&&(r=null);continue}if(a==='"'||a==="'"){r=a,n+=a;continue}if(a===";"||a===`
9
+ `){s();continue}if(a==="&"){t[i+1]==="&"&&(i+=1),s();continue}if(a==="|"){t[i+1]==="|"&&(i+=1),s();continue}n+=a}return s(),e}function $a(t){let e=[],n="",r=null,o=!1,s=()=>{n&&e.push(n),n=""};for(let i=0;i<t.length;i+=1){let a=t[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){o=!0;continue}if(r){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(/\s/.test(a)){s();continue}n+=a}return s(),e}function ro(t){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t)}function Da(t,e){let n=e;for(;n<t.length;){let r=no(t[n]??"");if(r==="sudo"){for(n+=1;n<t.length;){let o=t[n]??"";if(!o.startsWith("-"))break;n+=1,Ra.has(o)&&n<t.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<t.length;){let o=t[n]??"";if(o.startsWith("-")||ro(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function Ua(t){let e=$a(t);if(e.length===0)return null;let n=0;for(;n<e.length&&ro(e[n]??"");)n+=1;if(n=Da(e,n),n>=e.length)return null;let r=no(e[n]??"");return r?{raw:t,commandName:r,args:e.slice(n+1)}:null}function Ln(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return Pa.test(e)}function Fa(t){let e=t.trim().replace(/^['"]|['"]$/g,""),n=e.toLowerCase();return n==="/"||n==="/*"||n==="/.*"||n==="~"||n==="~/"||n==="~/*"||n==="$home"||n==="$home/"||n==="$home/*"||n==="${home}"||n==="${home}/"||n==="${home}/*"?!0:e.startsWith("/")&&!/[*?[\]{}$]/.test(e)?Aa.normalize(e)==="/":!1}function Ha(t){return t.startsWith("-")&&t!=="-"}function Ba(t){if(t.commandName!=="rm")return null;let e=!1,n=0;for(;n<t.args.length;){let o=t.args[n]??"";if(o==="--"){n+=1;break}if(!Ha(o))break;if(o==="--recursive"){e=!0,n+=1;continue}if(o.startsWith("--")){n+=1;continue}let s=o.slice(1);(s.includes("r")||s.includes("R"))&&(e=!0),n+=1}if(!e)return null;let r=t.args.slice(n);for(let o of r)if(Fa(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:t.raw};return null}function ja(t){return t.commandName==="mkfs"||t.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:t.raw}:null}function Wa(t){if(t.commandName!=="dd")return null;for(let e=0;e<t.args.length;e+=1){let n=t.args[e]??"",r=n.indexOf("=");if(r<=0)continue;let o=n.slice(0,r).toLowerCase(),s=n.slice(r+1);if(o==="of"&&Ln(s))return{ruleId:"dd_write_block_device",matchedSegment:t.raw}}for(let e=0;e<t.args.length-1;e+=1){let n=(t.args[e]??"").toLowerCase(),r=t.args[e+1]??"";if(n==="of"&&Ln(r))return{ruleId:"dd_write_block_device",matchedSegment:t.raw}}return null}function Ga(t){return!Ia.has(t.commandName)||!t.args.some(e=>Ln(e))?null:{ruleId:"disk_mutation_block_device",matchedSegment:t.raw}}function za(t){return ka.test(t)?{ruleId:"redirect_block_device",matchedSegment:t}:null}function qa(t){for(let e of Na(t)){let n=Ua(e);if(n){let o=Ba(n);if(o)return o;let s=ja(n);if(s)return s;let i=Wa(n);if(i)return i;let a=Ga(n);if(a)return a}let r=za(e);if(r)return r}return null}function Ka(t,e){let n=Oa(t.command),r=typeof t.sessionId=="number"?` session_id="${t.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${On(t.toolName)}" reason="dangerous_command" policy="blacklist" rule="${On(e.ruleId)}"${r} command="${On(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function Nn(t){let e=qa(t.command);return e?{blocked:!0,xml:Ka(t,e),match:e}:{blocked:!1}}function oo(t){let n=t.replace(/\r\n/g,`
10
10
  `).replace(/\r/g,`
11
11
  `).split(`
12
- `),r=n.pop()??"";return{completedLines:n,remainder:r}}function En(e){return e.length<=xr?e:e.slice(-xr)}var Qi=1e4,ea=250,ta=2e3,Bt=64;function na(e){return Math.ceil(e.length/4)}function ra(){return Math.random().toString(16).slice(2)||String(Date.now())}function oa(e){let t=e.login,n=e.shell?.trim();if(process.platform==="win32"){let o=n||"powershell.exe";return o.toLowerCase().includes("powershell")?{file:o,args:["-NoProfile","-Command",e.cmd]}:{file:o,args:[t?"-lc":"-c",e.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[t?"-lc":"-c",e.cmd]}}function sa(e,t){let r=(typeof t=="number"&&t>0?Math.floor(t):ta)*4,o=na(e);return e.length<=r?{output:e,originalTokenCount:o,deliveredChars:e.length}:{output:e.slice(0,r),originalTokenCount:o,deliveredChars:r}}function ia(e){let t=[];return t.push(`Chunk ID: ${e.chunkId}`),t.push(`Wall time: ${e.wallTimeSeconds.toFixed(4)} seconds`),e.exitCode!==null?t.push(`Process exited with code ${e.exitCode}`):t.push(`Process running with session ID ${e.sessionId}`),t.push(`Original token count: ${e.originalTokenCount}`),t.push("Output:"),t.push(e.output),t.join(`
13
- `)}function Ar(e,t){return typeof e!="number"||Number.isNaN(e)?t:e<0?0:Math.floor(e)}async function wr(e,t){t<=0||e.exited||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},t),o=()=>{clearTimeout(r),s(),n()},s=()=>{e.eventBus.off("exit",o)};e.eventBus.on("exit",o)})])}async function Mr(e,t){e.exited||t<=0||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},t),o=()=>{clearTimeout(r),s(),n()},s=()=>{e.eventBus.off("exit",o)};e.eventBus.on("exit",o)})])}var An=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Bt)return;let t=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,r)=>n.startedAtMs-r.startedAtMs);for(let n of t){if(this.sessions.size<=Bt)break;this.sessions.delete(n.id)}}activeSessionCount(){let t=0;for(let n of this.sessions.values())n.exited||(t+=1);return t}async terminateForTimeout(t){t.exited||(t.proc.kill("SIGTERM"),await Mr(t,200),t.exited||(t.proc.kill("SIGKILL"),await Mr(t,200)))}async start(t){let n=t.cmd.trim();if(!n)throw new Error("cmd must not be empty");if(this.cleanupSessions(),this.activeSessionCount()>=Bt)throw new Error(`too many active sessions (max ${Bt})`);let r=bn({toolName:t.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=oa({cmd:n,shell:t.shell,login:t.login!==!1}),a=t.workdir?.trim()?Zi(process.cwd(),t.workdir.trim()):process.cwd(),l=Ji(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),c={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new Yi,proc:l},u=(h,d)=>{let E=typeof d=="string"?d:d.toString("utf8");c.output+=h?`${h}${E}`:E,c.eventBus.emit("output")};l.stdout?.on("data",h=>u("",h)),l.stderr?.on("data",h=>u("",h)),l.on("error",h=>{c.output+=`
14
- [exec error] ${h.message}`,c.eventBus.emit("output")}),l.on("close",h=>{c.exited=!0,c.exitCode=typeof h=="number"?h:-1,c.eventBus.emit("exit")}),this.sessions.set(o,c),this.cleanupSessions();let p=typeof t.execution_timeout_ms=="number"&&t.execution_timeout_ms>0?Math.floor(t.execution_timeout_ms):null,y=Ar(t.yield_time_ms,Qi),m=p!==null?Math.min(y,Math.max(0,p)):y;if(await wr(c,m),p!==null&&!c.exited&&Date.now()-s>=p)throw await this.terminateForTimeout(c),this.cleanupSessions(),new Error(`command timed out after ${p}ms`);return this.buildResponseText(c,t.max_output_tokens)}async write(t){let n=this.sessions.get(t.session_id);if(!n)throw new Error(`session_id ${t.session_id} not found`);if(!n.exited&&t.chars&&t.chars.length>0){let o=En(`${n.pendingStdinInput}${t.chars}`),{completedLines:s,remainder:i}=Er(o);for(let a of s){if(!a.trim())continue;let l=bn({toolName:t.source_tool??"write_stdin",command:a,sessionId:n.id});if(l.blocked)return n.pendingStdinInput="",l.xml}n.pendingStdinInput=En(i),n.proc.stdin?.write(t.chars)}let r=Ar(t.yield_time_ms,ea);return await wr(n,r),this.buildResponseText(n,t.max_output_tokens)}buildResponseText(t,n){let r=t.output.slice(t.readOffset),o=sa(r,n);t.readOffset+=o.deliveredChars;let s={sessionId:t.id,chunkId:ra(),wallTimeSeconds:(Date.now()-t.startedAtMs)/1e3,exitCode:t.exited?t.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return ia(s)}},kr=new An;async function st(e){return kr.start(e)}async function Pr(e){return kr.write(e)}var aa=Ne.object({command:Ne.array(Ne.string().min(1)).min(1,"command cannot be empty"),workdir:Ne.string().optional(),timeout_ms:Ne.number().int().positive().optional(),sandbox_permissions:Ne.enum(["use_default","require_escalated"]).optional(),justification:Ne.string().optional(),prefix_rule:Ne.array(Ne.string().min(1)).optional()}).strict(),la=/^[A-Za-z0-9_./:@%+-]+$/;function ca(e){return e.length===0?"''":la.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function ua(e){return e.map(t=>ca(t)).join(" ")}var Ir=N({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:aa,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,timeout_ms:n})=>{try{let r=await st({cmd:ua(e),workdir:t,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return f(r)}catch(r){return f(`shell failed: ${r.message}`,!0)}}});import{z as $e}from"zod";var pa=$e.object({command:$e.string().min(1,"command cannot be empty"),workdir:$e.string().optional(),login:$e.boolean().optional(),timeout_ms:$e.number().int().positive().optional(),sandbox_permissions:$e.enum(["use_default","require_escalated"]).optional(),justification:$e.string().optional(),prefix_rule:$e.array($e.string().min(1)).optional()}).strict(),Rr=N({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:pa,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,login:n,timeout_ms:r})=>{try{let o=await st({cmd:e,workdir:t,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return f(o)}catch(o){return f(`shell_command failed: ${o.message}`,!0)}}});import{z as _e}from"zod";var da=_e.object({cmd:_e.string().min(1,"cmd cannot be empty"),workdir:_e.string().optional(),shell:_e.string().optional(),login:_e.boolean().optional(),tty:_e.boolean().optional(),yield_time_ms:_e.number().int().nonnegative().optional(),max_output_tokens:_e.number().int().positive().optional(),sandbox_permissions:_e.enum(["use_default","require_escalated"]).optional(),justification:_e.string().optional(),prefix_rule:_e.array(_e.string().min(1)).optional()}).strict(),wn=N({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:da,supportsParallelToolCalls:!0,isMutating:!0,execute:async e=>{try{let t=await st({...e,source_tool:"exec_command"});return f(t)}catch(t){return f(`exec_command failed: ${t.message}`,!0)}}});import{z as yt}from"zod";var ma=yt.object({session_id:yt.number().int().positive(),chars:yt.string().optional(),yield_time_ms:yt.number().int().nonnegative().optional(),max_output_tokens:yt.number().int().positive().optional()}).strict(),Mn=N({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:ma,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{try{let t=await Pr({...e,source_tool:"write_stdin"});return f(t)}catch(t){return f(`write_stdin failed: ${t.message}`,!0)}}});import{access as Wa,readFile as ja,realpath as za,writeFile as qa}from"fs/promises";import{z as de}from"zod";var Ua=Ti(Br(),1);import{normalize as Ia,resolve as Ra,dirname as hm,join as Oa,relative as La,isAbsolute as Na}from"path";import{homedir as $a}from"os";import{existsSync as _m,statSync as Sm,realpathSync as Da}from"fs";import{readFile as xm}from"fs/promises";function Ue(e){return Ia(Ra(e))}function jt(e){let t=Ue(e);try{return Ue(Da(t))}catch{return t}}function Ha(e,t){let n=La(t,e);return n===""||!n.startsWith("..")&&!Na(n)}function Fa(){let e=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>jt(t)):[]}function Wr(){let e=new Set;e.add(jt(process.cwd()));let t=process.env.MEMO_HOME?.trim()||Oa($a(),".memo");e.add(jt(t));for(let n of Fa())e.add(n);return Array.from(e)}function Ba(e){let t=jt(e);return Wr().some(r=>Ha(t,r))}function jr(e){if(Ba(e))return null;let t=Wr();return`sandbox write denied: ${e} is not within allowed directories (${t.join(", ")})`}var Ga=de.object({old_string:de.string().min(1,"old_string cannot be empty"),new_string:de.string(),replace_all:de.boolean().optional()}).strict(),Ka=de.object({file_path:de.string().min(1),old_string:de.string().optional(),new_string:de.string().optional(),replace_all:de.boolean().optional(),edits:de.array(Ga).min(1).optional()}).superRefine((e,t)=>{let n=!!(e.edits&&e.edits.length>0),r=e.old_string!==void 0||e.new_string!==void 0||e.replace_all!==void 0;if(n&&r){t.addIssue({code:de.ZodIssueCode.custom,message:"Use either edits or old_string/new_string fields, not both."});return}if(!n){if(typeof e.old_string!="string"||typeof e.new_string!="string"){t.addIssue({code:de.ZodIssueCode.custom,message:"Provide old_string/new_string, or use edits."});return}e.old_string.trim()||t.addIssue({code:de.ZodIssueCode.custom,message:"old_string cannot be empty",path:["old_string"]});return}for(let o=0;o<(e.edits?.length??0);o+=1){let s=e.edits?.[o];s&&(s.old_string.trim()||t.addIssue({code:de.ZodIssueCode.custom,message:"old_string cannot be empty",path:["edits",o,"old_string"]}))}}).strict();function Va(e){let t=jr(e);if(t)throw new Error(t)}function Xa(e){return e.edits&&e.edits.length>0?e.edits:[{old_string:e.old_string??"",new_string:e.new_string??"",replace_all:e.replace_all}]}var zr=N({name:"apply_patch",description:"Edit a local file by direct string replacement. Supports single replacement fields or batch edits.",inputSchema:Ka,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{let t=Ue(e.file_path);try{await Wa(t);let n=Ue(await za(t));Va(n);let r=await ja(n,"utf8"),o=Xa(e),s=r,i=0;for(let a=0;a<o.length;a+=1){let l=o[a];if(!l)continue;let c=l.old_string,u=l.replace_all??!1;if(!s.includes(c))return o.length===1?f("apply_patch failed: target text not found.",!0):f(`apply_patch failed: target text not found at edit ${a+1}.`,!0);if(u){let p=s.split(c),y=p.length-1;s=p.join(l.new_string),i+=y}else s=s.replace(c,l.new_string),i+=1}return s===r?f("No changes made."):(await qa(n,s,"utf8"),f(`Success. Updated file: ${n}
12
+ `),r=n.pop()??"";return{completedLines:n,remainder:r}}function $n(t){return t.length<=to?t:t.slice(-to)}var Ya=1e4,Za=250,Qa=2e3,Kt=64;function el(t){return Math.ceil(t.length/4)}function tl(){return Math.random().toString(16).slice(2)||String(Date.now())}function nl(t){let e=t.login,n=t.shell?.trim();if(process.platform==="win32"){let o=n||"powershell.exe";return o.toLowerCase().includes("powershell")?{file:o,args:["-NoProfile","-Command",t.cmd]}:{file:o,args:[e?"-lc":"-c",t.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[e?"-lc":"-c",t.cmd]}}function rl(t,e){let r=(typeof e=="number"&&e>0?Math.floor(e):Qa)*4,o=el(t);return t.length<=r?{output:t,originalTokenCount:o,deliveredChars:t.length}:{output:t.slice(0,r),originalTokenCount:o,deliveredChars:r}}function ol(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(`
13
+ `)}function so(t,e){return typeof t!="number"||Number.isNaN(t)?e:t<0?0:Math.floor(t)}async function io(t,e){e<=0||t.exited||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},e),o=()=>{clearTimeout(r),s(),n()},s=()=>{t.eventBus.off("exit",o)};t.eventBus.on("exit",o)})])}async function ao(t,e){t.exited||e<=0||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},e),o=()=>{clearTimeout(r),s(),n()},s=()=>{t.eventBus.off("exit",o)};t.eventBus.on("exit",o)})])}var Dn=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Kt)return;let e=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,r)=>n.startedAtMs-r.startedAtMs);for(let n of e){if(this.sessions.size<=Kt)break;this.sessions.delete(n.id)}}activeSessionCount(){let e=0;for(let n of this.sessions.values())n.exited||(e+=1);return e}async terminateForTimeout(e){e.exited||(e.proc.kill("SIGTERM"),await ao(e,200),e.exited||(e.proc.kill("SIGKILL"),await ao(e,200)))}async start(e){let n=e.cmd.trim();if(!n)throw new Error("cmd must not be empty");if(this.cleanupSessions(),this.activeSessionCount()>=Kt)throw new Error(`too many active sessions (max ${Kt})`);let r=Nn({toolName:e.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=nl({cmd:n,shell:e.shell,login:e.login!==!1}),a=e.workdir?.trim()?Ja(process.cwd(),e.workdir.trim()):process.cwd(),l=Va(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),c={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new Xa,proc:l},p=(h,f)=>{let T=typeof f=="string"?f:f.toString("utf8");c.output+=h?`${h}${T}`:T,c.eventBus.emit("output")};l.stdout?.on("data",h=>p("",h)),l.stderr?.on("data",h=>p("",h)),l.on("error",h=>{c.output+=`
14
+ [exec error] ${h.message}`,c.eventBus.emit("output")}),l.on("close",h=>{c.exited=!0,c.exitCode=typeof h=="number"?h:-1,c.eventBus.emit("exit")}),this.sessions.set(o,c),this.cleanupSessions();let u=typeof e.execution_timeout_ms=="number"&&e.execution_timeout_ms>0?Math.floor(e.execution_timeout_ms):null,g=so(e.yield_time_ms,Ya),_=u!==null?Math.min(g,Math.max(0,u)):g;if(await io(c,_),u!==null&&!c.exited&&Date.now()-s>=u)throw await this.terminateForTimeout(c),this.cleanupSessions(),new Error(`command timed out after ${u}ms`);return this.buildResponseText(c,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`);if(!n.exited&&e.chars&&e.chars.length>0){let o=$n(`${n.pendingStdinInput}${e.chars}`),{completedLines:s,remainder:i}=oo(o);for(let a of s){if(!a.trim())continue;let l=Nn({toolName:e.source_tool??"write_stdin",command:a,sessionId:n.id});if(l.blocked)return n.pendingStdinInput="",l.xml}n.pendingStdinInput=$n(i),n.proc.stdin?.write(e.chars)}let r=so(e.yield_time_ms,Za);return await io(n,r),this.buildResponseText(n,e.max_output_tokens)}buildResponseText(e,n){let r=e.output.slice(e.readOffset),o=rl(r,n);e.readOffset+=o.deliveredChars;let s={sessionId:e.id,chunkId:tl(),wallTimeSeconds:(Date.now()-e.startedAtMs)/1e3,exitCode:e.exited?e.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return ol(s)}},lo=new Dn;async function ct(t){return lo.start(t)}async function co(t){return lo.write(t)}var sl=Le.object({command:Le.array(Le.string().min(1)).min(1,"command cannot be empty"),workdir:Le.string().optional(),timeout_ms:Le.number().int().positive().optional(),sandbox_permissions:Le.enum(["use_default","require_escalated"]).optional(),justification:Le.string().optional(),prefix_rule:Le.array(Le.string().min(1)).optional()}).strict(),il=/^[A-Za-z0-9_./:@%+-]+$/;function al(t){return t.length===0?"''":il.test(t)?t:`'${t.replace(/'/g,`'"'"'`)}'`}function ll(t){return t.map(e=>al(e)).join(" ")}var uo=N({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:sl,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,timeout_ms:n})=>{try{let r=await ct({cmd:ll(t),workdir:e,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return d(r)}catch(r){return d(`shell failed: ${r.message}`,!0)}}});import{z as Ne}from"zod";var cl=Ne.object({command:Ne.string().min(1,"command cannot be empty"),workdir:Ne.string().optional(),login:Ne.boolean().optional(),timeout_ms:Ne.number().int().positive().optional(),sandbox_permissions:Ne.enum(["use_default","require_escalated"]).optional(),justification:Ne.string().optional(),prefix_rule:Ne.array(Ne.string().min(1)).optional()}).strict(),po=N({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:cl,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,login:n,timeout_ms:r})=>{try{let o=await ct({cmd:t,workdir:e,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return d(o)}catch(o){return d(`shell_command failed: ${o.message}`,!0)}}});import{z as ve}from"zod";var ul=ve.object({cmd:ve.string().min(1,"cmd cannot be empty"),workdir:ve.string().optional(),shell:ve.string().optional(),login:ve.boolean().optional(),tty:ve.boolean().optional(),yield_time_ms:ve.number().int().nonnegative().optional(),max_output_tokens:ve.number().int().positive().optional(),sandbox_permissions:ve.enum(["use_default","require_escalated"]).optional(),justification:ve.string().optional(),prefix_rule:ve.array(ve.string().min(1)).optional()}).strict(),Un=N({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:ul,supportsParallelToolCalls:!0,isMutating:!0,execute:async t=>{try{let e=await ct({...t,source_tool:"exec_command"});return d(e)}catch(e){return d(`exec_command failed: ${e.message}`,!0)}}});import{z as Mt}from"zod";var pl=Mt.object({session_id:Mt.number().int().positive(),chars:Mt.string().optional(),yield_time_ms:Mt.number().int().nonnegative().optional(),max_output_tokens:Mt.number().int().positive().optional()}).strict(),Fn=N({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:pl,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await co({...t,source_tool:"write_stdin"});return d(e)}catch(e){return d(`write_stdin failed: ${e.message}`,!0)}}});import{access as Hl,readFile as Bl,realpath as jl,writeFile as Wl}from"fs/promises";import{z as ce}from"zod";var $l=Xr(vo(),1);import{normalize as Pl,resolve as kl,dirname as Tg,join as Rl,relative as Il,isAbsolute as Ol}from"path";import{homedir as Ll}from"os";import{existsSync as xg,statSync as bg,realpathSync as Nl}from"fs";import{readFile as Mg}from"fs/promises";function De(t){return Pl(kl(t))}function Xt(t){let e=De(t);try{return De(Nl(e))}catch{return e}}function Dl(t,e){let n=Il(e,t);return n===""||!n.startsWith("..")&&!Ol(n)}function Ul(){let t=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>Xt(e)):[]}function Co(){let t=new Set;t.add(Xt(process.cwd()));let e=process.env.MEMO_HOME?.trim()||Rl(Ll(),".memo");t.add(Xt(e));for(let n of Ul())t.add(n);return Array.from(t)}function Fl(t){let e=Xt(t);return Co().some(r=>Dl(e,r))}function xo(t){if(Fl(t))return null;let e=Co();return`sandbox write denied: ${t} is not within allowed directories (${e.join(", ")})`}var Gl=ce.object({old_string:ce.string().min(1,"old_string cannot be empty"),new_string:ce.string(),replace_all:ce.boolean().optional()}).strict(),zl=ce.object({file_path:ce.string().min(1),old_string:ce.string().optional(),new_string:ce.string().optional(),replace_all:ce.boolean().optional(),edits:ce.array(Gl).min(1).optional()}).superRefine((t,e)=>{let n=!!(t.edits&&t.edits.length>0),r=t.old_string!==void 0||t.new_string!==void 0||t.replace_all!==void 0;if(n&&r){e.addIssue({code:ce.ZodIssueCode.custom,message:"Use either edits or old_string/new_string fields, not both."});return}if(!n){if(typeof t.old_string!="string"||typeof t.new_string!="string"){e.addIssue({code:ce.ZodIssueCode.custom,message:"Provide old_string/new_string, or use edits."});return}t.old_string.trim()||e.addIssue({code:ce.ZodIssueCode.custom,message:"old_string cannot be empty",path:["old_string"]});return}for(let o=0;o<(t.edits?.length??0);o+=1){let s=t.edits?.[o];s&&(s.old_string.trim()||e.addIssue({code:ce.ZodIssueCode.custom,message:"old_string cannot be empty",path:["edits",o,"old_string"]}))}}).strict();function ql(t){let e=xo(t);if(e)throw new Error(e)}function Kl(t){return t.edits&&t.edits.length>0?t.edits:[{old_string:t.old_string??"",new_string:t.new_string??"",replace_all:t.replace_all}]}var bo=N({name:"apply_patch",description:"Edit a local file by direct string replacement. Supports single replacement fields or batch edits.",inputSchema:zl,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{let e=De(t.file_path);try{await Hl(e);let n=De(await jl(e));ql(n);let r=await Bl(n,"utf8"),o=Kl(t),s=r,i=0;for(let a=0;a<o.length;a+=1){let l=o[a];if(!l)continue;let c=l.old_string,p=l.replace_all??!1;if(!s.includes(c))return o.length===1?d("apply_patch failed: target text not found.",!0):d(`apply_patch failed: target text not found at edit ${a+1}.`,!0);if(p){let u=s.split(c),g=u.length-1;s=u.join(l.new_string),i+=g}else s=s.replace(c,l.new_string),i+=1}return s===r?d("No changes made."):(await Wl(n,s,"utf8"),d(`Success. Updated file: ${n}
15
15
  Edits: ${o.length}
16
- Replacements: ${i}`))}catch(n){return n.code==="ENOENT"?f(`apply_patch failed: file does not exist: ${t}`,!0):f(`apply_patch failed: ${n.message}`,!0)}}});import{readFile as Ja}from"fs/promises";import{z as be}from"zod";var qr=500,Gr=200,Ya=be.object({file_path:be.string().min(1),offset:be.number().int().positive().optional(),limit:be.number().int().positive().optional(),mode:be.enum(["slice","indentation"]).optional(),indentation:be.object({anchor_line:be.number().int().positive().optional(),max_levels:be.number().int().nonnegative().optional(),include_siblings:be.boolean().optional(),include_header:be.boolean().optional(),max_lines:be.number().int().positive().optional()}).strict().optional()}).strict();function Za(e){return e.length<=qr?e:e.slice(0,qr)}function Qa(e){let t=0;for(let n of e)if(n===" ")t+=1;else if(n===" ")t+=4;else break;return t}function el(e){return e.split(/\r?\n/).map((n,r)=>({line:r+1,text:Za(n),indent:Qa(n)}))}function tl(e){return e.map(t=>`L${t.line}: ${t.text}`).join(`
17
- `)}function nl(e,t,n){let r=t-1;if(r>=e.length)throw new Error("offset exceeds file length");return e.slice(r,r+n)}function rl(e,t){let n=t.offset??1,r=t.limit??Gr,o=t.indentation,s=o?.anchor_line??n;if(s<=0||s>e.length)throw new Error("anchor_line exceeds file length");let i=e[s-1];if(!i)throw new Error("anchor_line exceeds file length");let a=o?.max_levels??0,l=o?.include_siblings??!0,c=o?.include_header??!0,u=o?.max_lines??r,p=Math.max(1,Math.min(r,u)),y=a===0?0:Math.max(0,i.indent-a*4),m=s-1,h=s-1;for(;m-1>=0;){let d=e[m-1];if(!d)break;let E=/^\s*(#|\/\/|--)/.test(d.text),v=d.text.trim().length===0;if(d.indent<y||!l&&d.indent===y&&!E&&!v||!c&&(E||v)&&d.indent<i.indent||(m-=1,h-m+1>=p))break}for(;h+1<e.length&&h-m+1<p;){let d=e[h+1];if(!d||d.indent<y||!l&&d.indent===y)break;h+=1}return e.slice(m,h+1)}var Kr=N({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Ya,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??1,n=e.limit??Gr;if(t<=0)return f("offset must be a 1-indexed line number",!0);if(n<=0)return f("limit must be greater than zero",!0);let r=e.file_path.trim();if(!r.startsWith("/"))return f("file_path must be an absolute path",!0);let o=Ue(r);try{let s=await Ja(o,"utf8"),i=el(s);if(i.length===0)return f("");let l=(e.mode??"slice")==="indentation"?rl(i,e):nl(i,t,n);return f(tl(l))}catch(s){return f(`read_file failed: ${s.message}`,!0)}}});import{readdir as ol,lstat as sl}from"fs/promises";import{join as il}from"path";import{z as Tt}from"zod";var al=1,ll=25,cl=2,ul=Tt.object({dir_path:Tt.string().min(1),offset:Tt.number().int().positive().optional(),limit:Tt.number().int().positive().optional(),depth:Tt.number().int().positive().optional()}).strict();function pl(e){let t=" ".repeat(e.displayDepth*2),n="";e.kind==="dir"&&(n="/"),e.kind==="symlink"&&(n="@"),e.kind==="other"&&(n="?");let r=e.path.split("/"),o=r[r.length-1]??e.path;return`${t}${o}${n}`}var Vr=N({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:ul,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??al,n=e.limit??ll,r=e.depth??cl;if(t<=0)return f("offset must be a 1-indexed entry number",!0);if(n<=0)return f("limit must be greater than zero",!0);if(r<=0)return f("depth must be greater than zero",!0);let o=e.dir_path.trim();if(!o.startsWith("/"))return f("dir_path must be an absolute path",!0);let s=Ue(o);try{let i=[{absPath:s,depth:r,displayDepth:0}],a=[];for(;i.length>0;){let p=i.shift();if(!p)continue;let y=await ol(p.absPath);y.sort((m,h)=>m.localeCompare(h));for(let m of y){let h=il(p.absPath,m),d=await sl(h),E=d.isSymbolicLink()?"symlink":d.isDirectory()?"dir":d.isFile()?"file":"other";a.push({path:h,displayDepth:p.displayDepth,kind:E}),E==="dir"&&p.depth>1&&i.push({absPath:h,depth:p.depth-1,displayDepth:p.displayDepth+1})}}if(a.length===0)return f(`Absolute path: ${s}`);let l=t-1;if(l>=a.length)return f("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),u=[`Absolute path: ${s}`,...c.map(pl)];return l+n<a.length&&u.push(`More than ${n} entries found`),f(u.join(`
18
- `))}catch(i){return f(`list_dir failed: ${i.message}`,!0)}}});import{spawn as dl}from"child_process";import{resolve as ml}from"path";import{z as _t}from"zod";var fl=100,gl=2e3,hl=3e4,yl=_t.object({pattern:_t.string().min(1),include:_t.string().optional(),path:_t.string().optional(),limit:_t.number().int().positive().optional()}).strict();function Tl(e){return new Promise((t,n)=>{let r=["--files-with-matches","--sortr=modified","--regexp",e.pattern,"--no-messages"];e.include?.trim()&&r.push("--glob",e.include.trim()),r.push("--",e.searchPath);let o=dl("rg",r,{cwd:e.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",l=>s.push(l)),o.stderr?.on("data",l=>i.push(l));let a=setTimeout(()=>{o.kill("SIGTERM"),n(new Error("rg timed out after 30 seconds"))},hl);o.on("error",l=>{clearTimeout(a),n(l)}),o.on("close",l=>{clearTimeout(a),t({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var Xr=N({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:yl,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.pattern.trim();if(!t)return f("pattern must not be empty",!0);let n=Math.min(e.limit??fl,gl),r=e.path?.trim()?ml(process.cwd(),e.path.trim()):process.cwd();try{let o=await Tl({pattern:t,include:e.include,searchPath:r,cwd:process.cwd(),limit:n});if(o.exitCode===1)return f("No matches found.");if(o.exitCode!==0)return f(`rg failed: ${o.stderr||o.stdout}`,!0);let s=o.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,n);return s.length===0?f("No matches found."):f(s.join(`
19
- `))}catch(o){return f(`grep_files failed: ${o.message}`,!0)}}});import{z as He}from"zod";var Jr=null;function Nn(e){Jr=e}function Yr(){return Jr}var _l=He.object({server:He.string().optional(),cursor:He.string().optional()}).strict(),Sl=He.object({server:He.string().optional(),cursor:He.string().optional()}).strict(),vl=He.object({server:He.string().min(1),uri:He.string().min(1)}).strict();function $n(){let e=Yr();if(!e)throw new Error("MCP pool is not initialized");return e}var Zr=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:_l,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=$n();if(e?.trim()){let s=n.get(e.trim());if(!s)return f(`MCP server not found: ${e}`,!0);let i=await s.client.listResources(t?{cursor:t}:void 0);return f(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(t)return f("cursor is only supported when server is specified",!0);let r=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),o=[];for(let s of r){let i=await s.client.listResources();for(let a of i.resources)o.push({server:s.name,...a})}return f(JSON.stringify({resources:o},null,2))}catch(n){return f(`list_mcp_resources failed: ${n.message}`,!0)}}}),Qr=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:Sl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=$n();if(e?.trim()){let s=n.get(e.trim());if(!s)return f(`MCP server not found: ${e}`,!0);let i=await s.client.listResourceTemplates(t?{cursor:t}:void 0);return f(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(t)return f("cursor is only supported when server is specified",!0);let r=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),o=[];for(let s of r){let i=await s.client.listResourceTemplates();for(let a of i.resourceTemplates)o.push({server:s.name,...a})}return f(JSON.stringify({resourceTemplates:o},null,2))}catch(n){return f(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),eo=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:vl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,uri:t})=>{try{let r=$n().get(e);if(!r)return f(`MCP server not found: ${e}`,!0);let o=await r.client.readResource({uri:t});return f(JSON.stringify({server:e,uri:t,...o},null,2))}catch(n){return f(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as it}from"zod";var xl=it.object({step:it.string().min(1),status:it.enum(["pending","in_progress","completed"])}).strict(),Cl=it.object({explanation:it.string().optional(),plan:it.array(xl).min(1)}).strict(),to=[],no=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:Cl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:e,plan:t})=>{if(t.filter(r=>r.status==="in_progress").length>1)return f("At most one step can be in_progress at a time",!0);if(t.length<4){let r=t[0]?.step??"";return f(`<system_hint tool="update_plan" reason="simple_task">Task "${r}" is simple (${t.length} step${t.length>1?"s":""}) - execute directly without update_plan.</system_hint>`)}return to=t,f(JSON.stringify({message:"Plan updated",explanation:e,plan:to},null,2))}});import{readFile as bl}from"fs/promises";import{homedir as El}from"os";import{join as ro}from"path";import{z as oo}from"zod";var Al=oo.object({memory_id:oo.string().min(1)}).strict();function wl(){let e=process.env.MEMO_HOME?.trim()||ro(El(),".memo");return ro(e,"Agents.md")}var so=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:Al,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:e})=>{try{let t=wl(),n=await bl(t,"utf8");return f(JSON.stringify({memory_id:e,memory_summary:n},null,2))}catch{return f(`memory not found for memory_id=${e}`,!0)}}});import{z as io}from"zod";var Ml=io.object({url:io.string().min(1)}).strict(),ao=1e4,St=512e3,Dn=4e3,kl=new Set(["http:","https:"]),Pl=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Il=/<\s*(br|hr)\s*\/?>/gi,Rl=/<\s*li[^>]*>/gi,Ol=/<[^>]+>/g,Ll=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Nl=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,(r,o)=>{try{let s=o.startsWith("x")||o.startsWith("X")?parseInt(o.slice(1),16):parseInt(o,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),$l=e=>{let r=e.replace(Ll," ").replace(Rl,"- ").replace(Il,`
20
- `).replace(Pl,`
21
- `).replace(Ol," "),s=Nl(r).replace(/\r/g,"").split(`
16
+ Replacements: ${i}`))}catch(n){return n.code==="ENOENT"?d(`apply_patch failed: file does not exist: ${e}`,!0):d(`apply_patch failed: ${n.message}`,!0)}}});import{readFile as Vl}from"fs/promises";import{z as Ae}from"zod";var Eo=500,Mo=200,Xl=Ae.object({file_path:Ae.string().min(1),offset:Ae.number().int().positive().optional(),limit:Ae.number().int().positive().optional(),mode:Ae.enum(["slice","indentation"]).optional(),indentation:Ae.object({anchor_line:Ae.number().int().positive().optional(),max_levels:Ae.number().int().nonnegative().optional(),include_siblings:Ae.boolean().optional(),include_header:Ae.boolean().optional(),max_lines:Ae.number().int().positive().optional()}).strict().optional()}).strict();function Jl(t){return t.length<=Eo?t:t.slice(0,Eo)}function Yl(t){let e=0;for(let n of t)if(n===" ")e+=1;else if(n===" ")e+=4;else break;return e}function Zl(t){return t.split(/\r?\n/).map((n,r)=>({line:r+1,text:Jl(n),indent:Yl(n)}))}function Ql(t){return t.map(e=>`L${e.line}: ${e.text}`).join(`
17
+ `)}function ec(t,e,n){let r=e-1;if(r>=t.length)throw new Error("offset exceeds file length");return t.slice(r,r+n)}function tc(t,e){let n=e.offset??1,r=e.limit??Mo,o=e.indentation,s=o?.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=o?.max_levels??0,l=o?.include_siblings??!0,c=o?.include_header??!0,p=o?.max_lines??r,u=Math.max(1,Math.min(r,p)),g=a===0?0:Math.max(0,i.indent-a*4),_=s-1,h=s-1;for(;_-1>=0;){let f=t[_-1];if(!f)break;let T=/^\s*(#|\/\/|--)/.test(f.text),x=f.text.trim().length===0;if(f.indent<g||!l&&f.indent===g&&!T&&!x||!c&&(T||x)&&f.indent<i.indent||(_-=1,h-_+1>=u))break}for(;h+1<t.length&&h-_+1<u;){let f=t[h+1];if(!f||f.indent<g||!l&&f.indent===g)break;h+=1}return t.slice(_,h+1)}var wo=N({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Xl,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??1,n=t.limit??Mo;if(e<=0)return d("offset must be a 1-indexed line number",!0);if(n<=0)return d("limit must be greater than zero",!0);let r=t.file_path.trim();if(!r.startsWith("/"))return d("file_path must be an absolute path",!0);let o=De(r);try{let s=await Vl(o,"utf8"),i=Zl(s);if(i.length===0)return d("");let l=(t.mode??"slice")==="indentation"?tc(i,t):ec(i,e,n);return d(Ql(l))}catch(s){return d(`read_file failed: ${s.message}`,!0)}}});import{readdir as nc,lstat as rc}from"fs/promises";import{join as oc}from"path";import{z as wt}from"zod";var sc=1,ic=25,ac=2,lc=wt.object({dir_path:wt.string().min(1),offset:wt.number().int().positive().optional(),limit:wt.number().int().positive().optional(),depth:wt.number().int().positive().optional()}).strict();function cc(t){let e=" ".repeat(t.displayDepth*2),n="";t.kind==="dir"&&(n="/"),t.kind==="symlink"&&(n="@"),t.kind==="other"&&(n="?");let r=t.path.split("/"),o=r[r.length-1]??t.path;return`${e}${o}${n}`}var Ao=N({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:lc,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??sc,n=t.limit??ic,r=t.depth??ac;if(e<=0)return d("offset must be a 1-indexed entry number",!0);if(n<=0)return d("limit must be greater than zero",!0);if(r<=0)return d("depth must be greater than zero",!0);let o=t.dir_path.trim();if(!o.startsWith("/"))return d("dir_path must be an absolute path",!0);let s=De(o);try{let i=[{absPath:s,depth:r,displayDepth:0}],a=[];for(;i.length>0;){let u=i.shift();if(!u)continue;let g=await nc(u.absPath);g.sort((_,h)=>_.localeCompare(h));for(let _ of g){let h=oc(u.absPath,_),f=await rc(h),T=f.isSymbolicLink()?"symlink":f.isDirectory()?"dir":f.isFile()?"file":"other";a.push({path:h,displayDepth:u.displayDepth,kind:T}),T==="dir"&&u.depth>1&&i.push({absPath:h,depth:u.depth-1,displayDepth:u.displayDepth+1})}}if(a.length===0)return d(`Absolute path: ${s}`);let l=e-1;if(l>=a.length)return d("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),p=[`Absolute path: ${s}`,...c.map(cc)];return l+n<a.length&&p.push(`More than ${n} entries found`),d(p.join(`
18
+ `))}catch(i){return d(`list_dir failed: ${i.message}`,!0)}}});import{spawn as uc}from"child_process";import{resolve as pc}from"path";import{z as At}from"zod";var dc=100,mc=2e3,fc=3e4,gc=At.object({pattern:At.string().min(1),include:At.string().optional(),path:At.string().optional(),limit:At.number().int().positive().optional()}).strict();function hc(t){return new Promise((e,n)=>{let r=["--files-with-matches","--sortr=modified","--regexp",t.pattern,"--no-messages"];t.include?.trim()&&r.push("--glob",t.include.trim()),r.push("--",t.searchPath);let o=uc("rg",r,{cwd:t.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",l=>s.push(l)),o.stderr?.on("data",l=>i.push(l));let a=setTimeout(()=>{o.kill("SIGTERM"),n(new Error("rg timed out after 30 seconds"))},fc);o.on("error",l=>{clearTimeout(a),n(l)}),o.on("close",l=>{clearTimeout(a),e({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var Po=N({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:gc,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.pattern.trim();if(!e)return d("pattern must not be empty",!0);let n=Math.min(t.limit??dc,mc),r=t.path?.trim()?pc(process.cwd(),t.path.trim()):process.cwd();try{let o=await hc({pattern:e,include:t.include,searchPath:r,cwd:process.cwd(),limit:n});if(o.exitCode===1)return d("No matches found.");if(o.exitCode!==0)return d(`rg failed: ${o.stderr||o.stdout}`,!0);let s=o.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,n);return s.length===0?d("No matches found."):d(s.join(`
19
+ `))}catch(o){return d(`grep_files failed: ${o.message}`,!0)}}});import{z as Ue}from"zod";import{createHash as yc}from"crypto";import{mkdir as _c,readFile as Sc,rename as Tc,writeFile as vc}from"fs/promises";import{homedir as Vn}from"os";import{dirname as Cc,join as Yn}from"path";var xc="mcp.json",Yt=2,bc=120,Ec=600*1e3,ko=1440*60*1e3;function qn(){return process.env.MEMO_FORCE_MCP_DISK_CACHE==="1"?!0:!(process.env.MEMO_FORCE_MCP_DISK_CACHE==="0"||process.env.NODE_ENV==="test"||typeof process.env.VITEST<"u"||typeof process.env.VITEST_WORKER_ID<"u")}function Mc(t){return t==="~"?Vn():t.startsWith("~/")?Yn(Vn(),t.slice(2)):t}function wc(){let t=process.env.MEMO_HOME?.trim();return t?Mc(t):Yn(Vn(),".memo")}function Ro(){return Yn(wc(),"cache",xc)}function Xn(t){if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>Xn(r)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Xn(e[r])}`).join(",")}}`}function Io(t){return yc("sha256").update(Xn(t)).digest("hex")}function Ac(t){return t instanceof Error?t.message:String(t)}function Jt(){return{version:Yt,toolsByServer:{},responses:{}}}var Jn=class{data=Jt();loaded=!1;loadPromise=null;persistTimer=null;persistRunning=!1;persistRequested=!1;responseInflight=new Map;pruneExpiredResponses(e=Date.now()){for(let[n,r]of Object.entries(this.data.responses))r.expiresAt<=e&&delete this.data.responses[n]}pruneExpiredTools(e=Date.now()){for(let[n,r]of Object.entries(this.data.toolsByServer))e-r.fetchedAt>ko&&delete this.data.toolsByServer[n]}async ensureLoaded(){if(!qn()){this.loaded=!0;return}if(!this.loaded){if(this.loadPromise){await this.loadPromise;return}this.loadPromise=(async()=>{let e=Ro();try{let n=await Sc(e,"utf8"),r=JSON.parse(n);if(r.version===Yt){let o=r;this.data={version:Yt,toolsByServer:o.toolsByServer??{},responses:o.responses??{}}}else r.version===1&&r.entries?this.data={version:Yt,toolsByServer:{},responses:r.entries}:this.data=Jt()}catch{this.data=Jt()}finally{this.pruneExpiredResponses(),this.pruneExpiredTools(),this.loaded=!0}})(),await this.loadPromise}}async persistToDisk(){if(!qn())return;this.pruneExpiredResponses(),this.pruneExpiredTools();let e=Ro(),n=`${e}.tmp`,r=Cc(e);await _c(r,{recursive:!0}),await vc(n,JSON.stringify(this.data,null,2),"utf8"),await Tc(n,e)}async flushPersistQueue(){if(!(!this.persistRequested||this.persistRunning)){this.persistRequested=!1,this.persistRunning=!0;try{await this.persistToDisk()}catch{}finally{this.persistRunning=!1,this.persistRequested&&this.flushPersistQueue()}}}schedulePersist(){qn()&&(this.persistRequested=!0,!this.persistTimer&&(this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersistQueue()},bc),this.persistTimer.unref?.()))}async getServerTools(e,n){await this.ensureLoaded();let r=this.data.toolsByServer[e];if(!r)return null;if(r.configHash!==Io(n))return delete this.data.toolsByServer[e],this.schedulePersist(),null;let o=Date.now()-r.fetchedAt;return o>ko?(delete this.data.toolsByServer[e],this.schedulePersist(),null):{tools:r.tools,stale:o>Ec,ageMs:o}}async setServerTools(e,n,r){await this.ensureLoaded(),this.data.toolsByServer[e]={fetchedAt:Date.now(),configHash:Io(n),tools:r},this.schedulePersist()}async withResponseCache(e,n,r){await this.ensureLoaded();let o=this.data.responses[e];if(o&&o.expiresAt>Date.now())return o.value;o&&o.expiresAt<=Date.now()&&delete this.data.responses[e];let s=this.responseInflight.get(e);if(s)return await s;let i=(async()=>{let a=await r();return this.data.responses[e]={expiresAt:Date.now()+n,value:a},this.schedulePersist(),a})();this.responseInflight.set(e,i);try{return await i}catch(a){throw new Error(Ac(a))}finally{this.responseInflight.delete(e)}}async flushForTests(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.persistRequested=!0,await this.flushPersistQueue()}resetForTests(){this.data=Jt(),this.loaded=!1,this.loadPromise=null,this.responseInflight.clear(),this.persistRequested=!1,this.persistRunning=!1,this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null)}},Kn=null;function Zt(){return Kn||(Kn=new Jn),Kn}var Oo=null,Lo=null;function Zn(t){Oo=t}function No(){return Oo}function Qn(t){Lo=t}function $o(){return Lo}var Pc=Ue.object({server:Ue.string().optional(),cursor:Ue.string().optional()}).strict(),kc=Ue.object({server:Ue.string().optional(),cursor:Ue.string().optional()}).strict(),Rc=Ue.object({server:Ue.string().min(1),uri:Ue.string().min(1)}).strict(),Qt=15e3,Ic=6e4;function er(){let t=No();if(!t)throw new Error("MCP pool is not initialized");return t}function tr(){return $o()??Zt()}function Fo(t){return t instanceof Error?t.message:String(t)}function Do(t,e){return`list_resources:${t}:${e??""}`}function Uo(t,e){return`list_resource_templates:${t}:${e??""}`}function Oc(t,e){return`read_resource:${t}:${e}`}function nr(t,e){return typeof t.hasServer=="function"?t.hasServer(e):typeof t.get=="function"?!!t.get(e):!1}async function rr(t,e){if(typeof t.get=="function"){let n=t.get(e);if(n)return n}if(typeof t.connect=="function")return t.connect(e)}async function Ho(t){if(typeof t.getKnownServerNames=="function"&&typeof t.connect=="function"){let n=t.getKnownServerNames().sort((s,i)=>s.localeCompare(i)),r=await Promise.allSettled(n.map(s=>t.connect(s))),o=[];return r.forEach((s,i)=>{if(s.status==="fulfilled"){o.push(s.value);return}let a=n[i];a&&o.push({name:a,client:null,__error:s.reason})}),o.sort((s,i)=>s.name.localeCompare(i.name))}return(typeof t.getAll=="function"?t.getAll():[]).sort((n,r)=>n.name.localeCompare(r.name))}var Bo=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:Pc,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=er(),r=tr(),o=t?.trim();if(o){if(!nr(n,o))return d(`MCP server not found: ${t}`,!0);let l=await rr(n,o);if(!l)return d(`MCP server not found: ${t}`,!0);let c=await r.withResponseCache(Do(l.name,e),Qt,async()=>{let p=await l.client.listResources(e?{cursor:e}:void 0);return{server:l.name,resources:p.resources,nextCursor:p.nextCursor}});return d(JSON.stringify(c,null,2))}if(e)return d("cursor is only supported when server is specified",!0);let s=await Ho(n),i=`all:${s.map(l=>l.name).join(",")}`,a=await r.withResponseCache(Do(i),Qt,async()=>{let l=await Promise.allSettled(s.map(async u=>{if(!u.client)throw new Error(`MCP server '${u.name}' is not connected`);return{server:u.name,result:await u.client.listResources()}})),c=[],p=[];return l.forEach((u,g)=>{let _=s[g]?.name??"unknown";if(u.status==="rejected"){p.push({server:_,error:Fo(u.reason)});return}for(let h of u.value.result.resources)c.push({server:u.value.server,...h})}),{resources:c,...p.length>0?{errors:p}:{}}});return d(JSON.stringify(a,null,2))}catch(n){return d(`list_mcp_resources failed: ${n.message}`,!0)}}}),jo=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:kc,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=er(),r=tr(),o=t?.trim();if(o){if(!nr(n,o))return d(`MCP server not found: ${t}`,!0);let l=await rr(n,o);if(!l)return d(`MCP server not found: ${t}`,!0);let c=await r.withResponseCache(Uo(l.name,e),Qt,async()=>{let p=await l.client.listResourceTemplates(e?{cursor:e}:void 0);return{server:l.name,resourceTemplates:p.resourceTemplates,nextCursor:p.nextCursor}});return d(JSON.stringify(c,null,2))}if(e)return d("cursor is only supported when server is specified",!0);let s=await Ho(n),i=`all:${s.map(l=>l.name).join(",")}`,a=await r.withResponseCache(Uo(i),Qt,async()=>{let l=await Promise.allSettled(s.map(async u=>{if(!u.client)throw new Error(`MCP server '${u.name}' is not connected`);return{server:u.name,result:await u.client.listResourceTemplates()}})),c=[],p=[];return l.forEach((u,g)=>{let _=s[g]?.name??"unknown";if(u.status==="rejected"){p.push({server:_,error:Fo(u.reason)});return}for(let h of u.value.result.resourceTemplates)c.push({server:u.value.server,...h})}),{resourceTemplates:c,...p.length>0?{errors:p}:{}}});return d(JSON.stringify(a,null,2))}catch(n){return d(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Wo=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:Rc,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let n=er(),r=tr(),o=t.trim();if(!nr(n,o))return d(`MCP server not found: ${t}`,!0);let s=await rr(n,o);if(!s)return d(`MCP server not found: ${t}`,!0);let i=await r.withResponseCache(Oc(o,e),Ic,async()=>{let a=await s.client.readResource({uri:e});return{server:o,uri:e,...a}});return d(JSON.stringify(i,null,2))}catch(n){return d(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as ut}from"zod";var Lc=ut.object({step:ut.string().min(1),status:ut.enum(["pending","in_progress","completed"])}).strict(),Nc=ut.object({explanation:ut.string().optional(),plan:ut.array(Lc).min(1)}).strict(),Go=[],zo=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:Nc,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>{if(e.filter(r=>r.status==="in_progress").length>1)return d("At most one step can be in_progress at a time",!0);if(e.length<4){let r=e[0]?.step??"";return d(`<system_hint tool="update_plan" reason="simple_task">Task "${r}" is simple (${e.length} step${e.length>1?"s":""}) - execute directly without update_plan.</system_hint>`)}return Go=e,d(JSON.stringify({message:"Plan updated",explanation:t,plan:Go},null,2))}});import{readFile as $c}from"fs/promises";import{homedir as Dc}from"os";import{join as qo}from"path";import{z as Ko}from"zod";var Uc=Ko.object({memory_id:Ko.string().min(1)}).strict();function Fc(){let t=process.env.MEMO_HOME?.trim()||qo(Dc(),".memo");return qo(t,"Agents.md")}var Vo=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:Uc,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=Fc(),n=await $c(e,"utf8");return d(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return d(`memory not found for memory_id=${t}`,!0)}}});import{z as Xo}from"zod";var Hc=Xo.object({url:Xo.string().min(1)}).strict(),Jo=1e4,Pt=512e3,or=4e3,Bc=new Set(["http:","https:"]),jc=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Wc=/<\s*(br|hr)\s*\/?>/gi,Gc=/<\s*li[^>]*>/gi,zc=/<[^>]+>/g,qc=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Kc=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,(r,o)=>{try{let s=o.startsWith("x")||o.startsWith("X")?parseInt(o.slice(1),16):parseInt(o,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),Vc=t=>{let r=t.replace(qc," ").replace(Gc,"- ").replace(Wc,`
20
+ `).replace(jc,`
21
+ `).replace(zc," "),s=Kc(r).replace(/\r/g,"").split(`
22
22
  `).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(`
23
- `).trim()},Dl=e=>e.replace(/\s+/g," ").trim(),lo=N({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:Ml,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t;try{t=new URL(e.url)}catch{return f(`Invalid URL: ${e.url}`,!0)}if(!kl.has(t.protocol))return f(`Unsupported protocol: ${t.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),ao);try{let o=await globalThis.fetch(t,{signal:n.signal}),s=o.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>St)return f(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(o.body&&o.body.getReader){let E=o.body.getReader(),v=[];for(;;){let{done:ee,value:q}=await E.read();if(ee)break;if(q){if(a+=q.byteLength,a>St)return n.abort(),f(`Request aborted: response body exceeds ${St} bytes`,!0);v.push(q)}}let S=new Uint8Array(a),W=0;for(let ee of v)S.set(ee,W),W+=ee.byteLength;l=new TextDecoder().decode(S)}else if(l=await o.text(),a=new TextEncoder().encode(l).byteLength,a>St)return f(`Request rejected: response body exceeds ${St} bytes`,!0);let c=o.headers.get("content-type")||"",u=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),p=u?$l(l):l.trim(),y=Dl(p),m=y.length>Dn?`${y.slice(0,Dn)}...`:y,h=y.length>Dn?" text_truncated=true":"",d=u?" source=html_stripped":"";return f(`status=${o.status} bytes=${a} text_chars=${y.length} text="${m}"${h}${d}`)}catch(o){return o.name==="AbortError"?f(`Request timeout or aborted (${ao}ms)`,!0):f(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as Ul}from"child_process";import{existsSync as Hl}from"fs";import{resolve as Fl}from"path";import{z as le}from"zod";var Bl=3e4,Wl=1e4,jl=3e5,co=4,zl=1500,uo=2e3,ze=new Map,ql=le.object({message:le.string().min(1),agent_type:le.string().optional()}).strict(),Gl=le.object({id:le.string().min(1),message:le.string().min(1),interrupt:le.boolean().optional()}).strict(),Kl=le.object({id:le.string().min(1)}).strict(),Vl=le.object({ids:le.array(le.string().min(1)).min(1),timeout_ms:le.number().int().positive().optional()}).strict(),Xl=le.object({id:le.string().min(1)}).strict();function at(){return new Date().toISOString()}function Un(e){return f(`agent not found: ${e}`,!0)}function Jl(){let e=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!e)return co;let t=Number(e);return!Number.isFinite(t)||t<=0?co:Math.floor(t)}function Yl(){let e=0;for(let t of ze.values())t.running&&(e+=1);return e}function Zl(){let e=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(e)return e;let t=Fl(process.cwd(),"dist/index.js");return Hl(t)?`node ${JSON.stringify(t)} --dangerous`:"memo --dangerous"}function Ql(e){return e!=="running"}function ec(e){return new Promise(t=>{setTimeout(t,e)})}function tc(e){return e===void 0?Bl:e<=0?null:Math.max(Wl,Math.min(jl,e))}function nc(e){return e.length<=uo?e:`${e.slice(0,uo)}
24
- ...[truncated]`}function rc(e,t){let n=[],r=e.trim(),o=t.trim();return r&&n.push(r),o&&n.push(`stderr:
25
- ${o}`),nc(n.join(`
26
-
27
- `))}async function po(e){let t=e.running;if(!t)return;t.interrupted=!0;let n=t.process;n.exitCode!==null||n.killed||await new Promise(r=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(i),n.off("close",s),r())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},zl);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function oc(e){let t=ze.get(e);return t?t.status:"not_found"}function sc(e){let t=ze.get(e);return t?{status:t.status,last_message:t.lastMessage,last_output:t.lastOutput,last_error:t.lastError,last_submission_id:t.lastSubmissionId,updated_at:t.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function ic(e){return{agent_id:e.id,status:e.status,created_at:e.createdAt,updated_at:e.updatedAt,last_message:e.lastMessage,last_submission_id:e.lastSubmissionId,has_last_output:!!e.lastOutput,has_last_error:!!e.lastError}}function ac(e){let{record:t,submissionId:n,stdout:r,stderr:o,exitCode:s,interrupted:i}=e;if(!(!t.running||t.running.id!==n)&&(t.running=null,t.updatedAt=at(),t.lastOutput=rc(r,o)||null,t.lastError=null,t.status!=="closed")){if(i){t.status="errored",t.lastError="interrupted",t.statusBeforeClose="errored";return}if(s===0){t.status="completed",t.statusBeforeClose="completed";return}t.status="errored",t.lastError=`submission failed with exit code ${s}`,t.statusBeforeClose="errored"}}async function mo(e,t){let n=Jl();if(Yl()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=Zl(),s=Ul(o,{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}`)}),e.running={id:r,message:t,process:s,startedAt:at(),interrupted:!1},e.status="running",e.lastMessage=t,e.lastSubmissionId=r,e.updatedAt=at(),s.on("close",l=>{let c=typeof l=="number"?l:-1,u=!!(e.running?.id===r&&e.running.interrupted);ac({record:e,submissionId:r,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:u})});try{s.stdin?.write(`${t.trim()}
28
- `)}catch{}try{s.stdin?.end()}catch{}return r}var fo=N({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:ql,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:e})=>{let t=e.trim();if(!t)return f("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=at(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:t,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};ze.set(n,o);try{let s=await mo(o,t);return f(JSON.stringify({...ic(o),submission_id:s},null,2))}catch(s){return ze.delete(n),f(`spawn_agent failed: ${s.message}`,!0)}}}),go=N({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Gl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e,message:t,interrupt:n})=>{let r=ze.get(e);if(!r)return Un(e);let o=t.trim();if(!o)return f("send_input failed: message must not be empty",!0);if(r.status==="closed")return f(`send_input failed: agent ${e} is closed; run resume_agent first`,!0);if(r.running){if(!n)return f(`send_input failed: agent ${e} is busy; set interrupt=true to cancel current submission`,!0);await po(r)}try{let s=await mo(r,o);return f(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return f(`send_input failed: ${s.message}`,!0)}}}),ho=N({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Kl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=ze.get(e);return t?(t.status==="closed"&&(t.status=t.statusBeforeClose,t.updatedAt=at()),f(JSON.stringify({agent_id:e,status:t.status},null,2))):Un(e)}}),yo=N({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Vl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:e,timeout_ms:t})=>{let n=tc(t);if(n===null)return f("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},a={};for(let l of e){let c=oc(l);Ql(c)&&(i[l]=c,a[l]=sc(l))}return{status:i,details:a}},o=r();if(Object.keys(o.status).length>0)return f(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await ec(100),o=r(),Object.keys(o.status).length>0)return f(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return f(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),To=N({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Xl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=ze.get(e);return t?t.status==="closed"?f(JSON.stringify({agent_id:e,status:"closed"},null,2)):(t.statusBeforeClose=t.running?"completed":t.status,t.status="closed",t.updatedAt=at(),await po(t),f(JSON.stringify({agent_id:e,status:"closed"},null,2))):Un(e)}});var Hn={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"},_o=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),zt={read:0,write:1,execute:2},So=["exec","run","shell","command","stdin"],vo=["write","patch","create","delete","modify","update"],xo=["read","get","fetch","search","list","find"],Co=new Set(["write","execute"]);function Bn(e){let t={...Hn,...e?.customLevels};return{getRiskLevel(n){if(n in t)return t[n];let r=n.toLowerCase();return Fn(r,So)?"execute":Fn(r,vo)?"write":Fn(r,xo)?"read":"write"},compareRisk(n,r){return zt[n]-zt[r]},needsApproval(n,r){return r==="strict"?!0:Co.has(n)}}}function Fn(e,t){return t.some(n=>e.includes(n))}import{createHash as lc}from"crypto";function qt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>qt(n)).join(",")+"]":`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${qt(r)}`).join(",")}}`}function Wn(e,t){let n=qt(t),r=`${e}:${n}`;return lc("sha256").update(r).digest("hex").slice(0,16)}function cc(e){return`Tool "${e}" requires approval.`}function jn(e){let{mode:t="auto",dangerous:n=!1,toolRiskLevels:r}=e||{},o=t==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=Bn({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(_o.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,o))return{needApproval:!1,decision:"auto-execute"};let u=Wn(a,l);return i.toolByFingerprint.set(u,a),i.sessionTools.has(a)||i.onceTools.has(a)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(a)?{needApproval:!0,fingerprint:u,riskLevel:c,reason:"This request was previously denied.",toolName:a,params:l}:{needApproval:!0,fingerprint:u,riskLevel:c,reason:cc(a),toolName:a,params:l}},recordDecision(a,l){let c=i.toolByFingerprint.get(a);if(c)switch(i.sessionTools.delete(c),i.onceTools.delete(c),i.deniedTools.delete(c),l){case"session":i.sessionTools.add(c);break;case"once":i.onceTools.add(c);break;case"deny":i.deniedTools.add(c);break}},isGranted(a){let l=i.toolByFingerprint.get(a);return l?i.sessionTools.has(l)||i.onceTools.has(l):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var bo=12e3,Eo=1e5;function uc(){let e=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!e)return bo;let t=Number(e);return!Number.isFinite(t)||t<=0?bo:Math.floor(t)}function pc(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function dc(e){let t=0;for(let n of e.content??[]){if(n.type==="text"){t+=n.text.length;continue}try{t+=JSON.stringify(n).length}catch{t+=100}}return t}function mc(e,t,n){return`<system_hint type="tool_output_omitted" tool="${pc(e)}" reason="too_long" actual_chars="${t}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function fc(e,t){let n=uc(),r=dc(t);return r<=n?t:{content:[{type:"text",text:mc(e,r,n)}],isError:!1}}function gc(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
29
- `)}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hc(e,t){let n=t;if(typeof t=="string"){if(t.length>Eo)return{ok:!1,error:`${e.name} invalid input: input string too large (max ${Eo} chars)`};let r=t.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!Ao(n))return{ok:!1,error:`${e.name} invalid input: expected object`};if(typeof e.validateInput=="function"){let r=e.validateInput(n);return r.ok?Ao(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${e.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function yc(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("sandbox")||t.includes("permission denied")||t.includes("operation not permitted")||t.includes("eacces")?"sandbox_denied":"execution_failed"}var zn=class{constructor(t){this.config=t;this.approvalManager=jn(t.approval)}approvalManager;async executeAction(t,n){let r=Date.now(),o=t.id??`${t.name}:${r}`,s=this.approvalManager.check(t.name,t.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:o,tool:t.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${t.name}`,durationMs:Date.now()-r,rejected:!0}}let i=this.config.tools[t.name];if(!i)return{actionId:o,tool:t.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${t.name}`,durationMs:Date.now()-r};try{let a=hc(i,t.input);if(!a.ok)return{actionId:o,tool:t.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-r};let l=await i.execute(a.data),c=fc(t.name,l);return{actionId:o,tool:t.name,status:"success",success:!0,observation:gc(c)||"(no tool output)",durationMs:Date.now()-r}}catch(a){let l=yc(a);return{actionId:o,tool:t.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-r}}}async executeActions(t,n={}){let r=n.executionMode??"sequential",o=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(r==="parallel"){let l=await Promise.all(t.map(c=>this.executeAction(c,n)));if(o==="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 t){let c=await this.executeAction(l,n);if(s.push(c),c.rejected&&o==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
30
-
31
- `);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function wo(e){return new zn(e)}var Gt=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,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}};import{Client as Tc}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as _c}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Sc}from"@modelcontextprotocol/sdk/client/stdio.js";function vc(e){if(!e)return;let t={...process.env,...e},n=Object.entries(t).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function Mo(){return new Tc({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function xc(e){if(!(!e||Object.keys(e).length===0))return{headers:e}}function Cc(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 bc(e){let t=new URL(e.url),n=xc(Cc(e));try{let r=Mo(),o=new _c(t,{requestInit:n});return await r.connect(o),{client:r,transport:o}}catch(r){let o=`Failed to connect via streamable_http (${r.message})`,s=new Error(o);throw s.cause=r,s}}async function Ec(e){if("url"in e)return bc(e);let t={command:e.command,args:e.args,env:vc(e.env),stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new Sc(t),r=Mo();return await r.connect(n),{client:r,transport:n}}var Kt=class{connections=new Map;async connect(t,n){let r=this.connections.get(t);if(r)return r;let{client:o,transport:s}=await Ec(n),i=await o.listTools(),a={name:t,client:o,transport:s,tools:(i.tools||[]).map(l=>({name:`${t}_${l.name}`,description:l.description||`Tool from ${t}: ${l.name}`,source:"mcp",serverName:t,originalName:l.name,inputSchema:l.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 r of n.tools)t.push({name:r.name,description:r.description,serverName:r.serverName,originalName:r.originalName,inputSchema:r.inputSchema,client:n.client});return t}async closeAll(){let t=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(r){console.error(`[MCP] Error closing client ${n.name}:`,r)}});await Promise.all(t),this.connections.clear()}get size(){return this.connections.size}};var Vt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new Kt,Nn(this.pool),this.shouldLog=!(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([r,o])=>{try{let s=await this.pool.connect(r,o);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 '${r}' with ${s.tools.length} tools`)}catch(s){this.shouldLog&&console.error(`[MCP] Failed to connect to server '${r}':`,s)}})),n}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),Nn(null)}getPool(){return this.pool}};var Xt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new Gt,this.mcpRegistry=new Vt}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 r=this.getTool(t);if(!r)throw new Error(`Tool '${t}' not found`);return r.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 r=t.filter(s=>s.source==="native"),o=t.filter(s=>s.source==="mcp");if(r.length>0){n.push("### Built-in Tools"),n.push("");for(let s of r)n.push(this.formatToolDescription(s));n.push("")}if(o.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(o);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(`
32
- `)}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(`
33
- `)}groupByServer(t){let n={};for(let r of t)if(r.source==="mcp"){let o=r.serverName;n[o]||(n[o]=[]),n[o].push(r)}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()}};function Ac(e){let t=process.env[e]?.trim();return t?new Set(t.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function wc(){let e=[],t=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=Ac("MEMO_EXPERIMENTAL_TOOLS"),r=n.size===0,o=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return t==="shell"?e.push(Ir):t==="shell_command"?e.push(Rr):t==="unified_exec"?e.push(wn,Mn):t!=="disabled"&&e.push(wn,Mn),e.push(Zr,Qr,eo),e.push(no),e.push(zr),(r||n.has("grep_files"))&&e.push(Xr),(r||n.has("read_file"))&&e.push(Kr),(r||n.has("list_dir"))&&e.push(Vr),s&&e.push(so),e.push(lo),o&&e.push(fo,go,ho,yo,To),e}function Mc(e){let t={};for(let n of e)t[n.name]=n;return t}var kc=Mc(wc()),Pc=Object.values(kc),ko=Pc;import Gc from"openai";import{encoding_for_model as Ic,get_encoding as Rc}from"@dqbd/tiktoken";var Po="cl100k_base";function Oc(e){let t=e?.trim()||Po;try{let n=()=>Ic(t);return n().free(),{model:t,factory:n}}catch{let n=Po,r=()=>Rc(n);return r().free(),{model:n,factory:r}}}function Lc(e){if(e.role==="assistant"){let t=e.reasoning_content?`
34
- ${e.reasoning_content}`:"";return e.tool_calls?.length?`${e.content}${t}
35
- ${JSON.stringify(e.tool_calls)}`:`${e.content}${t}`}return e.role==="tool"?`${e.content}
36
- ${e.tool_call_id}
37
- ${e.name??""}`:e.content}function Io(e){let{model:t,factory:n}=Oc(e),r=n(),o=4,s=2,i=1,a=c=>c?r.encode(c).length:0;return{model:t,countText:a,countMessages:c=>{if(!c.length)return 0;let u=0;for(let p of c)u+=o,u+=a(Lc(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>r.free()}}import{mkdir as Nc,writeFile as $c,readFile as Dc,access as Uc}from"fs/promises";import{homedir as Ro}from"os";import{dirname as Hc,join as xt}from"path";import{randomUUID as Sg}from"crypto";import{parse as Fc}from"toml";var Bc=xt(Ro(),".memo"),Wc="sessions",vt={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 jc(e){return/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e)}function zc(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r)continue;let o=Array.isArray(r)?r:[r];for(let s of o){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("~")?xt(Ro(),e.slice(1)):e}function qc(e){let t=e.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${jc(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(`
23
+ `).trim()},Xc=t=>t.replace(/\s+/g," ").trim(),Yo=N({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:Hc,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return d(`Invalid URL: ${t.url}`,!0)}if(!Bc.has(e.protocol))return d(`Unsupported protocol: ${e.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),Jo);try{let o=await globalThis.fetch(e,{signal:n.signal}),s=o.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>Pt)return d(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(o.body&&o.body.getReader){let T=o.body.getReader(),x=[];for(;;){let{done:X,value:z}=await T.read();if(X)break;if(z){if(a+=z.byteLength,a>Pt)return n.abort(),d(`Request aborted: response body exceeds ${Pt} bytes`,!0);x.push(z)}}let b=new Uint8Array(a),K=0;for(let X of x)b.set(X,K),K+=X.byteLength;l=new TextDecoder().decode(b)}else if(l=await o.text(),a=new TextEncoder().encode(l).byteLength,a>Pt)return d(`Request rejected: response body exceeds ${Pt} bytes`,!0);let c=o.headers.get("content-type")||"",p=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),u=p?Vc(l):l.trim(),g=Xc(u),_=g.length>or?`${g.slice(0,or)}...`:g,h=g.length>or?" text_truncated=true":"",f=p?" source=html_stripped":"";return d(`status=${o.status} bytes=${a} text_chars=${g.length} text="${_}"${h}${f}`)}catch(o){return o.name==="AbortError"?d(`Request timeout or aborted (${Jo}ms)`,!0):d(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as Jc}from"child_process";import{existsSync as Yc}from"fs";import{resolve as Zc}from"path";import{z as ae}from"zod";var Qc=3e4,eu=1e4,tu=3e5,Zo=4,nu=1500,Qo=2e3,We=new Map,ru=ae.object({message:ae.string().min(1),agent_type:ae.string().optional()}).strict(),ou=ae.object({id:ae.string().min(1),message:ae.string().min(1),interrupt:ae.boolean().optional()}).strict(),su=ae.object({id:ae.string().min(1)}).strict(),iu=ae.object({ids:ae.array(ae.string().min(1)).min(1),timeout_ms:ae.number().int().positive().optional()}).strict(),au=ae.object({id:ae.string().min(1)}).strict();function pt(){return new Date().toISOString()}function sr(t){return d(`agent not found: ${t}`,!0)}function lu(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return Zo;let e=Number(t);return!Number.isFinite(e)||e<=0?Zo:Math.floor(e)}function cu(){let t=0;for(let e of We.values())e.running&&(t+=1);return t}function uu(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=Zc(process.cwd(),"dist/index.js");return Yc(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function pu(t){return t!=="running"}function du(t){return new Promise(e=>{setTimeout(e,t)})}function mu(t){return t===void 0?Qc:t<=0?null:Math.max(eu,Math.min(tu,t))}function fu(t){return t.length<=Qo?t:`${t.slice(0,Qo)}
24
+ ...[truncated]`}function gu(t,e){let n=[],r=t.trim(),o=e.trim();return r&&n.push(r),o&&n.push(`stderr:
25
+ ${o}`),fu(n.join(`
26
+
27
+ `))}async function es(t){let e=t.running;if(!e)return;e.interrupted=!0;let n=e.process;n.exitCode!==null||n.killed||await new Promise(r=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(i),n.off("close",s),r())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},nu);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function hu(t){let e=We.get(t);return e?e.status:"not_found"}function yu(t){let e=We.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 _u(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 Su(t){let{record:e,submissionId:n,stdout:r,stderr:o,exitCode:s,interrupted:i}=t;if(!(!e.running||e.running.id!==n)&&(e.running=null,e.updatedAt=pt(),e.lastOutput=gu(r,o)||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 ts(t,e){let n=lu();if(cu()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=uu(),s=Jc(o,{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:r,message:e,process:s,startedAt:pt(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=r,t.updatedAt=pt(),s.on("close",l=>{let c=typeof l=="number"?l:-1,p=!!(t.running?.id===r&&t.running.interrupted);Su({record:t,submissionId:r,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:p})});try{s.stdin?.write(`${e.trim()}
28
+ `)}catch{}try{s.stdin?.end()}catch{}return r}var ns=N({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:ru,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return d("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=pt(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:e,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};We.set(n,o);try{let s=await ts(o,e);return d(JSON.stringify({..._u(o),submission_id:s},null,2))}catch(s){return We.delete(n),d(`spawn_agent failed: ${s.message}`,!0)}}}),rs=N({name:"send_input",description:"Send a message to an existing agent.",inputSchema:ou,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let r=We.get(t);if(!r)return sr(t);let o=e.trim();if(!o)return d("send_input failed: message must not be empty",!0);if(r.status==="closed")return d(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(r.running){if(!n)return d(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await es(r)}try{let s=await ts(r,o);return d(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return d(`send_input failed: ${s.message}`,!0)}}}),os=N({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:su,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=We.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=pt()),d(JSON.stringify({agent_id:t,status:e.status},null,2))):sr(t)}}),ss=N({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:iu,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=mu(e);if(n===null)return d("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},a={};for(let l of t){let c=hu(l);pu(c)&&(i[l]=c,a[l]=yu(l))}return{status:i,details:a}},o=r();if(Object.keys(o.status).length>0)return d(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await du(100),o=r(),Object.keys(o.status).length>0)return d(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return d(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),is=N({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:au,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=We.get(t);return e?e.status==="closed"?d(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=pt(),await es(e),d(JSON.stringify({agent_id:t,status:"closed"},null,2))):sr(t)}});var ir={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"},as=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),en={read:0,write:1,execute:2},ls=["exec","run","shell","command","stdin"],cs=["write","patch","create","delete","modify","update"],us=["read","get","fetch","search","list","find"],ps=new Set(["write","execute"]);function lr(t){let e={...ir,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let r=n.toLowerCase();return ar(r,ls)?"execute":ar(r,cs)?"write":ar(r,us)?"read":"write"},compareRisk(n,r){return en[n]-en[r]},needsApproval(n,r){return r==="strict"?!0:ps.has(n)}}}function ar(t,e){return e.some(n=>t.includes(n))}import{createHash as Tu}from"crypto";function tn(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>tn(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${tn(r)}`).join(",")}}`}function cr(t,e){let n=tn(e),r=`${t}:${n}`;return Tu("sha256").update(r).digest("hex").slice(0,16)}function vu(t){return`Tool "${t}" requires approval.`}function ur(t){let{mode:e="auto",dangerous:n=!1,toolRiskLevels:r}=t||{},o=e==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=lr({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(as.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,o))return{needApproval:!1,decision:"auto-execute"};let p=cr(a,l);return i.toolByFingerprint.set(p,a),i.sessionTools.has(a)||i.onceTools.has(a)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(a)?{needApproval:!0,fingerprint:p,riskLevel:c,reason:"This request was previously denied.",toolName:a,params:l}:{needApproval:!0,fingerprint:p,riskLevel:c,reason:vu(a),toolName:a,params:l}},recordDecision(a,l){let c=i.toolByFingerprint.get(a);if(c)switch(i.sessionTools.delete(c),i.onceTools.delete(c),i.deniedTools.delete(c),l){case"session":i.sessionTools.add(c);break;case"once":i.onceTools.add(c);break;case"deny":i.deniedTools.add(c);break}},isGranted(a){let l=i.toolByFingerprint.get(a);return l?i.sessionTools.has(l)||i.onceTools.has(l):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var ds=12e3,ms=1e5;function Cu(){let t=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!t)return ds;let e=Number(t);return!Number.isFinite(e)||e<=0?ds:Math.floor(e)}function xu(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function bu(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 Eu(t,e,n){return`<system_hint type="tool_output_omitted" tool="${xu(t)}" reason="too_long" actual_chars="${e}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function Mu(t,e){let n=Cu(),r=bu(e);return r<=n?e:{content:[{type:"text",text:Eu(t,r,n)}],isError:!1}}function wu(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
29
+ `)}function fs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Au(t,e){let n=e;if(typeof e=="string"){if(e.length>ms)return{ok:!1,error:`${t.name} invalid input: input string too large (max ${ms} chars)`};let r=e.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!fs(n))return{ok:!1,error:`${t.name} invalid input: expected object`};if(typeof t.validateInput=="function"){let r=t.validateInput(n);return r.ok?fs(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${t.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function Pu(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 pr=class{constructor(e){this.config=e;this.approvalManager=ur(e.approval)}approvalManager;async executeAction(e,n){let r=Date.now(),o=e.id??`${e.name}:${r}`,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:o,tool:e.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${e.name}`,durationMs:Date.now()-r,rejected:!0}}let i=this.config.tools[e.name];if(!i)return{actionId:o,tool:e.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${e.name}`,durationMs:Date.now()-r};try{let a=Au(i,e.input);if(!a.ok)return{actionId:o,tool:e.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-r};let l=await i.execute(a.data),c=Mu(e.name,l);return{actionId:o,tool:e.name,status:"success",success:!0,observation:wu(c)||"(no tool output)",durationMs:Date.now()-r}}catch(a){let l=Pu(a);return{actionId:o,tool:e.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-r}}}async executeActions(e,n={}){let r=n.executionMode??"sequential",o=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(r==="parallel"){let l=await Promise.all(e.map(c=>this.executeAction(c,n)));if(o==="fail_fast"){let c=l.findIndex(p=>p.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&&o==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
30
+
31
+ `);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function gs(t){return new pr(t)}var nn=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,r]of this.tools)e[n]=r;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}};import{Client as ku}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ru}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Iu}from"@modelcontextprotocol/sdk/client/stdio.js";function Ou(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function hs(){return new ku({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function Lu(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function Nu(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 $u(t){let e=new URL(t.url),n=Lu(Nu(t));try{let r=hs(),o=new Ru(e,{requestInit:n});return await r.connect(o),{client:r,transport:o}}catch(r){let o=`Failed to connect via streamable_http (${r.message})`,s=new Error(o);throw s.cause=r,s}}async function Du(t){if("url"in t)return $u(t);let e={command:t.command,args:t.args,env:Ou(t.env),stderr:t.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new Iu(e),r=hs();return await r.connect(n),{client:r,transport:n}}var rn=class{connections=new Map;pendingConnections=new Map;serverConfigs=new Map;setServerConfigs(e){this.serverConfigs=new Map(Object.entries(e))}hasServer(e){return this.connections.has(e)||this.serverConfigs.has(e)}async connect(e,n){n&&this.serverConfigs.set(e,n);let r=this.connections.get(e);if(r)return r;let o=this.pendingConnections.get(e);if(o)return o;let s=n??this.serverConfigs.get(e);if(!s)throw new Error(`MCP server config not found: ${e}`);let i=(async()=>{let{client:a,transport:l}=await Du(s);try{let c=await a.listTools(),p={name:e,client:a,transport:l,tools:(c.tools||[]).map(u=>({name:`${e}_${u.name}`,description:u.description||`Tool from ${e}: ${u.name}`,source:"mcp",serverName:e,originalName:u.name,inputSchema:u.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(e,p),p}catch(c){try{await a.close()}catch{}throw c}})();this.pendingConnections.set(e,i);try{return await i}finally{this.pendingConnections.delete(e)}}get(e){return this.connections.get(e)}getAll(){return Array.from(this.connections.values())}getKnownServerNames(){let e=new Set([...Array.from(this.serverConfigs.keys()),...Array.from(this.connections.keys())]);return Array.from(e.values())}getAllTools(){let e=[];for(let n of this.connections.values())for(let r of n.tools)e.push({name:r.name,description:r.description,serverName:r.serverName,originalName:r.originalName,inputSchema:r.inputSchema,client:n.client});return e}async closeAll(){let e=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(r){console.error(`[MCP] Error closing client ${n.name}:`,r)}});await Promise.all(e),this.connections.clear(),this.pendingConnections.clear()}get size(){return this.connections.size}};var on=class{pool;serverToolNames=new Map;refreshPromises=new Map;tools=new Map;cacheStore=Zt();shouldLog;constructor(){this.pool=new rn,Zn(this.pool),Qn(this.cacheStore),this.shouldLog=!(process.stdout.isTTY&&process.stdin.isTTY)}buildTool(e,n,r){return{name:`${e}_${r.originalName}`,description:r.description||`Tool from ${e}: ${r.originalName}`,source:"mcp",serverName:e,originalName:r.originalName,inputSchema:r.inputSchema??{},execute:async o=>(await this.pool.connect(e,n)).client.callTool({name:r.originalName,arguments:o})}}replaceServerTools(e,n){let r=this.serverToolNames.get(e);if(r)for(let s of r)this.tools.delete(s);let o=new Set;for(let s of n)this.tools.set(s.name,s),o.add(s.name);this.serverToolNames.set(e,o)}connectionToDescriptors(e,n){return n.tools.map(r=>({originalName:r.originalName,description:r.description||`Tool from ${e}: ${r.originalName}`,inputSchema:r.inputSchema}))}async refreshServer(e,n,r){let o=this.refreshPromises.get(e);if(o){r==="sync"&&await o;return}let s=(async()=>{try{let i=await this.pool.connect(e,n),a=this.connectionToDescriptors(e,i);await this.cacheStore.setServerTools(e,n,a);let l=a.map(c=>this.buildTool(e,n,c));this.replaceServerTools(e,l),this.shouldLog&&r==="background"&&console.log(`[MCP] Refreshed '${e}' tools in background (${l.length})`)}catch(i){this.shouldLog&&console.error(`[MCP] Failed to refresh server '${e}':`,i)}})();this.refreshPromises.set(e,s),s.finally(()=>{this.refreshPromises.delete(e)}),r==="sync"&&await s}removeToolsForMissingServers(e){for(let[n,r]of this.serverToolNames.entries())if(!e.has(n)){for(let o of r)this.tools.delete(o);this.serverToolNames.delete(n)}}async loadServers(e){if(!e||Object.keys(e).length===0)return 0;let n=Object.entries(e);this.pool.setServerConfigs(e),this.removeToolsForMissingServers(new Set(n.map(([o])=>o)));let r=[];for(let[o,s]of n){let i=await this.cacheStore.getServerTools(o,s);if(i){let a=i.tools.map(l=>this.buildTool(o,s,l));this.replaceServerTools(o,a),this.shouldLog&&console.log(`[MCP] Loaded ${a.length} cached tools for '${o}' (${i.stale?"stale":"fresh"})`),i.stale&&this.refreshServer(o,s,"background");continue}r.push(this.refreshServer(o,s,"sync"))}return await Promise.all(r),this.tools.size}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,r]of this.tools)e[n]=r;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),this.serverToolNames.clear(),this.refreshPromises.clear(),Zn(null),Qn(null)}getPool(){return this.pool}};var sn=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new nn,this.mcpRegistry=new on}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 r=this.getTool(e);if(!r)throw new Error(`Tool '${e}' not found`);return r.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 r=e.filter(s=>s.source==="native"),o=e.filter(s=>s.source==="mcp");if(r.length>0){n.push("### Built-in Tools"),n.push("");for(let s of r)n.push(this.formatToolDescription(s));n.push("")}if(o.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(o);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(`
32
+ `)}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(`
33
+ `)}groupByServer(e){let n={};for(let r of e)if(r.source==="mcp"){let o=r.serverName;n[o]||(n[o]=[]),n[o].push(r)}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 Uu(t){let e=process.env[t]?.trim();return e?new Set(e.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function Fu(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=Uu("MEMO_EXPERIMENTAL_TOOLS"),r=n.size===0,o=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return e==="shell"?t.push(uo):e==="shell_command"?t.push(po):e==="unified_exec"?t.push(Un,Fn):e!=="disabled"&&t.push(Un,Fn),t.push(Bo,jo,Wo),t.push(zo),t.push(bo),(r||n.has("grep_files"))&&t.push(Po),(r||n.has("read_file"))&&t.push(wo),(r||n.has("list_dir"))&&t.push(Ao),s&&t.push(Vo),t.push(Yo),o&&t.push(ns,rs,os,ss,is),t}function Hu(t){let e={};for(let n of t)e[n.name]=n;return e}var Bu=Hu(Fu()),ju=Object.values(Bu),ys=ju;import ip from"openai";import{encoding_for_model as Wu,get_encoding as Gu}from"@dqbd/tiktoken";var _s="cl100k_base";function zu(t){let e=t?.trim()||_s;try{let n=()=>Wu(e);return n().free(),{model:e,factory:n}}catch{let n=_s,r=()=>Gu(n);return r().free(),{model:n,factory:r}}}function qu(t){if(t.role==="assistant"){let e=t.reasoning_content?`
34
+ ${t.reasoning_content}`:"";return t.tool_calls?.length?`${t.content}${e}
35
+ ${JSON.stringify(t.tool_calls)}`:`${t.content}${e}`}return t.role==="tool"?`${t.content}
36
+ ${t.tool_call_id}
37
+ ${t.name??""}`:t.content}function Ss(t){let{model:e,factory:n}=zu(t),r=n(),o=4,s=2,i=1,a=c=>c?r.encode(c).length:0;return{model:e,countText:a,countMessages:c=>{if(!c.length)return 0;let p=0;for(let u of c)p+=o,p+=a(qu(u)),u.name&&(p+=i);return p+=s,p},dispose:()=>r.free()}}import{mkdir as Ku,writeFile as Vu,readFile as Xu,access as Ju}from"fs/promises";import{homedir as Ts}from"os";import{dirname as Yu,join as Qe,parse as Zu,resolve as Qu}from"path";import{randomUUID as Ry}from"crypto";import{parse as ep}from"toml";var tp=Qe(Ts(),".memo"),np="sessions",kt={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 rp(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function op(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=[];for(let[n,r]of Object.entries(t)){if(!r)continue;let o=Array.isArray(r)?r:[r];for(let s of o){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 vs(t){return t.startsWith("~")?Qe(Ts(),t.slice(1)):t}function sp(t){let e=t.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${rp(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(`
38
38
  `)}).filter(Boolean).join(`
39
39
 
40
- `),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 m=[`[mcp_servers.${s}]`];m.push(`type = "${i.type??"streamable_http"}"`),m.push(`url = "${i.url}"`),i.bearer_token_env_var&&m.push(`bearer_token_env_var = ${JSON.stringify(i.bearer_token_env_var)}`);let h=i.http_headers??i.headers;if(h&&Object.keys(h).length>0){let d=Object.entries(h).map(([v,S])=>`${JSON.stringify(v)} = ${JSON.stringify(S)}`).join(", "),E=i.http_headers?"http_headers":"headers";m.push(`${E} = { ${d} }`)}return m.join(`
40
+ `),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 _=[`[mcp_servers.${s}]`];_.push(`type = "${i.type??"streamable_http"}"`),_.push(`url = "${i.url}"`),i.bearer_token_env_var&&_.push(`bearer_token_env_var = ${JSON.stringify(i.bearer_token_env_var)}`);let h=i.http_headers??i.headers;if(h&&Object.keys(h).length>0){let f=Object.entries(h).map(([x,b])=>`${JSON.stringify(x)} = ${JSON.stringify(b)}`).join(", "),T=i.http_headers?"http_headers":"headers";_.push(`${T} = { ${f} }`)}return _.join(`
41
41
  `)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",l=i.type?`type = "${i.type}"
42
42
  `:"",c=i.stderr?`stderr = "${i.stderr}"
43
- `:"",u=`[mcp_servers.${s}]
43
+ `:"",p=`[mcp_servers.${s}]
44
44
  ${l}command = "${i.command}"
45
- ${c}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let y=p.map(([m,h])=>`${JSON.stringify(m)} = ${JSON.stringify(h)}`).join(`
46
- `);return`${u}
45
+ ${c}${a}`.trimEnd(),u=i.env?Object.entries(i.env):[];if(u.length===0)return p;let g=u.map(([_,h])=>`${JSON.stringify(_)} = ${JSON.stringify(h)}`).join(`
46
+ `);return`${p}
47
47
 
48
48
  [mcp_servers.${s}.env]
49
- ${y}`}).join(`
49
+ ${g}`}).join(`
50
50
 
51
- `));let r=[`current_provider = "${e.current_provider}"`];return typeof e.max_prompt_tokens=="number"&&Number.isFinite(e.max_prompt_tokens)&&r.push(`max_prompt_tokens = ${Math.floor(e.max_prompt_tokens)}`),Array.isArray(e.active_mcp_servers)&&r.push(`active_mcp_servers = ${JSON.stringify(e.active_mcp_servers)}`),[r.join(`
52
- `),t,n].filter(Boolean).join(`
51
+ `));let r=[`current_provider = "${t.current_provider}"`];return typeof t.max_prompt_tokens=="number"&&Number.isFinite(t.max_prompt_tokens)&&r.push(`max_prompt_tokens = ${Math.floor(t.max_prompt_tokens)}`),Array.isArray(t.active_mcp_servers)&&r.push(`active_mcp_servers = ${JSON.stringify(t.active_mcp_servers)}`),[r.join(`
52
+ `),e,n].filter(Boolean).join(`
53
53
 
54
- `)}async function Se(e,t){await Nc(Hc(e),{recursive:!0}),await $c(e,qc(t),"utf-8")}async function ce(){let e=process.env.MEMO_HOME?Oo(process.env.MEMO_HOME):Bc,t=xt(e,"config.toml");try{await Uc(t);let n=await Dc(t,"utf-8"),r=Fc(n),o=zc(r.providers),s=typeof r.max_prompt_tokens=="number"&&Number.isFinite(r.max_prompt_tokens)&&r.max_prompt_tokens>0?Math.floor(r.max_prompt_tokens):void 0,i=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(c=>typeof c=="string"&&c.trim().length>0):void 0,a={current_provider:r.current_provider??vt.current_provider,max_prompt_tokens:s??vt.max_prompt_tokens,providers:o,mcp_servers:r.mcp_servers??{},active_mcp_servers:i},l=!a.providers.length;return{config:l?vt:a,home:e,configPath:t,needsSetup:l}}catch{return{config:vt,home:e,configPath:t,needsSetup:!0}}}function Ye(e,t){let n=t||e.current_provider,r=e.providers.find(o=>o.name===n);return r||(e.providers?.[0]??vt.providers[0])}function Jt(e,t){let n=t.historyDir??xt(e.home,Wc);return Oo(n)}function Lo(e,t){let n=new Date,r=String(n.getFullYear()),o=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-${r}-${o}-${s}T${i}-${a}-${l}-${t}.jsonl`;return xt(e,r,o,s,c)}function Kc(e,t){if(!e||!t)return e;let n=new Set(t.map(o=>o.trim()).filter(Boolean));if(n.size===0)return{};let r={};for(let[o,s]of Object.entries(e))n.has(o)&&(r[o]=s);return r}function Vc(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}function Xc(e){if(e.role==="assistant"){let t={role:"assistant",content:e.content,tool_calls:e.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return e.reasoning_content&&(t.reasoning_content=e.reasoning_content),t}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:e.tool_call_id}:{role:e.role,content:e.content}}function Jc(e){let t=e?.reasoning_content;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}async function No(e,t,n){let r=await ce(),o=r.config,s=new Xt;if(s.registerNativeTools(ko),await s.loadMcpServers(Kc(o.mcp_servers,t.activeMcpServers)),e.tools)for(let[y,m]of Object.entries(e.tools))s.registerNativeTool({name:y,description:m.description,source:"native",inputSchema:{type:"object"},execute:m.execute});let i=s.toRegistry(),a=async()=>{let y=await(e.loadPrompt??_r)(),m=s.generateToolDescriptions();return m&&(y+=`
54
+ `)}async function Ce(t,e){await Ku(Yu(t),{recursive:!0}),await Vu(t,sp(e),"utf-8")}async function le(){let t=process.env.MEMO_HOME?vs(process.env.MEMO_HOME):tp,e=Qe(t,"config.toml");try{await Ju(e);let n=await Xu(e,"utf-8"),r=ep(n),o=op(r.providers),s=typeof r.max_prompt_tokens=="number"&&Number.isFinite(r.max_prompt_tokens)&&r.max_prompt_tokens>0?Math.floor(r.max_prompt_tokens):void 0,i=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(c=>typeof c=="string"&&c.trim().length>0):void 0,a={current_provider:r.current_provider??kt.current_provider,max_prompt_tokens:s??kt.max_prompt_tokens,providers:o,mcp_servers:r.mcp_servers??{},active_mcp_servers:i},l=!a.providers.length;return{config:l?kt:a,home:t,configPath:e,needsSetup:l}}catch{return{config:kt,home:t,configPath:e,needsSetup:!0}}}function et(t,e){let n=e||t.current_provider,r=t.providers.find(o=>o.name===n);return r||(t.providers?.[0]??kt.providers[0])}function an(t,e){let n=e.historyDir??Qe(t.home,np),r=vs(n),o=Qu(process.cwd()),s=Zu(o).root,a=o.slice(s.length).split(/[\\/]+/).filter(Boolean);if(process.platform==="win32"){let c=/^([A-Za-z]):/.exec(s)?.[1];c&&a.unshift(c.toUpperCase())}if(a.length===0)return Qe(r,"-root");let l=`-${a.map(c=>c.replace(/[^A-Za-z0-9._-]/g,"_")).join("-")}`;return Qe(r,l)}function Cs(t,e){let n=new Date,r=String(n.getFullYear()),o=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=`${r}-${o}-${s}T${i}-${a}-${l}`,p=e.replace(/[^A-Za-z0-9._-]/g,"_"),u=`${c}-${p}.jsonl`;return Qe(t,u)}function ap(t,e){if(!t||!e)return t;let n=new Set(e.map(o=>o.trim()).filter(Boolean));if(n.size===0)return{};let r={};for(let[o,s]of Object.entries(t))n.has(o)&&(r[o]=s);return r}function lp(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function cp(t){if(t.role==="assistant"){let e={role:"assistant",content:t.content,tool_calls:t.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return t.reasoning_content&&(e.reasoning_content=t.reasoning_content),e}return t.role==="tool"?{role:"tool",content:t.content,tool_call_id:t.tool_call_id}:{role:t.role,content:t.content}}function up(t){let e=t?.reasoning_content;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}async function xs(t,e,n){let r=await le(),o=r.config,s=new sn;if(s.registerNativeTools(ys),await s.loadMcpServers(ap(o.mcp_servers,e.activeMcpServers)),t.tools)for(let[g,_]of Object.entries(t.tools))s.registerNativeTool({name:g,description:_.description,source:"native",inputSchema:{type:"object"},execute:_.execute});let i=s.toRegistry(),a=async()=>{let g=await(t.loadPrompt??Zr)(),_=s.generateToolDescriptions();return _&&(g+=`
55
55
 
56
- ${m}`),y},l=s.generateToolDefinitions(),c=Jt(r,t),u=Lo(c,n),p=new Ft(u);return{tools:i,dispose:async()=>{e.dispose&&await e.dispose(),await s.dispose()},callLLM:e.callLLM??(async(y,m,h)=>{let d=Ye(o,t.providerName),E=process.env[d.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!E)throw new Error(`Missing env var ${d.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let v=new Gc({apiKey:E,baseURL:d.base_url}),S=y.map(Xc),W=h?.tools??l,ee=W.length>0?W.map(F=>({type:"function",function:{name:F.name,description:F.description,parameters:F.input_schema}})):void 0,q=await v.chat.completions.create({model:d.model,messages:S,tools:ee,tool_choice:ee?"auto":void 0},{signal:h?.signal}),V=q.choices?.[0]?.message,he=Jc(V);if(V?.tool_calls&&V.tool_calls.length>0){let F=[];V.content&&F.push({type:"text",text:V.content});for(let P of V.tool_calls)if(P.type==="function"){let ue=Vc(P.function.arguments);ue.ok?F.push({type:"tool_use",id:P.id,name:P.function.name,input:ue.data}):F.push({type:"text",text:`[tool_use parse error] ${ue.error}; raw: ${ue.raw}`})}let w=F.some(P=>P.type==="tool_use");return{content:F,reasoning_content:he,stop_reason:w?"tool_use":"end_turn",usage:{prompt:q.usage?.prompt_tokens??void 0,completion:q.usage?.completion_tokens??void 0,total:q.usage?.total_tokens??void 0}}}let A=V?.content;if(typeof A!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:A}],reasoning_content:he,stop_reason:"end_turn",usage:{prompt:q.usage?.prompt_tokens??void 0,completion:q.usage?.completion_tokens??void 0,total:q.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:e.historySinks??[p],tokenCounter:e.tokenCounter??Io(t.tokenizerModel),historyFilePath:u}}function Yc(e){let t=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=e.replace(n,(o,s,i)=>{let a=(i??"").trim();return a&&t.push(a),a});return{thinkingParts:t,cleaned:r.trim()}}function $o(e){if(e.length===0)return;let t=e.join(`
57
- `),{thinkingParts:n,cleaned:r}=Yc(t);return n.length>0?n.join(`
56
+ ${_}`),g},l=s.generateToolDefinitions(),c=an(r,e),p=Cs(c,n),u=new qt(p);return{tools:i,dispose:async()=>{t.dispose&&await t.dispose(),await s.dispose()},callLLM:t.callLLM??(async(g,_,h)=>{let f=et(o,e.providerName),T=process.env[f.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!T)throw new Error(`Missing env var ${f.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let x=new ip({apiKey:T,baseURL:f.base_url}),b=g.map(cp),K=h?.tools??l,X=K.length>0?K.map(U=>({type:"function",function:{name:U.name,description:U.description,parameters:U.input_schema}})):void 0,z=await x.chat.completions.create({model:f.model,messages:b,tools:X,tool_choice:X?"auto":void 0},{signal:h?.signal}),q=z.choices?.[0]?.message,ye=up(q);if(q?.tool_calls&&q.tool_calls.length>0){let U=[];q.content&&U.push({type:"text",text:q.content});for(let k of q.tool_calls)if(k.type==="function"){let L=lp(k.function.arguments);L.ok?U.push({type:"tool_use",id:k.id,name:k.function.name,input:L.data}):U.push({type:"text",text:`[tool_use parse error] ${L.error}; raw: ${L.raw}`})}let W=U.some(k=>k.type==="tool_use");return{content:U,reasoning_content:ye,stop_reason:W?"tool_use":"end_turn",usage:{prompt:z.usage?.prompt_tokens??void 0,completion:z.usage?.completion_tokens??void 0,total:z.usage?.total_tokens??void 0}}}let P=q?.content;if(typeof P!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:P}],reasoning_content:ye,stop_reason:"end_turn",usage:{prompt:z.usage?.prompt_tokens??void 0,completion:z.usage?.completion_tokens??void 0,total:z.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:t.historySinks??[u],tokenCounter:t.tokenCounter??Ss(e.tokenizerModel),historyFilePath:p}}function pp(t){let e=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=t.replace(n,(o,s,i)=>{let a=(i??"").trim();return a&&e.push(a),a});return{thinkingParts:e,cleaned:r.trim()}}function bs(t){if(t.length===0)return;let e=t.join(`
57
+ `),{thinkingParts:n,cleaned:r}=pp(e);return n.length>0?n.join(`
58
58
 
59
- `):r||void 0}import{randomUUID as ou}from"crypto";var Yt="interactive";var Gn="success",lt="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.",Do=`Generate a concise session title based on the user's first prompt.
59
+ `):r||void 0}import{randomUUID as _p}from"crypto";var ln="interactive";var mr="success",dt="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.",Es=`Generate a concise session title based on the user's first prompt.
60
60
  Requirements:
61
61
  - 3 to 8 words when possible
62
62
  - Keep it specific and descriptive
63
63
  - Return title only, no quotes, no punctuation-only output
64
- `;var Zc="Skipped tool execution after previous rejection.",Uo="Tool execution skipped: tools are disabled in current permission mode.";function Qc(e){process.stderr.write(`${JSON.stringify(e)}
65
- `)}function Ho(e){if(e.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let t=e.dangerous??!1;return{mode:t?"full":"auto",toolsDisabled:!1,dangerous:t,approvalMode:"auto"}}function Kn(){return{prompt:0,completion:0,total:0}}function Vn(e,t){if(!t)return;let n=t.prompt??0,r=t.completion??0,o=t.total??n+r;e.prompt+=n,e.completion+=r,e.total+=o}function Fo(e){let t=e.content.filter(r=>r.type==="text"),n=e.content.filter(r=>r.type==="tool_use");return{textContent:t.map(r=>r.text).join(`
66
- `),toolUseBlocks:n.map(r=>({id:r.id,name:r.name,input:r.input})),reasoningContent:typeof e.reasoning_content=="string"&&e.reasoning_content.trim().length>0?e.reasoning_content:void 0,stopReason:e.stop_reason,usage:e.usage}}async function Bo(e,t){for(let n of t)try{await n.append(e)}catch(r){Qc({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function Xn(e){return e instanceof Error&&e.name==="AbortError"}function Zt(e){return qn(e,new WeakSet,0)}var eu=100;function qn(e,t,n){if(n>eu)return JSON.stringify("[MaxDepthExceeded]");if(typeof e=="bigint")return JSON.stringify(e.toString());if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(t.has(e))return JSON.stringify("[Circular]");if(t.add(e),Array.isArray(e)){let s=`[${e.map(i=>qn(i,t,n+1)).join(",")}]`;return t.delete(e),s}let o=`{${Object.entries(e).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${JSON.stringify(s)}:${qn(i,t,n+1)}`).join(",")}}`;return t.delete(e),o}function Wo(e){return e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:Zt(t.input)}}))}function jo(e,t){let n=e.trim();if(!n)return null;let r=[n],o=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);o?.[1]&&r.push(o[1].trim());for(let s of r)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(t,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}function zo(e){return e.length<=60?e:`${e.slice(0,57).trimEnd()}...`}function qo(e){let t=e.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!t)return"";let n=t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?zo(n):""}function Go(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"New Session";if(!t.includes(" "))return t.length<=20?t:`${t.slice(0,20).trimEnd()}...`;let r=t.split(" ").filter(Boolean).slice(0,8).join(" ");return zo(r||t)}function Jn(e){return{role:"tool",content:e.observation,tool_call_id:e.actionId,name:e.tool}}function Ko(e,t,n){let r=new Map(t.map(o=>[o.actionId,o]));return e.map(o=>{let s=r.get(o.id);return s||{actionId:o.id,tool:o.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${Zc} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as ru}from"crypto";function tu(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function Vo(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),t.onTitleGenerated&&e.onTitleGenerated.push(t.onTitleGenerated))}function Xo(e){let t=tu();if(Vo(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)Vo(t,n);return t}async function Q(e,t,n){let r=e[t];if(r.length)for(let o of r)try{await o(n)}catch(s){console.warn(`Hook ${t} failed: ${s.message}`)}}function ct(e){return e.map(t=>t.role==="assistant"&&t.tool_calls?.length?{...t,tool_calls:t.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...t})}var Qt=class{constructor(t,n,r,o,s){this.deps=t;this.options=n;this.id=n.sessionId||ru(),this.mode=n.mode||Yt,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=t.historySinks??[],this.hooks=Xo(t),this.historyFilePath=s;let i=Ho(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=wo({tools:t.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=Kn();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(t,n){let r=`${t}:${Zt(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=Zt(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${o}${o.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(t,n){return{onApprovalRequest:async r=>{await Q(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:t,step:n,request:r})},requestApproval:async r=>this.deps.requestApproval?this.deps.requestApproval(r):"deny",onApprovalResponse:async({fingerprint:r,decision:o})=>{await Q(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:t,step:n,fingerprint:r,decision:o})}}}async executeToolAction(t,n,r,o,s){return this.toolOrchestrator.executeAction({id:t,name:n,input:r},this.buildToolApprovalHooks(o,s))}async maybeGenerateSessionTitle(t,n,r){if(t!==1||this.title)return;let o=Go(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Do},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=qo(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(o=a,s="llm")}catch(i){if(Xn(i))return}this.title=o,await this.emitEvent("session_title",{turn:t,content:o,meta:{source:s,original_prompt:n}}),await Q(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:t,title:o,originalPrompt:n})}async runTurn(t){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=Kn(),i=Date.now(),a=this.options.maxPromptTokens??12e4;if(!this.sessionStartEmitted){let l=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:l,role:l?"system":void 0,meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:t});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:t,meta:{tokens:{prompt:l}}}),await Q(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:t,promptTokens:l,history:ct(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,t,n.signal);let c="",u="ok",p,y=0,m=null,h=-1;for(let d=0;;d++){let E=this.tokenCounter.countMessages(this.history);if(E>a){let M=`Context tokens (${E}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:M}),u="prompt_limit",c=M,p=M,await this.emitEvent("final",{turn:r,step:d,content:M,role:"assistant",meta:{tokens:{prompt:E}}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:M,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&E>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${E}`);let v="",S=[],W,ee,q,V=!1;try{let M=await this.deps.callLLM(this.history,ne=>{ne&&(V=!0),this.deps.onAssistantStep?.(ne,d)},{signal:n.signal}),R=Fo(M);v=R.textContent,S=R.toolUseBlocks,ee=R.stopReason,W=R.usage,q=R.reasoningContent,v.trim().length>0&&(m=v,h=d)}catch(M){if(this.cancelling&&Xn(M)){u="cancelled",c="",p="Turn cancelled",await this.emitEvent("final",{turn:r,step:d,content:"",role:"assistant",meta:{cancelled:!0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}let R=`LLM call failed: ${M.message}`;this.history.push({role:"assistant",content:R}),u="error",c=R,p=R,await this.emitEvent("final",{turn:r,content:R,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}!V&&v&&this.deps.onAssistantStep?.(v,d);let he=S.length===0&&v?jo(v,this.deps.tools):null,A,F=null;if(S.length>0){let M=S[0];if(M){let R=v?$o([v]):void 0;A={action:{tool:M.name,input:M.input},thinking:R},F={role:"assistant",content:v,reasoning_content:q,tool_calls:Wo(S)}}else A={}}else v?(A={final:v},F={role:"assistant",content:v,reasoning_content:q}):A={};let w=this.tokenCounter.countText(v),P=W?.prompt??E,ue=W?.completion??w,we=W?.total??P+ue,te={prompt:P,completion:ue,total:we};if(Vn(s,te),Vn(this.sessionUsage,te),o.push({index:d,assistantText:v,parsed:A,tokenUsage:te}),await this.emitEvent("assistant",{turn:r,step:d,content:v,role:"assistant",meta:{tokens:te,protocol_violation:!!he,protocol_violation_count:he?y+1:y||void 0}}),he){y+=1;let M=`Model protocol error: returned plain-text tool JSON for "${he.tool}" ${y} times. Structured tool calls are required.`;u="error",c=M,p=M,this.history.push({role:"assistant",content:M}),await this.emitEvent("final",{turn:r,step:d,content:M,role:"assistant",meta:{error_type:"model_protocol_error",tool:he.tool,protocol_violation:!0,protocol_violation_count:y,tokens:te}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,errorMessage:p,tokenUsage:te,turnUsage:{...s},steps:o});break}if(F&&this.history.push(F),S.length>0&&this.toolsDisabled){for(let M of S)this.history.push({role:"tool",content:Uo,tool_call_id:M.id,name:M.name});u="error",c=lt,p=lt,this.history.push({role:"assistant",content:lt}),await this.emitEvent("final",{turn:r,step:d,content:lt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:S.length,tools:S.map(M=>M.name).join(","),tokens:te}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:lt,status:u,errorMessage:p,tokenUsage:te,turnUsage:{...s},steps:o});break}if(S.length>1){for(let k of S)this.maybeWarnRepeatedAction(k.name,k.input);await this.emitEvent("action",{turn:r,step:d,meta:{tools:S.map(k=>k.name),action_ids:S.map(k=>k.id),action_id:S[0]?.id,parallel:!0,phase:"dispatch",thinking:A.thinking,toolBlocks:S.map(k=>({id:k.id,name:k.name,input:k.input}))}});let M=S[0];M&&await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:d,action:{tool:M.name,input:M.input},parallelActions:S.map(k=>({tool:k.name,input:k.input})),thinking:A.thinking,history:ct(this.history)});let R=S.every(k=>!!this.deps.tools[k.name]?.supportsParallelToolCalls),ne=S.some(k=>!!this.deps.tools[k.name]?.isMutating),se=R&&!ne?"parallel":"sequential",Be=await this.toolOrchestrator.executeActions(S.map(k=>({id:k.id,name:k.name,input:k.input})),{...this.buildToolApprovalHooks(r,d),executionMode:se,failurePolicy:"fail_fast"}),Me=Ko(S,Be.results,Be.hasRejection);for(let[k,Y]of Me.entries())this.history.push(Jn(Y)),await this.emitEvent("observation",{turn:r,step:d,content:Y.observation,meta:{tool:Y.tool,index:k,action_id:Y.actionId,phase:"result",status:Y.status,error_type:Y.errorType,duration_ms:Y.durationMs,execution_mode:se}});let pe=Me.map(k=>`[${k.tool}]: ${k.observation}`).join(`
64
+ `;var dp="Skipped tool execution after previous rejection.",Ms="Tool execution skipped: tools are disabled in current permission mode.";function mp(t){process.stderr.write(`${JSON.stringify(t)}
65
+ `)}function ws(t){if(t.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(t.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(t.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let e=t.dangerous??!1;return{mode:e?"full":"auto",toolsDisabled:!1,dangerous:e,approvalMode:"auto"}}function fr(){return{prompt:0,completion:0,total:0}}function gr(t,e){if(!e)return;let n=e.prompt??0,r=e.completion??0,o=e.total??n+r;t.prompt+=n,t.completion+=r,t.total+=o}function As(t){let e=t.content.filter(r=>r.type==="text"),n=t.content.filter(r=>r.type==="tool_use");return{textContent:e.map(r=>r.text).join(`
66
+ `),toolUseBlocks:n.map(r=>({id:r.id,name:r.name,input:r.input})),reasoningContent:typeof t.reasoning_content=="string"&&t.reasoning_content.trim().length>0?t.reasoning_content:void 0,stopReason:t.stop_reason,usage:t.usage}}async function Ps(t,e){for(let n of e)try{await n.append(t)}catch(r){mp({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function hr(t){return t instanceof Error&&t.name==="AbortError"}function cn(t){return dr(t,new WeakSet,0)}var fp=100;function dr(t,e,n){if(n>fp)return JSON.stringify("[MaxDepthExceeded]");if(typeof t=="bigint")return JSON.stringify(t.toString());if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(e.has(t))return JSON.stringify("[Circular]");if(e.add(t),Array.isArray(t)){let s=`[${t.map(i=>dr(i,e,n+1)).join(",")}]`;return e.delete(t),s}let o=`{${Object.entries(t).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${JSON.stringify(s)}:${dr(i,e,n+1)}`).join(",")}}`;return e.delete(t),o}function ks(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:cn(e.input)}}))}function Rs(t,e){let n=t.trim();if(!n)return null;let r=[n],o=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);o?.[1]&&r.push(o[1].trim());for(let s of r)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}function Is(t){return t.length<=60?t:`${t.slice(0,57).trimEnd()}...`}function Os(t){let e=t.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!e)return"";let n=e.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?Is(n):""}function Ls(t){let e=t.replace(/\s+/g," ").trim();if(!e)return"New Session";if(!e.includes(" "))return e.length<=20?e:`${e.slice(0,20).trimEnd()}...`;let r=e.split(" ").filter(Boolean).slice(0,8).join(" ");return Is(r||e)}function yr(t){return{role:"tool",content:t.observation,tool_call_id:t.actionId,name:t.tool}}function Ns(t,e,n){let r=new Map(e.map(o=>[o.actionId,o]));return t.map(o=>{let s=r.get(o.id);return s||{actionId:o.id,tool:o.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${dp} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as yp}from"crypto";function gp(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function $s(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),e.onTitleGenerated&&t.onTitleGenerated.push(e.onTitleGenerated))}function Ds(t){let e=gp();if($s(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)$s(e,n);return e}async function ee(t,e,n){let r=t[e];if(r.length)for(let o of r)try{await o(n)}catch(s){console.warn(`Hook ${e} failed: ${s.message}`)}}function mt(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 un=class{constructor(e,n,r,o,s){this.deps=e;this.options=n;this.id=n.sessionId||yp(),this.mode=n.mode||ln,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=e.historySinks??[],this.hooks=Ds(e),this.historyFilePath=s;let i=ws(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=gs({tools:e.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=fr();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(e,n){let r=`${e}:${cn(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=cn(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${o}${o.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 r=>{await ee(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:e,step:n,request:r})},requestApproval:async r=>this.deps.requestApproval?this.deps.requestApproval(r):"deny",onApprovalResponse:async({fingerprint:r,decision:o})=>{await ee(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:e,step:n,fingerprint:r,decision:o})}}}async executeToolAction(e,n,r,o,s){return this.toolOrchestrator.executeAction({id:e,name:n,input:r},this.buildToolApprovalHooks(o,s))}async maybeGenerateSessionTitle(e,n,r){if(e!==1||this.title)return;let o=Ls(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Es},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=Os(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(o=a,s="llm")}catch(i){if(hr(i))return}this.title=o,await this.emitEvent("session_title",{turn:e,content:o,meta:{source:s,original_prompt:n}}),await ee(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:e,title:o,originalPrompt:n})}async runTurn(e){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=fr(),i=Date.now(),a=this.options.maxPromptTokens??12e4;if(!this.sessionStartEmitted){let l=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:l,role:l?"system":void 0,meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:e});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:e,meta:{tokens:{prompt:l}}}),await ee(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:e,promptTokens:l,history:mt(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,e,n.signal);let c="",p="ok",u,g=0,_=null,h=-1;for(let f=0;;f++){let T=this.tokenCounter.countMessages(this.history);if(T>a){let w=`Context tokens (${T}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:w}),p="prompt_limit",c=w,u=w,await this.emitEvent("final",{turn:r,step:f,content:w,role:"assistant",meta:{tokens:{prompt:T}}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:w,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&T>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${T}`);let x="",b=[],K,X,z,q=!1;try{let w=await this.deps.callLLM(this.history,J=>{J&&(q=!0),this.deps.onAssistantStep?.(J,f)},{signal:n.signal}),R=As(w);x=R.textContent,b=R.toolUseBlocks,X=R.stopReason,K=R.usage,z=R.reasoningContent,x.trim().length>0&&(_=x,h=f)}catch(w){if(this.cancelling&&hr(w)){p="cancelled",c="",u="Turn cancelled",await this.emitEvent("final",{turn:r,step:f,content:"",role:"assistant",meta:{cancelled:!0}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}let R=`LLM call failed: ${w.message}`;this.history.push({role:"assistant",content:R}),p="error",c=R,u=R,await this.emitEvent("final",{turn:r,content:R,role:"assistant"}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}!q&&x&&this.deps.onAssistantStep?.(x,f);let ye=b.length===0&&x?Rs(x,this.deps.tools):null,P,U=null;if(b.length>0){let w=b[0];if(w){let R=x?bs([x]):void 0;P={action:{tool:w.name,input:w.input},thinking:R},U={role:"assistant",content:x,reasoning_content:z,tool_calls:ks(b)}}else P={}}else x?(P={final:x},U={role:"assistant",content:x,reasoning_content:z}):P={};let W=this.tokenCounter.countText(x),k=K?.prompt??T,L=K?.completion??W,Re=K?.total??k+L,V={prompt:k,completion:L,total:Re};if(gr(s,V),gr(this.sessionUsage,V),o.push({index:f,assistantText:x,parsed:P,tokenUsage:V}),await this.emitEvent("assistant",{turn:r,step:f,content:x,role:"assistant",meta:{tokens:V,protocol_violation:!!ye,protocol_violation_count:ye?g+1:g||void 0}}),ye){g+=1;let w=`Model protocol error: returned plain-text tool JSON for "${ye.tool}" ${g} times. Structured tool calls are required.`;p="error",c=w,u=w,this.history.push({role:"assistant",content:w}),await this.emitEvent("final",{turn:r,step:f,content:w,role:"assistant",meta:{error_type:"model_protocol_error",tool:ye.tool,protocol_violation:!0,protocol_violation_count:g,tokens:V}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,tokenUsage:V,turnUsage:{...s},steps:o});break}if(U&&this.history.push(U),b.length>0&&this.toolsDisabled){for(let w of b)this.history.push({role:"tool",content:Ms,tool_call_id:w.id,name:w.name});p="error",c=dt,u=dt,this.history.push({role:"assistant",content:dt}),await this.emitEvent("final",{turn:r,step:f,content:dt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:b.length,tools:b.map(w=>w.name).join(","),tokens:V}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:dt,status:p,errorMessage:u,tokenUsage:V,turnUsage:{...s},steps:o});break}if(b.length>1){for(let M of b)this.maybeWarnRepeatedAction(M.name,M.input);await this.emitEvent("action",{turn:r,step:f,meta:{tools:b.map(M=>M.name),action_ids:b.map(M=>M.id),action_id:b[0]?.id,parallel:!0,phase:"dispatch",thinking:P.thinking,toolBlocks:b.map(M=>({id:M.id,name:M.name,input:M.input}))}});let w=b[0];w&&await ee(this.hooks,"onAction",{sessionId:this.id,turn:r,step:f,action:{tool:w.name,input:w.input},parallelActions:b.map(M=>({tool:M.name,input:M.input})),thinking:P.thinking,history:mt(this.history)});let R=b.every(M=>!!this.deps.tools[M.name]?.supportsParallelToolCalls),J=b.some(M=>!!this.deps.tools[M.name]?.isMutating),Me=R&&!J?"parallel":"sequential",_e=await this.toolOrchestrator.executeActions(b.map(M=>({id:M.id,name:M.name,input:M.input})),{...this.buildToolApprovalHooks(r,f),executionMode:Me,failurePolicy:"fail_fast"}),Ie=Ns(b,_e.results,_e.hasRejection);for(let[M,te]of Ie.entries())this.history.push(yr(te)),await this.emitEvent("observation",{turn:r,step:f,content:te.observation,meta:{tool:te.tool,index:M,action_id:te.actionId,phase:"result",status:te.status,error_type:te.errorType,duration_ms:te.durationMs,execution_mode:Me}});let pe=Ie.map(M=>`[${M.tool}]: ${M.observation}`).join(`
67
67
 
68
- `),ke=Me.map(k=>k.status),Xe=ke.find(k=>k!==Gn)??Gn,Le=o[o.length-1];if(Le&&(Le.observation=pe),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:d,tool:S.map(k=>k.name).join(", "),observation:pe,resultStatus:Xe,parallelResultStatuses:ke,history:ct(this.history)}),Be.hasRejection){let k=Me.find(Y=>Y.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:r,step:d,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:k?.actionId,error_type:k?.errorType??"approval_denied",duration_ms:k?.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}continue}else if(A.action){this.maybeWarnRepeatedAction(A.action.tool,A.action.input);let M=S[0]?.id??`${r}:${d}:single:${A.action.tool}`;await this.emitEvent("action",{turn:r,step:d,meta:{tool:A.action.tool,input:A.action.input,action_id:M,phase:"dispatch",thinking:A.thinking}}),await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:d,action:A.action,thinking:A.thinking,history:ct(this.history)});let R=await this.executeToolAction(M,A.action.tool,A.action.input,r,d);if(R.rejected){this.history.push(Jn({...R,observation:R.observation||`User denied tool execution: ${A.action.tool}`})),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:r,step:d,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:R.actionId,error_type:R.errorType??"approval_denied",duration_ms:R.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}let ne=R.observation;this.history.push({role:"tool",content:ne,tool_call_id:R.actionId,name:A.action.tool});let se=o[o.length-1];se&&(se.observation=ne),await this.emitEvent("observation",{turn:r,step:d,content:ne,meta:{tool:A.action.tool,action_id:R.actionId,phase:"result",status:R.status,error_type:R.errorType,duration_ms:R.durationMs}}),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:d,tool:A.action.tool,observation:ne,resultStatus:R.status,history:ct(this.history)});continue}if(ee==="end_turn"||A.final){this.resetActionRepetition();let M=ee==="end_turn"&&!A.final&&v.trim().length===0&&!!m&&h===d-1;c=M?m??"":A.final||v,A.final&&(A.final=c),await this.emitEvent("final",{turn:r,step:d,content:c,role:"assistant",meta:{tokens:te,fallback_from_previous_text:M||void 0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});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:r,content:c,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:u,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:y||void 0}}),{finalText:c,steps:o,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)try{n.close?await n.close():n.flush&&await n.flush()}catch(r){console.error(`History flush failed: ${r.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(t,n){if(!this.sinks.length)return;let r=Sr({sessionId:this.id,type:t,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Bo(r,this.sinks)}};async function en(e,t={}){let n=t.sessionId||ou(),r=await No(e,{...t,sessionId:n},n),o=await r.loadPrompt(),s=new Qt({...e,...r},{...t,sessionId:n,mode:t.mode??Yt},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as tt}from"crypto";import{readFile as ld}from"fs/promises";import{useCallback as J,useEffect as Nt,useMemo as $t,useReducer as cd,useRef as Tn,useState as re}from"react";import{Box as ni,Text as ud,useApp as pd}from"ink";import{memo as vu,useMemo as tn}from"react";import{Box as ls,Static as xu,Text as nn}from"ink";import{Box as qe,Text as oe}from"ink";var Fe={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import ut from"path";var su="success",Ct=".";function Yn(e){return e?e===su?Fe.SUCCESS:Fe.ERROR:Fe.SUCCESS}function Jo(e){if(e?.length)return e.map(t=>Yn(t))}function Yo(e,t){return!t||t<=0||!e||e<=0?0:Math.min(100,e/t*100)}function Zo(e){return e?`tokens: ${e.total} (prompt ${e.prompt} / completion ${e.completion})`:""}function bt(e,t=80){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function Qo(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Zn(e,t){let n=e.trim();if(!n)return e;if(n===Ct)return Ct;if(ut.isAbsolute(n)){let r=ut.relative(ut.resolve(t),n);return r?ut.normalize(r):Ct}if(n.startsWith("./")||n.startsWith("../")){let r=ut.normalize(n);return!r||r==="."||r==="./"?Ct:r}return n}function es(e){return e?e===Ct||ut.isAbsolute(e)?!0:e.startsWith("./")||e.startsWith("../"):!1}import{Box as Ee,Text as fe}from"ink";import{marked as iu}from"marked";var au=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Et(e){return e.map(t=>{let n=t;return typeof n.text=="string"?n.text:typeof n.raw=="string"?n.raw:Array.isArray(n.tokens)?Et(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Et(r.tokens):"").filter(Boolean).join(`
69
- `):""}).join("")}function lu(e){let t=[],n=e.replace(/<think>([\s\S]*?)<\/think>/gi,(r,o)=>{let s=o.trim();return s&&t.push(s),""});return{think:t,cleaned:n}}function cu(e){if(e.startsWith("`")&&e.endsWith("`"))return{type:"inlineCode",content:e.slice(1,-1)};if(e.startsWith("**")&&e.endsWith("**")||e.startsWith("__")&&e.endsWith("__"))return{type:"bold",content:e.slice(2,-2)};if(e.startsWith("*")&&e.endsWith("*")||e.startsWith("_")&&e.endsWith("_"))return{type:"italic",content:e.slice(1,-1)};let t=e.match(/^\[([^\]]+)\]\((.+)\)$/);return t?{type:"link",label:t[1]??"",href:t[2]??""}:{type:"text",content:e}}function ns(e){if(!e)return[];let t=[],n=0;for(let r of e.matchAll(au)){let o=r[0];if(!o)continue;let s=r.index??0;s>n&&t.push({type:"text",content:e.slice(n,s)}),t.push(cu(o)),n=s+o.length}return n<e.length&&t.push({type:"text",content:e.slice(n)}),t.filter(r=>r.type==="link"?r.label.length>0||r.href.length>0:r.content.length>0)}function uu(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Et(e.tokens):""}function pu(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Et(e.tokens):typeof e.raw=="string"?e.raw.split(`
70
- `).map(t=>t.replace(/^>\s?/,"")).join(`
71
- `).trim():""}function ts(e){return typeof e.text=="string"?e.text:Array.isArray(e.tokens)?Et(e.tokens):typeof e.raw=="string"?e.raw:""}function rs(e){let{think:t,cleaned:n}=lu(e),r=[];t.length>0&&r.push({type:"think",content:t.join(`
68
+ `),de=Ie.map(M=>M.status),Ct=de.find(M=>M!==mr)??mr,ke=o[o.length-1];if(ke&&(ke.observation=pe),await ee(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:f,tool:b.map(M=>M.name).join(", "),observation:pe,resultStatus:Ct,parallelResultStatuses:de,history:mt(this.history)}),_e.hasRejection){let M=Ie.find(te=>te.rejected);p="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:r,step:f,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:M?.actionId,error_type:M?.errorType??"approval_denied",duration_ms:M?.durationMs}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,tokenUsage:V,turnUsage:{...s},steps:o});break}continue}else if(P.action){this.maybeWarnRepeatedAction(P.action.tool,P.action.input);let w=b[0]?.id??`${r}:${f}:single:${P.action.tool}`;await this.emitEvent("action",{turn:r,step:f,meta:{tool:P.action.tool,input:P.action.input,action_id:w,phase:"dispatch",thinking:P.thinking}}),await ee(this.hooks,"onAction",{sessionId:this.id,turn:r,step:f,action:P.action,thinking:P.thinking,history:mt(this.history)});let R=await this.executeToolAction(w,P.action.tool,P.action.input,r,f);if(R.rejected){this.history.push(yr({...R,observation:R.observation||`User denied tool execution: ${P.action.tool}`})),p="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:r,step:f,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:R.actionId,error_type:R.errorType??"approval_denied",duration_ms:R.durationMs}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,tokenUsage:V,turnUsage:{...s},steps:o});break}let J=R.observation;this.history.push({role:"tool",content:J,tool_call_id:R.actionId,name:P.action.tool});let Me=o[o.length-1];Me&&(Me.observation=J),await this.emitEvent("observation",{turn:r,step:f,content:J,meta:{tool:P.action.tool,action_id:R.actionId,phase:"result",status:R.status,error_type:R.errorType,duration_ms:R.durationMs}}),await ee(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:f,tool:P.action.tool,observation:J,resultStatus:R.status,history:mt(this.history)});continue}if(X==="end_turn"||P.final){this.resetActionRepetition();let w=X==="end_turn"&&!P.final&&x.trim().length===0&&!!_&&h===f-1;c=w?_??"":P.final||x,P.final&&(P.final=c),await this.emitEvent("final",{turn:r,step:f,content:c,role:"assistant",meta:{tokens:V,fallback_from_previous_text:w||void 0}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,tokenUsage:V,turnUsage:{...s},steps:o});break}this.resetActionRepetition();break}return!c&&p!=="cancelled"&&(p==="ok"&&(p="error"),c="Unable to produce a final answer. Please retry or adjust the request.",u=c,this.history.push({role:"assistant",content:c}),await this.emitEvent("final",{turn:r,content:c,role:"assistant"}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:p,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:g||void 0}}),{finalText:c,steps:o,status:p,errorMessage:u,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)try{n.close?await n.close():n.flush&&await n.flush()}catch(r){console.error(`History flush failed: ${r.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(e,n){if(!this.sinks.length)return;let r=Qr({sessionId:this.id,type:e,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Ps(r,this.sinks)}};async function pn(t,e={}){let n=e.sessionId||_p(),r=await xs(t,{...e,sessionId:n},n),o=await r.loadPrompt(),s=new un({...t,...r},{...e,sessionId:n,mode:e.mode??ln},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as st}from"crypto";import{readFile as df}from"fs/promises";import{useCallback as Q,useEffect as jt,useMemo as Wt,useReducer as mf,useRef as Rn,useState as re}from"react";import{Box as ra,Text as ff,useApp as gf}from"ink";import{memo as Dp,useMemo as Zs,useRef as Qs,useEffect as Up}from"react";import{Box as Js,Static as Fp,Text as dn}from"ink";import{memo as vr}from"react";import{Box as Ge,Text as se}from"ink";var Fe={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import ft from"path";var Sp="success",Rt=".";function _r(t){return t?t===Sp?Fe.SUCCESS:Fe.ERROR:Fe.SUCCESS}function Us(t){if(t?.length)return t.map(e=>_r(e))}function Fs(t,e){return!e||e<=0||!t||t<=0?0:Math.min(100,t/e*100)}function Hs(t){return t?`tokens: ${t.total} (prompt ${t.prompt} / completion ${t.completion})`:""}function It(t,e=80){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function Bs(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function Sr(t,e){let n=t.trim();if(!n)return t;if(n===Rt)return Rt;if(ft.isAbsolute(n)){let r=ft.relative(ft.resolve(e),n);return r?ft.normalize(r):Rt}if(n.startsWith("./")||n.startsWith("../")){let r=ft.normalize(n);return!r||r==="."||r==="./"?Rt:r}return n}function js(t){return t?t===Rt||ft.isAbsolute(t)?!0:t.startsWith("./")||t.startsWith("../"):!1}import{memo as Mp,useMemo as wp}from"react";import{Box as Pe,Text as ge}from"ink";import{marked as Tp}from"marked";var vp=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Ot(t){return t.map(e=>{let n=e;return typeof n.text=="string"?n.text:typeof n.raw=="string"?n.raw:Array.isArray(n.tokens)?Ot(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Ot(r.tokens):"").filter(Boolean).join(`
69
+ `):""}).join("")}function Cp(t){let e=[],n=t.replace(/<think>([\s\S]*?)<\/think>/gi,(r,o)=>{let s=o.trim();return s&&e.push(s),""});return{think:e,cleaned:n}}function xp(t){if(t.startsWith("`")&&t.endsWith("`"))return{type:"inlineCode",content:t.slice(1,-1)};if(t.startsWith("**")&&t.endsWith("**")||t.startsWith("__")&&t.endsWith("__"))return{type:"bold",content:t.slice(2,-2)};if(t.startsWith("*")&&t.endsWith("*")||t.startsWith("_")&&t.endsWith("_"))return{type:"italic",content:t.slice(1,-1)};let e=t.match(/^\[([^\]]+)\]\((.+)\)$/);return e?{type:"link",label:e[1]??"",href:e[2]??""}:{type:"text",content:t}}function Gs(t){if(!t)return[];let e=[],n=0;for(let r of t.matchAll(vp)){let o=r[0];if(!o)continue;let s=r.index??0;s>n&&e.push({type:"text",content:t.slice(n,s)}),e.push(xp(o)),n=s+o.length}return n<t.length&&e.push({type:"text",content:t.slice(n)}),e.filter(r=>r.type==="link"?r.label.length>0||r.href.length>0:r.content.length>0)}function bp(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Ot(t.tokens):""}function Ep(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Ot(t.tokens):typeof t.raw=="string"?t.raw.split(`
70
+ `).map(e=>e.replace(/^>\s?/,"")).join(`
71
+ `).trim():""}function Ws(t){return typeof t.text=="string"?t.text:Array.isArray(t.tokens)?Ot(t.tokens):typeof t.raw=="string"?t.raw:""}function zs(t){let{think:e,cleaned:n}=Cp(t),r=[];e.length>0&&r.push({type:"think",content:e.join(`
72
72
 
73
- `)});let o=iu.lexer(n);for(let s of o)switch(s.type){case"html":{r.push({type:"html",content:s.text??s.raw??""});break}case"hr":{r.push({type:"hr"});break}case"heading":{r.push({type:"heading",level:typeof s.depth=="number"?s.depth:1,content:s.text??ts(s)});break}case"paragraph":case"text":{let i=ts(s);i.trim().length>0&&r.push({type:"paragraph",content:i});break}case"code":{r.push({type:"code",language:s.lang,content:s.text??""});break}case"blockquote":{let i=pu(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(a=>uu(a)).filter(a=>a.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as _u,jsx as B,jsxs as pt}from"react/jsx-runtime";var du="\u2014\u2014\u2014";function mu(e,t){return e.repeat(Math.max(0,t))}function fu(e){let t=e.split(`
74
- `);if(t.length===0)return["Think:"];let n=t.findIndex(r=>r.trim().length>0);return n<0&&(n=0),t.map((r,o)=>o===n?`Think: ${r}`:r)}function gu(e){return e.split(`
75
- `)}function hu({content:e}){let t=gu(e);return B(Ee,{flexDirection:"column",marginY:1,children:t.map((n,r)=>B(fe,{children:n},r))})}function yu({node:e}){switch(e.type){case"bold":return B(fe,{bold:!0,children:e.content});case"italic":return B(fe,{italic:!0,children:e.content});case"inlineCode":return B(fe,{color:"cyan",children:e.content});case"link":return pt(_u,{children:[B(fe,{color:"blue",underline:!0,children:e.label}),pt(fe,{color:"gray",children:[" (",e.href,")"]})]});case"text":return B(fe,{children:e.content});default:return null}}function Qn({content:e}){let t=ns(e);return B(Ee,{flexWrap:"wrap",children:t.map((n,r)=>B(yu,{node:n},r))})}function Tu(e,t){switch(e.type){case"html":return B(Ee,{children:B(fe,{color:"gray",dimColor:!0,children:e.content})},t);case"hr":return B(Ee,{marginY:1,children:B(fe,{color:"gray",dimColor:!0,children:du})},t);case"think":return B(Ee,{flexDirection:"column",marginY:1,children:fu(e.content).map((n,r)=>B(fe,{color:"gray",dimColor:!0,children:n},r))},t);case"heading":return B(Ee,{children:pt(fe,{bold:!0,color:"cyan",children:[mu("#",e.level)," ",e.content]})},t);case"paragraph":return B(Qn,{content:e.content},t);case"code":return B(hu,{content:e.content},t);case"blockquote":return B(Ee,{flexDirection:"column",children:e.content.split(`
76
- `).map((n,r)=>pt(Ee,{children:[B(fe,{color:"gray",dimColor:!0,children:"> "}),B(Qn,{content:n})]},r))},t);case"list":return B(Ee,{flexDirection:"column",children:e.items.map((n,r)=>pt(Ee,{children:[pt(fe,{color:"gray",children:[e.ordered?`${r+1}.`:"\u2022"," "]}),B(Qn,{content:n})]},r))},t);default:return null}}function os({content:e}){let t=rs(e);return B(Ee,{flexDirection:"column",children:t.map((n,r)=>Tu(n,`${n.type}-${r}`))})}import{jsx as me,jsxs as ve}from"react/jsx-runtime";function ss(e){return e===Fe.ERROR?"red":e===Fe.EXECUTING?"yellow":"green"}function is(e,t){if(e==null)return null;if(typeof e=="string"){let s=es(e)?Zn(e,t):e;return bt(s,70)}if(typeof e!="object"||Array.isArray(e))return bt(String(e),70);let n=e,r=["cmd","path","file_path","dir_path","query","pattern","url","content"],o=new Set(["path","file_path","dir_path"]);for(let s of r){let i=n[s];if(i==null||i==="")continue;let a=String(i),l=o.has(s)?Zn(a,t):a;return bt(l,70)}return bt(Qo(n),70)}function as({message:e}){let t=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return ve(qe,{flexDirection:"column",children:[ve(oe,{color:t,children:["\u25CF ",e.title]}),me(oe,{color:"gray",children:e.content})]})}function Su({step:e,cwd:t}){let n=!!(e.parallelActions&&e.parallelActions.length>1),r=!n&&e.action?is(e.action.input,t):null;return ve(qe,{flexDirection:"column",children:[e.thinking?ve(qe,{children:[me(oe,{color:"gray",children:"\u25CF "}),me(oe,{color:"gray",children:e.thinking})]}):null,n?e.parallelActions?.map((o,s)=>{let i=is(o.input,t);return ve(qe,{children:[ve(oe,{color:ss(e.parallelToolStatuses?.[s]??e.toolStatus),children:["\u25CF"," "]}),me(oe,{color:"gray",children:"Used "}),me(oe,{color:"cyan",children:o.tool}),i?ve(oe,{color:"gray",children:[" (",i,")"]}):null]},`${o.tool}-${s}`)}):null,!n&&e.action?ve(qe,{children:[me(oe,{color:ss(e.toolStatus),children:"\u25CF "}),me(oe,{color:"gray",children:"Used "}),me(oe,{color:"cyan",children:e.action.tool}),r?ve(oe,{color:"gray",children:[" (",r,")"]}):null]}):null]})}function er({turn:e,cwd:t}){return ve(qe,{flexDirection:"column",children:[ve(qe,{marginY:.5,children:[me(oe,{color:"gray",children:"\u203A "}),me(oe,{children:e.userInput})]}),e.steps.map(n=>me(Su,{step:n,cwd:t},`${e.index}-${n.index}`)),e.finalText?me(qe,{marginTop:0,children:me(os,{content:e.finalText})}):null,e.status&&e.status!=="ok"?ve(oe,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?me(oe,{color:"red",children:e.errorMessage}):null]})}import{jsx as At,jsxs as wt}from"react/jsx-runtime";function cs(e){return e.sequence??0}function Cu(e){return e.type==="header"}function bu(e){return e.id!==void 0}var us=vu(function({header:t,systemMessages:n,turns:r,historicalTurns:o}){let s=tn(()=>[...o,...r],[o,r]),i=s.length>0?s[s.length-1]:void 0,a=i&&!!(i.finalText||i.status&&i.status!=="ok"),l=a?s:s.slice(0,-1),c=a?void 0:i,u=tn(()=>({type:"header",data:t}),[t]),p=tn(()=>{let m=[...n,...l];return m.sort((h,d)=>cs(h)-cs(d)),m},[l,n]),y=tn(()=>[u,...p],[u,p]);return wt(ls,{flexDirection:"column",children:[At(xu,{items:y,children:m=>Cu(m)?wt(ls,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[At(nn,{bold:!0,children:"Memo CLI"}),wt(nn,{color:"gray",children:[m.data.providerName," / ",m.data.model," \u2022 v",m.data.version]}),wt(nn,{color:"gray",children:["cwd: ",m.data.cwd]}),wt(nn,{color:"gray",children:["mcp: ",m.data.mcpNames.join(", ")||"none"]})]},`header-${m.data.sessionId}`):bu(m)?At(as,{message:m},m.id):At(er,{turn:m,cwd:t.cwd},`turn-${m.sequence??m.index}`)}),c?At(er,{turn:c,cwd:t.cwd}):null]})});import{useCallback as et,useEffect as dn,useMemo as Ns,useRef as Pt,useState as Ge}from"react";import{Box as rr,Text as mn,useInput as pp,useStdout as dp}from"ink";var dt=[8e4,12e4,15e4,2e5],ps=dt[1],$={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",MODELS:"models",CONTEXT:"context",TOOLS:"tools",MCP:"mcp",INIT:"init"},H={NONE:"none",ONCE:"once",FULL:"full"};function ge(e){return`/${e}`}var ds="exit";var rn=[{name:$.HELP,description:"Show command and shortcut help"},{name:$.EXIT,description:"Exit current session"},{name:$.NEW,description:"Start a fresh session"},{name:$.RESUME,description:"List and load session history"},{name:$.MODELS,description:"List or switch configured models"},{name:$.CONTEXT,description:"Set context window (80k/120k/150k/200k)"},{name:$.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:$.MCP,description:"Show configured MCP servers"},{name:$.INIT,description:"Generate AGENTS.md with agent instructions"}],Eu={none:H.NONE,off:H.NONE,disabled:H.NONE,"no-tools":H.NONE,once:H.ONCE,ask:H.ONCE,single:H.ONCE,strict:H.ONCE,full:H.FULL,all:H.FULL,dangerous:H.FULL,"full-access":H.FULL};function Au(e){if(!e)return null;let t=e.trim().toLowerCase();return t?Eu[t]??null:null}function ms(e){return e===H.NONE?"none (no tools)":e===H.ONCE?"once (approval required)":"full (no approval)"}function wu(){let e=rn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...rn.map(n=>` ${ge(n.name).padEnd(e+3)} ${n.description}`)," exit Exit session (without slash)","","Shortcuts:"," Enter Send message"," Shift+Enter New line"," Up/Down Browse local input history"," Tab Accept active suggestion"," Ctrl+L Clear screen and start new session"," Esc Esc Interrupt running turn / clear input"].join(`
77
- `)}function Mu(e){if(!e)return null;let n=e.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!n)return null;let r=Number(n[1]);return Number.isFinite(r)?r*(n[2]?1e3:1):null}function fs(e,t){let[n,...r]=e.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case $.HELP:return{kind:"message",title:"Help",content:wu()};case $.EXIT:return{kind:"exit"};case $.NEW:return{kind:"new"};case $.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case $.MODELS:{if(!t.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${t.configPath}`};let s=r.join(" ").trim(),i=t.providers.find(c=>c.name===s)??t.providers.find(c=>c.model===s);if(i)return{kind:"switch_model",provider:i};let a=t.providers.map(c=>{let u=c.name===t.providerName&&c.model===t.model?" (current)":"",p=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${p}${u}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
73
+ `)});let o=Tp.lexer(n);for(let s of o)switch(s.type){case"html":{r.push({type:"html",content:s.text??s.raw??""});break}case"hr":{r.push({type:"hr"});break}case"heading":{r.push({type:"heading",level:typeof s.depth=="number"?s.depth:1,content:s.text??Ws(s)});break}case"paragraph":case"text":{let i=Ws(s);i.trim().length>0&&r.push({type:"paragraph",content:i});break}case"code":{r.push({type:"code",language:s.lang,content:s.text??""});break}case"blockquote":{let i=Ep(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(a=>bp(a)).filter(a=>a.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as Np,jsx as G,jsxs as gt}from"react/jsx-runtime";var Ap="\u2014\u2014\u2014";function Pp(t,e){return t.repeat(Math.max(0,e))}function kp(t){let e=t.split(`
74
+ `);if(e.length===0)return["Think:"];let n=e.findIndex(r=>r.trim().length>0);return n<0&&(n=0),e.map((r,o)=>o===n?`Think: ${r}`:r)}function Rp(t){return t.split(`
75
+ `)}function Ip({content:t}){let e=Rp(t);return G(Pe,{flexDirection:"column",marginY:1,children:e.map((n,r)=>G(ge,{children:n},r))})}function Op({node:t}){switch(t.type){case"bold":return G(ge,{bold:!0,children:t.content});case"italic":return G(ge,{italic:!0,children:t.content});case"inlineCode":return G(ge,{color:"cyan",children:t.content});case"link":return gt(Np,{children:[G(ge,{color:"blue",underline:!0,children:t.label}),gt(ge,{color:"gray",children:[" (",t.href,")"]})]});case"text":return G(ge,{children:t.content});default:return null}}function Tr({content:t}){let e=Gs(t);return G(Pe,{flexWrap:"wrap",children:e.map((n,r)=>G(Op,{node:n},r))})}function Lp(t,e){switch(t.type){case"html":return G(Pe,{children:G(ge,{color:"gray",dimColor:!0,children:t.content})},e);case"hr":return G(Pe,{marginY:1,children:G(ge,{color:"gray",dimColor:!0,children:Ap})},e);case"think":return G(Pe,{flexDirection:"column",marginY:1,children:kp(t.content).map((n,r)=>G(ge,{color:"gray",dimColor:!0,children:n},r))},e);case"heading":return G(Pe,{children:gt(ge,{bold:!0,color:"cyan",children:[Pp("#",t.level)," ",t.content]})},e);case"paragraph":return G(Tr,{content:t.content},e);case"code":return G(Ip,{content:t.content},e);case"blockquote":return G(Pe,{flexDirection:"column",children:t.content.split(`
76
+ `).map((n,r)=>gt(Pe,{children:[G(ge,{color:"gray",dimColor:!0,children:"> "}),G(Tr,{content:n})]},r))},e);case"list":return G(Pe,{flexDirection:"column",children:t.items.map((n,r)=>gt(Pe,{children:[gt(ge,{color:"gray",children:[t.ordered?`${r+1}.`:"\u2022"," "]}),G(Tr,{content:n})]},r))},e);default:return null}}var qs=Mp(function({content:e}){let n=wp(()=>zs(e),[e]);return G(Pe,{flexDirection:"column",children:n.map((r,o)=>Lp(r,`${r.type}-${o}`))})});import{jsx as ue,jsxs as xe}from"react/jsx-runtime";function Ks(t){return t===Fe.ERROR?"red":t===Fe.EXECUTING?"yellow":"green"}function Vs(t,e){if(t==null)return null;if(typeof t=="string"){let s=js(t)?Sr(t,e):t;return It(s,70)}if(typeof t!="object"||Array.isArray(t))return It(String(t),70);let n=t,r=["cmd","path","file_path","dir_path","query","pattern","url","content"],o=new Set(["path","file_path","dir_path"]);for(let s of r){let i=n[s];if(i==null||i==="")continue;let a=String(i),l=o.has(s)?Sr(a,e):a;return It(l,70)}return It(Bs(n),70)}var Xs=vr(function({message:e}){let n=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return xe(Ge,{flexDirection:"column",children:[xe(se,{color:n,children:["\u25CF ",e.title]}),ue(se,{color:"gray",children:e.content})]})}),$p=vr(function({step:e,cwd:n}){let r=!!(e.parallelActions&&e.parallelActions.length>1),o=!r&&e.action?Vs(e.action.input,n):null;return xe(Ge,{flexDirection:"column",children:[e.thinking?xe(Ge,{children:[ue(se,{color:"gray",children:"\u25CF "}),ue(se,{color:"gray",children:e.thinking})]}):null,r?e.parallelActions?.map((s,i)=>{let a=Vs(s.input,n);return xe(Ge,{children:[xe(se,{color:Ks(e.parallelToolStatuses?.[i]??e.toolStatus),children:["\u25CF"," "]}),ue(se,{color:"gray",children:"Used "}),ue(se,{color:"cyan",children:s.tool}),a?xe(se,{color:"gray",children:[" (",a,")"]}):null]},`${s.tool}-${i}`)}):null,!r&&e.action?xe(Ge,{children:[ue(se,{color:Ks(e.toolStatus),children:"\u25CF "}),ue(se,{color:"gray",children:"Used "}),ue(se,{color:"cyan",children:e.action.tool}),o?xe(se,{color:"gray",children:[" (",o,")"]}):null]}):null]})}),Cr=vr(function({turn:e,cwd:n}){return xe(Ge,{flexDirection:"column",children:[xe(Ge,{marginY:.5,children:[ue(se,{color:"gray",children:"\u203A "}),ue(se,{children:e.userInput})]}),e.steps.map(r=>ue($p,{step:r,cwd:n},`${e.index}-${r.index}`)),e.finalText?ue(Ge,{marginTop:0,children:ue(qs,{content:e.finalText})}):null,e.status&&e.status!=="ok"?xe(se,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?ue(se,{color:"red",children:e.errorMessage}):null]})});import{jsx as Lt,jsxs as Nt}from"react/jsx-runtime";function Ys(t){return t.sequence??0}function Hp(t){return t.type==="header"}function Bp(t){return t.id!==void 0}function jp(t){let e=Qs("");return Zs(()=>{let n=`${t.sessionId}-${t.providerName}-${t.model}-${t.version}`;return n!==e.current&&(e.current=n),e.current},[t.sessionId,t.providerName,t.model,t.version])}var ei=Dp(function({header:e,systemMessages:n,turns:r,historicalTurns:o}){let s=jp(e),i=Qs(e.cwd);Up(()=>{i.current=e.cwd},[e.cwd]);let{completedTurns:a,inProgressTurn:l,staticItems:c}=Zs(()=>{let u=[...o,...r],g=u.length>0?u[u.length-1]:void 0,_=g&&!!(g.finalText||g.status&&g.status!=="ok"),h=_?u:u.slice(0,-1),f=_?void 0:g,T={type:"header",data:e},x=[...n,...h];x.sort((K,X)=>Ys(K)-Ys(X));let b=[T,...x];return{completedTurns:h,inProgressTurn:f,staticItems:b}},[e,o,r,n]),p=i.current;return Nt(Js,{flexDirection:"column",children:[Lt(Fp,{items:c,children:u=>Hp(u)?Nt(Js,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[Lt(dn,{bold:!0,children:"Memo Code CLI"}),Nt(dn,{color:"gray",children:[u.data.providerName," / ",u.data.model," \u2022 v",u.data.version]}),Nt(dn,{color:"gray",children:["cwd: ",u.data.cwd]}),Nt(dn,{color:"gray",children:["mcp: ",u.data.mcpNames.join(", ")||"none"]})]},`header-${s}`):Bp(u)?Lt(Xs,{message:u},u.id):Lt(Cr,{turn:u,cwd:p},`turn-${u.sequence??u.index}`)}),l?Lt(Cr,{turn:l,cwd:p}):null]})});import{memo as om,useCallback as rt,useEffect as bn,useMemo as Di,useRef as Ft,useState as ze}from"react";import{Box as Or,Text as En,useInput as sm,useStdout as im}from"ink";var ht=[8e4,12e4,15e4,2e5],ti=ht[1],$={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",MODELS:"models",CONTEXT:"context",TOOLS:"tools",MCP:"mcp",INIT:"init"},B={NONE:"none",ONCE:"once",FULL:"full"};function he(t){return`/${t}`}var ni="exit";var mn=[{name:$.HELP,description:"Show command and shortcut help"},{name:$.EXIT,description:"Exit current session"},{name:$.NEW,description:"Start a fresh session"},{name:$.RESUME,description:"List and load session history"},{name:$.MODELS,description:"List or switch configured models"},{name:$.CONTEXT,description:"Set context window (80k/120k/150k/200k)"},{name:$.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:$.MCP,description:"Show configured MCP servers"},{name:$.INIT,description:"Generate AGENTS.md with agent instructions"}],Wp={none:B.NONE,off:B.NONE,disabled:B.NONE,"no-tools":B.NONE,once:B.ONCE,ask:B.ONCE,single:B.ONCE,strict:B.ONCE,full:B.FULL,all:B.FULL,dangerous:B.FULL,"full-access":B.FULL};function Gp(t){if(!t)return null;let e=t.trim().toLowerCase();return e?Wp[e]??null:null}function ri(t){return t===B.NONE?"none (no tools)":t===B.ONCE?"once (approval required)":"full (no approval)"}function zp(){let t=mn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...mn.map(n=>` ${he(n.name).padEnd(t+3)} ${n.description}`)," exit Exit session (without slash)","","Shortcuts:"," Enter Send message"," Shift+Enter New line"," Up/Down Browse local input history"," Tab Accept active suggestion"," Ctrl+L Clear screen and start new session"," Esc Esc Interrupt running turn / clear input"].join(`
77
+ `)}function qp(t){if(!t)return null;let n=t.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!n)return null;let r=Number(n[1]);return Number.isFinite(r)?r*(n[2]?1e3:1):null}function oi(t,e){let[n,...r]=t.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case $.HELP:return{kind:"message",title:"Help",content:zp()};case $.EXIT:return{kind:"exit"};case $.NEW:return{kind:"new"};case $.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case $.MODELS:{if(!e.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${e.configPath}`};let s=r.join(" ").trim(),i=e.providers.find(c=>c.name===s)??e.providers.find(c=>c.model===s);if(i)return{kind:"switch_model",provider:i};let a=e.providers.map(c=>{let p=c.name===e.providerName&&c.model===e.model?" (current)":"",u=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${u}${p}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
78
78
 
79
79
  `:""}${a.join(`
80
- `)}`}}case $.CONTEXT:{let s=Mu(r[0]),i=dt.map(a=>`${Math.floor(a/1e3)}k`).join(", ");return s===null?{kind:"message",title:"Context",content:`Current: ${(t.contextLimit/1e3).toFixed(0)}k
81
- Usage: ${ge($.CONTEXT)} <length>
82
- Choices: ${i}`}:dt.includes(s)?{kind:"set_context_limit",limit:s}:{kind:"message",title:"Context",content:`Unsupported value: ${s}. Choose one of ${i}`}}case $.TOOLS:{let s=r.join(" ").trim(),i=Au(s),a=["none","once","full"].join(", ");return s?i?i===t.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${ms(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
83
- Choose one of: ${a}`}:{kind:"message",title:"Tools",content:`Current: ${ms(t.toolPermissionMode)}
84
- Usage: ${ge($.TOOLS)} <mode>
85
- Modes: ${a}`}}case $.MCP:{let s=Object.keys(t.mcpServers);if(!s.length)return{kind:"message",title:"MCP Servers",content:"No MCP servers configured in current config."};let i=[];i.push(`Total: ${s.length}`),i.push("");for(let[a,l]of Object.entries(t.mcpServers))i.push(`- ${a}`),"url"in l?(i.push(` type: ${l.type??"streamable_http"}`),i.push(` url: ${l.url}`),l.bearer_token_env_var&&i.push(` bearer: ${l.bearer_token_env_var}`)):(i.push(` type: ${l.type??"stdio"}`),i.push(` command: ${l.command}`),l.args?.length&&i.push(` args: ${l.args.join(" ")}`)),i.push("");return{kind:"message",title:"MCP Servers",content:i.join(`
86
- `)}}case $.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${e}
87
- Type ${ge($.HELP)} for available commands.`}}}import{readdir as ku}from"fs/promises";import{join as Pu,relative as Iu,sep as Ru}from"path";var Ou=6,Lu=2500,gs=25,Nu=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),on=new Map;function $u(e){return e.split(Ru).join("/")}function Du(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):Ou,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):Lu,limit:typeof e.limit=="number"?Math.max(1,e.limit):gs,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}function Uu(e,t){let n=e.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>Nu.has(o))||r.endsWith(".log")?!0:t.ignoreGlobs.length?t.ignoreGlobs.some(o=>{let s=o.replace(/\\/g,"/").trim();if(!s)return!1;if(s.endsWith("/**")){let i=s.slice(0,-3);return e.startsWith(i)}if(s.startsWith("*")){let i=s.slice(1);return e.endsWith(i)}return e.includes(s)}):!1}function Hu(e){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,ignoreGlobs:e.ignoreGlobs})}async function Fu(e,t){let n=[],r=async(o,s)=>{if(n.length>=t.maxEntries)return;let i;try{i=await ku(o,{withFileTypes:!0})}catch{return}for(let a of i){if(n.length>=t.maxEntries)break;if(a.isSymbolicLink())continue;let l=Pu(o,a.name),c=Iu(e,l);if(!c)continue;let u=$u(c);if(Uu(u,t))continue;let p=u.split("/").filter(Boolean),y=a.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:p,segmentsLower:p.map(m=>m.toLowerCase()),depth:s,isDir:y}),y&&s<t.maxDepth&&await r(l,s+1)}};return await r(e,0),n.sort((o,s)=>o.path.localeCompare(s.path)),n}async function Bu(e,t){let n=Du(t),r=Hu(n),o=on.get(e);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=Fu(e,n).then(i=>(on.set(e,{entries:i,signature:r}),i)).catch(i=>{throw on.delete(e),i});return on.set(e,{entries:[],signature:r,pending:s}),s}function Wu(e,t){if(!t.length)return e.depth+(e.isDir?-.2:.2);let n=e.depth,r=0;for(let o of t){let s=-1;for(let i=r;i<e.segmentsLower.length;i++){let a=e.segmentsLower[i];if(a.startsWith(o)){s=i,n+=(i-r)*1.2,n+=a.length-o.length;break}let l=a.indexOf(o);if(l!==-1){s=i,n+=(i-r)*2+l+2;break}}if(s===-1)return null;r=s+1}return e.isDir&&(n-=.5),n}function ju(e,t,n){let o=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of e){let a=Wu(i,o);a!==null&&s.push({entry:i,score:a})}return s.sort((i,a)=>{let l=i.score-a.score;return l!==0?l:i.entry.path.localeCompare(a.entry.path)}),s.slice(0,n).map(({entry:i})=>({id:i.path,path:i.path,name:i.segments[i.segments.length-1]??i.path,parent:i.segments.length>1?i.segments.slice(0,-1).join("/"):void 0,isDir:i.isDir}))}async function hs(e){let t=await Bu(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):gs;return ju(t,e.query,n)}import{readdir as zu,readFile as qu,stat as Gu}from"fs/promises";import{basename as Ku,join as sn,resolve as Mt}from"path";function ys(e){let t=Mt(e);return process.platform==="win32"?t.toLowerCase():t}function Vu(e,t){return t?ys(e)===ys(t):!1}function Xu(e){return Ku(e).replace(/\.jsonl$/i,"")}function Ju(e){let t=null,n=null,r=null;for(let o of e.split(`
88
- `)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!(!i||typeof i!="object")){if(i.type==="session_start"&&!r){let a=i.meta?.cwd;typeof a=="string"&&a.trim()&&(r=a);continue}if(i.type==="turn_start"&&!t){let a=typeof i.content=="string"?i.content.trim():"";a&&(t=a)}if(i.type==="session_title"&&!n){let a=typeof i.content=="string"?i.content.trim():"";a&&(n=a)}}}return{firstPrompt:t,sessionTitle:n,sessionCwd:r}}async function Yu(e,t,n){try{let r=await qu(e,"utf8"),{firstPrompt:o,sessionTitle:s,sessionCwd:i}=Ju(r);if(!Vu(t,i))return null;let a=s?.trim()||o?.trim()||Xu(e);return{id:e,cwd:t,input:a,ts:n,sessionFile:e}}catch{return null}}async function Zu(e){let t=async s=>{try{return await zu(s,{withFileTypes:!0})}catch{return[]}},n=(await t(e)).filter(s=>s.isDirectory()&&/^\d{4}$/.test(s.name)),r=[];for(let s of n){let i=sn(e,s.name),a=(await t(i)).filter(l=>l.isDirectory()&&/^\d{2}$/.test(l.name));for(let l of a){let c=sn(i,l.name),u=(await t(c)).filter(p=>p.isDirectory()&&/^\d{2}$/.test(p.name));for(let p of u){let y=sn(c,p.name),m=(await t(y)).filter(h=>h.isFile()&&h.name.endsWith(".jsonl"));for(let h of m)r.push(sn(y,h.name))}}}return(await Promise.all(r.map(async s=>{try{let i=await Gu(s);return{path:s,mtimeMs:i.mtimeMs}}catch{return null}}))).filter(s=>!!s)}async function Ts(e){let t=e.activeSessionFile?Mt(e.activeSessionFile):null,r=(await Zu(e.sessionsDir)).filter(a=>!t||Mt(a.path)!==t).filter((a,l,c)=>c.findIndex(u=>Mt(u.path)===Mt(a.path))===l).sort((a,l)=>l.mtimeMs-a.mtimeMs),o=e.keyword?.trim().toLowerCase(),s=e.limit??10,i=[];for(let a of r){if(i.length>=s)break;let l=await Yu(a.path,e.cwd,a.mtimeMs);l&&(o&&!l.input.toLowerCase().includes(o)||i.push(l))}return i}import{Box as an,Text as ln}from"ink";import{jsx as Ze,jsxs as ep}from"react/jsx-runtime";var Qu="#3a3a3a",cn="#262626";function _s({items:e,activeIndex:t,loading:n}){return n?Ze(an,{paddingX:1,backgroundColor:cn,children:Ze(ln,{color:"gray",children:"Loading..."})}):e.length?Ze(an,{flexDirection:"column",backgroundColor:cn,children:e.map((r,o)=>{let s=o===t;return ep(an,{paddingX:1,gap:2,backgroundColor:s?Qu:cn,children:[Ze(ln,{color:s?"cyan":"white",bold:s,children:r.title}),r.subtitle?Ze(ln,{color:"gray",children:r.subtitle}):null]},r.id)})}):Ze(an,{paddingX:1,backgroundColor:cn,children:Ze(ln,{color:"gray",children:"No matches"})})}import tp from"string-width";var np=55296,rp=56319,op=56320,sp=57343;function Ss(e){return e>=np&&e<=rp}function vs(e){return e>=op&&e<=sp}function xe(e,t){if(!Number.isFinite(t)||t<=0)return 0;if(t>=e.length)return e.length;if(e.length===0)return 0;let n=Math.floor(t);if(n<=0)return 0;if(n>=e.length)return e.length;let r=e.charCodeAt(n),o=e.charCodeAt(n-1);return vs(r)&&Ss(o)?n-1:n}function xs(e,t){let n=xe(e,t);if(n>=e.length)return e.length;let r=e.codePointAt(n);return r===void 0?Math.min(e.length,n+1):Math.min(e.length,n+(r>65535?2:1))}function Qe(e,t){let n=xe(e,t);if(n<=0)return 0;let r=n-1;if(r<=0)return r;let o=e.charCodeAt(r),s=e.charCodeAt(r-1);return vs(o)&&Ss(s)?r-1:r}function un(e,t){let n=xe(e,t),r=e.lastIndexOf(`
89
- `,Math.max(0,n-1));return r===-1?0:r+1}function pn(e,t){let n=xe(e,t),r=e.indexOf(`
90
- `,n);return r===-1?e.length:r}function ip(e){return/[\p{L}\p{N}_]/u.test(e)}function Cs(e,t,n){let r=xe(e,t);return n?{value:`${e.slice(0,r)}${n}${e.slice(r)}`,cursor:r+n.length}:{value:e,cursor:r}}function bs(e,t){let n=xe(e,t);if(n<=0)return{value:e,cursor:n};let r=Qe(e,n);return{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function tr(e,t){let n=xe(e,t);if(n>=e.length)return{value:e,cursor:n};let r=xs(e,n);return{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function Es(e,t){let n=xe(e,t);if(n<=0)return{value:e,cursor:n};let r=n;for(;r>0;){let s=Qe(e,r);if(e.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=Qe(e,r),i=e.slice(s,r);if(!ip(i))break;r=s}return r===n&&(r=Qe(e,n)),{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function As(e,t){let n=xe(e,t),r=un(e,n);return r>=n?{value:e,cursor:n}:{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function ws(e,t){let n=xe(e,t),r=pn(e,n);return r<=n?{value:e,cursor:n}:{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function Ms(e,t){return Qe(e,t)}function ks(e,t){return xs(e,t)}function Ps(e,t){return un(e,t)}function Is(e,t){return pn(e,t)}function nr(e,t,n,r){let o=xe(e,t),s=un(e,o),i=pn(e,o),a=o-s,l=r??a;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:l,changed:!1};let y=s-1,m=un(e,y),h=Math.min(m+l,y);return{cursor:h,preferredColumn:l,changed:h!==o}}if(i>=e.length)return{cursor:o,preferredColumn:l,changed:!1};let c=i+1,u=pn(e,c),p=Math.min(c+l,u);return{cursor:p,preferredColumn:l,changed:p!==o}}function Rs(e,t,n){let r=xe(e,t),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,a=0,l="",c=0,u=()=>{s.push({text:l,start:i,end:a})},p=0;for(let h of e){let d=p;if(p+=h.length,h===`
91
- `){a=d,u(),i=p,a=p,l="",c=0;continue}let E=Math.max(0,tp(h));l.length>0&&c+E>o&&(u(),i=d,a=d,l="",c=0),l+=h,a=p,c+=E}if(u(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let y=Math.max(0,s.length-1),m=(s[y]?.text??"").length;for(let h=0;h<s.length;h+=1){let d=s[h];if(d&&!(r<d.start)&&r<=d.end){y=h,m=r-d.start;break}}return{lines:s,row:y,cursorInRow:m}}function Os(e,t){let n=e==="\b"||e==="\x7F",r=!!t.ctrl&&e.toLowerCase()==="h";return t.backspace||n||r||t.delete&&!(t.ctrl||t.meta)?"backspace":t.delete?"delete":"none"}var ap=3,Ls=8,lp=120,cp=process.platform==="win32"?60:8,kt=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(t={}){this.minChars=t.minChars??ap,this.charIntervalMs=t.charIntervalMs??Ls,this.enterSuppressWindowMs=t.enterSuppressWindowMs??lp,this.activeIdleTimeoutMs=t.activeIdleTimeoutMs??cp}static recommendedFlushDelayMs(){return Ls+1}recommendedActiveFlushDelayMs(){return this.activeIdleTimeoutMs+1}onPlainChar(t,n){let r=Array.from(t)[0]??"";return this.notePlainChar(n),this.active?(this.extendWindow(n),{type:"buffer_append"}):this.pendingFirstChar&&n-this.pendingFirstChar.atMs<=this.charIntervalMs?(this.active=!0,this.buffer+=this.pendingFirstChar.ch,this.pendingFirstChar=null,this.extendWindow(n),{type:"begin_buffer_from_pending"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:r?(this.pendingFirstChar={ch:r,atMs:n},{type:"retain_first_char"}):{type:"retain_first_char"}}onPlainCharNoHold(t){return this.notePlainChar(t),this.active?(this.extendWindow(t),{type:"buffer_append"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:null}flushIfDue(t){let n=this.isActiveInternal()?this.activeIdleTimeoutMs:this.charIntervalMs;if(!(this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs>n))return{type:"none"};if(this.isActiveInternal()){this.active=!1;let o=this.buffer;return this.buffer="",{type:"paste",text:o}}if(this.pendingFirstChar){let o=this.pendingFirstChar.ch;return this.pendingFirstChar=null,{type:"typed",text:o}}return{type:"none"}}appendNewlineIfActive(t){return this.isActiveInternal()?(this.buffer+=`
92
- `,this.extendWindow(t),!0):!1}newlineShouldInsertInsteadOfSubmit(t){let n=this.burstWindowUntilMs!==null&&t<=this.burstWindowUntilMs;return this.isActiveInternal()||n}extendWindow(t){this.burstWindowUntilMs=t+this.enterSuppressWindowMs}beginWithRetroGrabbed(t,n){t&&(this.buffer+=t),this.active=!0,this.extendWindow(n)}appendCharToBuffer(t,n){t&&(this.buffer+=t,this.extendWindow(n))}decideBeginBuffer(t,n,r){let o=up(n,r),s=n.slice(o);return/\s/u.test(s)||Array.from(s).length>=16?(this.beginWithRetroGrabbed(s,t),{start:o,grabbed:s}):null}flushBeforeModifiedInput(){if(!this.isActive())return null;this.active=!1;let t=this.buffer;return this.buffer="",this.pendingFirstChar&&(t+=this.pendingFirstChar.ch,this.pendingFirstChar=null),t}clearWindowAfterNonChar(){this.consecutivePlainChars=0,this.lastPlainCharAtMs=null,this.burstWindowUntilMs=null,this.active=!1,this.pendingFirstChar=null}isActive(){return this.isActiveInternal()||this.pendingFirstChar!==null}isBuffering(){return this.isActiveInternal()}hasPendingFirstChar(){return this.pendingFirstChar!==null}clearAfterExplicitPaste(){this.lastPlainCharAtMs=null,this.consecutivePlainChars=0,this.burstWindowUntilMs=null,this.active=!1,this.buffer="",this.pendingFirstChar=null}notePlainChar(t){this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs<=this.charIntervalMs?this.consecutivePlainChars+=1:this.consecutivePlainChars=1,this.lastPlainCharAtMs=t}isActiveInternal(){return this.active||this.buffer.length>0}};function up(e,t){if(t<=0)return e.length;let n=e.length,r=t;for(;r>0&&n>0;)n=Qe(e,n),r-=1;return n}import{jsx as mt,jsxs as $s}from"react/jsx-runtime";var mp=400,or=ge($.MODELS),sr=ge($.CONTEXT),ir=ge($.TOOLS),fp=ge($.INIT),gp=[{mode:H.NONE,description:"Disable all tool calls"},{mode:H.ONCE,description:"Require approval when needed"},{mode:H.FULL,description:"Run tools without approval"}];function hp(e){let t=e.lastIndexOf("@");if(t===-1)return null;if(t>0){let r=e[t-1];if(r&&!/\s/.test(r))return null}let n=e.slice(t+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:t+1}}function yp(e){let t=e.trimStart(),n=e.length-t.length;if(!t.length)return null;let r=t;if(r.startsWith("/")&&(r=r.slice(1)),!r.toLowerCase().startsWith($.RESUME)||e.slice(0,n).trim().length>0)return null;let s=r.slice($.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function Tp(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1);return n.includes(" ")?null:n.length?/^[a-zA-Z-]+$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:null:{type:"slash",keyword:""}}function _p(e){let t=e.trimStart();if(!t.startsWith(or))return null;let n=t.slice(or.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function Sp(e){let t=e.trimStart();if(!t.startsWith(sr))return null;let n=t.slice(sr.length);return n&&!n.startsWith(" ")?null:{type:"context"}}function vp(e){let t=e.trimStart();if(!t.startsWith(ir))return null;let n=t.slice(ir.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function xp(e){return vp(e)??Sp(e)??_p(e)??Tp(e)??hp(e)??yp(e)}function Cp(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getFullYear()),r=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${s}:${i}`}function bp(e,t){return{mode:"model",items:e.filter(r=>{if(!t)return!0;let o=r.name.toLowerCase(),s=r.model.toLowerCase();return o.includes(t)||s.includes(t)}).map(r=>({id:r.name,title:`${r.name}: ${r.model}`,subtitle:r.base_url,kind:"model",value:`${or} ${r.name}`,meta:{type:"model",provider:r}}))}}function Ep(e){return{mode:"context",items:dt.map(n=>({id:`${n}`,title:`${Math.floor(n/1e3)}k tokens`,subtitle:n===e?"Current":void 0,kind:"context",value:`${sr} ${Math.floor(n/1e3)}k`,meta:{type:"context",value:n}}))}}function Ap(e){return{mode:"tools",items:gp.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===e?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${ir} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function wp(e){return{mode:"slash",items:rn.filter(n=>n.name.startsWith(e)).map(n=>({id:n.name,title:`/${n.name}`,subtitle:n.description,kind:"slash",value:`/${n.name}`,meta:{type:"slash"}}))}}async function Mp({trigger:e,cwd:t,sessionsDir:n,currentSessionFile:r,providers:o,contextLimit:s,toolPermissionMode:i}){switch(e.type){case"file":return{mode:"file",items:(await hs({cwd:t,query:e.query,limit:8})).map(c=>({id:c.id,title:c.isDir?`${c.path}/`:c.path,kind:"file",value:c.isDir?`${c.path}/`:c.path,meta:{type:"file",isDir:c.isDir}}))};case"history":return{mode:"history",items:(await Ts({sessionsDir:n,cwd:t,keyword:e.keyword,activeSessionFile:r})).map(c=>({id:c.id,title:c.input,subtitle:Cp(c.ts),kind:"history",value:c.input,meta:{type:"history",entry:c}}))};case"models":return bp(o,e.keyword);case"context":return Ep(s);case"tools":return Ap(i);case"slash":return wp(e.keyword)}}function Ds({disabled:e,busy:t,history:n,cwd:r,sessionsDir:o,currentSessionFile:s,providers:i,configPath:a,providerName:l,model:c,contextLimit:u,toolPermissionMode:p,mcpServers:y,onSubmit:m,onExit:h,onClear:d,onNewSession:E,onCancelRun:v,onHistorySelect:S,onModelSelect:W,onSetContextLimit:ee,onSetToolPermission:q,onSystemMessage:V}){let{stdout:he}=dp(),[A,F]=Ge({value:"",cursor:0}),w=Pt(A),P=Pt(null),[ue,we]=Ge(null),[te,M]=Ge(""),[R,ne]=Ge("none"),[se,Be]=Ge([]),[Me,pe]=Ge(0),[ke,Xe]=Ge(!1),[Le,k]=Ge(!1),Y=Pt(0),nt=Pt(0),G=Pt(new kt);dn(()=>{w.current=A,k(!1)},[A]);let _n=Ns(()=>({configPath:a,providerName:l,model:c,mcpServers:y,providers:i,contextLimit:u,toolPermissionMode:p}),[a,l,c,y,i,u,p]),j=Ns(()=>e||Le?null:xp(A.value),[e,A.value,Le]),z=et((T=!0)=>{T&&k(!0),ne("none"),Be([]),pe(0),Xe(!1)},[]),O=et((T,x=!1)=>{w.current=T,F(T),x&&(we(null),M(""))},[]),Pe=et(()=>{O({value:"",cursor:0},!0)},[O]),ie=et((T,x=!0)=>{if(!T)return;let U=w.current;P.current=null;let Z=Cs(U.value,U.cursor,T);O(Z,x),T.includes(`
93
- `)&&z(!1)},[O,z]),K=et(T=>T.type==="none"?!1:T.type==="paste"?(T.text&&ie(T.text,!0),!0):(ie(T.text,!0),!0),[ie]),Ce=et((T=!0)=>{let x=G.current.flushBeforeModifiedInput();return x&&ie(x,!0),T&&G.current.clearWindowAfterNonChar(),!!x},[ie]);dn(()=>{let T=setInterval(()=>{let x=G.current.flushIfDue(Date.now());K(x)},kt.recommendedFlushDelayMs());return()=>{clearInterval(T)}},[K]),dn(()=>{e&&z(!1)},[e,z]),dn(()=>{if(!j){z(!1);return}let T=!1,x=++Y.current;return Xe(!0),(async()=>{try{let{mode:U,items:Z}=await Mp({trigger:j,cwd:r,sessionsDir:o,currentSessionFile:s,providers:i,contextLimit:u,toolPermissionMode:p});if(T||x!==Y.current)return;ne(U),Be(Z),pe(ye=>Z.length?Math.min(ye,Z.length-1):0)}finally{!T&&x===Y.current&&Xe(!1)}})(),()=>{T=!0}},[j,r,o,s,i,u,p,z]);let We=et(T=>{if(T){if(R==="file"&&j?.type==="file"){let x=w.current.value,U=x.slice(0,j.tokenStart),Z=x.slice(j.tokenStart+j.query.length),ye=`${U}${T.value}${Z}`,Ie=U.length+T.value.length;O({value:ye,cursor:Ie},!0),T.meta?.type==="file"&&T.meta.isDir||z();return}switch(T.meta?.type){case"history":S(T.meta.entry),O({value:T.value,cursor:T.value.length},!1),z();return;case"model":W(T.meta.provider),Pe(),z();return;case"context":ee(T.meta.value),Pe(),z();return;case"tools":q(T.meta.mode),Pe(),z();return;case"slash":O({value:`${T.value} `,cursor:`${T.value} `.length},!0),z(!1);return;default:O({value:T.value,cursor:T.value.length},!0),z()}}},[O,R,j,z,Pe,S,W,ee,q]);pp((T,x)=>{if(x.ctrl&&T==="c"){h();return}if(e)return;let U=Date.now();K(G.current.flushIfDue(U));let Z=R!=="none",ye=Z&&se.length>0,Ie=Os(T,x),Sn=!!(x.ctrl||x.meta),rt=!!T&&!Sn&&!x.return&&!x.tab&&Ie==="none"&&!x.escape&&!x.upArrow&&!x.downArrow&&!x.leftArrow&&!x.rightArrow;if(!rt&&!x.return&&Ce(!0),x.ctrl&&T==="a"){let C=w.current,L=Ps(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.ctrl&&T==="e"){let C=w.current,L=Is(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.ctrl&&T==="u"){let C=w.current,L=As(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="k"){let C=w.current,L=ws(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="w"){let C=w.current,L=Es(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="d"){let C=w.current;if(!C.value){h();return}let L=tr(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="l"){O({value:"",cursor:0},!0),z(),d(),E();return}if(x.escape){if(U-nt.current<=mp){nt.current=0,t?v():(P.current=null,O({value:"",cursor:0},!0),z());return}nt.current=U,Z&&z();return}if(x.upArrow){if(ye){pe(D=>D<=0?se.length-1:D-1);return}let C=w.current;if(C.value.includes(`
94
- `)){let D=nr(C.value,C.cursor,"up",P.current??void 0);if(D.changed){P.current=D.preferredColumn,O({value:C.value,cursor:D.cursor},!1);return}}if(!n.length)return;if(ue===null){M(C.value);let D=n.length-1;we(D);let Re=n[D]??"";P.current=null,O({value:Re,cursor:Re.length},!1);return}let L=Math.max(0,ue-1);we(L);let ae=n[L]??"";P.current=null,O({value:ae,cursor:ae.length},!1);return}if(x.downArrow){if(ye){pe(D=>(D+1)%se.length);return}let C=w.current;if(C.value.includes(`
95
- `)){let D=nr(C.value,C.cursor,"down",P.current??void 0);if(D.changed){P.current=D.preferredColumn,O({value:C.value,cursor:D.cursor},!1);return}}if(ue===null)return;let L=ue+1;if(L>=n.length){we(null),P.current=null,O({value:te,cursor:te.length},!1),M("");return}we(L);let ae=n[L]??"";P.current=null,O({value:ae,cursor:ae.length},!1);return}if(x.leftArrow){let C=w.current,L=Ms(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.rightArrow){let C=w.current,L=ks(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.tab&&ye){We(se[Me]);return}if(x.return){if(ye){We(se[Me]);return}G.current.hasPendingFirstChar()&&!G.current.isBuffering()&&Ce(!1);let C=w.current.value.trimStart().startsWith("/");if(!x.shift&&!C){if(G.current.appendNewlineIfActive(U))return;if(G.current.newlineShouldInsertInsteadOfSubmit(U)){Ce(!1),ie(`
96
- `,!0),G.current.extendWindow(U);return}}if(Ce(!0),x.shift){ie(`
97
- `,!0);return}let ae=w.current.value.trim();if(!ae)return;if(ae.startsWith("/")){let D=fs(ae,_n);D.kind==="message"?V(D.title,D.content):D.kind==="new"?E():D.kind==="exit"?h():D.kind==="switch_model"?W(D.provider):D.kind==="set_context_limit"?ee(D.limit):D.kind==="set_tool_permission"?q(D.mode):D.kind==="init_agents_md"&&m(fp),P.current=null,O({value:"",cursor:0},!0),z(!1);return}m(ae),P.current=null,O({value:"",cursor:0},!0),z(!1);return}if(Ie!=="none"){let C=w.current,L=Ie==="backspace"?bs(C.value,C.cursor):tr(C.value,C.cursor);P.current=null,O(L,!0);return}if(T&&rt){let C=Array.from(T);if(C.length!==1){Ce(!1),ie(T,!0),G.current.clearAfterExplicitPaste();return}let L=C[0]??"";if(!L)return;let ae=je=>{let ot=w.current,Ht=ot.value.slice(0,ot.cursor),vn=ot.value.slice(ot.cursor),ht=G.current.decideBeginBuffer(U,Ht,je);return ht?(P.current=null,O({value:`${Ht.slice(0,ht.start)}${vn}`,cursor:ht.start},!0),G.current.appendCharToBuffer(L,U),!0):!1};if(!((L.codePointAt(0)??0)<=127)){let je=G.current.onPlainCharNoHold(U);if(je?.type==="buffer_append"){G.current.appendCharToBuffer(L,U);return}if(je?.type==="begin_buffer"&&ae(je.retroChars))return;Ce(!1),ie(L,!0);return}let Re=G.current.onPlainChar(L,U);if(Re.type==="retain_first_char")return;if(Re.type==="buffer_append"||Re.type==="begin_buffer_from_pending"){G.current.appendCharToBuffer(L,U);return}if(Re.type==="begin_buffer"&&ae(Re.retroChars))return;Ce(!1),ie(L,!0);return}T&&(ie(T,!0),G.current.clearWindowAfterNonChar())});let Dt=he?.columns??process.stdout?.columns??80,X=Math.max(1,Dt-3),b=Rs(A.value,A.cursor,X),Ut=b.lines;return $s(rr,{flexDirection:"column",gap:1,children:[mt(rr,{flexDirection:"column",paddingY:1,children:Ut.map((T,x)=>{let U=T.text,Z=!e&&x===b.row,ye=Z?U.slice(0,b.cursorInRow):U,Ie=Z?U.slice(b.cursorInRow):"";return $s(rr,{children:[mt(mn,{color:"gray",children:x===0?"\u203A ":" "}),mt(mn,{children:ye}),Z?mt(mn,{color:"cyan",children:"\u258A"}):null,Z?mt(mn,{children:Ie}):null]},`line-${x}`)})}),R!=="none"?mt(_s,{items:se.map(({value:T,meta:x,...U})=>U),activeIndex:Me,loading:ke}):null]})}import{Box as kp,Text as Us}from"ink";import{jsx as Pp,jsxs as Hs}from"react/jsx-runtime";function Fs({busy:e,pendingApproval:t=!1,contextPercent:n,tokenLine:r}){let o=`${n.toFixed(1)}%`;return Hs(kp,{justifyContent:"space-between",children:[Pp(Us,{color:"gray",children:t?"Approval pending \u2022 \u2191/\u2193 select \u2022 Enter confirm \u2022 Esc deny":e?"Working... Esc Esc to interrupt":"Enter send \u2022 Shift+Enter newline \u2022 /help"}),Hs(Us,{color:"gray",children:[r?`${r} \u2022 `:"","context: ",o]})]})}import{useState as Ip}from"react";import{Box as Bs,Text as fn,useInput as Rp}from"ink";import{jsx as ar,jsxs as lr}from"react/jsx-runtime";var Op=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function Lp(e){if(!e)return"";if(typeof e!="object")return String(e);let t=Object.entries(e);if(!t.length)return"";let[n,r]=t[0]??[];if(!n)return"";let o=typeof r=="string"?r:JSON.stringify(r);return`${n}=${o?.slice(0,60)??""}${o&&o.length>60?"...":""}`}function Ws({request:e,onDecision:t}){let[n,r]=Ip(0),o=Op;Rp((i,a)=>{if(a.upArrow){r(l=>l<=0?o.length-1:l-1);return}if(a.downArrow){r(l=>(l+1)%o.length);return}if(a.return){let l=o[n];l&&t(l.decision);return}(a.escape||a.ctrl&&i==="c")&&t("deny")});let s=Lp(e.params);return lr(Bs,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[ar(fn,{bold:!0,color:"yellow",children:"Tool Approval Required"}),lr(fn,{children:[e.toolName,s?` (${s})`:""]}),ar(fn,{color:"gray",children:e.reason}),ar(Bs,{marginTop:1,flexDirection:"column",children:o.map((i,a)=>lr(fn,{color:n===a?"green":"gray",children:[n===a?"> ":" ",i.label]},i.decision))})]})}import{useMemo as js,useState as cr}from"react";import{Box as ur,Text as ft,useInput as Np}from"ink";import{jsx as gn,jsxs as It}from"react/jsx-runtime";function $p(e,t){let n=new Set(e);return t.filter(r=>n.has(r))}function zs({serverNames:e,defaultSelected:t,onConfirm:n,onExit:r}){let o=js(()=>{let m=$p(e,t);return t.length===0?[]:m.length>0?m:[...e]},[t,e]),[s,i]=cr(o),[a,l]=cr(0),[c,u]=cr(!0),p=js(()=>new Set(s),[s]),y=s.length===e.length;return Np((m,h)=>{if(h.ctrl&&m==="c"){r();return}if(h.upArrow){l(d=>d<=0?e.length-1:d-1);return}if(h.downArrow){l(d=>(d+1)%e.length);return}if(h.return){n(s,c);return}if(m===" "){let d=e[a];if(!d)return;i(E=>{let v=new Set(E);return v.has(d)?v.delete(d):v.add(d),e.filter(S=>v.has(S))});return}if(m.toLowerCase()==="a"){i([...e]);return}if(m.toLowerCase()==="n"){i([]);return}if(m.toLowerCase()==="p"){u(d=>!d);return}h.escape&&n(s,c)}),It(ur,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[gn(ft,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),gn(ft,{color:"gray",children:"Select servers to load for this run."}),gn(ur,{marginTop:1,flexDirection:"column",children:e.map((m,h)=>{let d=p.has(m);return It(ft,{color:h===a?"green":"gray",children:[h===a?"> ":" ","[",d?"x":" ","] ",m]},m)})}),It(ur,{marginTop:1,flexDirection:"column",children:[It(ft,{color:"gray",children:["Selected: ",s.length,"/",e.length,y?" (all)":""]}),It(ft,{color:"gray",children:["Persist as default: ",c?"yes":"no"]}),gn(ft,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, A all, N none, P persist, Enter confirm"})]})]})}import{spawn as Dp}from"child_process";var pr="\x07",Up="Memo: Approval required",Hp="Memo CLI",Fp=2e3;function Bp(e){return e.replace(/\s+/g," ").trim()}function Wp(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function jp(e){let t=Bp(e.reason),n=`Tool ${e.toolName} is waiting for your approval.`;return t?Wp(`${n} ${t}`,220):n}function qs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function zp(e,t=process.platform){let n=Up,r=jp(e);return t==="darwin"?{command:"osascript",args:["-e",`display notification "${qs(r)}" with title "${qs(n)}"`]}:t==="linux"?{command:"notify-send",args:["--app-name",Hp,n,r]}:null}async function qp(e,t){await new Promise((n,r)=>{let o=Dp(e,t,{stdio:"ignore"}),s=!1,i=l=>{if(!s){if(s=!0,l){r(l);return}n()}},a=setTimeout(()=>{try{o.kill()}catch{}i()},Fp);o.once("error",l=>{clearTimeout(a),i(l)}),o.once("exit",l=>{if(clearTimeout(a),l===0||l===null){i();return}i(new Error(`${e} exited with code ${l}`))})})}function Gp(e){if(e){e(pr);return}try{if(process.stdout?.isTTY){process.stdout.write(pr);return}process.stderr?.isTTY&&process.stderr.write(pr)}catch{}}async function Gs(e,t={}){Gp(t.writeBell);let n=zp(e,t.platform??process.platform);if(!n)return;let r=t.runCommand??qp;try{await r(n.command,n.args)}catch{}}import{Box as Rt,Text as Ae,useInput as Kp}from"ink";import{useCallback as Ks,useMemo as Vp,useState as Ot}from"react";import{jsx as Oe,jsxs as gt}from"react/jsx-runtime";var Ke=[{key:"name",label:"Provider name",hint:"Used for /models switching",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Read at runtime from environment variables",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",defaultValue:"https://api.deepseek.com"}];function Vs({configPath:e,onComplete:t,onExit:n}){let[r,o]=Ot(0),[s,i]=Ot(""),[a,l]=Ot({}),[c,u]=Ot(!1),[p,y]=Ot(null),m=Ke[r]??Ke[0],h=Ks(async v=>{u(!0),y(null);try{let S={current_provider:v.name,providers:[{name:v.name,env_api_key:v.envKey,model:v.model,base_url:v.baseUrl||void 0}]};await Se(e,S),t()}catch(S){y(S.message),u(!1)}},[e,t]),d=Ks(async()=>{if(!m)return;let v=s.trim()||m.defaultValue,S={...a,[m.key]:v};if(l(S),i(""),r<Ke.length-1){o(r+1);return}let W={name:S.name||Ke[0].defaultValue,envKey:S.envKey||Ke[1].defaultValue,model:S.model||Ke[2].defaultValue,baseUrl:S.baseUrl||Ke[3].defaultValue};await h(W)},[s,h,m,r,a]);Kp((v,S)=>{if(!c){if(S.ctrl&&v==="c"){n();return}if(S.return){d();return}if(S.backspace||S.delete){i(W=>W.slice(0,-1));return}v&&i(W=>W+v)}});let E=Vp(()=>`Step ${r+1}/${Ke.length}`,[r]);return m?gt(Rt,{flexDirection:"column",children:[Oe(Ae,{bold:!0,children:"Memo setup"}),Oe(Ae,{color:"gray",children:"No provider config found. Complete setup to continue."}),gt(Ae,{color:"gray",children:["Config path: ",e]}),gt(Rt,{marginTop:1,flexDirection:"column",children:[Oe(Ae,{color:"cyan",children:E}),Oe(Ae,{children:m.label}),gt(Ae,{color:"gray",children:["Default: ",m.defaultValue]}),m.hint?Oe(Ae,{color:"gray",children:m.hint}):null]}),gt(Rt,{marginTop:1,children:[Oe(Ae,{children:"> "}),Oe(Ae,{children:s})]}),Oe(Rt,{marginTop:1,children:Oe(Ae,{color:"gray",children:"Enter to continue, Ctrl+C to exit."})}),p?Oe(Rt,{marginTop:1,children:gt(Ae,{color:"red",children:["Failed to save config: ",p]})}):null]}):null}function Xs(e){let t=[],n=[],r=[],o=e.split(`
98
- `).map(l=>l.trim()).filter(Boolean),s=null,i=0,a=0;for(let l of o){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&&(t.push({role:"user",content:u}),r.push(`User: ${u}`)),i+=1;continue}if(c.type==="assistant"){let u=typeof c.content=="string"?c.content:"";if(u&&(t.push({role:"assistant",content:u}),r.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:"",y=u.input,m=typeof u.thinking=="string"?u.thinking:"",d=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(v=>{let S=typeof v?.name=="string"?v.name:"";return S?{tool:S,input:v?.input}:null}).filter(Boolean),E=s.steps[s.steps.length-1];E&&(d.length>1?(E.action=d[0],E.parallelActions=d):p&&(E.action={tool:p,input:y}),m&&(E.thinking=m))}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:r.join(`
99
- `),messages:t,turns:n,maxSequence:a}}function mr(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function Xp(e,t){return{index:e,userInput:"",steps:[],sequence:t}}function dr(e,t){let n=e.slice();for(;n.length<=t;)n.push({index:n.length,assistantText:""});return n}function Lt(e,t,n){let r=e.turns.slice(),o=r.findIndex(i=>i.index===t);if(o===-1){let i=e.sequence+1;return r.push(n(Xp(t,i))),{turns:r,sequence:i}}let s=r[o];return s?(r[o]=n(s),{turns:r,sequence:e.sequence}):{turns:r,sequence:e.sequence}}function Jp(e){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:e.title,content:e.content,tone:e.tone??"info",sequence:e.sequence}}function Js(e,t){switch(t.type){case"append_system_message":{let n=e.sequence+1;return{...e,sequence:n,systemMessages:[...e.systemMessages,Jp({title:t.title,content:t.content,tone:t.tone,sequence:n})]}}case"turn_start":{let n=Lt(e,t.turn,r=>({...r,index:t.turn,userInput:t.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:t.promptTokens??r.contextPromptTokens}));return{...e,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Lt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,assistantText:`${s.assistantText}${t.chunk}`},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Lt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,action:t.action,thinking:t.thinking,parallelActions:t.parallelActions&&t.parallelActions.length>1?t.parallelActions:void 0,toolStatus:Fe.EXECUTING},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Lt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,observation:t.observation,toolStatus:t.toolStatus,parallelToolStatuses:t.parallelToolStatuses},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=Lt(e,t.turn,r=>{let o=r.startedAt??Date.now(),s=Math.max(0,Date.now()-o),i=t.tokenUsage?.prompt??r.contextPromptTokens;return{...r,finalText:t.finalText,status:t.status,errorMessage:t.errorMessage,tokenUsage:t.turnUsage,contextPromptTokens:i,startedAt:o,durationMs:s}});return{...e,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...e,historicalTurns:t.turns,sequence:Math.max(e.sequence,t.maxSequence)};case"clear_current_timeline":return{...e,turns:[],systemMessages:[]};case"reset_all":return mr();default:return e}}import{dirname as hn,join as Zs,resolve as Yp}from"path";import{statSync as Zp,existsSync as Qs,readFileSync as Qp}from"fs";import{readFile as ed}from"fs/promises";import{get as td}from"https";import{fileURLToPath as nd}from"url";function Ys(e){let t=e.trim().replace(/^v/i,""),[n="",r]=t.split("-",2),o=n.split(".").map(s=>Number(s));return o.length<3||o.some(s=>!Number.isFinite(s))?null:{major:o[0]??0,minor:o[1]??0,patch:o[2]??0,prerelease:r??null}}function rd(e,t){let n=Ys(e),r=Ys(t);return!n||!r?!1:n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch!==r.patch?n.patch>r.patch:n.prerelease&&!r.prerelease?!1:!n.prerelease&&r.prerelease?!0:n.prerelease&&r.prerelease?n.prerelease>r.prerelease:!1}function ei(){try{let t=nd(import.meta.url);return hn(t)}catch{}let e=Yp(process.argv[1]??process.cwd());try{return Zp(e).isFile()?hn(e):e}catch{return process.cwd()}}async function od(e){let t=Zs(e,"package.json");if(!Qs(t))return null;let n=await ed(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function sd(e){let t=Zs(e,"package.json");if(!Qs(t))return null;try{let n=Qp(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function id(){let e=ei();for(;;){let t=await od(e);if(t&&t.name==="@memo-code/memo")return t;let n=hn(e);if(n===e)break;e=n}return null}function yn(){let e=ei();for(;;){let t=sd(e);if(t&&t.name==="@memo-code/memo")return t;let n=hn(e);if(n===e)break;e=n}return null}async function ad(e,t=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(o=>{let s=td(r,{timeout:t},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));o(l.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function ti(){let e=await id();if(!e)return null;let t=await ad(e.name);return!t||!rd(t,e.version)?null:{current:e.version,latest:t}}import{jsx as Ve,jsxs as gd}from"react/jsx-runtime";function dd(e,t){if(e.length===0)return[];if(t===void 0)return[...e];if(t.length===0)return[];let n=new Set(e),r=t.filter(o=>n.has(o));return r.length>0?r:[...e]}function md(e,t){if(e.length===0)return[];if(t.length===0)return[];let n=new Set(e);return t.filter(r=>n.has(r))}function fd(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function ri({sessionOptions:e,providerName:t,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:u}=pd(),p=$t(()=>Object.keys(o??{}).sort(),[o]),y=$t(()=>dd(p,e.activeMcpServers),[p,e.activeMcpServers]),m=e.toolPermissionMode??(l?H.FULL:H.ONCE),[h,d]=cd(Js,void 0,mr),[E,v]=re(t),[S,W]=re(n),[ee,q]=re(a),[V,he]=re(m),[A,F]=re({...e,providerName:t,dangerous:m===H.FULL,toolPermissionMode:m}),[w,P]=re(!1),[ue,we]=re([]),[te,M]=re(null),[R,ne]=re(null),[se,Be]=re(e.maxPromptTokens??ps),[Me,pe]=re(0),[ke,Xe]=re(c),[Le,k]=re(!c&&p.length>0),[Y,nt]=re(y),[G,_n]=re(null),[j,z]=re(null),O=Tn(null),Pe=Tn(null),ie=Tn(null),[K,Ce]=re(null),We=Tn(null),Dt=$t(()=>yn(),[]),X=J(g=>{d(g)},[]);Nt(()=>{ke||(nt(y),k(p.length>0))},[ke,y,p.length]);let b=J((g,_,I="info")=>{X({type:"append_system_message",title:g,content:_,tone:I})},[X]),Ut=$t(()=>({onAssistantStep:(g,_)=>{let I=Pe.current;I&&X({type:"assistant_chunk",turn:I,step:_,chunk:g})},requestApproval:V===H.FULL||V===H.NONE?void 0:g=>new Promise(_=>{Gs(g),Ce(g),We.current=_}),hooks:{onTurnStart:({turn:g,input:_,promptTokens:I})=>{Pe.current=g;let Te=ie.current;Te&&(ie.current=null);let Je=Te??_;I&&I>0&&pe(I),X({type:"turn_start",turn:g,input:Je,promptTokens:I})},onAction:({turn:g,step:_,action:I,thinking:Te,parallelActions:Je})=>{X({type:"tool_action",turn:g,step:_,action:I,thinking:Te,parallelActions:Je})},onObservation:({turn:g,step:_,observation:I,resultStatus:Te,parallelResultStatuses:Je})=>{X({type:"tool_observation",turn:g,step:_,observation:I,toolStatus:Yn(Te),parallelToolStatuses:Jo(Je)})},onFinal:({turn:g,finalText:_,status:I,errorMessage:Te,turnUsage:Je,tokenUsage:ui})=>{X({type:"turn_final",turn:g,finalText:_,status:I,errorMessage:Te,turnUsage:Je,tokenUsage:ui}),P(!1)}}}),[X,V]);Nt(()=>{let g=!1;return(async()=>{if(!(ke||Le))try{let _=O.current;_&&await _.close();let I=await en(Ut,A);if(g){await I.close();return}O.current=I,z(I),M(I.historyFilePath??null)}catch(_){if(g)return;O.current=null,z(null),M(null),P(!1),b("Session",`Failed to create session: ${_.message}`,"error")}})(),()=>{g=!0}},[b,Ut,Le,A,ke]),Nt(()=>{let g=!1;return(async()=>{let _=await ti();g||!_||b("Update",`Update available: v${_.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{g=!0}},[b]),Nt(()=>()=>{O.current&&O.current.close()},[]);let T=J(async()=>{let g=We.current;g&&(g("deny"),We.current=null),K&&Ce(null),O.current&&await O.current.close(),_n("Bye!"),setTimeout(()=>u(),250)},[u,K]),x=J(()=>{if(w){b("Clear","Cancel current run before clearing timeline.","warning");return}if(K){b("Clear","Resolve current approval request before clearing timeline.","warning");return}X({type:"clear_current_timeline"}),ne(null),pe(0),fd()},[b,w,X,K]),U=J(()=>{if(w){b("New Session","Cancel current run before starting a new session.","warning");return}if(K){b("New Session","Resolve current approval request before starting a new session.","warning");return}X({type:"reset_all"}),ne(null),pe(0),Pe.current=null,F(g=>({...g,sessionId:tt()})),b("New Session","Started a fresh session.")},[b,w,X,K]),Z=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,current_provider:g})}catch(_){b("Config",`Failed to persist provider: ${_.message}`,"warning")}},[b]),ye=J(async g=>{if(w){b("Model switch","Cancel current run before switching models.","warning");return}if(g.name===E&&g.model===S){b("Model switch",`Already using ${g.name} (${g.model}).`);return}X({type:"reset_all"}),pe(0),Pe.current=null,v(g.name),W(g.model),F(_=>({..._,sessionId:tt(),providerName:g.name})),await Z(g.name),b("Model switch",`Switched to ${g.name} (${g.model}).`)},[b,w,S,E,X,Z]),Ie=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,max_prompt_tokens:g})}catch(_){b("Context",`Failed to persist context limit: ${_.message}`,"warning")}},[b]),Sn=J(g=>{if(w){b("Context","Cancel current run before changing context window.","warning");return}if(K){b("Context","Resolve current approval request before changing context window.","warning");return}Be(g),pe(0),F(_=>({..._,maxPromptTokens:g,sessionId:tt()})),b("Context",`Context window set to ${Math.floor(g/1e3)}k.`),Ie(g)},[b,w,K,Ie]),rt=J(g=>g===H.NONE?"none (no tools)":g===H.ONCE?"once (approval required)":"full (no approval)",[]),C=J(g=>{if(w){b("Tools","Cancel current run before changing tool permission mode.","warning");return}if(K){b("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(g===V){b("Tools",`Already using ${rt(g)}.`);return}he(g),F(_=>({..._,sessionId:tt(),dangerous:g===H.FULL,toolPermissionMode:g})),b("Tools",`Tool permission set to ${rt(g)}.`)},[b,w,K,rt,V]),L=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,active_mcp_servers:g})}catch(_){b("MCP",`Failed to persist active MCP servers: ${_.message}`,"warning")}},[b]),ae=J((g,_)=>{let I=md(p,g);nt(I),k(!1),F(Te=>({...Te,sessionId:tt(),activeMcpServers:I})),_&&L(I)},[p,L]),D=J(async g=>{if(w){b("History","Cancel current run before loading session history.","warning");return}if(K){b("History","Resolve current approval request before loading session history.","warning");return}try{let _=await ld(g.sessionFile,"utf8"),I=Xs(_);X({type:"clear_current_timeline"}),X({type:"replace_history",turns:I.turns,maxSequence:I.maxSequence}),ne(I.messages),P(!1),z(null),M(null),pe(0),Pe.current=null,F(Te=>({...Te,sessionId:tt()})),b("History",I.summary||g.input)}catch(_){b("History",`Failed to load ${g.sessionFile}: ${_.message}`,"error")}},[b,w,X,K]),Re=J(()=>{w&&j?.cancelCurrentTurn?.()},[w,j]),je=J(async()=>{if(!j||w)return;let g=`Please analyze the current project and create an AGENTS.md file at the project root.
80
+ `)}`}}case $.CONTEXT:{let s=qp(r[0]),i=ht.map(a=>`${Math.floor(a/1e3)}k`).join(", ");return s===null?{kind:"message",title:"Context",content:`Current: ${(e.contextLimit/1e3).toFixed(0)}k
81
+ Usage: ${he($.CONTEXT)} <length>
82
+ Choices: ${i}`}:ht.includes(s)?{kind:"set_context_limit",limit:s}:{kind:"message",title:"Context",content:`Unsupported value: ${s}. Choose one of ${i}`}}case $.TOOLS:{let s=r.join(" ").trim(),i=Gp(s),a=["none","once","full"].join(", ");return s?i?i===e.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${ri(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
83
+ Choose one of: ${a}`}:{kind:"message",title:"Tools",content:`Current: ${ri(e.toolPermissionMode)}
84
+ Usage: ${he($.TOOLS)} <mode>
85
+ Modes: ${a}`}}case $.MCP:{let s=Object.keys(e.mcpServers);if(!s.length)return{kind:"message",title:"MCP Servers",content:"No MCP servers configured in current config."};let i=[];i.push(`Total: ${s.length}`),i.push("");for(let[a,l]of Object.entries(e.mcpServers))i.push(`- ${a}`),"url"in l?(i.push(` type: ${l.type??"streamable_http"}`),i.push(` url: ${l.url}`),l.bearer_token_env_var&&i.push(` bearer: ${l.bearer_token_env_var}`)):(i.push(` type: ${l.type??"stdio"}`),i.push(` command: ${l.command}`),l.args?.length&&i.push(` args: ${l.args.join(" ")}`)),i.push("");return{kind:"message",title:"MCP Servers",content:i.join(`
86
+ `)}}case $.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${t}
87
+ Type ${he($.HELP)} for available commands.`}}}var hi=Xr(mi(),1);import{existsSync as kr,statSync as md}from"fs";import{readFile as fd,readdir as gd}from"fs/promises";import{dirname as fi,join as _n,relative as gi,resolve as hd,sep as yd}from"path";var _d=6,Sd=2500,yi=25,Td=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),yn=new Map,Pr=new Map;function vd(t){return t.split(yd).join("/")}function Cd(t){return{maxDepth:typeof t.maxDepth=="number"?Math.max(1,t.maxDepth):_d,maxEntries:typeof t.maxEntries=="number"?Math.max(100,t.maxEntries):Sd,limit:typeof t.limit=="number"?Math.max(1,t.limit):yi,respectGitIgnore:t.respectGitIgnore??!0,ignoreGlobs:t.ignoreGlobs?.length?t.ignoreGlobs:[]}}function xd(t,e){let n=t.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>Td.has(o))||r.endsWith(".log")?!0:e.ignoreGlobs.length?e.ignoreGlobs.some(o=>{let s=o.replace(/\\/g,"/").trim();if(!s)return!1;if(s.endsWith("/**")){let i=s.slice(0,-3);return t.startsWith(i)}if(s.startsWith("*")){let i=s.slice(1);return t.endsWith(i)}return t.includes(s)}):!1}function bd(t){return t.replace(/\\/g,"/")}function Ed(t){let e=hd(t);try{md(e).isFile()&&(e=fi(e))}catch{e=process.cwd()}let n=e;for(;;){if(kr(_n(e,".gitignore"))||kr(_n(e,".git")))return e;let r=fi(e);if(r===e)return n;e=r}}async function Md(t){let e=_n(t,".gitignore");if(!kr(e))return[];try{return(await fd(e,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#"))}catch{return[]}}function wd(t){let e=(0,hi.default)();return t.length>0&&e.add(t),e}async function Ad(t){let e=wd(await Md(t));return{root:t,ignores:n=>{let r=gi(t,n);return!r||r.startsWith("..")?!1:e.ignores(bd(r))}}}async function Pd(t){let e=Ed(t),n=Pr.get(e);if(n)return n;let r=Ad(e).catch(o=>{throw Pr.delete(e),o});return Pr.set(e,r),r}function kd(t){return JSON.stringify({maxDepth:t.maxDepth,maxEntries:t.maxEntries,respectGitIgnore:t.respectGitIgnore,ignoreGlobs:t.ignoreGlobs})}async function Rd(t,e){let n=[],r=e.respectGitIgnore?await Pd(t):null,o=async(s,i)=>{if(n.length>=e.maxEntries)return;let a;try{a=await gd(s,{withFileTypes:!0})}catch{return}for(let l of a){if(n.length>=e.maxEntries)break;if(l.isSymbolicLink())continue;let c=_n(s,l.name);if(r?.ignores(c))continue;let p=gi(t,c);if(!p)continue;let u=vd(p);if(xd(u,e))continue;let g=u.split("/").filter(Boolean),_=l.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:g,segmentsLower:g.map(h=>h.toLowerCase()),depth:i,isDir:_}),_&&i<e.maxDepth&&await o(c,i+1)}};return await o(t,0),n.sort((s,i)=>s.path.localeCompare(i.path)),n}async function Id(t,e){let n=Cd(e),r=kd(n),o=yn.get(t);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=Rd(t,n).then(i=>(yn.set(t,{entries:i,signature:r}),i)).catch(i=>{throw yn.delete(t),i});return yn.set(t,{entries:[],signature:r,pending:s}),s}function Od(t,e){if(!e.length)return t.depth+(t.isDir?-.2:.2);let n=t.depth,r=0;for(let o of e){let s=-1;for(let i=r;i<t.segmentsLower.length;i++){let a=t.segmentsLower[i];if(a.startsWith(o)){s=i,n+=(i-r)*1.2,n+=a.length-o.length;break}let l=a.indexOf(o);if(l!==-1){s=i,n+=(i-r)*2+l+2;break}}if(s===-1)return null;r=s+1}return t.isDir&&(n-=.5),n}function Ld(t,e,n){let o=e.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of t){let a=Od(i,o);a!==null&&s.push({entry:i,score:a})}return s.sort((i,a)=>{let l=i.score-a.score;return l!==0?l:i.entry.path.localeCompare(a.entry.path)}),s.slice(0,n).map(({entry:i})=>({id:i.path,path:i.path,name:i.segments[i.segments.length-1]??i.path,parent:i.segments.length>1?i.segments.slice(0,-1).join("/"):void 0,isDir:i.isDir}))}async function _i(t){let e=await Id(t.cwd,t),n=typeof t.limit=="number"?Math.max(1,t.limit):yi;return Ld(e,t.query,n)}import{readdir as Nd,readFile as $d,stat as Dd}from"fs/promises";import{basename as Ud,join as Fd,resolve as Dt}from"path";function Si(t){let e=Dt(t);return process.platform==="win32"?e.toLowerCase():e}function Hd(t,e){return e?Si(t)===Si(e):!1}function Bd(t){return Ud(t).replace(/\.jsonl$/i,"")}function jd(t){let e=null,n=null,r=null;for(let o of t.split(`
88
+ `)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!(!i||typeof i!="object")){if(i.type==="session_start"&&!r){let a=i.meta?.cwd;typeof a=="string"&&a.trim()&&(r=a);continue}if(i.type==="turn_start"&&!e){let a=typeof i.content=="string"?i.content.trim():"";a&&(e=a)}if(i.type==="session_title"&&!n){let a=typeof i.content=="string"?i.content.trim():"";a&&(n=a)}}}return{firstPrompt:e,sessionTitle:n,sessionCwd:r}}async function Wd(t,e,n){try{let r=await $d(t,"utf8"),{firstPrompt:o,sessionTitle:s,sessionCwd:i}=jd(r);if(!Hd(e,i))return null;let a=s?.trim()||o?.trim()||Bd(t);return{id:t,cwd:e,input:a,ts:n,sessionFile:t}}catch{return null}}async function Gd(t){let e=[],n=async r=>{let o;try{o=await Nd(r,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async s=>{let i=Fd(r,s.name);if(!s.isSymbolicLink()){if(s.isDirectory()){await n(i);return}if(!(!s.isFile()||!s.name.endsWith(".jsonl")))try{let a=await Dd(i);e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}}))};return await n(t),e}async function Ti(t){let e=t.activeSessionFile?Dt(t.activeSessionFile):null,r=(await Gd(t.sessionsDir)).filter(a=>!e||Dt(a.path)!==e).filter((a,l,c)=>c.findIndex(p=>Dt(p.path)===Dt(a.path))===l).sort((a,l)=>l.mtimeMs-a.mtimeMs),o=t.keyword?.trim().toLowerCase(),s=t.limit??10,i=[];for(let a of r){if(i.length>=s)break;let l=await Wd(a.path,t.cwd,a.mtimeMs);l&&(o&&!l.input.toLowerCase().includes(o)||i.push(l))}return i}import{memo as zd}from"react";import{Box as Sn,Text as Tn}from"ink";import{jsx as tt,jsxs as Kd}from"react/jsx-runtime";var qd="#3a3a3a",vn="#262626",vi=zd(function({items:e,activeIndex:n,loading:r}){return r?tt(Sn,{paddingX:1,backgroundColor:vn,children:tt(Tn,{color:"gray",children:"Loading..."})}):e.length?tt(Sn,{flexDirection:"column",backgroundColor:vn,children:e.map((o,s)=>{let i=s===n;return Kd(Sn,{paddingX:1,gap:2,backgroundColor:i?qd:vn,children:[tt(Tn,{color:i?"cyan":"white",bold:i,children:o.title}),o.subtitle?tt(Tn,{color:"gray",children:o.subtitle}):null]},o.id)})}):tt(Sn,{paddingX:1,backgroundColor:vn,children:tt(Tn,{color:"gray",children:"No matches"})})});import Vd from"string-width";var Xd=55296,Jd=56319,Yd=56320,Zd=57343;function Ci(t){return t>=Xd&&t<=Jd}function xi(t){return t>=Yd&&t<=Zd}function be(t,e){if(!Number.isFinite(e)||e<=0)return 0;if(e>=t.length)return t.length;if(t.length===0)return 0;let n=Math.floor(e);if(n<=0)return 0;if(n>=t.length)return t.length;let r=t.charCodeAt(n),o=t.charCodeAt(n-1);return xi(r)&&Ci(o)?n-1:n}function bi(t,e){let n=be(t,e);if(n>=t.length)return t.length;let r=t.codePointAt(n);return r===void 0?Math.min(t.length,n+1):Math.min(t.length,n+(r>65535?2:1))}function nt(t,e){let n=be(t,e);if(n<=0)return 0;let r=n-1;if(r<=0)return r;let o=t.charCodeAt(r),s=t.charCodeAt(r-1);return xi(o)&&Ci(s)?r-1:r}function Cn(t,e){let n=be(t,e),r=t.lastIndexOf(`
89
+ `,Math.max(0,n-1));return r===-1?0:r+1}function xn(t,e){let n=be(t,e),r=t.indexOf(`
90
+ `,n);return r===-1?t.length:r}function Qd(t){return/[\p{L}\p{N}_]/u.test(t)}function Ei(t,e,n){let r=be(t,e);if(!n)return{value:t,cursor:r};let o=n.replace(/\r\n?/g,`
91
+ `);return o?{value:`${t.slice(0,r)}${o}${t.slice(r)}`,cursor:r+o.length}:{value:t,cursor:r}}function Mi(t,e){let n=be(t,e);if(n<=0)return{value:t,cursor:n};let r=nt(t,n);return{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function Rr(t,e){let n=be(t,e);if(n>=t.length)return{value:t,cursor:n};let r=bi(t,n);return{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function wi(t,e){let n=be(t,e);if(n<=0)return{value:t,cursor:n};let r=n;for(;r>0;){let s=nt(t,r);if(t.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=nt(t,r),i=t.slice(s,r);if(!Qd(i))break;r=s}return r===n&&(r=nt(t,n)),{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function Ai(t,e){let n=be(t,e),r=Cn(t,n);return r>=n?{value:t,cursor:n}:{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function Pi(t,e){let n=be(t,e),r=xn(t,n);return r<=n?{value:t,cursor:n}:{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function ki(t,e){return nt(t,e)}function Ri(t,e){return bi(t,e)}function Ii(t,e){return Cn(t,e)}function Oi(t,e){return xn(t,e)}function Ir(t,e,n,r){let o=be(t,e),s=Cn(t,o),i=xn(t,o),a=o-s,l=r??a;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:l,changed:!1};let g=s-1,_=Cn(t,g),h=Math.min(_+l,g);return{cursor:h,preferredColumn:l,changed:h!==o}}if(i>=t.length)return{cursor:o,preferredColumn:l,changed:!1};let c=i+1,p=xn(t,c),u=Math.min(c+l,p);return{cursor:u,preferredColumn:l,changed:u!==o}}function Li(t,e,n){let r=be(t,e),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,a=0,l="",c=0,p=()=>{s.push({text:l,start:i,end:a})},u=0;for(let h of t){let f=u;if(u+=h.length,h===`
92
+ `){a=f,p(),i=u,a=u,l="",c=0;continue}let T=Math.max(0,Vd(h));l.length>0&&c+T>o&&(p(),i=f,a=f,l="",c=0),l+=h,a=u,c+=T}if(p(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let g=Math.max(0,s.length-1),_=(s[g]?.text??"").length;for(let h=0;h<s.length;h+=1){let f=s[h];if(f&&!(r<f.start)&&r<=f.end){g=h,_=r-f.start;break}}return{lines:s,row:g,cursorInRow:_}}function Ni(t,e){let n=t==="\b"||t==="\x7F",r=!!e.ctrl&&t.toLowerCase()==="h";return e.backspace||n||r||e.delete&&!(e.ctrl||e.meta)?"backspace":e.delete?"delete":"none"}var em=3,$i=8,tm=120,nm=process.platform==="win32"?60:8,Ut=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(e={}){this.minChars=e.minChars??em,this.charIntervalMs=e.charIntervalMs??$i,this.enterSuppressWindowMs=e.enterSuppressWindowMs??tm,this.activeIdleTimeoutMs=e.activeIdleTimeoutMs??nm}static recommendedFlushDelayMs(){return $i+1}recommendedActiveFlushDelayMs(){return this.activeIdleTimeoutMs+1}onPlainChar(e,n){let r=Array.from(e)[0]??"";return this.notePlainChar(n),this.active?(this.extendWindow(n),{type:"buffer_append"}):this.pendingFirstChar&&n-this.pendingFirstChar.atMs<=this.charIntervalMs?(this.active=!0,this.buffer+=this.pendingFirstChar.ch,this.pendingFirstChar=null,this.extendWindow(n),{type:"begin_buffer_from_pending"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:r?(this.pendingFirstChar={ch:r,atMs:n},{type:"retain_first_char"}):{type:"retain_first_char"}}onPlainCharNoHold(e){return this.notePlainChar(e),this.active?(this.extendWindow(e),{type:"buffer_append"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:null}flushIfDue(e){let n=this.isActiveInternal()?this.activeIdleTimeoutMs:this.charIntervalMs;if(!(this.lastPlainCharAtMs!==null&&e-this.lastPlainCharAtMs>n))return{type:"none"};if(this.isActiveInternal()){this.active=!1;let o=this.buffer;return this.buffer="",{type:"paste",text:o}}if(this.pendingFirstChar){let o=this.pendingFirstChar.ch;return this.pendingFirstChar=null,{type:"typed",text:o}}return{type:"none"}}appendNewlineIfActive(e){return this.isActiveInternal()?(this.buffer+=`
93
+ `,this.extendWindow(e),!0):!1}newlineShouldInsertInsteadOfSubmit(e){let n=this.burstWindowUntilMs!==null&&e<=this.burstWindowUntilMs;return this.isActiveInternal()||n}extendWindow(e){this.burstWindowUntilMs=e+this.enterSuppressWindowMs}beginWithRetroGrabbed(e,n){e&&(this.buffer+=e),this.active=!0,this.extendWindow(n)}appendCharToBuffer(e,n){e&&(this.buffer+=e,this.extendWindow(n))}decideBeginBuffer(e,n,r){let o=rm(n,r),s=n.slice(o);return/\s/u.test(s)||Array.from(s).length>=16?(this.beginWithRetroGrabbed(s,e),{start:o,grabbed:s}):null}flushBeforeModifiedInput(){if(!this.isActive())return null;this.active=!1;let e=this.buffer;return this.buffer="",this.pendingFirstChar&&(e+=this.pendingFirstChar.ch,this.pendingFirstChar=null),e}clearWindowAfterNonChar(){this.consecutivePlainChars=0,this.lastPlainCharAtMs=null,this.burstWindowUntilMs=null,this.active=!1,this.pendingFirstChar=null}isActive(){return this.isActiveInternal()||this.pendingFirstChar!==null}isBuffering(){return this.isActiveInternal()}hasPendingFirstChar(){return this.pendingFirstChar!==null}clearAfterExplicitPaste(){this.lastPlainCharAtMs=null,this.consecutivePlainChars=0,this.burstWindowUntilMs=null,this.active=!1,this.buffer="",this.pendingFirstChar=null}notePlainChar(e){this.lastPlainCharAtMs!==null&&e-this.lastPlainCharAtMs<=this.charIntervalMs?this.consecutivePlainChars+=1:this.consecutivePlainChars=1,this.lastPlainCharAtMs=e}isActiveInternal(){return this.active||this.buffer.length>0}};function rm(t,e){if(e<=0)return t.length;let n=t.length,r=e;for(;r>0&&n>0;)n=nt(t,n),r-=1;return n}import{jsx as St,jsxs as Ui}from"react/jsx-runtime";var am=400,Lr=he($.MODELS),Nr=he($.CONTEXT),$r=he($.TOOLS),lm=he($.INIT),cm=[{mode:B.NONE,description:"Disable all tool calls"},{mode:B.ONCE,description:"Require approval when needed"},{mode:B.FULL,description:"Run tools without approval"}];function um(t){let e=t.lastIndexOf("@");if(e===-1)return null;if(e>0){let r=t[e-1];if(r&&!/\s/.test(r))return null}let n=t.slice(e+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:e+1}}function pm(t){let e=t.trimStart(),n=t.length-e.length;if(!e.length)return null;let r=e;if(r.startsWith("/")&&(r=r.slice(1)),!r.toLowerCase().startsWith($.RESUME)||t.slice(0,n).trim().length>0)return null;let s=r.slice($.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function dm(t){let e=t.trimStart();if(!e.startsWith("/"))return null;let n=e.slice(1);return n.includes(" ")?null:n.length?/^[a-zA-Z-]+$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:null:{type:"slash",keyword:""}}function mm(t){let e=t.trimStart();if(!e.startsWith(Lr))return null;let n=e.slice(Lr.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function fm(t){let e=t.trimStart();if(!e.startsWith(Nr))return null;let n=e.slice(Nr.length);return n&&!n.startsWith(" ")?null:{type:"context"}}function gm(t){let e=t.trimStart();if(!e.startsWith($r))return null;let n=e.slice($r.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function hm(t){return gm(t)??fm(t)??mm(t)??dm(t)??um(t)??pm(t)}function ym(t){let e=new Date(t);if(Number.isNaN(e.getTime()))return"";let n=String(e.getFullYear()),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${s}:${i}`}function _m(t,e){return{mode:"model",items:t.filter(r=>{if(!e)return!0;let o=r.name.toLowerCase(),s=r.model.toLowerCase();return o.includes(e)||s.includes(e)}).map(r=>({id:r.name,title:`${r.name}: ${r.model}`,subtitle:r.base_url,kind:"model",value:`${Lr} ${r.name}`,meta:{type:"model",provider:r}}))}}function Sm(t){return{mode:"context",items:ht.map(n=>({id:`${n}`,title:`${Math.floor(n/1e3)}k tokens`,subtitle:n===t?"Current":void 0,kind:"context",value:`${Nr} ${Math.floor(n/1e3)}k`,meta:{type:"context",value:n}}))}}function Tm(t){return{mode:"tools",items:cm.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===t?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${$r} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function vm(t){return{mode:"slash",items:mn.filter(n=>n.name.startsWith(t)).map(n=>({id:n.name,title:`/${n.name}`,subtitle:n.description,kind:"slash",value:`/${n.name}`,meta:{type:"slash"}}))}}async function Cm({trigger:t,cwd:e,sessionsDir:n,currentSessionFile:r,providers:o,contextLimit:s,toolPermissionMode:i}){switch(t.type){case"file":return{mode:"file",items:(await _i({cwd:e,query:t.query,limit:8,respectGitIgnore:!0})).map(c=>({id:c.id,title:c.isDir?`${c.path}/`:c.path,kind:"file",value:c.isDir?`${c.path}/`:c.path,meta:{type:"file",isDir:c.isDir}}))};case"history":return{mode:"history",items:(await Ti({sessionsDir:n,cwd:e,keyword:t.keyword,activeSessionFile:r})).map(c=>({id:c.id,title:c.input,subtitle:ym(c.ts),kind:"history",value:c.input,meta:{type:"history",entry:c}}))};case"models":return _m(o,t.keyword);case"context":return Sm(s);case"tools":return Tm(i);case"slash":return vm(t.keyword)}}var Fi=om(function({disabled:e,busy:n,history:r,cwd:o,sessionsDir:s,currentSessionFile:i,providers:a,configPath:l,providerName:c,model:p,contextLimit:u,toolPermissionMode:g,mcpServers:_,onSubmit:h,onExit:f,onClear:T,onNewSession:x,onCancelRun:b,onHistorySelect:K,onModelSelect:X,onSetContextLimit:z,onSetToolPermission:q,onSystemMessage:ye}){let{stdout:P}=im(),[U,W]=ze({value:"",cursor:0}),k=Ft(U),L=Ft(null),[Re,V]=ze(null),[w,R]=ze(""),[J,Me]=ze("none"),[_e,Ie]=ze([]),[pe,de]=ze(0),[Ct,ke]=ze(!1),[M,te]=ze(!1),it=Ft(0),at=Ft(0),Y=Ft(new Ut);bn(()=>{k.current=U,te(!1)},[U]);let oe=Di(()=>({configPath:l,providerName:c,model:p,mcpServers:_,providers:a,contextLimit:u,toolPermissionMode:g}),[l,c,p,_,a,u,g]),Se=Di(()=>e||M?null:hm(U.value),[e,U.value,M]),j=rt((S=!0)=>{S&&te(!0),Me("none"),Ie([]),de(0),ke(!1)},[]),O=rt((S,C=!1)=>{k.current=S,W(S),C&&(V(null),R(""))},[]),je=rt(()=>{O({value:"",cursor:0},!0)},[O]),H=rt((S,C=!0)=>{if(!S)return;let F=k.current;L.current=null;let ne=Ei(F.value,F.cursor,S);O(ne,C),S.includes(`
94
+ `)&&j(!1)},[O,j]),Ve=rt(S=>S.type==="none"?!1:S.type==="paste"?(S.text&&H(S.text,!0),!0):(H(S.text,!0),!0),[H]),me=rt((S=!0)=>{let C=Y.current.flushBeforeModifiedInput();return C&&H(C,!0),S&&Y.current.clearWindowAfterNonChar(),!!C},[H]);bn(()=>{let S=setInterval(()=>{let C=Y.current.flushIfDue(Date.now());Ve(C)},Ut.recommendedFlushDelayMs());return()=>{clearInterval(S)}},[Ve]),bn(()=>{e&&j(!1)},[e,j]),bn(()=>{if(!Se){j(!1);return}let S=!1,C=++it.current;return ke(!0),(async()=>{try{let{mode:F,items:ne}=await Cm({trigger:Se,cwd:o,sessionsDir:s,currentSessionFile:i,providers:a,contextLimit:u,toolPermissionMode:g});if(S||C!==it.current)return;Me(F),Ie(ne),de(fe=>ne.length?Math.min(fe,ne.length-1):0)}finally{!S&&C===it.current&&ke(!1)}})(),()=>{S=!0}},[Se,o,s,i,a,u,g,j]);let xt=rt(S=>{if(S){if(J==="file"&&Se?.type==="file"){let C=k.current.value,F=C.slice(0,Se.tokenStart),ne=C.slice(Se.tokenStart+Se.query.length),fe=`${F}${S.value}${ne}`,Oe=F.length+S.value.length;O({value:fe,cursor:Oe},!0),S.meta?.type==="file"&&S.meta.isDir||j();return}switch(S.meta?.type){case"history":K(S.meta.entry),O({value:S.value,cursor:S.value.length},!1),j();return;case"model":X(S.meta.provider),je(),j();return;case"context":z(S.meta.value),je(),j();return;case"tools":q(S.meta.mode),je(),j();return;case"slash":O({value:`${S.value} `,cursor:`${S.value} `.length},!0),j(!1);return;default:O({value:S.value,cursor:S.value.length},!0),j()}}},[O,J,Se,j,je,K,X,z,q]);sm((S,C)=>{if(C.ctrl&&S==="c"){f();return}if(e)return;let F=Date.now();Ve(Y.current.flushIfDue(F));let ne=J!=="none",fe=ne&&_e.length>0,Oe=Ni(S,C),bt=!!(C.ctrl||C.meta),Gt=!!S&&!bt&&!C.return&&!C.tab&&Oe==="none"&&!C.escape&&!C.upArrow&&!C.downArrow&&!C.leftArrow&&!C.rightArrow;if(!Gt&&!C.return&&me(!0),C.ctrl&&S==="a"){let v=k.current,I=Ii(v.value,v.cursor);L.current=null,O({value:v.value,cursor:I},!1);return}if(C.ctrl&&S==="e"){let v=k.current,I=Oi(v.value,v.cursor);L.current=null,O({value:v.value,cursor:I},!1);return}if(C.ctrl&&S==="u"){let v=k.current,I=Ai(v.value,v.cursor);L.current=null,O(I,!0);return}if(C.ctrl&&S==="k"){let v=k.current,I=Pi(v.value,v.cursor);L.current=null,O(I,!0);return}if(C.ctrl&&S==="w"){let v=k.current,I=wi(v.value,v.cursor);L.current=null,O(I,!0);return}if(C.ctrl&&S==="d"){let v=k.current;if(!v.value){f();return}let I=Rr(v.value,v.cursor);L.current=null,O(I,!0);return}if(C.ctrl&&S==="l"){O({value:"",cursor:0},!0),j(),T(),x();return}if(C.escape){if(F-at.current<=am){at.current=0,n?b():(L.current=null,O({value:"",cursor:0},!0),j());return}at.current=F,ne&&j();return}if(C.upArrow){if(fe){de(D=>D<=0?_e.length-1:D-1);return}let v=k.current;if(v.value.includes(`
95
+ `)){let D=Ir(v.value,v.cursor,"up",L.current??void 0);if(D.changed){L.current=D.preferredColumn,O({value:v.value,cursor:D.cursor},!1);return}}if(!r.length)return;if(Re===null){R(v.value);let D=r.length-1;V(D);let we=r[D]??"";L.current=null,O({value:we,cursor:we.length},!1);return}let I=Math.max(0,Re-1);V(I);let ie=r[I]??"";L.current=null,O({value:ie,cursor:ie.length},!1);return}if(C.downArrow){if(fe){de(D=>(D+1)%_e.length);return}let v=k.current;if(v.value.includes(`
96
+ `)){let D=Ir(v.value,v.cursor,"down",L.current??void 0);if(D.changed){L.current=D.preferredColumn,O({value:v.value,cursor:D.cursor},!1);return}}if(Re===null)return;let I=Re+1;if(I>=r.length){V(null),L.current=null,O({value:w,cursor:w.length},!1),R("");return}V(I);let ie=r[I]??"";L.current=null,O({value:ie,cursor:ie.length},!1);return}if(C.leftArrow){let v=k.current,I=ki(v.value,v.cursor);L.current=null,O({value:v.value,cursor:I},!1);return}if(C.rightArrow){let v=k.current,I=Ri(v.value,v.cursor);L.current=null,O({value:v.value,cursor:I},!1);return}if(C.tab&&fe){xt(_e[pe]);return}if(C.return){if(fe){xt(_e[pe]);return}Y.current.hasPendingFirstChar()&&!Y.current.isBuffering()&&me(!1);let v=k.current.value.trimStart().startsWith("/");if(!C.shift&&!v){if(Y.current.appendNewlineIfActive(F))return;if(Y.current.newlineShouldInsertInsteadOfSubmit(F)){me(!1),H(`
97
+ `,!0),Y.current.extendWindow(F);return}}if(me(!0),C.shift){H(`
98
+ `,!0);return}let ie=k.current.value.trim();if(!ie)return;if(ie.startsWith("/")){let D=oi(ie,oe);D.kind==="message"?ye(D.title,D.content):D.kind==="new"?x():D.kind==="exit"?f():D.kind==="switch_model"?X(D.provider):D.kind==="set_context_limit"?z(D.limit):D.kind==="set_tool_permission"?q(D.mode):D.kind==="init_agents_md"&&h(lm),L.current=null,O({value:"",cursor:0},!0),j(!1);return}h(ie),L.current=null,O({value:"",cursor:0},!0),j(!1);return}if(Oe!=="none"){let v=k.current,I=Oe==="backspace"?Mi(v.value,v.cursor):Rr(v.value,v.cursor);L.current=null,O(I,!0);return}if(S&&Gt){let v=Array.from(S);if(v.length!==1){me(!1),H(S,!0),Y.current.clearAfterExplicitPaste();return}let I=v[0]??"";if(!I)return;let ie=Ye=>{let lt=k.current,zt=lt.value.slice(0,lt.cursor),In=lt.value.slice(lt.cursor),Et=Y.current.decideBeginBuffer(F,zt,Ye);return Et?(L.current=null,O({value:`${zt.slice(0,Et.start)}${In}`,cursor:Et.start},!0),Y.current.appendCharToBuffer(I,F),!0):!1};if(!((I.codePointAt(0)??0)<=127)){let Ye=Y.current.onPlainCharNoHold(F);if(Ye?.type==="buffer_append"){Y.current.appendCharToBuffer(I,F);return}if(Ye?.type==="begin_buffer"&&ie(Ye.retroChars))return;me(!1),H(I,!0);return}let we=Y.current.onPlainChar(I,F);if(we.type==="retain_first_char")return;if(we.type==="buffer_append"||we.type==="begin_buffer_from_pending"){Y.current.appendCharToBuffer(I,F);return}if(we.type==="begin_buffer"&&ie(we.retroChars))return;me(!1),H(I,!0);return}S&&(H(S,!0),Y.current.clearWindowAfterNonChar())});let Z=P?.columns??process.stdout?.columns??80,E=Math.max(1,Z-3),Xe=Li(U.value,U.cursor,E),Je=Xe.lines;return Ui(Or,{flexDirection:"column",gap:1,children:[St(Or,{flexDirection:"column",paddingY:1,children:Je.map((S,C)=>{let F=S.text,ne=!e&&C===Xe.row,fe=ne?F.slice(0,Xe.cursorInRow):F,Oe=ne?F.slice(Xe.cursorInRow):"";return Ui(Or,{children:[St(En,{color:"gray",children:C===0?"\u203A ":" "}),St(En,{children:fe}),ne?St(En,{color:"cyan",children:"\u258A"}):null,ne?St(En,{children:Oe}):null]},`line-${C}`)})}),J!=="none"?St(vi,{items:_e.map(({value:S,meta:C,...F})=>F),activeIndex:pe,loading:Ct}):null]})});import{memo as xm}from"react";import{Box as Hi,Text as Dr}from"ink";import{jsx as Ur,jsxs as Bi}from"react/jsx-runtime";var ji=xm(function({busy:e,pendingApproval:n=!1,contextPercent:r,tokenLine:o}){let s=`${r.toFixed(1)}%`;return Bi(Hi,{justifyContent:"space-between",children:[Ur(Hi,{children:e?Ur(Dr,{color:"yellow",children:"Working..."}):Ur(Dr,{color:"gray",children:n?"Approval pending \u2022 Enter confirm \u2022 Esc deny":"Enter send \u2022 Shift+Enter newline \u2022 /help"})}),Bi(Dr,{color:"gray",children:[o?`${o} \u2022 `:"","context: ",s]})]})});import{memo as bm}from"react";import{Box as Mn,Text as Fr,useInput as Em}from"ink";import{Select as Mm,StatusMessage as wm}from"@inkjs/ui";import{jsx as ot,jsxs as Wi}from"react/jsx-runtime";var Am=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function Pm(t){if(!t)return"";if(typeof t!="object")return String(t);let e=Object.entries(t);if(!e.length)return"";let[n,r]=e[0]??[];if(!n)return"";let o=typeof r=="string"?r:JSON.stringify(r);return`${n}=${o?.slice(0,60)??""}${o&&o.length>60?"...":""}`}var Gi=bm(function({request:e,onDecision:n}){Em((o,s)=>{(s.escape||s.ctrl&&o==="c")&&n("deny")});let r=Pm(e.params);return Wi(Mn,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[ot(Fr,{bold:!0,color:"yellow",children:"Tool Approval Required"}),Wi(Fr,{children:[e.toolName,r?` (${r})`:""]}),ot(Mn,{marginTop:1,children:ot(wm,{variant:"warning",children:e.reason})}),ot(Mn,{marginTop:1,flexDirection:"column",children:ot(Mm,{options:Am.map(o=>({label:o.label,value:o.decision})),onChange:o=>{n(o)}})}),ot(Mn,{marginTop:1,children:ot(Fr,{color:"gray",children:"Enter confirm \u2022 Esc deny"})})]})});import{memo as km,useMemo as Rm,useState as Im}from"react";import{Box as Hr,Text as wn,useInput as Om}from"ink";import{MultiSelect as Lm}from"@inkjs/ui";import{jsx as Ht,jsxs as Br}from"react/jsx-runtime";function Nm(t,e){let n=new Set(t);return e.filter(r=>n.has(r))}var zi=km(function({serverNames:e,defaultSelected:n,onConfirm:r,onExit:o}){let s=Rm(()=>{let c=Nm(e,n);return n.length===0?[]:c.length>0?c:[...e]},[n,e]),[i,a]=Im(s),l=i.length===e.length;return Om((c,p)=>{if(p.ctrl&&c==="c"){o();return}p.escape&&r(i,!1)}),Br(Hr,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[Ht(wn,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),Ht(wn,{color:"gray",children:"Select servers to load for this run."}),Ht(Hr,{marginTop:1,flexDirection:"column",children:Ht(Lm,{options:e.map(c=>({label:c,value:c})),defaultValue:s,onChange:a,onSubmit:c=>{r(c,!0)}})}),Br(Hr,{marginTop:1,flexDirection:"column",children:[Br(wn,{color:"gray",children:["Selected: ",i.length,"/",e.length,l?" (all)":""]}),Ht(wn,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, Enter confirm"})]})]})});import{spawn as $m}from"child_process";var jr="\x07",Dm="Memo: Approval required",Um="Memo CLI",Fm=2e3;function Hm(t){return t.replace(/\s+/g," ").trim()}function Bm(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function jm(t){let e=Hm(t.reason),n=`Tool ${t.toolName} is waiting for your approval.`;return e?Bm(`${n} ${e}`,220):n}function qi(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Wm(t,e=process.platform){let n=Dm,r=jm(t);return e==="darwin"?{command:"osascript",args:["-e",`display notification "${qi(r)}" with title "${qi(n)}"`]}:e==="linux"?{command:"notify-send",args:["--app-name",Um,n,r]}:null}async function Gm(t,e){await new Promise((n,r)=>{let o=$m(t,e,{stdio:"ignore"}),s=!1,i=l=>{if(!s){if(s=!0,l){r(l);return}n()}},a=setTimeout(()=>{try{o.kill()}catch{}i()},Fm);o.once("error",l=>{clearTimeout(a),i(l)}),o.once("exit",l=>{if(clearTimeout(a),l===0||l===null){i();return}i(new Error(`${t} exited with code ${l}`))})})}function zm(t){if(t){t(jr);return}try{if(process.stdout?.isTTY){process.stdout.write(jr);return}process.stderr?.isTTY&&process.stderr.write(jr)}catch{}}async function Ki(t,e={}){zm(e.writeBell);let n=Wm(t,e.platform??process.platform);if(!n)return;let r=e.runCommand??Gm;try{await r(n.command,n.args)}catch{}}import{Box as Tt,Text as Be,useInput as qm}from"ink";import{Spinner as Km,StatusMessage as Vm,TextInput as Xm}from"@inkjs/ui";import{memo as Jm,useCallback as Vi,useMemo as Ym,useState as An}from"react";import{jsx as Ee,jsxs as vt}from"react/jsx-runtime";var qe=[{key:"name",label:"Provider name",hint:"Used for /models switching",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Read at runtime from environment variables",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",defaultValue:"https://api.deepseek.com"}],Xi=Jm(function({configPath:e,onComplete:n,onExit:r}){let[o,s]=An(0),[i,a]=An({}),[l,c]=An(!1),[p,u]=An(null),g=qe[o]??qe[0],_=Vi(async T=>{c(!0),u(null);try{let x={current_provider:T.name,providers:[{name:T.name,env_api_key:T.envKey,model:T.model,base_url:T.baseUrl||void 0}]};await Ce(e,x),n()}catch(x){u(x.message),c(!1)}},[e,n]),h=Vi(async T=>{if(!g)return;let x=T.trim()||g.defaultValue,b={...i,[g.key]:x};if(a(b),o<qe.length-1){s(o+1);return}let K={name:b.name||qe[0].defaultValue,envKey:b.envKey||qe[1].defaultValue,model:b.model||qe[2].defaultValue,baseUrl:b.baseUrl||qe[3].defaultValue};await _(K)},[_,g,o,i]);qm((T,x)=>{x.ctrl&&T==="c"&&r()});let f=Ym(()=>`Step ${o+1}/${qe.length}`,[o]);return g?vt(Tt,{flexDirection:"column",children:[Ee(Be,{bold:!0,children:"Memo setup"}),Ee(Be,{color:"gray",children:"No provider config found. Complete setup to continue."}),vt(Be,{color:"gray",children:["Config path: ",e]}),vt(Tt,{marginTop:1,flexDirection:"column",children:[Ee(Be,{color:"cyan",children:f}),Ee(Be,{children:g.label}),vt(Be,{color:"gray",children:["Default: ",g.defaultValue]}),g.hint?Ee(Be,{color:"gray",children:g.hint}):null]}),vt(Tt,{marginTop:1,children:[Ee(Be,{color:"gray",children:"> "}),Ee(Xm,{isDisabled:l,defaultValue:i[g.key]??"",placeholder:g.defaultValue,onSubmit:T=>{h(T)}},g.key)]}),Ee(Tt,{marginTop:1,children:Ee(Be,{color:"gray",children:"Enter to continue, Ctrl+C to exit"})}),l?Ee(Tt,{marginTop:1,children:Ee(Km,{label:"Saving config..."})}):null,p?Ee(Tt,{marginTop:1,children:vt(Vm,{variant:"error",children:["Failed to save config: ",p]})}):null]}):null});function Ji(t){let e=[],n=[],r=[],o=t.split(`
99
+ `).map(l=>l.trim()).filter(Boolean),s=null,i=0,a=0;for(let l of o){let c;try{c=JSON.parse(l)}catch{continue}if(!(!c||typeof c!="object")){if(c.type==="turn_start"){let p=typeof c.content=="string"?c.content:"";s={index:-(i+1),userInput:p,steps:[],status:"ok",sequence:a+=1},n.push(s),p&&(e.push({role:"user",content:p}),r.push(`User: ${p}`)),i+=1;continue}if(c.type==="assistant"){let p=typeof c.content=="string"?c.content:"";if(p&&(e.push({role:"assistant",content:p}),r.push(`Assistant: ${p}`),s)){let u={index:s.steps.length,assistantText:p};s.steps=[...s.steps,u],s.finalText=p}continue}if(c.type==="action"&&s){let p=c.meta;if(p&&typeof p=="object"){let u=typeof p.tool=="string"?p.tool:"",g=p.input,_=typeof p.thinking=="string"?p.thinking:"",f=(Array.isArray(p.toolBlocks)?p.toolBlocks:[]).map(x=>{let b=typeof x?.name=="string"?x.name:"";return b?{tool:b,input:x?.input}:null}).filter(Boolean),T=s.steps[s.steps.length-1];T&&(f.length>1?(T.action=f[0],T.parallelActions=f):u&&(T.action={tool:u,input:g}),_&&(T.thinking=_))}continue}if(c.type==="observation"&&s){let p=typeof c.content=="string"?c.content:"",u=s.steps[s.steps.length-1];u&&(u.observation=p);continue}}}return{summary:r.join(`
100
+ `),messages:e,turns:n,maxSequence:a}}function Gr(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function Zm(t,e){return{index:t,userInput:"",steps:[],sequence:e}}function Wr(t,e){if(t.length>e)return t;let n=t.slice();for(;n.length<=e;)n.push({index:n.length,assistantText:""});return n}function Bt(t,e,n){let r=t.turns.slice(),o=r.findIndex(i=>i.index===e);if(o===-1){let i=t.sequence+1;return r.push(n(Zm(e,i))),{turns:r,sequence:i}}let s=r[o];return s?(r[o]=n(s),{turns:r,sequence:t.sequence}):{turns:r,sequence:t.sequence}}function Qm(t){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:t.title,content:t.content,tone:t.tone??"info",sequence:t.sequence}}function Yi(t,e){switch(e.type){case"append_system_message":{let n=t.sequence+1;return{...t,sequence:n,systemMessages:[...t.systemMessages,Qm({title:e.title,content:e.content,tone:e.tone,sequence:n})]}}case"turn_start":{let n=Bt(t,e.turn,r=>({...r,index:e.turn,userInput:e.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:e.promptTokens??r.contextPromptTokens}));return{...t,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Bt(t,e.turn,r=>{let o=Wr(r.steps,e.step),s=o[e.step];if(!s)return r;let i=`${s.assistantText}${e.chunk}`;return i===s.assistantText?r:(o[e.step]={...s,assistantText:i},{...r,steps:o})});return{...t,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Bt(t,e.turn,r=>{let o=Wr(r.steps,e.step),s=o[e.step];return s?(o[e.step]={...s,action:e.action,thinking:e.thinking,parallelActions:e.parallelActions&&e.parallelActions.length>1?e.parallelActions:void 0,toolStatus:Fe.EXECUTING},{...r,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Bt(t,e.turn,r=>{let o=Wr(r.steps,e.step),s=o[e.step];return s?(o[e.step]={...s,observation:e.observation,toolStatus:e.toolStatus,parallelToolStatuses:e.parallelToolStatuses},{...r,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=Bt(t,e.turn,r=>{let o=r.startedAt??Date.now(),s=Math.max(0,Date.now()-o),i=e.tokenUsage?.prompt??r.contextPromptTokens;return{...r,finalText:e.finalText,status:e.status,errorMessage:e.errorMessage,tokenUsage:e.turnUsage,contextPromptTokens:i,startedAt:o,durationMs:s}});return{...t,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...t,historicalTurns:e.turns,sequence:Math.max(t.sequence,e.maxSequence)};case"clear_current_timeline":return{...t,turns:[],systemMessages:[]};case"reset_all":return Gr();default:return t}}import{dirname as Pn,join as Qi,resolve as ef}from"path";import{statSync as tf,existsSync as ea,readFileSync as nf}from"fs";import{readFile as rf}from"fs/promises";import{get as of}from"https";import{fileURLToPath as sf}from"url";function Zi(t){let e=t.trim().replace(/^v/i,""),[n="",r]=e.split("-",2),o=n.split(".").map(s=>Number(s));return o.length<3||o.some(s=>!Number.isFinite(s))?null:{major:o[0]??0,minor:o[1]??0,patch:o[2]??0,prerelease:r??null}}function af(t,e){let n=Zi(t),r=Zi(e);return!n||!r?!1:n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch!==r.patch?n.patch>r.patch:n.prerelease&&!r.prerelease?!1:!n.prerelease&&r.prerelease?!0:n.prerelease&&r.prerelease?n.prerelease>r.prerelease:!1}function ta(){try{let e=sf(import.meta.url);return Pn(e)}catch{}let t=ef(process.argv[1]??process.cwd());try{return tf(t).isFile()?Pn(t):t}catch{return process.cwd()}}async function lf(t){let e=Qi(t,"package.json");if(!ea(e))return null;let n=await rf(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function cf(t){let e=Qi(t,"package.json");if(!ea(e))return null;try{let n=nf(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function uf(){let t=ta();for(;;){let e=await lf(t);if(e&&e.name==="@memo-code/memo")return e;let n=Pn(t);if(n===t)break;t=n}return null}function kn(){let t=ta();for(;;){let e=cf(t);if(e&&e.name==="@memo-code/memo")return e;let n=Pn(t);if(n===t)break;t=n}return null}async function pf(t,e=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(o=>{let s=of(r,{timeout:e},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));o(l.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function na(){let t=await uf();if(!t)return null;let e=await pf(t.name);return!e||!af(e,t.version)?null:{current:t.version,latest:e}}import{jsx as Ke,jsxs as Sf}from"react/jsx-runtime";function hf(t,e){if(t.length===0)return[];if(e===void 0)return[...t];if(e.length===0)return[];let n=new Set(t),r=e.filter(o=>n.has(o));return r.length>0?r:[...t]}function yf(t,e){if(t.length===0)return[];if(e.length===0)return[];let n=new Set(t);return e.filter(r=>n.has(r))}function _f(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function oa({sessionOptions:t,providerName:e,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:p}=gf(),u=Wt(()=>Object.keys(o??{}).sort(),[o]),g=Wt(()=>hf(u,t.activeMcpServers),[u,t.activeMcpServers]),_=t.toolPermissionMode??(l?B.FULL:B.ONCE),[h,f]=mf(Yi,void 0,Gr),[T,x]=re(e),[b,K]=re(n),[X,z]=re(a),[q,ye]=re(_),[P,U]=re({...t,providerName:e,dangerous:_===B.FULL,toolPermissionMode:_}),[W,k]=re(!1),[L,Re]=re([]),[V,w]=re(null),[R,J]=re(null),[Me,_e]=re(t.maxPromptTokens??ti),[Ie,pe]=re(0),[de,Ct]=re(c),[ke,M]=re(!c&&u.length>0),[te,it]=re(g),[at,Y]=re(null),[oe,Se]=re(null),j=Rn(null),O=Rn(null),je=Rn(null),[H,Ve]=re(null),me=Rn(null),xt=Wt(()=>kn(),[]),Z=Q(m=>{f(m)},[]);jt(()=>{de||(it(g),M(u.length>0))},[de,g,u.length]);let E=Q((m,y,A="info")=>{Z({type:"append_system_message",title:m,content:y,tone:A})},[Z]),Xe=Wt(()=>({onAssistantStep:(m,y)=>{let A=O.current;A&&Z({type:"assistant_chunk",turn:A,step:y,chunk:m})},requestApproval:q===B.FULL||q===B.NONE?void 0:m=>new Promise(y=>{Ki(m),Ve(m),me.current=y}),hooks:{onTurnStart:({turn:m,input:y,promptTokens:A})=>{O.current=m;let Te=je.current;Te&&(je.current=null);let Ze=Te??y;A&&A>0&&pe(A),Z({type:"turn_start",turn:m,input:Ze,promptTokens:A})},onAction:({turn:m,step:y,action:A,thinking:Te,parallelActions:Ze})=>{Z({type:"tool_action",turn:m,step:y,action:A,thinking:Te,parallelActions:Ze})},onObservation:({turn:m,step:y,observation:A,resultStatus:Te,parallelResultStatuses:Ze})=>{Z({type:"tool_observation",turn:m,step:y,observation:A,toolStatus:_r(Te),parallelToolStatuses:Us(Ze)})},onFinal:({turn:m,finalText:y,status:A,errorMessage:Te,turnUsage:Ze,tokenUsage:ua})=>{Z({type:"turn_final",turn:m,finalText:y,status:A,errorMessage:Te,turnUsage:Ze,tokenUsage:ua}),k(!1)}}}),[Z,q]);jt(()=>{let m=!1;return(async()=>{if(!(de||ke))try{let y=j.current;y&&await y.close();let A=await pn(Xe,P);if(m){await A.close();return}j.current=A,Se(A),w(A.historyFilePath??null)}catch(y){if(m)return;j.current=null,Se(null),w(null),k(!1),E("Session",`Failed to create session: ${y.message}`,"error")}})(),()=>{m=!0}},[E,Xe,ke,P,de]),jt(()=>{let m=!1;return(async()=>{let y=await na();m||!y||E("Update",`Update available: v${y.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{m=!0}},[E]),jt(()=>()=>{j.current&&j.current.close()},[]);let Je=Q(async()=>{let m=me.current;m&&(m("deny"),me.current=null),H&&Ve(null),j.current&&await j.current.close(),Y("Bye!"),setTimeout(()=>p(),250)},[p,H]),S=Q(()=>{if(W){E("Clear","Cancel current run before clearing timeline.","warning");return}if(H){E("Clear","Resolve current approval request before clearing timeline.","warning");return}Z({type:"clear_current_timeline"}),J(null),pe(0),_f()},[E,W,Z,H]),C=Q(()=>{if(W){E("New Session","Cancel current run before starting a new session.","warning");return}if(H){E("New Session","Resolve current approval request before starting a new session.","warning");return}Z({type:"reset_all"}),J(null),pe(0),O.current=null,U(m=>({...m,sessionId:st()})),E("New Session","Started a fresh session.")},[E,W,Z,H]),F=Q(async m=>{try{let y=await le();await Ce(y.configPath,{...y.config,current_provider:m})}catch(y){E("Config",`Failed to persist provider: ${y.message}`,"warning")}},[E]),ne=Q(async m=>{if(W){E("Model switch","Cancel current run before switching models.","warning");return}if(m.name===T&&m.model===b){E("Model switch",`Already using ${m.name} (${m.model}).`);return}Z({type:"reset_all"}),pe(0),O.current=null,x(m.name),K(m.model),U(y=>({...y,sessionId:st(),providerName:m.name})),await F(m.name),E("Model switch",`Switched to ${m.name} (${m.model}).`)},[E,W,b,T,Z,F]),fe=Q(async m=>{try{let y=await le();await Ce(y.configPath,{...y.config,max_prompt_tokens:m})}catch(y){E("Context",`Failed to persist context limit: ${y.message}`,"warning")}},[E]),Oe=Q(m=>{if(W){E("Context","Cancel current run before changing context window.","warning");return}if(H){E("Context","Resolve current approval request before changing context window.","warning");return}_e(m),pe(0),U(y=>({...y,maxPromptTokens:m,sessionId:st()})),E("Context",`Context window set to ${Math.floor(m/1e3)}k.`),fe(m)},[E,W,H,fe]),bt=Q(m=>m===B.NONE?"none (no tools)":m===B.ONCE?"once (approval required)":"full (no approval)",[]),Gt=Q(m=>{if(W){E("Tools","Cancel current run before changing tool permission mode.","warning");return}if(H){E("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(m===q){E("Tools",`Already using ${bt(m)}.`);return}ye(m),U(y=>({...y,sessionId:st(),dangerous:m===B.FULL,toolPermissionMode:m})),E("Tools",`Tool permission set to ${bt(m)}.`)},[E,W,H,bt,q]),v=Q(async m=>{try{let y=await le();await Ce(y.configPath,{...y.config,active_mcp_servers:m})}catch(y){E("MCP",`Failed to persist active MCP servers: ${y.message}`,"warning")}},[E]),I=Q((m,y)=>{let A=yf(u,m);it(A),M(!1),U(Te=>({...Te,sessionId:st(),activeMcpServers:A})),y&&v(A)},[u,v]),ie=Q(async m=>{if(W){E("History","Cancel current run before loading session history.","warning");return}if(H){E("History","Resolve current approval request before loading session history.","warning");return}try{let y=await df(m.sessionFile,"utf8"),A=Ji(y);Z({type:"clear_current_timeline"}),Z({type:"replace_history",turns:A.turns,maxSequence:A.maxSequence}),J(A.messages),k(!1),Se(null),w(null),pe(0),O.current=null,U(Te=>({...Te,sessionId:st()})),E("History",A.summary||m.input)}catch(y){E("History",`Failed to load ${m.sessionFile}: ${y.message}`,"error")}},[E,W,Z,H]),D=Q(()=>{W&&oe?.cancelCurrentTurn?.()},[W,oe]),we=Q(async()=>{if(!oe||W)return;let m=`Please analyze the current project and create an AGENTS.md file at the project root.
100
101
 
101
102
  The AGENTS.md should include:
102
103
  1. Project name and brief description
@@ -112,7 +113,7 @@ Steps:
112
113
  3. Understand stack and conventions
113
114
  4. Create AGENTS.md using apply_patch
114
115
 
115
- Keep the result concise and actionable.`,_=ge($.INIT);we(I=>[...I,_]),P(!0);try{ie.current=_,await j.runTurn(g)}catch(I){P(!1),b("Init",`Failed to run init task: ${I.message}`,"error")}},[b,w,j]),ot=J(async g=>{let _=g.trim();if(_){if(_.toLowerCase()===ds){await T();return}if(_===ge($.INIT)){await je();return}if(!(!j||w)){we(I=>[...I,_]),P(!0);try{await j.runTurn(_)}catch(I){P(!1),b("Run",`Turn failed: ${I.message}`,"error")}}}},[b,w,T,je,j]),Ht=J(async()=>{try{let g=await ce(),_=Ye(g.config);q(g.config.providers),v(_.name),W(_.model),F(I=>({...I,sessionId:tt(),providerName:_.name})),Xe(!1),b("Setup",`Config saved to ${g.configPath}`)}catch(g){b("Setup",`Failed to reload config: ${g.message}`,"error")}},[b]);Nt(()=>{if(!j||!R?.length)return;let g=j.history[0];g&&(j.history.splice(0,j.history.length,g,...R),ne(null))},[R,j]);let vn=J(g=>{let _=We.current;_&&(_(g),We.current=null),Ce(null)},[]),ht=Zo(h.turns[h.turns.length-1]?.tokenUsage),li=Yo(Me,se),ci=$t(()=>({providerName:E,model:S,cwd:s,sessionId:A.sessionId??"unknown",mcpNames:Y,version:Dt?.version??"unknown"}),[Y,S,E,s,Dt?.version,A.sessionId]);return G?Ve(ni,{children:Ve(ud,{color:"green",children:G})}):ke?Ve(Vs,{configPath:r,onComplete:Ht,onExit:T}):Le?Ve(zs,{serverNames:p,defaultSelected:y,onConfirm:ae,onExit:()=>{T()}}):gd(ni,{flexDirection:"column",children:[Ve(us,{header:ci,systemMessages:h.systemMessages,turns:h.turns,historicalTurns:h.historicalTurns}),Ve(Ds,{disabled:!j||!!K,busy:w,history:ue,cwd:s,sessionsDir:i,currentSessionFile:te??void 0,providers:ee,configPath:r,providerName:E,model:S,contextLimit:se,toolPermissionMode:V,mcpServers:o,onSubmit:g=>{ot(g)},onExit:()=>{T()},onClear:x,onNewSession:U,onCancelRun:Re,onHistorySelect:g=>{D(g)},onModelSelect:g=>{ye(g)},onSetContextLimit:Sn,onSetToolPermission:C,onSystemMessage:b}),K?Ve(Ws,{request:K,onDecision:vn}):null,Ve(Fs,{busy:w,pendingApproval:!!K,contextPercent:li,tokenLine:ht})]})}var hd=`
116
+ Keep the result concise and actionable.`,y=he($.INIT);Re(A=>[...A,y]),k(!0);try{je.current=y,await oe.runTurn(m)}catch(A){k(!1),E("Init",`Failed to run init task: ${A.message}`,"error")}},[E,W,oe]),Ye=Q(async m=>{let y=m.trim();if(y){if(y.toLowerCase()===ni){await Je();return}if(y===he($.INIT)){await we();return}if(!(!oe||W)){Re(A=>[...A,y]),k(!0);try{await oe.runTurn(y)}catch(A){k(!1),E("Run",`Turn failed: ${A.message}`,"error")}}}},[E,W,Je,we,oe]),lt=Q(async()=>{try{let m=await le(),y=et(m.config);z(m.config.providers),x(y.name),K(y.model),U(A=>({...A,sessionId:st(),providerName:y.name})),Ct(!1),E("Setup",`Config saved to ${m.configPath}`)}catch(m){E("Setup",`Failed to reload config: ${m.message}`,"error")}},[E]);jt(()=>{if(!oe||!R?.length)return;let m=oe.history[0];m&&(oe.history.splice(0,oe.history.length,m,...R),J(null))},[R,oe]);let zt=Q(m=>{let y=me.current;y&&(y(m),me.current=null),Ve(null)},[]),In=Hs(h.turns[h.turns.length-1]?.tokenUsage),Et=Fs(Ie,Me),ca=Wt(()=>({providerName:T,model:b,cwd:s,sessionId:P.sessionId??"unknown",mcpNames:te,version:xt?.version??"unknown"}),[te,b,T,s,xt?.version,P.sessionId]);return at?Ke(ra,{children:Ke(ff,{color:"green",children:at})}):de?Ke(Xi,{configPath:r,onComplete:lt,onExit:Je}):ke?Ke(zi,{serverNames:u,defaultSelected:g,onConfirm:I,onExit:()=>{Je()}}):Sf(ra,{flexDirection:"column",children:[Ke(ei,{header:ca,systemMessages:h.systemMessages,turns:h.turns,historicalTurns:h.historicalTurns}),Ke(Fi,{disabled:!oe||!!H,busy:W,history:L,cwd:s,sessionsDir:i,currentSessionFile:V??void 0,providers:X,configPath:r,providerName:T,model:b,contextLimit:Me,toolPermissionMode:q,mcpServers:o,onSubmit:m=>{Ye(m)},onExit:()=>{Je()},onClear:S,onNewSession:C,onCancelRun:D,onHistorySelect:m=>{ie(m)},onModelSelect:m=>{ne(m)},onSetContextLimit:Oe,onSetToolPermission:Gt,onSystemMessage:E}),H?Ke(Gi,{request:H,onDecision:zt}):null,Ke(ji,{busy:W,pendingApproval:!!H,contextPercent:Et,tokenLine:In})]})}var Tf=`
116
117
  Usage:
117
118
  memo mcp list [--json]
118
119
  memo mcp get <name> [--json]
@@ -121,14 +122,14 @@ Usage:
121
122
  memo mcp remove <name>
122
123
  memo mcp login <name> [--scopes scope1,scope2]
123
124
  memo mcp logout <name>
124
- `;function fr(){console.log(hd.trim())}function yd(e){let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1);return n?{key:n,value:r}:null}function oi(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 r=t.http_headers??t.headers;r&&Object.keys(r).length>0&&n.push(` headers: ${Object.entries(r).map(([o,s])=>`${o}=${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(([r,o])=>`${r}=${o}`).join(", ")}`);return n.join(`
125
- `)}function Td(e){let t=e.shift();if(!t)return{error:"Missing server name."};let n,r,o={},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 l=e[i+1];if(!l)return{error:"Missing value for --url."};n=l,i+=1;continue}if(a==="--bearer-token-env-var"){let l=e[i+1];if(!l)return{error:"Missing value for --bearer-token-env-var."};r=l,i+=1;continue}if(a==="--env"){let l=e[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=yd(l);if(!c)return{error:"Invalid --env format. Use KEY=VALUE."};o[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(o).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:t,url:n,bearerTokenEnvVar:r}}:r?{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(o).length>0?o:void 0}}}function _d(e){let[t,...n]=e;return!t||t==="--help"||t==="-h"||t==="help"?{command:"help",rest:[]}:{command:t,rest:n}}function gr(e,t=[]){let n=new Set(t);for(let r=0;r<e.length;r+=1){let o=e[r];if(o){if(o.startsWith("--")){n.has(o)&&(r+=1);continue}return o}}return null}async function si(e){let{command:t,rest:n}=_d(e);if(t==="help"){fr();return}if(t==="list"){let r=n.includes("--json"),s=(await ce()).config.mcp_servers??{};if(r){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(oi(a,l))}return}if(t==="get"){let r=n.includes("--json"),o=gr(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await ce()).config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(r){console.log(JSON.stringify(i,null,2));return}console.log(oi(o,i));return}if(t==="add"){let r=Td(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),fr();return}let o=r.options;if(!o)return;if(o.url)try{new URL(o.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await ce(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let a;o.url?a={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:a={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=a,await Se(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(t==="remove"){let r=gr(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await ce(),s={...o.config.mcp_servers??{}};if(!s[r]){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}delete s[r],await Se(o.configPath,{...o.config,mcp_servers:s}),console.log(`Removed MCP server "${r}".`);return}if(t==="login"||t==="logout"){let r=gr(n,["--scopes"]);if(!r){console.error("Missing server name."),process.exitCode=1;return}let s=(await ce()).config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),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}`),fr(),process.exitCode=1}import{jsx as kd}from"react/jsx-runtime";function bd(e){let t={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o!==void 0){if(o==="--version"||o==="-v"){t.showVersion=!0;continue}if(o==="--once"){t.removedOnceFlag=!0;continue}if(o==="--dangerous"||o==="-d"){t.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:t}}async function ai(e){let t=await ce();if(!t.needsSetup)return t;let n=t.config.providers[0],o=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&o)return await Se(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=Sd({input:vd,output:xd}),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 Se(t.configPath,p),console.log(`Config written to ${t.configPath}
126
- `),{...t,config:p,needsSetup:!1}}finally{s.close()}}async function Ed(e){let t=await ai("plain"),n=Ye(t.config),o={sessionId:ii(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous};e.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={requestApproval:e.options.dangerous?void 0:l=>(console.log(`
125
+ `;function zr(){console.log(Tf.trim())}function vf(t){let e=t.indexOf("=");if(e<=0)return null;let n=t.slice(0,e).trim(),r=t.slice(e+1);return n?{key:n,value:r}:null}function sa(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 r=e.http_headers??e.headers;r&&Object.keys(r).length>0&&n.push(` headers: ${Object.entries(r).map(([o,s])=>`${o}=${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(([r,o])=>`${r}=${o}`).join(", ")}`);return n.join(`
126
+ `)}function Cf(t){let e=t.shift();if(!e)return{error:"Missing server name."};let n,r,o={},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."};r=l,i+=1;continue}if(a==="--env"){let l=t[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=vf(l);if(!c)return{error:"Invalid --env format. Use KEY=VALUE."};o[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(o).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:e,url:n,bearerTokenEnvVar:r}}:r?{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(o).length>0?o:void 0}}}function xf(t){let[e,...n]=t;return!e||e==="--help"||e==="-h"||e==="help"?{command:"help",rest:[]}:{command:e,rest:n}}function qr(t,e=[]){let n=new Set(e);for(let r=0;r<t.length;r+=1){let o=t[r];if(o){if(o.startsWith("--")){n.has(o)&&(r+=1);continue}return o}}return null}async function ia(t){let{command:e,rest:n}=xf(t);if(e==="help"){zr();return}if(e==="list"){let r=n.includes("--json"),s=(await le()).config.mcp_servers??{};if(r){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(sa(a,l))}return}if(e==="get"){let r=n.includes("--json"),o=qr(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await le()).config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(r){console.log(JSON.stringify(i,null,2));return}console.log(sa(o,i));return}if(e==="add"){let r=Cf(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),zr();return}let o=r.options;if(!o)return;if(o.url)try{new URL(o.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await le(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let a;o.url?a={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:a={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=a,await Ce(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(e==="remove"){let r=qr(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await le(),s={...o.config.mcp_servers??{}};if(!s[r]){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}delete s[r],await Ce(o.configPath,{...o.config,mcp_servers:s}),console.log(`Removed MCP server "${r}".`);return}if(e==="login"||e==="logout"){let r=qr(n,["--scopes"]);if(!r){console.error("Missing server name."),process.exitCode=1;return}let s=(await le()).config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),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}`),zr(),process.exitCode=1}import{jsx as Of}from"react/jsx-runtime";function Af(t){let e={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o!==void 0){if(o==="--version"||o==="-v"){e.showVersion=!0;continue}if(o==="--once"){e.removedOnceFlag=!0;continue}if(o==="--dangerous"||o==="-d"){e.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:e}}async function la(t){let e=await le();if(!e.needsSetup)return e;let n=e.config.providers[0],o=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&o)return await Ce(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=bf({input:Ef,output:Mf}),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"),p=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),u={current_provider:a,providers:[{name:a,env_api_key:l,model:c,base_url:p||void 0}]};return await Ce(e.configPath,u),console.log(`Config written to ${e.configPath}
127
+ `),{...e,config:u,needsSetup:!1}}finally{s.close()}}async function Pf(t){let e=await la("plain"),n=et(e.config),o={sessionId:aa(),mode:"interactive",maxPromptTokens:e.config.max_prompt_tokens,activeMcpServers:e.config.active_mcp_servers,generateSessionTitle:!0,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(`
127
128
  [approval required] ${l.toolName}: ${l.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:l})=>{console.log(`
128
- [tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await en(s,o),a=e.question;if(!a&&!process.stdin.isTTY&&(a=await Md()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
129
+ [tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await pn(s,o),a=t.question;if(!a&&!process.stdin.isTTY&&(a=await If()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
129
130
  `);let l=await i.runTurn(a);console.log(`
130
131
  ${l.finalText}`),console.log(`
131
132
  [tokens] prompt=${l.tokenUsage.prompt} completion=${l.tokenUsage.completion} total=${l.tokenUsage.total}`),console.log(`
132
- provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function Ad(e){let t=await ai("tui"),n=Ye(t.config),o={sessionId:ii(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous},s=Jt(t,o);e.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
133
- `)),await Cd(kd(ri,{sessionOptions:o,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 wd(){let e=process.argv.slice(2);if(e[0]==="mcp"||e[0]==="--"&&e[1]==="mcp"){let r=e[0]==="--"?2:1;await si(e.slice(r));return}let t=bd(e);if(t.options.removedOnceFlag){console.error("`--once` has been removed. Use `memo` (interactive) or pipe input to `memo`."),process.exitCode=1;return}if(t.options.showVersion){let o=yn()?.version??"unknown";console.log(o);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await Ed(t);return}await Ad(t)}wd();async function Md(){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()})}
133
+ provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function kf(t){let e=await la("tui"),n=et(e.config),o={sessionId:aa(),mode:"interactive",maxPromptTokens:e.config.max_prompt_tokens,activeMcpServers:e.config.active_mcp_servers,generateSessionTitle:!0,dangerous:t.options.dangerous},s=an(e,o);t.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
134
+ `)),await wf(Of(oa,{sessionOptions:o,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 Rf(){let t=process.argv.slice(2);if(t[0]==="mcp"||t[0]==="--"&&t[1]==="mcp"){let r=t[0]==="--"?2:1;await ia(t.slice(r));return}let e=Af(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 o=kn()?.version??"unknown";console.log(o);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await Pf(e);return}await kf(e)}Rf();async function If(){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()})}
134
135
  //# sourceMappingURL=index.js.map