@memo-code/memo 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -14
- package/README.zh.md +43 -11
- package/dist/index.js +94 -104
- package/dist/task-prompts/init_agents.md +40 -0
- package/dist/task-prompts/review_pull_request.md +53 -0
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -1,118 +1,109 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var di=Object.create;var yr=Object.defineProperty;var fi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var Ti=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var _i=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gi(t))!yi.call(e,o)&&o!==n&&yr(e,o,{get:()=>t[o],enumerable:!(r=fi(t,o))||r.enumerable});return e};var Si=(e,t,n)=>(n=e!=null?di(hi(e)):{},_i(t||!e||!e.__esModule?yr(n,"default",{value:e,enumerable:!0}):n,e));var Wr=Ti((Rd,Br)=>{"use strict";function Lr(e){return Array.isArray(e)?e:[e]}var In="",Nr=" ",kn="\\",ha=/^\s+$/,ya=/(?:[^\\]|^)\\$/,Ta=/^\\!/,_a=/^\\#/,Sa=/\r?\n/g,va=/^\.*\/|^\.+$/,Pn="/",Ur="node-ignore";typeof Symbol<"u"&&(Ur=Symbol.for("node-ignore"));var $r=Ur,xa=(e,t,n)=>Object.defineProperty(e,t,{value:n}),ba=/([0-z])-([0-z])/g,Hr=()=>!1,Ca=e=>e.replace(ba,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:In),Ea=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Aa=[[/^\uFEFF/,()=>In],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Nr:In)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Nr}],[/[\\$.|*+(){^]/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}${Ea(r)}${o}`:o==="]"&&r.length%2===0?`[${Ca(n)}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Dr=Object.create(null),Ma=(e,t)=>{let n=Dr[e];return n||(n=Aa.reduce((r,[o,s])=>r.replace(o,s.bind(e)),e),Dr[e]=n),t?new RegExp(n,"i"):new RegExp(n)},Ln=e=>typeof e=="string",wa=e=>e&&Ln(e)&&!ha.test(e)&&!ya.test(e)&&e.indexOf("#")!==0,ka=e=>e.split(Sa),Rn=class{constructor(t,n,r,o){this.origin=t,this.pattern=n,this.negative=r,this.regex=o}},Pa=(e,t)=>{let n=e,r=!1;e.indexOf("!")===0&&(r=!0,e=e.substr(1)),e=e.replace(Ta,"!").replace(_a,"#");let o=Ma(e,t);return new Rn(n,e,r,o)},Ia=(e,t)=>{throw new t(e)},$e=(e,t,n)=>Ln(e)?e?$e.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),Fr=e=>va.test(e);$e.isNotRelative=Fr;$e.convert=e=>e;var On=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){xa(this,$r,!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[$r]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(wa(t)){let n=Pa(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Lr(Ln(t)?ka(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&&$e.convert(t);return $e(s,t,this._allowRelativePaths?Hr:Ia),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 Lr(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},zt=e=>new On(e),Ra=e=>$e(e&&$e.convert(e),e,Hr);zt.isPathValid=Ra;zt.default=zt;Br.exports=zt;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,"/");$e.convert=e;let t=/^[a-z]:\//i;$e.isNotRelative=n=>t.test(n)||Fr(n)}});import{randomUUID as ci}from"crypto";import{createInterface as Um}from"readline/promises";import{stdin as Hm,stdout as Fm}from"process";import{render as Bm}from"ink";import vi from"os";import{readFile as Tr}from"fs/promises";import{join as _r,dirname as xi}from"path";import{fileURLToPath as bi}from"url";var Ci=/{{\s*([\w.-]+)\s*}}/g;function Ei(e,t){return e.replace(Ci,(n,r)=>t[r]??"")}function Ai(){try{return vi.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function Mi(e){let t=_r(e,"AGENTS.md");try{let n=await Tr(t,"utf-8");return n.trim()?{path:t,content:n}:null}catch{return null}}function wi(e,t){return`${e}
|
|
2
|
+
var Ra=Object.create;var Qr=Object.defineProperty;var Ia=Object.getOwnPropertyDescriptor;var Oa=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,Na=Object.prototype.hasOwnProperty;var eo=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $a=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Oa(e))!Na.call(t,o)&&o!==n&&Qr(t,o,{get:()=>e[o],enumerable:!(r=Ia(e,o))||r.enumerable});return t};var to=(t,e,n)=>(n=t!=null?Ra(La(t)):{},$a(e||!t||!t.__esModule?Qr(n,"default",{value:t,enumerable:!0}):n,t));var Oo=eo((Oh,Io)=>{"use strict";function wo(t){return Array.isArray(t)?t:[t]}var Gn="",Mo=" ",Wn="\\",rc=/^\s+$/,oc=/(?:[^\\]|^)\\$/,sc=/^\\!/,ic=/^\\#/,ac=/\r?\n/g,lc=/^\.*\/|^\.+$/,jn="/",Po="node-ignore";typeof Symbol<"u"&&(Po=Symbol.for("node-ignore"));var Eo=Po,cc=(t,e,n)=>Object.defineProperty(t,e,{value:n}),uc=/([0-z])-([0-z])/g,ko=()=>!1,pc=t=>t.replace(uc,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Gn),dc=t=>{let{length:e}=t;return t.slice(0,e-e%2)},mc=[[/^\uFEFF/,()=>Gn],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?Mo:Gn)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+Mo}],[/[\\$.|*+(){^]/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,()=>Wn],[/\\\\/g,()=>Wn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Wn?`\\[${n}${dc(r)}${o}`:o==="]"&&r.length%2===0?`[${pc(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Ao=Object.create(null),fc=(t,e)=>{let n=Ao[t];return n||(n=mc.reduce((r,[o,s])=>r.replace(o,s.bind(t)),t),Ao[t]=n),e?new RegExp(n,"i"):new RegExp(n)},Kn=t=>typeof t=="string",gc=t=>t&&Kn(t)&&!rc.test(t)&&!oc.test(t)&&t.indexOf("#")!==0,hc=t=>t.split(ac),zn=class{constructor(e,n,r,o){this.origin=e,this.pattern=n,this.negative=r,this.regex=o}},yc=(t,e)=>{let n=t,r=!1;t.indexOf("!")===0&&(r=!0,t=t.substr(1)),t=t.replace(sc,"!").replace(ic,"#");let o=fc(t,e);return new zn(n,t,r,o)},_c=(t,e)=>{throw new e(t)},Oe=(t,e,n)=>Kn(t)?t?Oe.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),Ro=t=>lc.test(t);Oe.isNotRelative=Ro;Oe.convert=t=>t;var qn=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){cc(this,Eo,!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[Eo]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(gc(e)){let n=yc(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,wo(Kn(e)?hc(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&&Oe.convert(e);return Oe(s,e,this._allowRelativePaths?ko:_c),this._t(s,n,r,o)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(jn)),o.pop(),!o.length)return n[e]=this._testOne(e,r);let s=this._t(o.join(jn)+jn,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 wo(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Xt=t=>new qn(t),Sc=t=>Oe(t&&Oe.convert(t),t,ko);Xt.isPathValid=Sc;Xt.default=Xt;Io.exports=Xt;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,"/");Oe.convert=t;let e=/^[a-z]:\//i;Oe.isNotRelative=n=>e.test(n)||Ro(n)}});var Ai=eo((oT,yn)=>{"use strict";function bi(t){return Array.isArray(t)?t:[t]}var Wd=void 0,Pr="",Ti=" ",Ar="\\",jd=/^\s+$/,Gd=/(?:[^\\]|^)\\$/,zd=/^\\!/,qd=/^\\#/,Kd=/\r?\n/g,Vd=/^\.{0,2}\/|^\.{1,2}$/,Xd=/\/$/,gt="/",Ci="node-ignore";typeof Symbol<"u"&&(Ci=Symbol.for("node-ignore"));var xi=Ci,ht=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),Jd=/([0-z])-([0-z])/g,wi=()=>!1,Yd=t=>t.replace(Jd,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Pr),Zd=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Qd=[[/^\uFEFF/,()=>Pr],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?Ti:Pr)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+Ti}],[/[\\$.|*+(){^]/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,()=>Ar],[/\\\\/g,()=>Ar],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Ar?`\\[${n}${Zd(r)}${o}`:o==="]"&&r.length%2===0?`[${Yd(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],em=/(^|\\\/)?\\\*$/,$t="regex",gn="checkRegex",vi="_",tm={[$t](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[gn](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},nm=t=>Qd.reduce((e,[n,r])=>e.replace(n,r.bind(t)),t),hn=t=>typeof t=="string",rm=t=>t&&hn(t)&&!jd.test(t)&&!Gd.test(t)&&t.indexOf("#")!==0,om=t=>t.split(Kd).filter(Boolean),kr=class{constructor(e,n,r,o,s,i){this.pattern=e,this.mark=n,this.negative=s,ht(this,"body",r),ht(this,"ignoreCase",o),ht(this,"regexPrefix",i)}get regex(){let e=vi+$t;return this[e]?this[e]:this._make($t,e)}get checkRegex(){let e=vi+gn;return this[e]?this[e]:this._make(gn,e)}_make(e,n){let r=this.regexPrefix.replace(em,tm[e]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return ht(this,n,o)}},sm=({pattern:t,mark:e},n)=>{let r=!1,o=t;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(zd,"!").replace(qd,"#");let s=nm(o);return new kr(t,e,o,n,r,s)},Rr=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[xi]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(hn(e)&&(e={pattern:e}),rm(e.pattern)){let n=sm(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,bi(hn(e)?om(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?Wd:l)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},im=(t,e)=>{throw new e(t)},De=(t,e,n)=>hn(t)?t?De.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),Mi=t=>Vd.test(t);De.isNotRelative=Mi;De.convert=t=>t;var Ir=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){ht(this,xi,!0),this._rules=new Rr(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&&De.convert(e);return De(s,e,this._strictPathCheck?im:wi),this._t(s,n,r,o)}checkIgnore(e){if(!Xd.test(e))return this.test(e);let n=e.split(gt).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(gt)+gt,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(e,!1,gn)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(gt).filter(Boolean)),o.pop(),!o.length)return n[e]=this._rules.test(e,r,$t);let s=this._t(o.join(gt)+gt,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 bi(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Or=t=>new Ir(t),am=t=>De(t&&De.convert(t),t,wi),Ei=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");De.convert=t;let e=/^[a-z]:\//i;De.isNotRelative=n=>e.test(n)||Mi(n)};typeof process<"u"&&process.platform==="win32"&&Ei();yn.exports=Or;Or.default=Or;yn.exports.isPathValid=am;ht(yn.exports,Symbol.for("setupWindows"),Ei)});import{randomUUID as Ca}from"crypto";import{createInterface as Ig}from"readline/promises";import{stdin as Og,stdout as Lg}from"process";import{render as Ng}from"ink";import al from"os";import{readFile as lo}from"fs/promises";import{join as co,dirname as ll}from"path";import{fileURLToPath as cl}from"url";import{access as Da,readFile as Ua,readdir as Ha,stat as Fa}from"fs/promises";import{constants as Ba}from"fs";import{homedir as ro}from"os";import{dirname as Wa,isAbsolute as ja,join as it,resolve as qt}from"path";import Ga from"fast-glob";var za="SKILL.md",qa=6,Ka=200,Va=64,Xa=1024,Ja="- Discovery: The list above is the skills available in this session (name + description + file path). Skill bodies live on disk at the listed paths.\n- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\n- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback.\n- How to use a skill (progressive disclosure):\n 1) After deciding to use a skill, open its `SKILL.md`. Read only enough to follow the workflow.\n 2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the skill directory listed above first, and only consider other paths if needed.\n 3) If `SKILL.md` points to extra folders such as `references/`, load only the specific files needed for the request; don't bulk-load everything.\n 4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks.\n 5) If `assets/` or templates exist, reuse them instead of recreating from scratch.\n- Coordination and sequencing:\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\n - Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why.\n- Context hygiene:\n - Keep context small: summarize long sections instead of pasting them; only load extra files when needed.\n - Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked.\n - When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice.\n- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue.";function oo(t){return t.trim().split(/\s+/).join(" ")}function Ya(t){let e=t.trim();return e.length>=2&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))?e.slice(1,-1):e}function Za(t){let e=t.split(/\r?\n/);if(e[0]?.trim()!=="---")return null;let n=[],r=!1;for(let o of e.slice(1)){if(o.trim()==="---"){r=!0;break}n.push(o)}return!r||n.length===0?null:n.join(`
|
|
3
|
+
`)}function Qa(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){if(!r){s.match(new RegExp(`^${e}\\s*:\\s*[|>]\\s*$`))&&(r=!0);continue}if(!/^\s+/.test(s))break;o.push(s.replace(/^\s+/,""))}return o.length===0?null:oo(o.join(" "))}function no(t,e){let n=Qa(t,e);if(n)return n;let r=new RegExp(`^${e}\\s*:\\s*(.+?)\\s*$`,"m"),o=t.match(r);return o?.[1]?oo(Ya(o[1])):null}function el(t,e){let n=Za(t);if(!n)return null;let r=no(n,"name"),o=no(n,"description");return!r||!o||r.length>Va||o.length>Xa?null:{name:r,description:o,path:e}}function so(t,e){return t==="~"?e:t.startsWith("~/")?it(e,t.slice(2)):t}async function tl(t){try{return(await Fa(t)).isDirectory()}catch{return!1}}async function nl(t){try{return await Da(it(t,".git"),Ba.F_OK),!0}catch{return!1}}async function rl(t){let e=qt(t),n=e;for(;;){if(await nl(n))return n;let r=Wa(n);if(r===n)break;n=r}return e}async function ol(t){let e=[it(t,".agents","skills")];try{let r=(await Ha(t,{withFileTypes:!0})).filter(o=>o.isDirectory()&&o.name.startsWith(".")).map(o=>o.name).filter(o=>o!==".git").sort((o,s)=>o.localeCompare(s));for(let o of r)e.push(it(t,o,"skills"))}catch{return zt(e)}return zt(e)}function zt(t){let e=[],n=new Set;for(let r of t){let o=qt(r);n.has(o)||(n.add(o),e.push(o))}return e}async function sl(t){let e=t.cwd??process.cwd(),n=t.homeDir??ro(),r=so(t.memoHome??process.env.MEMO_HOME??it(n,".memo"),n),o=await rl(e),s=await ol(o);return s.push(it(r,"skills")),zt(s)}async function il(t){if(t.skillRoots&&t.skillRoots.length>0){let e=t.homeDir??ro(),n=t.skillRoots.map(r=>{let o=so(r,e);return ja(o)?o:qt(o)});return zt(n)}return sl(t)}async function io(t={}){let e=await il(t),n=Math.max(1,t.maxSkills??Ka),r=[],o=new Set;for(let s of e){if(!await tl(s))continue;let i=await Ga(`**/${za}`,{cwd:s,absolute:!0,onlyFiles:!0,deep:qa,caseSensitiveMatch:!1,followSymbolicLinks:!0,suppressErrors:!0,unique:!0,ignore:["**/.git/**","**/node_modules/**"]});i.sort((a,l)=>a.localeCompare(l));for(let a of i){let l=qt(a);if(o.has(l))continue;let c;try{c=await Ua(l,"utf-8")}catch{continue}let p=el(c,l);if(p&&(r.push(p),o.add(l),r.length>=n))return r}}return r}function ao(t){if(t.length===0)return null;let e=[];e.push("## Skills"),e.push("A skill is a set of local instructions to follow that is stored in a `SKILL.md` file. Below is the list of skills that can be used. Each entry includes a name, description, and file path so you can open the source for full instructions when using a specific skill."),e.push("### Available skills");for(let n of t)e.push(`- ${n.name}: ${n.description} (file: ${n.path})`);return e.push("### How to use skills"),e.push(Ja),e.join(`
|
|
4
|
+
`)}var ul=/{{\s*([\w.-]+)\s*}}/g;function pl(t,e){return t.replace(ul,(n,r)=>e[r]??"")}function dl(){try{return al.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function ml(t){let e=co(t,"AGENTS.md");try{let n=await lo(e,"utf-8");return n.trim()?{path:e,content:n}:null}catch{return null}}function fl(t,e){return`${t}
|
|
3
5
|
|
|
4
6
|
## Project AGENTS.md (Startup Root)
|
|
5
|
-
Loaded from: ${
|
|
7
|
+
Loaded from: ${e.path}
|
|
6
8
|
|
|
7
|
-
${
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
${e.content}`}function gl(t,e){return`${t}
|
|
10
|
+
|
|
11
|
+
${e}`}async function uo(t={}){let e=t.cwd??process.cwd(),n=ll(cl(import.meta.url)),r=co(n,"prompt.md"),o=await lo(r,"utf-8"),s={date:new Date().toISOString(),user:dl(),pwd:e},i=pl(o,s),a=await ml(e);if(a&&(i=fl(i,a)),t.includeSkills!==!1){let l=await io({cwd:e,skillRoots:t.skillRoots,homeDir:t.homeDir,memoHome:t.memoHome}),c=ao(l);c&&(i=gl(i,c))}return i}import{appendFile as hl,mkdir as yl}from"fs/promises";import{dirname as _l}from"path";var Kt=class{constructor(e){this.filePath=e}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=yl(_l(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 hl(this.filePath,`${JSON.stringify(e)}
|
|
12
|
+
`,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function po(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 Re}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 m(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}import{spawn as Hl}from"child_process";import{EventEmitter as Fl}from"events";import{resolve as Bl}from"path";import{posix as Sl}from"path";var mo=220,fo=4096,Tl=/^\/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,vl=/(?:^|[\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,bl=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Cl=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function Nn(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function xl(t){let e=t.replace(/\s+/g," ").trim();return e.length>mo?`${e.slice(0,mo)}\u2026`:e}function go(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return(e.split(/[\\/]/).at(-1)??e).toLowerCase()}function wl(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 Ml(t){let e=[],n="",r=null,o=!1,s=()=>{let i=wl(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===`
|
|
13
|
+
`){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 El(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 ho(t){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t)}function Al(t,e){let n=e;for(;n<t.length;){let r=go(t[n]??"");if(r==="sudo"){for(n+=1;n<t.length;){let o=t[n]??"";if(!o.startsWith("-"))break;n+=1,bl.has(o)&&n<t.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<t.length;){let o=t[n]??"";if(o.startsWith("-")||ho(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function Pl(t){let e=El(t);if(e.length===0)return null;let n=0;for(;n<e.length&&ho(e[n]??"");)n+=1;if(n=Al(e,n),n>=e.length)return null;let r=go(e[n]??"");return r?{raw:t,commandName:r,args:e.slice(n+1)}:null}function $n(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return Tl.test(e)}function kl(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)?Sl.normalize(e)==="/":!1}function Rl(t){return t.startsWith("-")&&t!=="-"}function Il(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(!Rl(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(kl(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:t.raw};return null}function Ol(t){return t.commandName==="mkfs"||t.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:t.raw}:null}function Ll(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"&&$n(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"&&$n(r))return{ruleId:"dd_write_block_device",matchedSegment:t.raw}}return null}function Nl(t){return!Cl.has(t.commandName)||!t.args.some(e=>$n(e))?null:{ruleId:"disk_mutation_block_device",matchedSegment:t.raw}}function $l(t){return vl.test(t)?{ruleId:"redirect_block_device",matchedSegment:t}:null}function Dl(t){for(let e of Ml(t)){let n=Pl(e);if(n){let o=Il(n);if(o)return o;let s=Ol(n);if(s)return s;let i=Ll(n);if(i)return i;let a=Nl(n);if(a)return a}let r=$l(e);if(r)return r}return null}function Ul(t,e){let n=xl(t.command),r=typeof t.sessionId=="number"?` session_id="${t.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${Nn(t.toolName)}" reason="dangerous_command" policy="blacklist" rule="${Nn(e.ruleId)}"${r} command="${Nn(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function Dn(t){let e=Dl(t.command);return e?{blocked:!0,xml:Ul(t,e),match:e}:{blocked:!1}}function yo(t){let n=t.replace(/\r\n/g,`
|
|
10
14
|
`).replace(/\r/g,`
|
|
11
15
|
`).split(`
|
|
12
|
-
`),r=n.pop()??"";return{completedLines:n,remainder:r}}function
|
|
13
|
-
`)}function
|
|
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
|
|
16
|
+
`),r=n.pop()??"";return{completedLines:n,remainder:r}}function Un(t){return t.length<=fo?t:t.slice(-fo)}var Wl=1e4,jl=250,Gl=2e3,Vt=64;function zl(t){return Math.ceil(t.length/4)}function ql(){return Math.random().toString(16).slice(2)||String(Date.now())}function Kl(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 Vl(t,e){let r=(typeof e=="number"&&e>0?Math.floor(e):Gl)*4,o=zl(t);return t.length<=r?{output:t,originalTokenCount:o,deliveredChars:t.length}:{output:t.slice(0,r),originalTokenCount:o,deliveredChars:r}}function Xl(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(`
|
|
17
|
+
`)}function _o(t,e){return typeof t!="number"||Number.isNaN(t)?e:t<0?0:Math.floor(t)}async function So(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 To(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 Hn=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Vt)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<=Vt)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 To(e,200),e.exited||(e.proc.kill("SIGKILL"),await To(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()>=Vt)throw new Error(`too many active sessions (max ${Vt})`);let r=Dn({toolName:e.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=Kl({cmd:n,shell:e.shell,login:e.login!==!1}),a=e.workdir?.trim()?Bl(process.cwd(),e.workdir.trim()):process.cwd(),l=Hl(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 Fl,proc:l},p=(h,f)=>{let x=typeof f=="string"?f:f.toString("utf8");c.output+=h?`${h}${x}`:x,c.eventBus.emit("output")};l.stdout?.on("data",h=>p("",h)),l.stderr?.on("data",h=>p("",h)),l.on("error",h=>{c.output+=`
|
|
18
|
+
[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=_o(e.yield_time_ms,Wl),v=u!==null?Math.min(g,Math.max(0,u)):g;if(await So(c,v),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=Un(`${n.pendingStdinInput}${e.chars}`),{completedLines:s,remainder:i}=yo(o);for(let a of s){if(!a.trim())continue;let l=Dn({toolName:e.source_tool??"write_stdin",command:a,sessionId:n.id});if(l.blocked)return n.pendingStdinInput="",l.xml}n.pendingStdinInput=Un(i),n.proc.stdin?.write(e.chars)}let r=_o(e.yield_time_ms,jl);return await So(n,r),this.buildResponseText(n,e.max_output_tokens)}buildResponseText(e,n){let r=e.output.slice(e.readOffset),o=Vl(r,n);e.readOffset+=o.deliveredChars;let s={sessionId:e.id,chunkId:ql(),wallTimeSeconds:(Date.now()-e.startedAtMs)/1e3,exitCode:e.exited?e.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return Xl(s)}},vo=new Hn;async function at(t){return vo.start(t)}async function bo(t){return vo.write(t)}var Jl=Re.object({command:Re.array(Re.string().min(1)).min(1,"command cannot be empty"),workdir:Re.string().optional(),timeout_ms:Re.number().int().positive().optional(),sandbox_permissions:Re.enum(["use_default","require_escalated"]).optional(),justification:Re.string().optional(),prefix_rule:Re.array(Re.string().min(1)).optional()}).strict(),Yl=/^[A-Za-z0-9_./:@%+-]+$/;function Zl(t){return t.length===0?"''":Yl.test(t)?t:`'${t.replace(/'/g,`'"'"'`)}'`}function Ql(t){return t.map(e=>Zl(e)).join(" ")}var Co=N({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:Jl,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,timeout_ms:n})=>{try{let r=await at({cmd:Ql(t),workdir:e,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return m(r)}catch(r){return m(`shell failed: ${r.message}`,!0)}}});import{z as Ie}from"zod";var ec=Ie.object({command:Ie.string().min(1,"command cannot be empty"),workdir:Ie.string().optional(),login:Ie.boolean().optional(),timeout_ms:Ie.number().int().positive().optional(),sandbox_permissions:Ie.enum(["use_default","require_escalated"]).optional(),justification:Ie.string().optional(),prefix_rule:Ie.array(Ie.string().min(1)).optional()}).strict(),xo=N({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:ec,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,login:n,timeout_ms:r})=>{try{let o=await at({cmd:t,workdir:e,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return m(o)}catch(o){return m(`shell_command failed: ${o.message}`,!0)}}});import{z as ve}from"zod";var tc=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(),Fn=N({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:tc,supportsParallelToolCalls:!0,isMutating:!0,execute:async t=>{try{let e=await at({...t,source_tool:"exec_command"});return m(e)}catch(e){return m(`exec_command failed: ${e.message}`,!0)}}});import{z as Mt}from"zod";var nc=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(),Bn=N({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:nc,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await bo({...t,source_tool:"write_stdin"});return m(e)}catch(e){return m(`write_stdin failed: ${e.message}`,!0)}}});import{access as Rc,readFile as Ic,realpath as Oc,writeFile as Lc}from"fs/promises";import{z as pe}from"zod";var Ec=to(Oo(),1);import{normalize as Tc,resolve as vc,dirname as Nh,join as bc,relative as Cc,isAbsolute as xc}from"path";import{homedir as wc}from"os";import{existsSync as Uh,statSync as Hh,realpathSync as Mc}from"fs";import{readFile as Bh}from"fs/promises";function Le(t){return Tc(vc(t))}function Jt(t){let e=Le(t);try{return Le(Mc(e))}catch{return e}}function Ac(t,e){let n=Cc(e,t);return n===""||!n.startsWith("..")&&!xc(n)}function Pc(){let t=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>Jt(e)):[]}function Lo(){let t=new Set;t.add(Jt(process.cwd()));let e=process.env.MEMO_HOME?.trim()||bc(wc(),".memo");t.add(Jt(e));for(let n of Pc())t.add(n);return Array.from(t)}function kc(t){let e=Jt(t);return Lo().some(r=>Ac(e,r))}function No(t){if(kc(t))return null;let e=Lo();return`sandbox write denied: ${t} is not within allowed directories (${e.join(", ")})`}var Nc=pe.object({old_string:pe.string().min(1,"old_string cannot be empty"),new_string:pe.string(),replace_all:pe.boolean().optional()}).strict(),$c=pe.object({file_path:pe.string().min(1),old_string:pe.string().optional(),new_string:pe.string().optional(),replace_all:pe.boolean().optional(),edits:pe.array(Nc).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:pe.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:pe.ZodIssueCode.custom,message:"Provide old_string/new_string, or use edits."});return}t.old_string.trim()||e.addIssue({code:pe.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:pe.ZodIssueCode.custom,message:"old_string cannot be empty",path:["edits",o,"old_string"]}))}}).strict();function Dc(t){let e=No(t);if(e)throw new Error(e)}function Uc(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 $o=N({name:"apply_patch",description:"Edit a local file by direct string replacement. Supports single replacement fields or batch edits.",inputSchema:$c,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{let e=Le(t.file_path);try{await Rc(e);let n=Le(await Oc(e));Dc(n);let r=await Ic(n,"utf8"),o=Uc(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?m("apply_patch failed: target text not found.",!0):m(`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?m("No changes made."):(await Lc(n,s,"utf8"),m(`Success. Updated file: ${n}
|
|
15
19
|
Edits: ${o.length}
|
|
16
|
-
Replacements: ${i}`))}catch(n){return n.code==="ENOENT"?m(`apply_patch failed: file does not exist: ${
|
|
17
|
-
`)}function
|
|
18
|
-
`))}catch(i){return m(`list_dir failed: ${i.message}`,!0)}}});import{spawn as
|
|
19
|
-
`))}catch(o){return m(`grep_files failed: ${o.message}`,!0)}}});import{z as Ue}from"zod";var Yr=null;function Nn(e){Yr=e}function Zr(){return Yr}var vl=Ue.object({server:Ue.string().optional(),cursor:Ue.string().optional()}).strict(),xl=Ue.object({server:Ue.string().optional(),cursor:Ue.string().optional()}).strict(),bl=Ue.object({server:Ue.string().min(1),uri:Ue.string().min(1)}).strict();function $n(){let e=Zr();if(!e)throw new Error("MCP pool is not initialized");return e}var Qr=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:vl,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 m(`MCP server not found: ${e}`,!0);let i=await s.client.listResources(t?{cursor:t}:void 0);return m(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(t)return m("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 m(JSON.stringify({resources:o},null,2))}catch(n){return m(`list_mcp_resources failed: ${n.message}`,!0)}}}),eo=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:xl,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 m(`MCP server not found: ${e}`,!0);let i=await s.client.listResourceTemplates(t?{cursor:t}:void 0);return m(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(t)return m("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 m(JSON.stringify({resourceTemplates:o},null,2))}catch(n){return m(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),to=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:bl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,uri:t})=>{try{let r=$n().get(e);if(!r)return m(`MCP server not found: ${e}`,!0);let o=await r.client.readResource({uri:t});return m(JSON.stringify({server:e,uri:t,...o},null,2))}catch(n){return m(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as lt}from"zod";var Cl=lt.object({step:lt.string().min(1),status:lt.enum(["pending","in_progress","completed"])}).strict(),El=lt.object({explanation:lt.string().optional(),plan:lt.array(Cl).min(1)}).strict(),no=[],ro=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:El,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:e,plan:t})=>{if(t.filter(r=>r.status==="in_progress").length>1)return m("At most one step can be in_progress at a time",!0);if(t.length<4){let r=t[0]?.step??"";return m(`<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 no=t,m(JSON.stringify({message:"Plan updated",explanation:e,plan:no},null,2))}});import{readFile as Al}from"fs/promises";import{homedir as Ml}from"os";import{join as oo}from"path";import{z as so}from"zod";var wl=so.object({memory_id:so.string().min(1)}).strict();function kl(){let e=process.env.MEMO_HOME?.trim()||oo(Ml(),".memo");return oo(e,"Agents.md")}var io=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:wl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:e})=>{try{let t=kl(),n=await Al(t,"utf8");return m(JSON.stringify({memory_id:e,memory_summary:n},null,2))}catch{return m(`memory not found for memory_id=${e}`,!0)}}});import{z as ao}from"zod";var Pl=ao.object({url:ao.string().min(1)}).strict(),lo=1e4,Et=512e3,Dn=4e3,Il=new Set(["http:","https:"]),Rl=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Ol=/<\s*(br|hr)\s*\/?>/gi,Ll=/<\s*li[^>]*>/gi,Nl=/<[^>]+>/g,$l=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Dl=e=>e.replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/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""}}),Ul=e=>{let r=e.replace($l," ").replace(Ll,"- ").replace(Ol,`
|
|
20
|
-
`).replace(
|
|
21
|
-
`).replace(
|
|
20
|
+
Replacements: ${i}`))}catch(n){return n.code==="ENOENT"?m(`apply_patch failed: file does not exist: ${e}`,!0):m(`apply_patch failed: ${n.message}`,!0)}}});import{readFile as Hc}from"fs/promises";import{z as we}from"zod";var Do=500,Uo=200,Fc=we.object({file_path:we.string().min(1),offset:we.number().int().positive().optional(),limit:we.number().int().positive().optional(),mode:we.enum(["slice","indentation"]).optional(),indentation:we.object({anchor_line:we.number().int().positive().optional(),max_levels:we.number().int().nonnegative().optional(),include_siblings:we.boolean().optional(),include_header:we.boolean().optional(),max_lines:we.number().int().positive().optional()}).strict().optional()}).strict();function Bc(t){return t.length<=Do?t:t.slice(0,Do)}function Wc(t){let e=0;for(let n of t)if(n===" ")e+=1;else if(n===" ")e+=4;else break;return e}function jc(t){return t.split(/\r?\n/).map((n,r)=>({line:r+1,text:Bc(n),indent:Wc(n)}))}function Gc(t){return t.map(e=>`L${e.line}: ${e.text}`).join(`
|
|
21
|
+
`)}function zc(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 qc(t,e){let n=e.offset??1,r=e.limit??Uo,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),v=s-1,h=s-1;for(;v-1>=0;){let f=t[v-1];if(!f)break;let x=/^\s*(#|\/\/|--)/.test(f.text),b=f.text.trim().length===0;if(f.indent<g||!l&&f.indent===g&&!x&&!b||!c&&(x||b)&&f.indent<i.indent||(v-=1,h-v+1>=u))break}for(;h+1<t.length&&h-v+1<u;){let f=t[h+1];if(!f||f.indent<g||!l&&f.indent===g)break;h+=1}return t.slice(v,h+1)}var Ho=N({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Fc,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??1,n=t.limit??Uo;if(e<=0)return m("offset must be a 1-indexed line number",!0);if(n<=0)return m("limit must be greater than zero",!0);let r=t.file_path.trim();if(!r.startsWith("/"))return m("file_path must be an absolute path",!0);let o=Le(r);try{let s=await Hc(o,"utf8"),i=jc(s);if(i.length===0)return m("");let l=(t.mode??"slice")==="indentation"?qc(i,t):zc(i,e,n);return m(Gc(l))}catch(s){return m(`read_file failed: ${s.message}`,!0)}}});import{readdir as Kc,lstat as Vc}from"fs/promises";import{join as Xc}from"path";import{z as Et}from"zod";var Jc=1,Yc=25,Zc=2,Qc=Et.object({dir_path:Et.string().min(1),offset:Et.number().int().positive().optional(),limit:Et.number().int().positive().optional(),depth:Et.number().int().positive().optional()}).strict();function eu(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 Fo=N({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:Qc,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??Jc,n=t.limit??Yc,r=t.depth??Zc;if(e<=0)return m("offset must be a 1-indexed entry number",!0);if(n<=0)return m("limit must be greater than zero",!0);if(r<=0)return m("depth must be greater than zero",!0);let o=t.dir_path.trim();if(!o.startsWith("/"))return m("dir_path must be an absolute path",!0);let s=Le(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 Kc(u.absPath);g.sort((v,h)=>v.localeCompare(h));for(let v of g){let h=Xc(u.absPath,v),f=await Vc(h),x=f.isSymbolicLink()?"symlink":f.isDirectory()?"dir":f.isFile()?"file":"other";a.push({path:h,displayDepth:u.displayDepth,kind:x}),x==="dir"&&u.depth>1&&i.push({absPath:h,depth:u.depth-1,displayDepth:u.displayDepth+1})}}if(a.length===0)return m(`Absolute path: ${s}`);let l=e-1;if(l>=a.length)return m("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),p=[`Absolute path: ${s}`,...c.map(eu)];return l+n<a.length&&p.push(`More than ${n} entries found`),m(p.join(`
|
|
22
|
+
`))}catch(i){return m(`list_dir failed: ${i.message}`,!0)}}});import{spawn as tu}from"child_process";import{resolve as nu}from"path";import{z as At}from"zod";var ru=100,ou=2e3,su=3e4,iu=At.object({pattern:At.string().min(1),include:At.string().optional(),path:At.string().optional(),limit:At.number().int().positive().optional()}).strict();function au(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=tu("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"))},su);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 Bo=N({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:iu,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.pattern.trim();if(!e)return m("pattern must not be empty",!0);let n=Math.min(t.limit??ru,ou),r=t.path?.trim()?nu(process.cwd(),t.path.trim()):process.cwd();try{let o=await au({pattern:e,include:t.include,searchPath:r,cwd:process.cwd(),limit:n});if(o.exitCode===1)return m("No matches found.");if(o.exitCode!==0)return m(`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?m("No matches found."):m(s.join(`
|
|
23
|
+
`))}catch(o){return m(`grep_files failed: ${o.message}`,!0)}}});import{z as Ne}from"zod";import{createHash as lu}from"crypto";import{mkdir as cu,readFile as uu,rename as pu,writeFile as du}from"fs/promises";import{homedir as Jn}from"os";import{dirname as mu,join as Qn}from"path";var fu="mcp.json",Zt=2,gu=120,hu=600*1e3,Wo=1440*60*1e3;function Vn(){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 yu(t){return t==="~"?Jn():t.startsWith("~/")?Qn(Jn(),t.slice(2)):t}function _u(){let t=process.env.MEMO_HOME?.trim();return t?yu(t):Qn(Jn(),".memo")}function jo(){return Qn(_u(),"cache",fu)}function Yn(t){if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>Yn(r)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Yn(e[r])}`).join(",")}}`}function Go(t){return lu("sha256").update(Yn(t)).digest("hex")}function Su(t){return t instanceof Error?t.message:String(t)}function Yt(){return{version:Zt,toolsByServer:{},responses:{}}}var Zn=class{data=Yt();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>Wo&&delete this.data.toolsByServer[n]}async ensureLoaded(){if(!Vn()){this.loaded=!0;return}if(!this.loaded){if(this.loadPromise){await this.loadPromise;return}this.loadPromise=(async()=>{let e=jo();try{let n=await uu(e,"utf8"),r=JSON.parse(n);if(r.version===Zt){let o=r;this.data={version:Zt,toolsByServer:o.toolsByServer??{},responses:o.responses??{}}}else r.version===1&&r.entries?this.data={version:Zt,toolsByServer:{},responses:r.entries}:this.data=Yt()}catch{this.data=Yt()}finally{this.pruneExpiredResponses(),this.pruneExpiredTools(),this.loaded=!0}})(),await this.loadPromise}}async persistToDisk(){if(!Vn())return;this.pruneExpiredResponses(),this.pruneExpiredTools();let e=jo(),n=`${e}.tmp`,r=mu(e);await cu(r,{recursive:!0}),await du(n,JSON.stringify(this.data,null,2),"utf8"),await pu(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(){Vn()&&(this.persistRequested=!0,!this.persistTimer&&(this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersistQueue()},gu),this.persistTimer.unref?.()))}async getServerTools(e,n){await this.ensureLoaded();let r=this.data.toolsByServer[e];if(!r)return null;if(r.configHash!==Go(n))return delete this.data.toolsByServer[e],this.schedulePersist(),null;let o=Date.now()-r.fetchedAt;return o>Wo?(delete this.data.toolsByServer[e],this.schedulePersist(),null):{tools:r.tools,stale:o>hu,ageMs:o}}async setServerTools(e,n,r){await this.ensureLoaded(),this.data.toolsByServer[e]={fetchedAt:Date.now(),configHash:Go(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(Su(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=Yt(),this.loaded=!1,this.loadPromise=null,this.responseInflight.clear(),this.persistRequested=!1,this.persistRunning=!1,this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null)}},Xn=null;function Qt(){return Xn||(Xn=new Zn),Xn}var zo=null,qo=null;function er(t){zo=t}function Ko(){return zo}function tr(t){qo=t}function Vo(){return qo}var Tu=Ne.object({server:Ne.string().optional(),cursor:Ne.string().optional()}).strict(),vu=Ne.object({server:Ne.string().optional(),cursor:Ne.string().optional()}).strict(),bu=Ne.object({server:Ne.string().min(1),uri:Ne.string().min(1)}).strict(),en=15e3,Cu=6e4;function nr(){let t=Ko();if(!t)throw new Error("MCP pool is not initialized");return t}function rr(){return Vo()??Qt()}function Yo(t){return t instanceof Error?t.message:String(t)}function Xo(t,e){return`list_resources:${t}:${e??""}`}function Jo(t,e){return`list_resource_templates:${t}:${e??""}`}function xu(t,e){return`read_resource:${t}:${e}`}function or(t,e){return typeof t.hasServer=="function"?t.hasServer(e):typeof t.get=="function"?!!t.get(e):!1}async function sr(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 Zo(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 Qo=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:Tu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=nr(),r=rr(),o=t?.trim();if(o){if(!or(n,o))return m(`MCP server not found: ${t}`,!0);let l=await sr(n,o);if(!l)return m(`MCP server not found: ${t}`,!0);let c=await r.withResponseCache(Xo(l.name,e),en,async()=>{let p=await l.client.listResources(e?{cursor:e}:void 0);return{server:l.name,resources:p.resources,nextCursor:p.nextCursor}});return m(JSON.stringify(c,null,2))}if(e)return m("cursor is only supported when server is specified",!0);let s=await Zo(n),i=`all:${s.map(l=>l.name).join(",")}`,a=await r.withResponseCache(Xo(i),en,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 v=s[g]?.name??"unknown";if(u.status==="rejected"){p.push({server:v,error:Yo(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 m(JSON.stringify(a,null,2))}catch(n){return m(`list_mcp_resources failed: ${n.message}`,!0)}}}),es=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:vu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=nr(),r=rr(),o=t?.trim();if(o){if(!or(n,o))return m(`MCP server not found: ${t}`,!0);let l=await sr(n,o);if(!l)return m(`MCP server not found: ${t}`,!0);let c=await r.withResponseCache(Jo(l.name,e),en,async()=>{let p=await l.client.listResourceTemplates(e?{cursor:e}:void 0);return{server:l.name,resourceTemplates:p.resourceTemplates,nextCursor:p.nextCursor}});return m(JSON.stringify(c,null,2))}if(e)return m("cursor is only supported when server is specified",!0);let s=await Zo(n),i=`all:${s.map(l=>l.name).join(",")}`,a=await r.withResponseCache(Jo(i),en,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 v=s[g]?.name??"unknown";if(u.status==="rejected"){p.push({server:v,error:Yo(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 m(JSON.stringify(a,null,2))}catch(n){return m(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),ts=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:bu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let n=nr(),r=rr(),o=t.trim();if(!or(n,o))return m(`MCP server not found: ${t}`,!0);let s=await sr(n,o);if(!s)return m(`MCP server not found: ${t}`,!0);let i=await r.withResponseCache(xu(o,e),Cu,async()=>{let a=await s.client.readResource({uri:e});return{server:o,uri:e,...a}});return m(JSON.stringify(i,null,2))}catch(n){return m(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as lt}from"zod";var wu=lt.object({step:lt.string().min(1),status:lt.enum(["pending","in_progress","completed"])}).strict(),Mu=lt.object({explanation:lt.string().optional(),plan:lt.array(wu).min(1)}).strict(),ns=[],rs=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:Mu,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>{if(e.filter(r=>r.status==="in_progress").length>1)return m("At most one step can be in_progress at a time",!0);if(e.length<4){let r=e[0]?.step??"";return m(`<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 ns=e,m(JSON.stringify({message:"Plan updated",explanation:t,plan:ns},null,2))}});import{readFile as Eu}from"fs/promises";import{homedir as Au}from"os";import{join as os}from"path";import{z as ss}from"zod";var Pu=ss.object({memory_id:ss.string().min(1)}).strict();function ku(){let t=process.env.MEMO_HOME?.trim()||os(Au(),".memo");return os(t,"Agents.md")}var is=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:Pu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=ku(),n=await Eu(e,"utf8");return m(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return m(`memory not found for memory_id=${t}`,!0)}}});import{z as as}from"zod";var Ru=as.object({url:as.string().min(1)}).strict(),ls=1e4,Pt=512e3,ir=4e3,Iu=new Set(["http:","https:"]),Ou=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Lu=/<\s*(br|hr)\s*\/?>/gi,Nu=/<\s*li[^>]*>/gi,$u=/<[^>]+>/g,Du=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Uu=t=>t.replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/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""}}),Hu=t=>{let r=t.replace(Du," ").replace(Nu,"- ").replace(Lu,`
|
|
24
|
+
`).replace(Ou,`
|
|
25
|
+
`).replace($u," "),s=Uu(r).replace(/\r/g,"").split(`
|
|
22
26
|
`).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()},
|
|
24
|
-
...[truncated]`}function
|
|
25
|
-
${o}`),
|
|
26
|
-
|
|
27
|
-
`))}async function
|
|
28
|
-
`)}catch{}try{s.stdin?.end()}catch{}return r}var
|
|
29
|
-
`)}function
|
|
30
|
-
|
|
31
|
-
`);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function
|
|
32
|
-
`)}formatToolDescription(
|
|
33
|
-
`)}groupByServer(
|
|
34
|
-
${
|
|
35
|
-
${JSON.stringify(
|
|
36
|
-
${
|
|
37
|
-
${
|
|
27
|
+
`).trim()},Fu=t=>t.replace(/\s+/g," ").trim(),cs=N({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:Ru,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return m(`Invalid URL: ${t.url}`,!0)}if(!Iu.has(e.protocol))return m(`Unsupported protocol: ${e.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),ls);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 m(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(o.body&&o.body.getReader){let x=o.body.getReader(),b=[];for(;;){let{done:q,value:fe}=await x.read();if(q)break;if(fe){if(a+=fe.byteLength,a>Pt)return n.abort(),m(`Request aborted: response body exceeds ${Pt} bytes`,!0);b.push(fe)}}let E=new Uint8Array(a),B=0;for(let q of b)E.set(q,B),B+=q.byteLength;l=new TextDecoder().decode(E)}else if(l=await o.text(),a=new TextEncoder().encode(l).byteLength,a>Pt)return m(`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?Hu(l):l.trim(),g=Fu(u),v=g.length>ir?`${g.slice(0,ir)}...`:g,h=g.length>ir?" text_truncated=true":"",f=p?" source=html_stripped":"";return m(`status=${o.status} bytes=${a} text_chars=${g.length} text="${v}"${h}${f}`)}catch(o){return o.name==="AbortError"?m(`Request timeout or aborted (${ls}ms)`,!0):m(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as Bu}from"child_process";import{existsSync as Wu}from"fs";import{resolve as ju}from"path";import{z as le}from"zod";var Gu=3e4,zu=1e4,qu=3e5,us=4,Ku=1500,ps=2e3,We=new Map,Vu=le.object({message:le.string().min(1),agent_type:le.string().optional()}).strict(),Xu=le.object({id:le.string().min(1),message:le.string().min(1),interrupt:le.boolean().optional()}).strict(),Ju=le.object({id:le.string().min(1)}).strict(),Yu=le.object({ids:le.array(le.string().min(1)).min(1),timeout_ms:le.number().int().positive().optional()}).strict(),Zu=le.object({id:le.string().min(1)}).strict();function ct(){return new Date().toISOString()}function ar(t){return m(`agent not found: ${t}`,!0)}function Qu(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return us;let e=Number(t);return!Number.isFinite(e)||e<=0?us:Math.floor(e)}function ep(){let t=0;for(let e of We.values())e.running&&(t+=1);return t}function tp(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=ju(process.cwd(),"dist/index.js");return Wu(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function np(t){return t!=="running"}function rp(t){return new Promise(e=>{setTimeout(e,t)})}function op(t){return t===void 0?Gu:t<=0?null:Math.max(zu,Math.min(qu,t))}function sp(t){return t.length<=ps?t:`${t.slice(0,ps)}
|
|
28
|
+
...[truncated]`}function ip(t,e){let n=[],r=t.trim(),o=e.trim();return r&&n.push(r),o&&n.push(`stderr:
|
|
29
|
+
${o}`),sp(n.join(`
|
|
30
|
+
|
|
31
|
+
`))}async function ds(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()}},Ku);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function ap(t){let e=We.get(t);return e?e.status:"not_found"}function lp(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 cp(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 up(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=ct(),e.lastOutput=ip(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 ms(t,e){let n=Qu();if(ep()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=tp(),s=Bu(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:ct(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=r,t.updatedAt=ct(),s.on("close",l=>{let c=typeof l=="number"?l:-1,p=!!(t.running?.id===r&&t.running.interrupted);up({record:t,submissionId:r,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:p})});try{s.stdin?.write(`${e.trim()}
|
|
32
|
+
`)}catch{}try{s.stdin?.end()}catch{}return r}var fs=N({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:Vu,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return m("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=ct(),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 ms(o,e);return m(JSON.stringify({...cp(o),submission_id:s},null,2))}catch(s){return We.delete(n),m(`spawn_agent failed: ${s.message}`,!0)}}}),gs=N({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Xu,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let r=We.get(t);if(!r)return ar(t);let o=e.trim();if(!o)return m("send_input failed: message must not be empty",!0);if(r.status==="closed")return m(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(r.running){if(!n)return m(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await ds(r)}try{let s=await ms(r,o);return m(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return m(`send_input failed: ${s.message}`,!0)}}}),hs=N({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Ju,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=We.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=ct()),m(JSON.stringify({agent_id:t,status:e.status},null,2))):ar(t)}}),ys=N({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Yu,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=op(e);if(n===null)return m("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},a={};for(let l of t){let c=ap(l);np(c)&&(i[l]=c,a[l]=lp(l))}return{status:i,details:a}},o=r();if(Object.keys(o.status).length>0)return m(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await rp(100),o=r(),Object.keys(o.status).length>0)return m(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return m(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),_s=N({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Zu,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=We.get(t);return e?e.status==="closed"?m(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=ct(),await ds(e),m(JSON.stringify({agent_id:t,status:"closed"},null,2))):ar(t)}});var lr={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"},Ss=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),tn={read:0,write:1,execute:2},Ts=["exec","run","shell","command","stdin"],vs=["write","patch","create","delete","modify","update"],bs=["read","get","fetch","search","list","find"],Cs=new Set(["write","execute"]);function ur(t){let e={...lr,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let r=n.toLowerCase();return cr(r,Ts)?"execute":cr(r,vs)?"write":cr(r,bs)?"read":"write"},compareRisk(n,r){return tn[n]-tn[r]},needsApproval(n,r){return r==="strict"?!0:Cs.has(n)}}}function cr(t,e){return e.some(n=>t.includes(n))}import{createHash as pp}from"crypto";function nn(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>nn(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${nn(r)}`).join(",")}}`}function pr(t,e){let n=nn(e),r=`${t}:${n}`;return pp("sha256").update(r).digest("hex").slice(0,16)}function dp(t){return`Tool "${t}" requires approval.`}function dr(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=ur({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(Ss.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=pr(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:dp(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 xs=12e3,ws=1e5;function mp(){let t=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!t)return xs;let e=Number(t);return!Number.isFinite(e)||e<=0?xs:Math.floor(e)}function fp(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function gp(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 hp(t,e,n){return`<system_hint type="tool_output_omitted" tool="${fp(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 yp(t,e){let n=mp(),r=gp(e);return r<=n?e:{content:[{type:"text",text:hp(t,r,n)}],isError:!1}}function _p(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
|
|
33
|
+
`)}function Ms(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Sp(t,e){let n=e;if(typeof e=="string"){if(e.length>ws)return{ok:!1,error:`${t.name} invalid input: input string too large (max ${ws} chars)`};let r=e.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!Ms(n))return{ok:!1,error:`${t.name} invalid input: expected object`};if(typeof t.validateInput=="function"){let r=t.validateInput(n);return r.ok?Ms(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${t.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function Tp(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 mr=class{constructor(e){this.config=e;this.approvalManager=dr(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=Sp(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=yp(e.name,l);return{actionId:o,tool:e.name,status:"success",success:!0,observation:_p(c)||"(no tool output)",durationMs:Date.now()-r}}catch(a){let l=Tp(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(`
|
|
34
|
+
|
|
35
|
+
`);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function Es(t){return new mr(t)}var rn=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 vp}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as bp}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Cp}from"@modelcontextprotocol/sdk/client/stdio.js";function xp(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function As(){return new vp({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function wp(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function Mp(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 Ep(t){let e=new URL(t.url),n=wp(Mp(t));try{let r=As(),o=new bp(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 Ap(t){if("url"in t)return Ep(t);let e={command:t.command,args:t.args,env:xp(t.env),stderr:t.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new Cp(e),r=As();return await r.connect(n),{client:r,transport:n}}var on=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 Ap(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 sn=class{pool;serverToolNames=new Map;refreshPromises=new Map;tools=new Map;cacheStore=Qt();shouldLog;constructor(){this.pool=new on,er(this.pool),tr(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(),er(null),tr(null)}getPool(){return this.pool}};var an=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new rn,this.mcpRegistry=new sn}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(`
|
|
36
|
+
`)}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(`
|
|
37
|
+
`)}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 Pp(t){let e=process.env[t]?.trim();return e?new Set(e.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function kp(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=Pp("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(Co):e==="shell_command"?t.push(xo):e==="unified_exec"?t.push(Fn,Bn):e!=="disabled"&&t.push(Fn,Bn),t.push(Qo,es,ts),t.push(rs),t.push($o),(r||n.has("grep_files"))&&t.push(Bo),(r||n.has("read_file"))&&t.push(Ho),(r||n.has("list_dir"))&&t.push(Fo),s&&t.push(is),t.push(cs),o&&t.push(fs,gs,hs,ys,_s),t}function Rp(t){let e={};for(let n of t)e[n.name]=n;return e}var Ip=Rp(kp()),Op=Object.values(Ip),Ps=Op;import td from"openai";import{encoding_for_model as Lp,get_encoding as Np}from"@dqbd/tiktoken";var ks="cl100k_base";function $p(t){let e=t?.trim()||ks;try{let n=()=>Lp(e);return n().free(),{model:e,factory:n}}catch{let n=ks,r=()=>Np(n);return r().free(),{model:n,factory:r}}}function Dp(t){if(t.role==="assistant"){let e=t.reasoning_content?`
|
|
38
|
+
${t.reasoning_content}`:"";return t.tool_calls?.length?`${t.content}${e}
|
|
39
|
+
${JSON.stringify(t.tool_calls)}`:`${t.content}${e}`}return t.role==="tool"?`${t.content}
|
|
40
|
+
${t.tool_call_id}
|
|
41
|
+
${t.name??""}`:t.content}function Rs(t){let{model:e,factory:n}=$p(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(Dp(u)),u.name&&(p+=i);return p+=s,p},dispose:()=>r.free()}}import{mkdir as Up,writeFile as Hp,readFile as Fp,access as Bp}from"fs/promises";import{homedir as Ls}from"os";import{dirname as Wp,join as Ye,parse as jp,resolve as Gp}from"path";import{randomUUID as q_}from"crypto";import{parse as zp}from"toml";var qp=Ye(Ls(),".memo"),Kp="sessions",gr=12e4,kt={current_provider:"deepseek",max_prompt_tokens:gr,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function fr(t){return t.trim().toLowerCase()}function Is(t){if(typeof t?.context_window=="number"&&Number.isFinite(t.context_window)&&t.context_window>0)return Math.floor(t.context_window)}function ut(t,e){let n=t.model_profiles;if(!n)return gr;let r=new Map;for(let[a,l]of Object.entries(n))r.set(fr(a),l);let o=fr(e.name),s=fr(e.model),i=`${o}:${s}`;return Is(r.get(i))??Is(r.get(s))??gr}function Os(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function Vp(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 Xp(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,r]of Object.entries(t)){if(!r||typeof r!="object"||Array.isArray(r))continue;let o=r,s={};typeof o.supports_parallel_tool_calls=="boolean"&&(s.supports_parallel_tool_calls=o.supports_parallel_tool_calls),typeof o.supports_reasoning_content=="boolean"&&(s.supports_reasoning_content=o.supports_reasoning_content),typeof o.context_window=="number"&&Number.isFinite(o.context_window)&&o.context_window>0&&(s.context_window=Math.floor(o.context_window)),Object.keys(s).length>0&&(e[n]=s)}return Object.keys(e).length>0?e:void 0}function Ns(t){return t.startsWith("~")?Ye(Ls(),t.slice(1)):t}function Jp(t){let e=t.providers.map(i=>{let a=typeof i?.name=="string"?i.name:"";if(!a)return"";let c=[`[[providers.${Os(a)}]]`,`name = ${JSON.stringify(a)}`,`env_api_key = ${JSON.stringify(String(i.env_api_key??""))}`,`model = ${JSON.stringify(String(i.model??""))}`];return i.base_url&&c.push(`base_url = ${JSON.stringify(String(i.base_url))}`),c.join(`
|
|
38
42
|
`)}).filter(Boolean).join(`
|
|
39
43
|
|
|
40
|
-
`),n=
|
|
41
|
-
`)}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
${
|
|
45
|
-
|
|
44
|
+
`),n=t.model_profiles?Object.entries(t.model_profiles).map(([i,a])=>{let l=[],c=Os(i);return l.push(`[model_profiles.${c}]`),typeof a.supports_parallel_tool_calls=="boolean"&&l.push(`supports_parallel_tool_calls = ${a.supports_parallel_tool_calls}`),typeof a.supports_reasoning_content=="boolean"&&l.push(`supports_reasoning_content = ${a.supports_reasoning_content}`),typeof a.context_window=="number"&&Number.isFinite(a.context_window)&&a.context_window>0&&l.push(`context_window = ${Math.floor(a.context_window)}`),l.length>1?l.join(`
|
|
45
|
+
`):""}).filter(Boolean).join(`
|
|
46
|
+
|
|
47
|
+
`):"",r="";t.mcp_servers&&Object.keys(t.mcp_servers).length>0&&(r=Object.entries(t.mcp_servers).map(([i,a])=>{if("url"in a){let h=[`[mcp_servers.${i}]`];h.push(`type = "${a.type??"streamable_http"}"`),h.push(`url = "${a.url}"`),a.bearer_token_env_var&&h.push(`bearer_token_env_var = ${JSON.stringify(a.bearer_token_env_var)}`);let f=a.http_headers??a.headers;if(f&&Object.keys(f).length>0){let x=Object.entries(f).map(([E,B])=>`${JSON.stringify(E)} = ${JSON.stringify(B)}`).join(", "),b=a.http_headers?"http_headers":"headers";h.push(`${b} = { ${x} }`)}return h.join(`
|
|
48
|
+
`)}let l=a.args?`args = ${JSON.stringify(a.args)}`:"",c=a.type?`type = "${a.type}"
|
|
49
|
+
`:"",p=a.stderr?`stderr = "${a.stderr}"
|
|
50
|
+
`:"",u=`[mcp_servers.${i}]
|
|
51
|
+
${c}command = "${a.command}"
|
|
52
|
+
${p}${l}`.trimEnd(),g=a.env?Object.entries(a.env):[];if(g.length===0)return u;let v=g.map(([h,f])=>`${JSON.stringify(h)} = ${JSON.stringify(f)}`).join(`
|
|
46
53
|
`);return`${u}
|
|
47
54
|
|
|
48
|
-
[mcp_servers.${
|
|
49
|
-
${
|
|
55
|
+
[mcp_servers.${i}.env]
|
|
56
|
+
${v}`}).join(`
|
|
50
57
|
|
|
51
|
-
`));let
|
|
52
|
-
`),
|
|
58
|
+
`));let o=[`current_provider = "${t.current_provider}"`];return typeof t.max_prompt_tokens=="number"&&Number.isFinite(t.max_prompt_tokens)&&o.push(`max_prompt_tokens = ${Math.floor(t.max_prompt_tokens)}`),Array.isArray(t.active_mcp_servers)&&o.push(`active_mcp_servers = ${JSON.stringify(t.active_mcp_servers)}`),[o.join(`
|
|
59
|
+
`),e,n,r].filter(Boolean).join(`
|
|
53
60
|
|
|
54
|
-
`)}async function
|
|
61
|
+
`)}async function Me(t,e){await Up(Wp(t),{recursive:!0}),await Hp(t,Jp(e),"utf-8")}async function de(){let t=process.env.MEMO_HOME?Ns(process.env.MEMO_HOME):qp,e=Ye(t,"config.toml");try{await Bp(e);let n=await Fp(e,"utf-8"),r=zp(n),o=Vp(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(p=>typeof p=="string"&&p.trim().length>0):void 0,a=Xp(r.model_profiles),l={current_provider:r.current_provider??kt.current_provider,max_prompt_tokens:s??kt.max_prompt_tokens,providers:o,model_profiles:a,mcp_servers:r.mcp_servers??{},active_mcp_servers:i},c=!l.providers.length;return{config:c?kt:l,home:t,configPath:e,needsSetup:c}}catch{return{config:kt,home:t,configPath:e,needsSetup:!0}}}function Ze(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 ln(t,e){let n=e.historyDir??Ye(t.home,Kp),r=Ns(n),o=Gp(process.cwd()),s=jp(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 Ye(r,"-root");let l=`-${a.map(c=>c.replace(/[^A-Za-z0-9._-]/g,"_")).join("-")}`;return Ye(r,l)}function $s(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 Ye(t,u)}import"openai";var Yp={supportsParallelToolCalls:!1,supportsReasoningContent:!1};function hr(t){return t.trim().toLowerCase()}function Zp(t,e,n){if(!n)return;let r=new Map;for(let[s,i]of Object.entries(n))r.set(hr(s),i);let o=r.get(`${t}:${e}`);return o||r.get(e)}function Qp(t,e){if(!e)return{capabilities:t,usedOverride:!1};let n={...t},r=!1;return typeof e.supports_parallel_tool_calls=="boolean"&&(n.supportsParallelToolCalls=e.supports_parallel_tool_calls,r=!0),typeof e.supports_reasoning_content=="boolean"&&(n.supportsReasoningContent=e.supports_reasoning_content,r=!0),typeof e.context_window=="number"&&Number.isFinite(e.context_window)&&e.context_window>0&&(n.contextWindow=Math.floor(e.context_window),r=!0),{capabilities:n,usedOverride:r}}function Ds(t,e){let n=hr(t.name),r=hr(t.model),{capabilities:o,usedOverride:s}=Qp(Yp,Zp(n,r,e));return{profile:{wireApi:"chat_completions",...o,isFallback:!s}}}function ed(t){if(t.length!==0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}function Us(t){let e=ed(t.toolDefinitions),n={model:t.model,messages:t.messages,tools:e,tool_choice:e?"auto":void 0};return e&&t.profile.supportsParallelToolCalls&&(n.parallel_tool_calls=!0),n}function nd(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 rd(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function od(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 sd(t){let e=t?.reasoning_content;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}async function Hs(t,e,n){let r=await de(),o=r.config,s=new an;if(s.registerNativeTools(Ps),await s.loadMcpServers(nd(o.mcp_servers,e.activeMcpServers)),t.tools)for(let[g,v]of Object.entries(t.tools))s.registerNativeTool({name:g,description:v.description,source:"native",inputSchema:{type:"object"},execute:v.execute});let i=s.toRegistry(),a=async()=>{let g=await(t.loadPrompt??uo)(),v=s.generateToolDescriptions();return v&&(g+=`
|
|
55
62
|
|
|
56
|
-
${
|
|
57
|
-
`),{thinkingParts:n,cleaned:r}=
|
|
63
|
+
${v}`),g},l=s.generateToolDefinitions(),c=ln(r,e),p=$s(c,n),u=new Kt(p);return{tools:i,dispose:async()=>{t.dispose&&await t.dispose(),await s.dispose()},callLLM:t.callLLM??(async(g,v,h)=>{let f=Ze(o,e.providerName),x=process.env[f.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!x)throw new Error(`Missing env var ${f.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let b=new td({apiKey:x,baseURL:f.base_url}),E=g.map(od),{profile:B}=Ds(f,o.model_profiles),q=h?.tools??l,fe=Us({model:f.model,messages:E,toolDefinitions:q,profile:B}),ce=await b.chat.completions.create(fe,{signal:h?.signal}),J=ce.choices?.[0]?.message,P=sd(J);if(J?.tool_calls&&J.tool_calls.length>0){let H=[];J.content&&H.push({type:"text",text:J.content});for(let K of J.tool_calls)if(K.type==="function"){let V=rd(K.function.arguments);V.ok?H.push({type:"tool_use",id:K.id,name:K.function.name,input:V.data}):H.push({type:"text",text:`[tool_use parse error] ${V.error}; raw: ${V.raw}`})}let O=H.some(K=>K.type==="tool_use");return{content:H,reasoning_content:P,stop_reason:O?"tool_use":"end_turn",usage:{prompt:ce.usage?.prompt_tokens??void 0,completion:ce.usage?.completion_tokens??void 0,total:ce.usage?.total_tokens??void 0}}}let Y=J?.content;if(typeof Y!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:Y}],reasoning_content:P,stop_reason:"end_turn",usage:{prompt:ce.usage?.prompt_tokens??void 0,completion:ce.usage?.completion_tokens??void 0,total:ce.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:t.historySinks??[u],tokenCounter:t.tokenCounter??Rs(e.tokenizerModel),historyFilePath:p}}function id(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 Fs(t){if(t.length===0)return;let e=t.join(`
|
|
64
|
+
`),{thinkingParts:n,cleaned:r}=id(e);return n.length>0?n.join(`
|
|
58
65
|
|
|
59
|
-
`):r||void 0}import{randomUUID as
|
|
66
|
+
`):r||void 0}import{randomUUID as md}from"crypto";var cn="interactive";var _r="success",pt="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.",Bs=`Generate a concise session title based on the user's first prompt.
|
|
60
67
|
Requirements:
|
|
61
68
|
- 3 to 8 words when possible
|
|
62
69
|
- Keep it specific and descriptive
|
|
63
70
|
- Return title only, no quotes, no punctuation-only output
|
|
64
|
-
`;var
|
|
65
|
-
`)}function
|
|
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 Wo(e,t){for(let n of t)try{await n.append(e)}catch(r){tu({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 en(e){return qn(e,new WeakSet,0)}var nu=100;function qn(e,t,n){if(n>nu)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 jo(e){return e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:en(t.input)}}))}function zo(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 qo(e){return e.length<=60?e:`${e.slice(0,57).trimEnd()}...`}function Go(e){let t=e.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!t)return"";let n=t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?qo(n):""}function Ko(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 qo(r||t)}function Jn(e){return{role:"tool",content:e.observation,tool_call_id:e.actionId,name:e.tool}}function Vo(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?`${eu} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as su}from"crypto";function ru(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function Xo(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 Jo(e){let t=ru();if(Xo(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)Xo(t,n);return t}async function ee(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 pt(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 tn=class{constructor(t,n,r,o,s){this.deps=t;this.options=n;this.id=n.sessionId||su(),this.mode=n.mode||Qt,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=t.historySinks??[],this.hooks=Jo(t),this.historyFilePath=s;let i=Fo(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}:${en(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=en(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 ee(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 ee(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=Ko(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Uo},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=Go(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 ee(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 ee(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:t,promptTokens:l,history:pt(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,t,n.signal);let c="",u="ok",p,g=0,_=null,h=-1;for(let f=0;;f++){let S=this.tokenCounter.countMessages(this.history);if(S>a){let M=`Context tokens (${S}) 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:f,content:M,role:"assistant",meta:{tokens:{prompt:S}}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:M,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&S>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${S}`);let b="",C=[],K,X,q,G=!1;try{let M=await this.deps.callLLM(this.history,J=>{J&&(G=!0),this.deps.onAssistantStep?.(J,f)},{signal:n.signal}),I=Bo(M);b=I.textContent,C=I.toolUseBlocks,X=I.stopReason,K=I.usage,q=I.reasoningContent,b.trim().length>0&&(_=b,h=f)}catch(M){if(this.cancelling&&Xn(M)){u="cancelled",c="",p="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:u,errorMessage:p,turnUsage:{...s},steps:o});break}let I=`LLM call failed: ${M.message}`;this.history.push({role:"assistant",content:I}),u="error",c=I,p=I,await this.emitEvent("final",{turn:r,content:I,role:"assistant"}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}!G&&b&&this.deps.onAssistantStep?.(b,f);let ye=C.length===0&&b?zo(b,this.deps.tools):null,k,U=null;if(C.length>0){let M=C[0];if(M){let I=b?Do([b]):void 0;k={action:{tool:M.name,input:M.input},thinking:I},U={role:"assistant",content:b,reasoning_content:q,tool_calls:jo(C)}}else k={}}else b?(k={final:b},U={role:"assistant",content:b,reasoning_content:q}):k={};let j=this.tokenCounter.countText(b),P=K?.prompt??S,L=K?.completion??j,Ie=K?.total??P+L,V={prompt:P,completion:L,total:Ie};if(Vn(s,V),Vn(this.sessionUsage,V),o.push({index:f,assistantText:b,parsed:k,tokenUsage:V}),await this.emitEvent("assistant",{turn:r,step:f,content:b,role:"assistant",meta:{tokens:V,protocol_violation:!!ye,protocol_violation_count:ye?g+1:g||void 0}}),ye){g+=1;let M=`Model protocol error: returned plain-text tool JSON for "${ye.tool}" ${g} 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:f,content:M,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:u,errorMessage:p,tokenUsage:V,turnUsage:{...s},steps:o});break}if(U&&this.history.push(U),C.length>0&&this.toolsDisabled){for(let M of C)this.history.push({role:"tool",content:Ho,tool_call_id:M.id,name:M.name});u="error",c=ut,p=ut,this.history.push({role:"assistant",content:ut}),await this.emitEvent("final",{turn:r,step:f,content:ut,role:"assistant",meta:{error_type:"tool_disabled",tool_count:C.length,tools:C.map(M=>M.name).join(","),tokens:V}}),await ee(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:ut,status:u,errorMessage:p,tokenUsage:V,turnUsage:{...s},steps:o});break}if(C.length>1){for(let A of C)this.maybeWarnRepeatedAction(A.name,A.input);await this.emitEvent("action",{turn:r,step:f,meta:{tools:C.map(A=>A.name),action_ids:C.map(A=>A.id),action_id:C[0]?.id,parallel:!0,phase:"dispatch",thinking:k.thinking,toolBlocks:C.map(A=>({id:A.id,name:A.name,input:A.input}))}});let M=C[0];M&&await ee(this.hooks,"onAction",{sessionId:this.id,turn:r,step:f,action:{tool:M.name,input:M.input},parallelActions:C.map(A=>({tool:A.name,input:A.input})),thinking:k.thinking,history:pt(this.history)});let I=C.every(A=>!!this.deps.tools[A.name]?.supportsParallelToolCalls),J=C.some(A=>!!this.deps.tools[A.name]?.isMutating),Ae=I&&!J?"parallel":"sequential",Te=await this.toolOrchestrator.executeActions(C.map(A=>({id:A.id,name:A.name,input:A.input})),{...this.buildToolApprovalHooks(r,f),executionMode:Ae,failurePolicy:"fail_fast"}),Re=Vo(C,Te.results,Te.hasRejection);for(let[A,te]of Re.entries())this.history.push(Jn(te)),await this.emitEvent("observation",{turn:r,step:f,content:te.observation,meta:{tool:te.tool,index:A,action_id:te.actionId,phase:"result",status:te.status,error_type:te.errorType,duration_ms:te.durationMs,execution_mode:Ae}});let pe=Re.map(A=>`[${A.tool}]: ${A.observation}`).join(`
|
|
67
|
-
|
|
68
|
-
`),
|
|
69
|
-
`):""}).join("")}function
|
|
70
|
-
`).map(
|
|
71
|
-
`).trim():""}function
|
|
72
|
-
|
|
73
|
-
`)});let o=
|
|
74
|
-
`);if(
|
|
75
|
-
`)}function
|
|
76
|
-
`).map((n,r)=>
|
|
77
|
-
`)}function
|
|
71
|
+
`;var ad="Skipped tool execution after previous rejection.",Ws="Tool execution skipped: tools are disabled in current permission mode.";function ld(t){process.stderr.write(`${JSON.stringify(t)}
|
|
72
|
+
`)}function js(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 Sr(){return{prompt:0,completion:0,total:0}}function Tr(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 Gs(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(`
|
|
73
|
+
`),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 zs(t,e){for(let n of e)try{await n.append(t)}catch(r){ld({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function vr(t){return t instanceof Error&&t.name==="AbortError"}function un(t){return yr(t,new WeakSet,0)}var cd=100;function yr(t,e,n){if(n>cd)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=>yr(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)}:${yr(i,e,n+1)}`).join(",")}}`;return e.delete(t),o}function qs(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:un(e.input)}}))}function Ks(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 Vs(t){return t.length<=60?t:`${t.slice(0,57).trimEnd()}...`}function Xs(t){let e=t.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!e)return"";let n=e.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?Vs(n):""}function Js(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 Vs(r||e)}function br(t){return{role:"tool",content:t.observation,tool_call_id:t.actionId,name:t.tool}}function Ys(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?`${ad} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as dd}from"crypto";function ud(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function Zs(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 Qs(t){let e=ud();if(Zs(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)Zs(e,n);return e}async function Q(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 dt(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 pn=class{constructor(e,n,r,o,s){this.deps=e;this.options=n;this.id=n.sessionId||dd(),this.mode=n.mode||cn,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=e.historySinks??[],this.hooks=Qs(e),this.historyFilePath=s;let i=js(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=Es({tools:e.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=Sr();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}:${un(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=un(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 Q(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 Q(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=Js(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Bs},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=Xs(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(o=a,s="llm")}catch(i){if(vr(i))return}this.title=o,await this.emitEvent("session_title",{turn:e,content:o,meta:{source:s,original_prompt:n}}),await Q(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=Sr(),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 Q(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:e,promptTokens:l,history:dt(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,e,n.signal);let c="",p="ok",u,g=0,v=null,h=-1;for(let f=0;;f++){let x=this.tokenCounter.countMessages(this.history);if(x>a){let M=`Context tokens (${x}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:M}),p="prompt_limit",c=M,u=M,await this.emitEvent("final",{turn:r,step:f,content:M,role:"assistant",meta:{tokens:{prompt:x}}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:M,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&x>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${x}`);let b="",E=[],B,q,fe,ce=!1;try{let M=await this.deps.callLLM(this.history,te=>{te&&(ce=!0),this.deps.onAssistantStep?.(te,f)},{signal:n.signal}),I=Gs(M);b=I.textContent,E=I.toolUseBlocks,q=I.stopReason,B=I.usage,fe=I.reasoningContent,b.trim().length>0&&(v=b,h=f)}catch(M){if(this.cancelling&&vr(M)){p="cancelled",c="",u="Turn cancelled",await this.emitEvent("final",{turn:r,step:f,content:"",role:"assistant",meta:{cancelled:!0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}let I=`LLM call failed: ${M.message}`;this.history.push({role:"assistant",content:I}),p="error",c=I,u=I,await this.emitEvent("final",{turn:r,content:I,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}!ce&&b&&this.deps.onAssistantStep?.(b,f);let J=E.length===0&&b?Ks(b,this.deps.tools):null,P,Y=null;if(E.length>0){let M=E[0];if(M){let I=b?Fs([b]):void 0;P={action:{tool:M.name,input:M.input},thinking:I},Y={role:"assistant",content:b,reasoning_content:fe,tool_calls:qs(E)}}else P={}}else b?(P={final:b},Y={role:"assistant",content:b,reasoning_content:fe}):P={};let H=this.tokenCounter.countText(b),O=B?.prompt??x,K=B?.completion??H,V=B?.total??O+K,R={prompt:O,completion:K,total:V};if(Tr(s,R),Tr(this.sessionUsage,R),o.push({index:f,assistantText:b,parsed:P,tokenUsage:R}),await this.emitEvent("assistant",{turn:r,step:f,content:b,role:"assistant",meta:{tokens:R,protocol_violation:!!J,protocol_violation_count:J?g+1:g||void 0}}),J){g+=1;let M=`Model protocol error: returned plain-text tool JSON for "${J.tool}" ${g} times. Structured tool calls are required.`;p="error",c=M,u=M,this.history.push({role:"assistant",content:M}),await this.emitEvent("final",{turn:r,step:f,content:M,role:"assistant",meta:{error_type:"model_protocol_error",tool:J.tool,protocol_violation:!0,protocol_violation_count:g,tokens:R}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,tokenUsage:R,turnUsage:{...s},steps:o});break}if(Y&&this.history.push(Y),E.length>0&&this.toolsDisabled){for(let M of E)this.history.push({role:"tool",content:Ws,tool_call_id:M.id,name:M.name});p="error",c=pt,u=pt,this.history.push({role:"assistant",content:pt}),await this.emitEvent("final",{turn:r,step:f,content:pt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:E.length,tools:E.map(M=>M.name).join(","),tokens:R}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:pt,status:p,errorMessage:u,tokenUsage:R,turnUsage:{...s},steps:o});break}if(E.length>1){for(let A of E)this.maybeWarnRepeatedAction(A.name,A.input);await this.emitEvent("action",{turn:r,step:f,meta:{tools:E.map(A=>A.name),action_ids:E.map(A=>A.id),action_id:E[0]?.id,parallel:!0,phase:"dispatch",thinking:P.thinking,toolBlocks:E.map(A=>({id:A.id,name:A.name,input:A.input}))}});let M=E[0];M&&await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:f,action:{tool:M.name,input:M.input},parallelActions:E.map(A=>({tool:A.name,input:A.input})),thinking:P.thinking,history:dt(this.history)});let I=E.every(A=>!!this.deps.tools[A.name]?.supportsParallelToolCalls),te=E.some(A=>!!this.deps.tools[A.name]?.isMutating),ue=I&&!te?"parallel":"sequential",Ae=await this.toolOrchestrator.executeActions(E.map(A=>({id:A.id,name:A.name,input:A.input})),{...this.buildToolApprovalHooks(r,f),executionMode:ue,failurePolicy:"fail_fast"}),_e=Ys(E,Ae.results,Ae.hasRejection);for(let[A,j]of _e.entries())this.history.push(br(j)),await this.emitEvent("observation",{turn:r,step:f,content:j.observation,meta:{tool:j.tool,index:A,action_id:j.actionId,phase:"result",status:j.status,error_type:j.errorType,duration_ms:j.durationMs,execution_mode:ue}});let Se=_e.map(A=>`[${A.tool}]: ${A.observation}`).join(`
|
|
74
|
+
|
|
75
|
+
`),rt=_e.map(A=>A.status),He=rt.find(A=>A!==_r)??_r,Ke=o[o.length-1];if(Ke&&(Ke.observation=Se),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:f,tool:E.map(A=>A.name).join(", "),observation:Se,resultStatus:He,parallelResultStatuses:rt,history:dt(this.history)}),Ae.hasRejection){let A=_e.find(j=>j.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:A?.actionId,error_type:A?.errorType??"approval_denied",duration_ms:A?.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,tokenUsage:R,turnUsage:{...s},steps:o});break}continue}else if(P.action){this.maybeWarnRepeatedAction(P.action.tool,P.action.input);let M=E[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:M,phase:"dispatch",thinking:P.thinking}}),await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:f,action:P.action,thinking:P.thinking,history:dt(this.history)});let I=await this.executeToolAction(M,P.action.tool,P.action.input,r,f);if(I.rejected){this.history.push(br({...I,observation:I.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:I.actionId,error_type:I.errorType??"approval_denied",duration_ms:I.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,tokenUsage:R,turnUsage:{...s},steps:o});break}let te=I.observation;this.history.push({role:"tool",content:te,tool_call_id:I.actionId,name:P.action.tool});let ue=o[o.length-1];ue&&(ue.observation=te),await this.emitEvent("observation",{turn:r,step:f,content:te,meta:{tool:P.action.tool,action_id:I.actionId,phase:"result",status:I.status,error_type:I.errorType,duration_ms:I.durationMs}}),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:f,tool:P.action.tool,observation:te,resultStatus:I.status,history:dt(this.history)});continue}if(q==="end_turn"||P.final){this.resetActionRepetition();let M=q==="end_turn"&&!P.final&&b.trim().length===0&&!!v&&h===f-1;c=M?v??"":P.final||b,P.final&&(P.final=c),await this.emitEvent("final",{turn:r,step:f,content:c,role:"assistant",meta:{tokens:R,fallback_from_previous_text:M||void 0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,tokenUsage:R,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 Q(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())}listToolNames(){return Object.keys(this.deps.tools)}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=po({sessionId:this.id,type:e,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await zs(r,this.sinks)}};async function dn(t,e={}){let n=e.sessionId||md(),r=await Hs(t,{...e,sessionId:n},n),o=await r.loadPrompt(),s=new pn({...t,...r},{...e,sessionId:n,mode:e.mode??cn},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as Tt}from"crypto";import{readFile as Tg}from"fs/promises";import{useCallback as X,useEffect as Wt,useMemo as jt,useReducer as vg,useRef as In,useState as ee}from"react";import{Box as Sa,Text as bg,useApp as Cg}from"ink";import{memo as Id,useMemo as fi,useRef as gi,useEffect as Od}from"react";import{Box as di,Static as Ld,Text as mn}from"ink";import{memo as Mr}from"react";import{Box as je,Text as se}from"ink";var $e={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import mt from"path";var fd="success",Rt=".";function Cr(t){return t?t===fd?$e.SUCCESS:$e.ERROR:$e.SUCCESS}function ei(t){if(t?.length)return t.map(e=>Cr(e))}function ti(t,e){return!e||e<=0||!t||t<=0?0:Math.min(100,t/e*100)}function ni(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 ri(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function xr(t,e){let n=t.trim();if(!n)return t;if(n===Rt)return Rt;if(mt.isAbsolute(n)){let r=mt.relative(mt.resolve(e),n);return r?mt.normalize(r):Rt}if(n.startsWith("./")||n.startsWith("../")){let r=mt.normalize(n);return!r||r==="."||r==="./"?Rt:r}return n}function oi(t){return t?t===Rt||mt.isAbsolute(t)?!0:t.startsWith("./")||t.startsWith("../"):!1}import{memo as vd,useMemo as bd}from"react";import{Box as Ee,Text as he}from"ink";import{marked as gd}from"marked";var hd=/(`[^`\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(`
|
|
76
|
+
`):""}).join("")}function yd(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 _d(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 ii(t){if(!t)return[];let e=[],n=0;for(let r of t.matchAll(hd)){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(_d(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 Sd(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Ot(t.tokens):""}function Td(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(`
|
|
77
|
+
`).map(e=>e.replace(/^>\s?/,"")).join(`
|
|
78
|
+
`).trim():""}function si(t){return typeof t.text=="string"?t.text:Array.isArray(t.tokens)?Ot(t.tokens):typeof t.raw=="string"?t.raw:""}function ai(t){let{think:e,cleaned:n}=yd(t),r=[];e.length>0&&r.push({type:"think",content:e.join(`
|
|
79
|
+
|
|
80
|
+
`)});let o=gd.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??si(s)});break}case"paragraph":case"text":{let i=si(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=Td(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(a=>Sd(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 kd,jsx as W,jsxs as ft}from"react/jsx-runtime";var Cd="\u2014\u2014\u2014";function xd(t,e){return t.repeat(Math.max(0,e))}function wd(t){let e=t.split(`
|
|
81
|
+
`);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 Md(t){return t.split(`
|
|
82
|
+
`)}function Ed({content:t}){let e=Md(t);return W(Ee,{flexDirection:"column",marginY:1,children:e.map((n,r)=>W(he,{children:n},r))})}function Ad({node:t}){switch(t.type){case"bold":return W(he,{bold:!0,children:t.content});case"italic":return W(he,{italic:!0,children:t.content});case"inlineCode":return W(he,{color:"cyan",children:t.content});case"link":return ft(kd,{children:[W(he,{color:"blue",underline:!0,children:t.label}),ft(he,{color:"gray",children:[" (",t.href,")"]})]});case"text":return W(he,{children:t.content});default:return null}}function wr({content:t}){let e=ii(t);return W(Ee,{flexWrap:"wrap",children:e.map((n,r)=>W(Ad,{node:n},r))})}function Pd(t,e){switch(t.type){case"html":return W(Ee,{children:W(he,{color:"gray",dimColor:!0,children:t.content})},e);case"hr":return W(Ee,{marginY:1,children:W(he,{color:"gray",dimColor:!0,children:Cd})},e);case"think":return W(Ee,{flexDirection:"column",marginY:1,children:wd(t.content).map((n,r)=>W(he,{color:"gray",dimColor:!0,children:n},r))},e);case"heading":return W(Ee,{children:ft(he,{bold:!0,color:"cyan",children:[xd("#",t.level)," ",t.content]})},e);case"paragraph":return W(wr,{content:t.content},e);case"code":return W(Ed,{content:t.content},e);case"blockquote":return W(Ee,{flexDirection:"column",children:t.content.split(`
|
|
83
|
+
`).map((n,r)=>ft(Ee,{children:[W(he,{color:"gray",dimColor:!0,children:"> "}),W(wr,{content:n})]},r))},e);case"list":return W(Ee,{flexDirection:"column",children:t.items.map((n,r)=>ft(Ee,{children:[ft(he,{color:"gray",children:[t.ordered?`${r+1}.`:"\u2022"," "]}),W(wr,{content:n})]},r))},e);default:return null}}var li=vd(function({content:e}){let n=bd(()=>ai(e),[e]);return W(Ee,{flexDirection:"column",children:n.map((r,o)=>Pd(r,`${r.type}-${o}`))})});import{jsx as me,jsxs as be}from"react/jsx-runtime";function ci(t){return t===$e.ERROR?"red":t===$e.EXECUTING?"yellow":"green"}function ui(t,e){if(t==null)return null;if(typeof t=="string"){let s=oi(t)?xr(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)?xr(a,e):a;return It(l,70)}return It(ri(n),70)}var pi=Mr(function({message:e}){let n=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return be(je,{flexDirection:"column",children:[be(se,{color:n,children:["\u25CF ",e.title]}),me(se,{color:"gray",children:e.content})]})}),Rd=Mr(function({step:e,cwd:n}){let r=!!(e.parallelActions&&e.parallelActions.length>1),o=!r&&e.action?ui(e.action.input,n):null;return be(je,{flexDirection:"column",children:[e.thinking?be(je,{children:[me(se,{color:"gray",children:"\u25CF "}),me(se,{color:"gray",children:e.thinking})]}):null,r?e.parallelActions?.map((s,i)=>{let a=ui(s.input,n);return be(je,{children:[be(se,{color:ci(e.parallelToolStatuses?.[i]??e.toolStatus),children:["\u25CF"," "]}),me(se,{color:"gray",children:"Used "}),me(se,{color:"cyan",children:s.tool}),a?be(se,{color:"gray",children:[" (",a,")"]}):null]},`${s.tool}-${i}`)}):null,!r&&e.action?be(je,{children:[me(se,{color:ci(e.toolStatus),children:"\u25CF "}),me(se,{color:"gray",children:"Used "}),me(se,{color:"cyan",children:e.action.tool}),o?be(se,{color:"gray",children:[" (",o,")"]}):null]}):null]})}),Er=Mr(function({turn:e,cwd:n}){return be(je,{flexDirection:"column",children:[be(je,{marginY:.5,children:[me(se,{color:"gray",children:"\u203A "}),me(se,{children:e.userInput})]}),e.steps.map(r=>me(Rd,{step:r,cwd:n},`${e.index}-${r.index}`)),e.finalText?me(je,{marginTop:0,children:me(li,{content:e.finalText})}):null,e.status&&e.status!=="ok"?be(se,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?me(se,{color:"red",children:e.errorMessage}):null]})});import{jsx as Lt,jsxs as Nt}from"react/jsx-runtime";function mi(t){return t.sequence??0}function Nd(t){return t.type==="header"}function $d(t){return t.id!==void 0}function Dd(t){let e=gi("");return fi(()=>{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 hi=Id(function({header:e,systemMessages:n,turns:r,historicalTurns:o}){let s=Dd(e),i=gi(e.cwd);Od(()=>{i.current=e.cwd},[e.cwd]);let{completedTurns:a,inProgressTurn:l,staticItems:c}=fi(()=>{let u=[...o,...r],g=u.length>0?u[u.length-1]:void 0,v=g&&!!(g.finalText||g.status&&g.status!=="ok"),h=v?u:u.slice(0,-1),f=v?void 0:g,x={type:"header",data:e},b=[...n,...h];b.sort((B,q)=>mi(B)-mi(q));let E=[x,...b];return{completedTurns:h,inProgressTurn:f,staticItems:E}},[e,o,r,n]),p=i.current;return Nt(di,{flexDirection:"column",children:[Lt(Ld,{items:c,children:u=>Nd(u)?Nt(di,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[Lt(mn,{bold:!0,children:"Memo Code CLI"}),Nt(mn,{color:"gray",children:[u.data.providerName," / ",u.data.model," \u2022 v",u.data.version]}),Nt(mn,{color:"gray",children:["cwd: ",u.data.cwd]}),Nt(mn,{color:"gray",children:["mcp: ",u.data.mcpNames.join(", ")||"none"]})]},`header-${s}`):$d(u)?Lt(pi,{message:u},u.id):Lt(Er,{turn:u,cwd:p},`turn-${u.sequence??u.index}`)}),l?Lt(Er,{turn:l,cwd:p}):null]})});import{memo as Qm,useCallback as tt,useEffect as wn,useMemo as Zi,useRef as Ht,useState as Ge}from"react";import{Box as Ur,Text as Mn,useInput as ef,useStdout as tf}from"ink";var $={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",MCP:"mcp",INIT:"init"},U={NONE:"none",ONCE:"once",FULL:"full"};function ye(t){return`/${t}`}var yi="exit";var fn=[{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:$.REVIEW,description:"Review a GitHub pull request and post comments"},{name:$.MODELS,description:"List or switch configured models"},{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"}],Ud={none:U.NONE,off:U.NONE,disabled:U.NONE,"no-tools":U.NONE,once:U.ONCE,ask:U.ONCE,single:U.ONCE,strict:U.ONCE,full:U.FULL,all:U.FULL,dangerous:U.FULL,"full-access":U.FULL};function Hd(t){if(!t)return null;let e=t.trim().toLowerCase();return e?Ud[e]??null:null}function _i(t){return t===U.NONE?"none (no tools)":t===U.ONCE?"once (approval required)":"full (no approval)"}function Fd(){let t=fn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...fn.map(n=>` ${ye(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(`
|
|
84
|
+
`)}function Bd(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=e.match(/^#?(\d+)$/);if(n){let o=Number(n[1]);return Number.isInteger(o)&&o>0?o:null}let r=e.match(/\/pull\/(\d+)(?:[/?#].*)?$/i);if(r){let o=Number(r[1]);return Number.isInteger(o)&&o>0?o:null}return null}function Si(t,e){let[n,...r]=t.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case $.HELP:return{kind:"message",title:"Help",content:Fd()};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 $.REVIEW:{let s=r.join(" ").trim(),i=Bd(s);return i?{kind:"review_pr",prNumber:i}:{kind:"message",title:"Review",content:`Usage: ${ye($.REVIEW)} <prNumber>
|
|
85
|
+
Examples: /review 999, /review #999`}}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
86
|
|
|
79
87
|
`:""}${a.join(`
|
|
80
|
-
`)}`}}case $.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
`)}}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
`,
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
`)
|
|
94
|
-
`)){let
|
|
95
|
-
|
|
96
|
-
`,!0),
|
|
97
|
-
|
|
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:"",g=u.input,_=typeof u.thinking=="string"?u.thinking:"",f=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(b=>{let C=typeof b?.name=="string"?b.name:"";return C?{tool:C,input:b?.input}:null}).filter(Boolean),S=s.steps[s.steps.length-1];S&&(f.length>1?(S.action=f[0],S.parallelActions=f):p&&(S.action={tool:p,input:g}),_&&(S.thinking=_))}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 fr(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function dm(e,t){return{index:e,userInput:"",steps:[],sequence:t}}function dr(e,t){if(e.length>t)return e;let n=e.slice();for(;n.length<=t;)n.push({index:n.length,assistantText:""});return n}function Dt(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(dm(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 fm(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 Qs(e,t){switch(t.type){case"append_system_message":{let n=e.sequence+1;return{...e,sequence:n,systemMessages:[...e.systemMessages,fm({title:t.title,content:t.content,tone:t.tone,sequence:n})]}}case"turn_start":{let n=Dt(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=Dt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];if(!s)return r;let i=`${s.assistantText}${t.chunk}`;return i===s.assistantText?r:(o[t.step]={...s,assistantText:i},{...r,steps:o})});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Dt(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:He.EXECUTING},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Dt(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=Dt(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 fr();default:return e}}import{dirname as Tn,join as ti,resolve as gm}from"path";import{statSync as hm,existsSync as ni,readFileSync as ym}from"fs";import{readFile as Tm}from"fs/promises";import{get as _m}from"https";import{fileURLToPath as Sm}from"url";function ei(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 vm(e,t){let n=ei(e),r=ei(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 ri(){try{let t=Sm(import.meta.url);return Tn(t)}catch{}let e=gm(process.argv[1]??process.cwd());try{return hm(e).isFile()?Tn(e):e}catch{return process.cwd()}}async function xm(e){let t=ti(e,"package.json");if(!ni(t))return null;let n=await Tm(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function bm(e){let t=ti(e,"package.json");if(!ni(t))return null;try{let n=ym(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function Cm(){let e=ri();for(;;){let t=await xm(e);if(t&&t.name==="@memo-code/memo")return t;let n=Tn(e);if(n===e)break;e=n}return null}function _n(){let e=ri();for(;;){let t=bm(e);if(t&&t.name==="@memo-code/memo")return t;let n=Tn(e);if(n===e)break;e=n}return null}async function Em(e,t=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(o=>{let s=_m(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 oi(){let e=await Cm();if(!e)return null;let t=await Em(e.name);return!t||!vm(t,e.version)?null:{current:e.version,latest:t}}import{jsx as Ge,jsxs as Om}from"react/jsx-runtime";function Pm(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 Im(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 Rm(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function ii({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}=km(),p=Ht(()=>Object.keys(o??{}).sort(),[o]),g=Ht(()=>Pm(p,e.activeMcpServers),[p,e.activeMcpServers]),_=e.toolPermissionMode??(l?B.FULL:B.ONCE),[h,f]=Mm(Qs,void 0,fr),[S,b]=re(t),[C,K]=re(n),[X,q]=re(a),[G,ye]=re(_),[k,U]=re({...e,providerName:t,dangerous:_===B.FULL,toolPermissionMode:_}),[j,P]=re(!1),[L,Ie]=re([]),[V,M]=re(null),[I,J]=re(null),[Ae,Te]=re(e.maxPromptTokens??fs),[Re,pe]=re(0),[me,Tt]=re(c),[Pe,A]=re(!c&&p.length>0),[te,ot]=re(g),[st,Y]=re(null),[oe,_e]=re(null),W=Sn(null),O=Sn(null),Be=Sn(null),[F,Ke]=re(null),de=Sn(null),_t=Ht(()=>_n(),[]),Z=Q(d=>{f(d)},[]);Ut(()=>{me||(ot(g),A(p.length>0))},[me,g,p.length]);let E=Q((d,y,w="info")=>{Z({type:"append_system_message",title:d,content:y,tone:w})},[Z]),Ve=Ht(()=>({onAssistantStep:(d,y)=>{let w=O.current;w&&Z({type:"assistant_chunk",turn:w,step:y,chunk:d})},requestApproval:G===B.FULL||G===B.NONE?void 0:d=>new Promise(y=>{Xs(d),Ke(d),de.current=y}),hooks:{onTurnStart:({turn:d,input:y,promptTokens:w})=>{O.current=d;let Se=Be.current;Se&&(Be.current=null);let Ye=Se??y;w&&w>0&&pe(w),Z({type:"turn_start",turn:d,input:Ye,promptTokens:w})},onAction:({turn:d,step:y,action:w,thinking:Se,parallelActions:Ye})=>{Z({type:"tool_action",turn:d,step:y,action:w,thinking:Se,parallelActions:Ye})},onObservation:({turn:d,step:y,observation:w,resultStatus:Se,parallelResultStatuses:Ye})=>{Z({type:"tool_observation",turn:d,step:y,observation:w,toolStatus:Yn(Se),parallelToolStatuses:Yo(Ye)})},onFinal:({turn:d,finalText:y,status:w,errorMessage:Se,turnUsage:Ye,tokenUsage:mi})=>{Z({type:"turn_final",turn:d,finalText:y,status:w,errorMessage:Se,turnUsage:Ye,tokenUsage:mi}),P(!1)}}}),[Z,G]);Ut(()=>{let d=!1;return(async()=>{if(!(me||Pe))try{let y=W.current;y&&await y.close();let w=await nn(Ve,k);if(d){await w.close();return}W.current=w,_e(w),M(w.historyFilePath??null)}catch(y){if(d)return;W.current=null,_e(null),M(null),P(!1),E("Session",`Failed to create session: ${y.message}`,"error")}})(),()=>{d=!0}},[E,Ve,Pe,k,me]),Ut(()=>{let d=!1;return(async()=>{let y=await oi();d||!y||E("Update",`Update available: v${y.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{d=!0}},[E]),Ut(()=>()=>{W.current&&W.current.close()},[]);let Xe=Q(async()=>{let d=de.current;d&&(d("deny"),de.current=null),F&&Ke(null),W.current&&await W.current.close(),Y("Bye!"),setTimeout(()=>u(),250)},[u,F]),T=Q(()=>{if(j){E("Clear","Cancel current run before clearing timeline.","warning");return}if(F){E("Clear","Resolve current approval request before clearing timeline.","warning");return}Z({type:"clear_current_timeline"}),J(null),pe(0),Rm()},[E,j,Z,F]),x=Q(()=>{if(j){E("New Session","Cancel current run before starting a new session.","warning");return}if(F){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(d=>({...d,sessionId:rt()})),E("New Session","Started a fresh session.")},[E,j,Z,F]),H=Q(async d=>{try{let y=await le();await xe(y.configPath,{...y.config,current_provider:d})}catch(y){E("Config",`Failed to persist provider: ${y.message}`,"warning")}},[E]),ne=Q(async d=>{if(j){E("Model switch","Cancel current run before switching models.","warning");return}if(d.name===S&&d.model===C){E("Model switch",`Already using ${d.name} (${d.model}).`);return}Z({type:"reset_all"}),pe(0),O.current=null,b(d.name),K(d.model),U(y=>({...y,sessionId:rt(),providerName:d.name})),await H(d.name),E("Model switch",`Switched to ${d.name} (${d.model}).`)},[E,j,C,S,Z,H]),fe=Q(async d=>{try{let y=await le();await xe(y.configPath,{...y.config,max_prompt_tokens:d})}catch(y){E("Context",`Failed to persist context limit: ${y.message}`,"warning")}},[E]),Oe=Q(d=>{if(j){E("Context","Cancel current run before changing context window.","warning");return}if(F){E("Context","Resolve current approval request before changing context window.","warning");return}Te(d),pe(0),U(y=>({...y,maxPromptTokens:d,sessionId:rt()})),E("Context",`Context window set to ${Math.floor(d/1e3)}k.`),fe(d)},[E,j,F,fe]),St=Q(d=>d===B.NONE?"none (no tools)":d===B.ONCE?"once (approval required)":"full (no approval)",[]),Ft=Q(d=>{if(j){E("Tools","Cancel current run before changing tool permission mode.","warning");return}if(F){E("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(d===G){E("Tools",`Already using ${St(d)}.`);return}ye(d),U(y=>({...y,sessionId:rt(),dangerous:d===B.FULL,toolPermissionMode:d})),E("Tools",`Tool permission set to ${St(d)}.`)},[E,j,F,St,G]),v=Q(async d=>{try{let y=await le();await xe(y.configPath,{...y.config,active_mcp_servers:d})}catch(y){E("MCP",`Failed to persist active MCP servers: ${y.message}`,"warning")}},[E]),R=Q((d,y)=>{let w=Im(p,d);ot(w),A(!1),U(Se=>({...Se,sessionId:rt(),activeMcpServers:w})),y&&v(w)},[p,v]),ie=Q(async d=>{if(j){E("History","Cancel current run before loading session history.","warning");return}if(F){E("History","Resolve current approval request before loading session history.","warning");return}try{let y=await Am(d.sessionFile,"utf8"),w=Zs(y);Z({type:"clear_current_timeline"}),Z({type:"replace_history",turns:w.turns,maxSequence:w.maxSequence}),J(w.messages),P(!1),_e(null),M(null),pe(0),O.current=null,U(Se=>({...Se,sessionId:rt()})),E("History",w.summary||d.input)}catch(y){E("History",`Failed to load ${d.sessionFile}: ${y.message}`,"error")}},[E,j,Z,F]),D=Q(()=>{j&&oe?.cancelCurrentTurn?.()},[j,oe]),Me=Q(async()=>{if(!oe||j)return;let d=`Please analyze the current project and create an AGENTS.md file at the project root.
|
|
100
|
-
|
|
101
|
-
The AGENTS.md should include:
|
|
102
|
-
1. Project name and brief description
|
|
103
|
-
2. Directory structure overview
|
|
104
|
-
3. Key technologies and stack
|
|
105
|
-
4. Coding conventions and style guidelines
|
|
106
|
-
5. Build/test/development commands
|
|
107
|
-
6. Any project-specific notes for AI assistants
|
|
108
|
-
|
|
109
|
-
Steps:
|
|
110
|
-
1. Explore project structure using list_dir and exec_command tools
|
|
111
|
-
2. Read key configuration files
|
|
112
|
-
3. Understand stack and conventions
|
|
113
|
-
4. Create AGENTS.md using apply_patch
|
|
114
|
-
|
|
115
|
-
Keep the result concise and actionable.`,y=he($.INIT);Ie(w=>[...w,y]),P(!0);try{Be.current=y,await oe.runTurn(d)}catch(w){P(!1),E("Init",`Failed to run init task: ${w.message}`,"error")}},[E,j,oe]),Je=Q(async d=>{let y=d.trim();if(y){if(y.toLowerCase()===gs){await Xe();return}if(y===he($.INIT)){await Me();return}if(!(!oe||j)){Ie(w=>[...w,y]),P(!0);try{await oe.runTurn(y)}catch(w){P(!1),E("Run",`Turn failed: ${w.message}`,"error")}}}},[E,j,Xe,Me,oe]),it=Q(async()=>{try{let d=await le(),y=Ze(d.config);q(d.config.providers),b(y.name),K(y.model),U(w=>({...w,sessionId:rt(),providerName:y.name})),Tt(!1),E("Setup",`Config saved to ${d.configPath}`)}catch(d){E("Setup",`Failed to reload config: ${d.message}`,"error")}},[E]);Ut(()=>{if(!oe||!I?.length)return;let d=oe.history[0];d&&(oe.history.splice(0,oe.history.length,d,...I),J(null))},[I,oe]);let Bt=Q(d=>{let y=de.current;y&&(y(d),de.current=null),Ke(null)},[]),vn=Qo(h.turns[h.turns.length-1]?.tokenUsage),vt=Zo(Re,Ae),pi=Ht(()=>({providerName:S,model:C,cwd:s,sessionId:k.sessionId??"unknown",mcpNames:te,version:_t?.version??"unknown"}),[te,C,S,s,_t?.version,k.sessionId]);return st?Ge(si,{children:Ge(wm,{color:"green",children:st})}):me?Ge(Ys,{configPath:r,onComplete:it,onExit:Xe}):Pe?Ge(Ks,{serverNames:p,defaultSelected:g,onConfirm:R,onExit:()=>{Xe()}}):Om(si,{flexDirection:"column",children:[Ge(ds,{header:pi,systemMessages:h.systemMessages,turns:h.turns,historicalTurns:h.historicalTurns}),Ge(Fs,{disabled:!oe||!!F,busy:j,history:L,cwd:s,sessionsDir:i,currentSessionFile:V??void 0,providers:X,configPath:r,providerName:S,model:C,contextLimit:Ae,toolPermissionMode:G,mcpServers:o,onSubmit:d=>{Je(d)},onExit:()=>{Xe()},onClear:T,onNewSession:x,onCancelRun:D,onHistorySelect:d=>{ie(d)},onModelSelect:d=>{ne(d)},onSetContextLimit:Oe,onSetToolPermission:Ft,onSystemMessage:E}),F?Ge(Gs,{request:F,onDecision:Bt}):null,Ge(zs,{busy:j,pendingApproval:!!F,contextPercent:vt,tokenLine:vn})]})}var Lm=`
|
|
88
|
+
`)}`}}case $.TOOLS:{let s=r.join(" ").trim(),i=Hd(s),a=["none","once","full"].join(", ");return s?i?i===e.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${_i(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
|
|
89
|
+
Choose one of: ${a}`}:{kind:"message",title:"Tools",content:`Current: ${_i(e.toolPermissionMode)}
|
|
90
|
+
Usage: ${ye($.TOOLS)} <mode>
|
|
91
|
+
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(`
|
|
92
|
+
`)}}case $.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${t}
|
|
93
|
+
Type ${ye($.HELP)} for available commands.`}}}var Ri=to(Ai(),1);import{existsSync as Nr,statSync as lm}from"fs";import{readFile as cm,readdir as um}from"fs/promises";import{dirname as Pi,join as Sn,relative as ki,resolve as pm,sep as dm}from"path";var mm=6,fm=2500,Ii=25,gm=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),_n=new Map,Lr=new Map;function hm(t){return t.split(dm).join("/")}function ym(t){return{maxDepth:typeof t.maxDepth=="number"?Math.max(1,t.maxDepth):mm,maxEntries:typeof t.maxEntries=="number"?Math.max(100,t.maxEntries):fm,limit:typeof t.limit=="number"?Math.max(1,t.limit):Ii,respectGitIgnore:t.respectGitIgnore??!0,ignoreGlobs:t.ignoreGlobs?.length?t.ignoreGlobs:[]}}function _m(t,e){let n=t.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>gm.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 Sm(t){return t.replace(/\\/g,"/")}function Tm(t){let e=pm(t);try{lm(e).isFile()&&(e=Pi(e))}catch{e=process.cwd()}let n=e;for(;;){if(Nr(Sn(e,".gitignore"))||Nr(Sn(e,".git")))return e;let r=Pi(e);if(r===e)return n;e=r}}async function vm(t){let e=Sn(t,".gitignore");if(!Nr(e))return[];try{return(await cm(e,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#"))}catch{return[]}}function bm(t){let e=(0,Ri.default)();return t.length>0&&e.add(t),e}async function Cm(t){let e=bm(await vm(t));return{root:t,ignores:n=>{let r=ki(t,n);return!r||r.startsWith("..")?!1:e.ignores(Sm(r))}}}async function xm(t){let e=Tm(t),n=Lr.get(e);if(n)return n;let r=Cm(e).catch(o=>{throw Lr.delete(e),o});return Lr.set(e,r),r}function wm(t){return JSON.stringify({maxDepth:t.maxDepth,maxEntries:t.maxEntries,respectGitIgnore:t.respectGitIgnore,ignoreGlobs:t.ignoreGlobs})}async function Mm(t,e){let n=[],r=e.respectGitIgnore?await xm(t):null,o=async(s,i)=>{if(n.length>=e.maxEntries)return;let a;try{a=await um(s,{withFileTypes:!0})}catch{return}for(let l of a){if(n.length>=e.maxEntries)break;if(l.isSymbolicLink())continue;let c=Sn(s,l.name);if(r?.ignores(c))continue;let p=ki(t,c);if(!p)continue;let u=hm(p);if(_m(u,e))continue;let g=u.split("/").filter(Boolean),v=l.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:g,segmentsLower:g.map(h=>h.toLowerCase()),depth:i,isDir:v}),v&&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 Em(t,e){let n=ym(e),r=wm(n),o=_n.get(t);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=Mm(t,n).then(i=>(_n.set(t,{entries:i,signature:r}),i)).catch(i=>{throw _n.delete(t),i});return _n.set(t,{entries:[],signature:r,pending:s}),s}function Am(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 Pm(t,e,n){let o=e.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of t){let a=Am(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 Oi(t){let e=await Em(t.cwd,t),n=typeof t.limit=="number"?Math.max(1,t.limit):Ii;return Pm(e,t.query,n)}import{readdir as km,readFile as Rm,stat as Im}from"fs/promises";import{basename as Om,join as Lm,resolve as Dt}from"path";function Li(t){let e=Dt(t);return process.platform==="win32"?e.toLowerCase():e}function Nm(t,e){return e?Li(t)===Li(e):!1}function $m(t){return Om(t).replace(/\.jsonl$/i,"")}function Dm(t){let e=null,n=null,r=null;for(let o of t.split(`
|
|
94
|
+
`)){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 Um(t,e,n){try{let r=await Rm(t,"utf8"),{firstPrompt:o,sessionTitle:s,sessionCwd:i}=Dm(r);if(!Nm(e,i))return null;let a=s?.trim()||o?.trim()||$m(t);return{id:t,cwd:e,input:a,ts:n,sessionFile:t}}catch{return null}}async function Hm(t){let e=[],n=async r=>{let o;try{o=await km(r,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async s=>{let i=Lm(r,s.name);if(!s.isSymbolicLink()){if(s.isDirectory()){await n(i);return}if(!(!s.isFile()||!s.name.endsWith(".jsonl")))try{let a=await Im(i);e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}}))};return await n(t),e}async function Ni(t){let e=t.activeSessionFile?Dt(t.activeSessionFile):null,r=(await Hm(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 Um(a.path,t.cwd,a.mtimeMs);l&&(o&&!l.input.toLowerCase().includes(o)||i.push(l))}return i}import{memo as Fm}from"react";import{Box as Tn,Text as vn}from"ink";import{jsx as Qe,jsxs as Wm}from"react/jsx-runtime";var Bm="#3a3a3a",bn="#262626",$i=Fm(function({items:e,activeIndex:n,loading:r}){return r?Qe(Tn,{paddingX:1,backgroundColor:bn,children:Qe(vn,{color:"gray",children:"Loading..."})}):e.length?Qe(Tn,{flexDirection:"column",backgroundColor:bn,children:e.map((o,s)=>{let i=s===n;return Wm(Tn,{paddingX:1,gap:2,backgroundColor:i?Bm:bn,children:[Qe(vn,{color:i?"cyan":"white",bold:i,children:o.title}),o.subtitle?Qe(vn,{color:"gray",children:o.subtitle}):null]},o.id)})}):Qe(Tn,{paddingX:1,backgroundColor:bn,children:Qe(vn,{color:"gray",children:"No matches"})})});import jm from"string-width";var Gm=55296,zm=56319,qm=56320,Km=57343;function Di(t){return t>=Gm&&t<=zm}function Ui(t){return t>=qm&&t<=Km}function Ce(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 Ui(r)&&Di(o)?n-1:n}function Hi(t,e){let n=Ce(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 et(t,e){let n=Ce(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 Ui(o)&&Di(s)?r-1:r}function Cn(t,e){let n=Ce(t,e),r=t.lastIndexOf(`
|
|
95
|
+
`,Math.max(0,n-1));return r===-1?0:r+1}function xn(t,e){let n=Ce(t,e),r=t.indexOf(`
|
|
96
|
+
`,n);return r===-1?t.length:r}function Vm(t){return/[\p{L}\p{N}_]/u.test(t)}function Fi(t,e,n){let r=Ce(t,e);if(!n)return{value:t,cursor:r};let o=n.replace(/\r\n?/g,`
|
|
97
|
+
`);return o?{value:`${t.slice(0,r)}${o}${t.slice(r)}`,cursor:r+o.length}:{value:t,cursor:r}}function Bi(t,e){let n=Ce(t,e);if(n<=0)return{value:t,cursor:n};let r=et(t,n);return{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function $r(t,e){let n=Ce(t,e);if(n>=t.length)return{value:t,cursor:n};let r=Hi(t,n);return{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function Wi(t,e){let n=Ce(t,e);if(n<=0)return{value:t,cursor:n};let r=n;for(;r>0;){let s=et(t,r);if(t.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=et(t,r),i=t.slice(s,r);if(!Vm(i))break;r=s}return r===n&&(r=et(t,n)),{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function ji(t,e){let n=Ce(t,e),r=Cn(t,n);return r>=n?{value:t,cursor:n}:{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function Gi(t,e){let n=Ce(t,e),r=xn(t,n);return r<=n?{value:t,cursor:n}:{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function zi(t,e){return et(t,e)}function qi(t,e){return Hi(t,e)}function Ki(t,e){return Cn(t,e)}function Vi(t,e){return xn(t,e)}function Dr(t,e,n,r){let o=Ce(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,v=Cn(t,g),h=Math.min(v+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 Xi(t,e,n){let r=Ce(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===`
|
|
98
|
+
`){a=f,p(),i=u,a=u,l="",c=0;continue}let x=Math.max(0,jm(h));l.length>0&&c+x>o&&(p(),i=f,a=f,l="",c=0),l+=h,a=u,c+=x}if(p(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let g=Math.max(0,s.length-1),v=(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,v=r-f.start;break}}return{lines:s,row:g,cursorInRow:v}}function Ji(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 Xm=3,Yi=8,Jm=120,Ym=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??Xm,this.charIntervalMs=e.charIntervalMs??Yi,this.enterSuppressWindowMs=e.enterSuppressWindowMs??Jm,this.activeIdleTimeoutMs=e.activeIdleTimeoutMs??Ym}static recommendedFlushDelayMs(){return Yi+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+=`
|
|
99
|
+
`,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=Zm(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 Zm(t,e){if(e<=0)return t.length;let n=t.length,r=e;for(;r>0&&n>0;)n=et(t,n),r-=1;return n}import{jsx as yt,jsxs as Qi}from"react/jsx-runtime";var nf=400,Hr=ye($.MODELS),Fr=ye($.TOOLS),rf=ye($.INIT),of=[{mode:U.NONE,description:"Disable all tool calls"},{mode:U.ONCE,description:"Require approval when needed"},{mode:U.FULL,description:"Run tools without approval"}];function sf(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 af(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 lf(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 cf(t){let e=t.trimStart();if(!e.startsWith(Hr))return null;let n=e.slice(Hr.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function uf(t){let e=t.trimStart();if(!e.startsWith(Fr))return null;let n=e.slice(Fr.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function pf(t){return uf(t)??cf(t)??lf(t)??sf(t)??af(t)}function df(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 mf(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:`${Hr} ${r.name}`,meta:{type:"model",provider:r}}))}}function ff(t){return{mode:"tools",items:of.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===t?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${Fr} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function gf(t){return{mode:"slash",items:fn.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 hf({trigger:t,cwd:e,sessionsDir:n,currentSessionFile:r,providers:o,toolPermissionMode:s}){switch(t.type){case"file":return{mode:"file",items:(await Oi({cwd:e,query:t.query,limit:8,respectGitIgnore:!0})).map(l=>({id:l.id,title:l.isDir?`${l.path}/`:l.path,kind:"file",value:l.isDir?`${l.path}/`:l.path,meta:{type:"file",isDir:l.isDir}}))};case"history":return{mode:"history",items:(await Ni({sessionsDir:n,cwd:e,keyword:t.keyword,activeSessionFile:r})).map(l=>({id:l.id,title:l.input,subtitle:df(l.ts),kind:"history",value:l.input,meta:{type:"history",entry:l}}))};case"models":return mf(o,t.keyword);case"tools":return ff(s);case"slash":return gf(t.keyword)}}var ea=Qm(function({disabled:e,busy:n,history:r,cwd:o,sessionsDir:s,currentSessionFile:i,providers:a,configPath:l,providerName:c,model:p,toolPermissionMode:u,mcpServers:g,onSubmit:v,onExit:h,onClear:f,onNewSession:x,onCancelRun:b,onHistorySelect:E,onModelSelect:B,onSetToolPermission:q,onReviewPullRequest:fe,onSystemMessage:ce}){let{stdout:J}=tf(),[P,Y]=Ge({value:"",cursor:0}),H=Ht(P),O=Ht(null),[K,V]=Ge(null),[R,M]=Ge(""),[I,te]=Ge("none"),[ue,Ae]=Ge([]),[_e,Se]=Ge(0),[rt,He]=Ge(!1),[Ke,A]=Ge(!1),j=Ht(0),vt=Ht(0),G=Ht(new Ut);wn(()=>{H.current=P,A(!1)},[P]);let Gt=Zi(()=>({configPath:l,providerName:c,model:p,mcpServers:g,providers:a,toolPermissionMode:u}),[l,c,p,g,a,u]),ge=Zi(()=>e||Ke?null:pf(P.value),[e,P.value,Ke]),z=tt((T=!0)=>{T&&A(!0),te("none"),Ae([]),Se(0),He(!1)},[]),L=tt((T,_=!1)=>{H.current=T,Y(T),_&&(V(null),M(""))},[]),bt=tt(()=>{L({value:"",cursor:0},!0)},[L]),D=tt((T,_=!0)=>{if(!T)return;let y=H.current;O.current=null;let Z=Fi(y.value,y.cursor,T);L(Z,_),T.includes(`
|
|
100
|
+
`)&&z(!1)},[L,z]),Ve=tt(T=>T.type==="none"?!1:T.type==="paste"?(T.text&&D(T.text,!0),!0):(D(T.text,!0),!0),[D]),ie=tt((T=!0)=>{let _=G.current.flushBeforeModifiedInput();return _&&D(_,!0),T&&G.current.clearWindowAfterNonChar(),!!_},[D]);wn(()=>{let T=setInterval(()=>{let _=G.current.flushIfDue(Date.now());Ve(_)},Ut.recommendedFlushDelayMs());return()=>{clearInterval(T)}},[Ve]),wn(()=>{e&&z(!1)},[e,z]),wn(()=>{if(!ge){z(!1);return}let T=!1,_=++j.current;return He(!0),(async()=>{try{let{mode:y,items:Z}=await hf({trigger:ge,cwd:o,sessionsDir:s,currentSessionFile:i,providers:a,toolPermissionMode:u});if(T||_!==j.current)return;te(y),Ae(Z),Se(re=>Z.length?Math.min(re,Z.length-1):0)}finally{!T&&_===j.current&&He(!1)}})(),()=>{T=!0}},[ge,o,s,i,a,u,z]);let Fe=tt(T=>{if(T){if(I==="file"&&ge?.type==="file"){let _=H.current.value,y=_.slice(0,ge.tokenStart),Z=_.slice(ge.tokenStart+ge.query.length),re=`${y}${T.value}${Z}`,Pe=y.length+T.value.length;L({value:re,cursor:Pe},!0),T.meta?.type==="file"&&T.meta.isDir||z();return}switch(T.meta?.type){case"history":E(T.meta.entry),L({value:T.value,cursor:T.value.length},!1),z();return;case"model":B(T.meta.provider),bt(),z();return;case"tools":q(T.meta.mode),bt(),z();return;case"slash":L({value:`${T.value} `,cursor:`${T.value} `.length},!0),z(!1);return;default:L({value:T.value,cursor:T.value.length},!0),z()}}},[L,I,ge,z,bt,E,B,q]);ef((T,_)=>{if(_.ctrl&&T==="c"){h();return}if(e)return;let y=Date.now();Ve(G.current.flushIfDue(y));let Z=I!=="none",re=Z&&ue.length>0,Pe=Ji(T,_),On=!!(_.ctrl||_.meta),Ct=!!T&&!On&&!_.return&&!_.tab&&Pe==="none"&&!_.escape&&!_.upArrow&&!_.downArrow&&!_.leftArrow&&!_.rightArrow;if(!Ct&&!_.return&&ie(!0),_.ctrl&&T==="a"){let C=H.current,k=Ki(C.value,C.cursor);O.current=null,L({value:C.value,cursor:k},!1);return}if(_.ctrl&&T==="e"){let C=H.current,k=Vi(C.value,C.cursor);O.current=null,L({value:C.value,cursor:k},!1);return}if(_.ctrl&&T==="u"){let C=H.current,k=ji(C.value,C.cursor);O.current=null,L(k,!0);return}if(_.ctrl&&T==="k"){let C=H.current,k=Gi(C.value,C.cursor);O.current=null,L(k,!0);return}if(_.ctrl&&T==="w"){let C=H.current,k=Wi(C.value,C.cursor);O.current=null,L(k,!0);return}if(_.ctrl&&T==="d"){let C=H.current;if(!C.value){h();return}let k=$r(C.value,C.cursor);O.current=null,L(k,!0);return}if(_.ctrl&&T==="l"){L({value:"",cursor:0},!0),z(),f(),x();return}if(_.escape){if(y-vt.current<=nf){vt.current=0,n?b():(O.current=null,L({value:"",cursor:0},!0),z());return}vt.current=y,Z&&z();return}if(_.upArrow){if(re){Se(F=>F<=0?ue.length-1:F-1);return}let C=H.current;if(C.value.includes(`
|
|
101
|
+
`)){let F=Dr(C.value,C.cursor,"up",O.current??void 0);if(F.changed){O.current=F.preferredColumn,L({value:C.value,cursor:F.cursor},!1);return}}if(!r.length)return;if(K===null){M(C.value);let F=r.length-1;V(F);let Te=r[F]??"";O.current=null,L({value:Te,cursor:Te.length},!1);return}let k=Math.max(0,K-1);V(k);let ae=r[k]??"";O.current=null,L({value:ae,cursor:ae.length},!1);return}if(_.downArrow){if(re){Se(F=>(F+1)%ue.length);return}let C=H.current;if(C.value.includes(`
|
|
102
|
+
`)){let F=Dr(C.value,C.cursor,"down",O.current??void 0);if(F.changed){O.current=F.preferredColumn,L({value:C.value,cursor:F.cursor},!1);return}}if(K===null)return;let k=K+1;if(k>=r.length){V(null),O.current=null,L({value:R,cursor:R.length},!1),M("");return}V(k);let ae=r[k]??"";O.current=null,L({value:ae,cursor:ae.length},!1);return}if(_.leftArrow){let C=H.current,k=zi(C.value,C.cursor);O.current=null,L({value:C.value,cursor:k},!1);return}if(_.rightArrow){let C=H.current,k=qi(C.value,C.cursor);O.current=null,L({value:C.value,cursor:k},!1);return}if(_.tab&&re){Fe(ue[_e]);return}if(_.return){if(re){Fe(ue[_e]);return}G.current.hasPendingFirstChar()&&!G.current.isBuffering()&&ie(!1);let C=H.current.value.trimStart().startsWith("/");if(!_.shift&&!C){if(G.current.appendNewlineIfActive(y))return;if(G.current.newlineShouldInsertInsteadOfSubmit(y)){ie(!1),D(`
|
|
103
|
+
`,!0),G.current.extendWindow(y);return}}if(ie(!0),_.shift){D(`
|
|
104
|
+
`,!0);return}let ae=H.current.value.trim();if(!ae)return;if(ae.startsWith("/")){let F=Si(ae,Gt);switch(F.kind){case"message":ce(F.title,F.content);break;case"new":x();break;case"exit":h();break;case"switch_model":B(F.provider);break;case"set_tool_permission":q(F.mode);break;case"review_pr":fe(F.prNumber);break;case"init_agents_md":v(rf);break;default:{let Te=F}}O.current=null,L({value:"",cursor:0},!0),z(!1);return}v(ae),O.current=null,L({value:"",cursor:0},!0),z(!1);return}if(Pe!=="none"){let C=H.current,k=Pe==="backspace"?Bi(C.value,C.cursor):$r(C.value,C.cursor);O.current=null,L(k,!0);return}if(T&&Ct){let C=Array.from(T);if(C.length!==1){ie(!1),D(T,!0),G.current.clearAfterExplicitPaste();return}let k=C[0]??"";if(!k)return;let ae=Je=>{let st=H.current,xt=st.value.slice(0,st.cursor),Ln=st.value.slice(st.cursor),wt=G.current.decideBeginBuffer(y,xt,Je);return wt?(O.current=null,L({value:`${xt.slice(0,wt.start)}${Ln}`,cursor:wt.start},!0),G.current.appendCharToBuffer(k,y),!0):!1};if(!((k.codePointAt(0)??0)<=127)){let Je=G.current.onPlainCharNoHold(y);if(Je?.type==="buffer_append"){G.current.appendCharToBuffer(k,y);return}if(Je?.type==="begin_buffer"&&ae(Je.retroChars))return;ie(!1),D(k,!0);return}let Te=G.current.onPlainChar(k,y);if(Te.type==="retain_first_char")return;if(Te.type==="buffer_append"||Te.type==="begin_buffer_from_pending"){G.current.appendCharToBuffer(k,y);return}if(Te.type==="begin_buffer"&&ae(Te.retroChars))return;ie(!1),D(k,!0);return}T&&(D(T,!0),G.current.clearWindowAfterNonChar())});let ot=J?.columns??process.stdout?.columns??80,ne=Math.max(1,ot-3),Be=Xi(P.value,P.cursor,ne),Xe=Be.lines;return Qi(Ur,{flexDirection:"column",gap:1,children:[yt(Ur,{flexDirection:"column",paddingY:1,children:Xe.map((T,_)=>{let y=T.text,Z=!e&&_===Be.row,re=Z?y.slice(0,Be.cursorInRow):y,Pe=Z?y.slice(Be.cursorInRow):"";return Qi(Ur,{children:[yt(Mn,{color:"gray",children:_===0?"\u203A ":" "}),yt(Mn,{children:re}),Z?yt(Mn,{color:"cyan",children:"\u258A"}):null,Z?yt(Mn,{children:Pe}):null]},`line-${_}`)})}),I!=="none"?yt($i,{items:ue.map(({value:T,meta:_,...y})=>y),activeIndex:_e,loading:rt}):null]})});import{memo as yf}from"react";import{Box as ta,Text as Br}from"ink";import{jsx as Wr,jsxs as na}from"react/jsx-runtime";var ra=yf(function({busy:e,pendingApproval:n=!1,contextPercent:r,tokenLine:o}){let s=`${r.toFixed(1)}%`;return na(ta,{justifyContent:"space-between",children:[Wr(ta,{children:e?Wr(Br,{color:"yellow",children:"Working..."}):Wr(Br,{color:"gray",children:n?"Approval pending \u2022 Enter confirm \u2022 Esc deny":"Enter send \u2022 Shift+Enter newline \u2022 /help"})}),na(Br,{color:"gray",children:[o?`${o} \u2022 `:"","context: ",s]})]})});import{memo as _f}from"react";import{Box as En,Text as jr,useInput as Sf}from"ink";import{Select as Tf,StatusMessage as vf}from"@inkjs/ui";import{jsx as nt,jsxs as oa}from"react/jsx-runtime";var bf=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function Cf(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 sa=_f(function({request:e,onDecision:n}){Sf((o,s)=>{(s.escape||s.ctrl&&o==="c")&&n("deny")});let r=Cf(e.params);return oa(En,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[nt(jr,{bold:!0,color:"yellow",children:"Tool Approval Required"}),oa(jr,{children:[e.toolName,r?` (${r})`:""]}),nt(En,{marginTop:1,children:nt(vf,{variant:"warning",children:e.reason})}),nt(En,{marginTop:1,flexDirection:"column",children:nt(Tf,{options:bf.map(o=>({label:o.label,value:o.decision})),onChange:o=>{n(o)}})}),nt(En,{marginTop:1,children:nt(jr,{color:"gray",children:"Enter confirm \u2022 Esc deny"})})]})});import{memo as xf,useMemo as wf,useState as Mf}from"react";import{Box as Gr,Text as An,useInput as Ef}from"ink";import{MultiSelect as Af}from"@inkjs/ui";import{jsx as Ft,jsxs as zr}from"react/jsx-runtime";function Pf(t,e){let n=new Set(t);return e.filter(r=>n.has(r))}var ia=xf(function({serverNames:e,defaultSelected:n,onConfirm:r,onExit:o}){let s=wf(()=>{let c=Pf(e,n);return n.length===0?[]:c.length>0?c:[...e]},[n,e]),[i,a]=Mf(s),l=i.length===e.length;return Ef((c,p)=>{if(p.ctrl&&c==="c"){o();return}p.escape&&r(i,!1)}),zr(Gr,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[Ft(An,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),Ft(An,{color:"gray",children:"Select servers to load for this run."}),Ft(Gr,{marginTop:1,flexDirection:"column",children:Ft(Af,{options:e.map(c=>({label:c,value:c})),defaultValue:s,onChange:a,onSubmit:c=>{r(c,!0)}})}),zr(Gr,{marginTop:1,flexDirection:"column",children:[zr(An,{color:"gray",children:["Selected: ",i.length,"/",e.length,l?" (all)":""]}),Ft(An,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, Enter confirm"})]})]})});import{spawn as kf}from"child_process";var qr="\x07",Rf="Memo: Approval required",If="Memo CLI",Of=2e3;function Lf(t){return t.replace(/\s+/g," ").trim()}function Nf(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function $f(t){let e=Lf(t.reason),n=`Tool ${t.toolName} is waiting for your approval.`;return e?Nf(`${n} ${e}`,220):n}function aa(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Df(t,e=process.platform){let n=Rf,r=$f(t);return e==="darwin"?{command:"osascript",args:["-e",`display notification "${aa(r)}" with title "${aa(n)}"`]}:e==="linux"?{command:"notify-send",args:["--app-name",If,n,r]}:null}async function Uf(t,e){await new Promise((n,r)=>{let o=kf(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()},Of);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 Hf(t){if(t){t(qr);return}try{if(process.stdout?.isTTY){process.stdout.write(qr);return}process.stderr?.isTTY&&process.stderr.write(qr)}catch{}}async function la(t,e={}){Hf(e.writeBell);let n=Df(t,e.platform??process.platform);if(!n)return;let r=e.runCommand??Uf;try{await r(n.command,n.args)}catch{}}import{Box as _t,Text as Ue,useInput as Ff}from"ink";import{Spinner as Bf,StatusMessage as Wf,TextInput as jf}from"@inkjs/ui";import{memo as Gf,useCallback as ca,useMemo as zf,useState as Pn}from"react";import{jsx as xe,jsxs as St}from"react/jsx-runtime";var ze=[{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"}],ua=Gf(function({configPath:e,onComplete:n,onExit:r}){let[o,s]=Pn(0),[i,a]=Pn({}),[l,c]=Pn(!1),[p,u]=Pn(null),g=ze[o]??ze[0],v=ca(async x=>{c(!0),u(null);try{let b={current_provider:x.name,providers:[{name:x.name,env_api_key:x.envKey,model:x.model,base_url:x.baseUrl||void 0}]};await Me(e,b),n()}catch(b){u(b.message),c(!1)}},[e,n]),h=ca(async x=>{if(!g)return;let b=x.trim()||g.defaultValue,E={...i,[g.key]:b};if(a(E),o<ze.length-1){s(o+1);return}let B={name:E.name||ze[0].defaultValue,envKey:E.envKey||ze[1].defaultValue,model:E.model||ze[2].defaultValue,baseUrl:E.baseUrl||ze[3].defaultValue};await v(B)},[v,g,o,i]);Ff((x,b)=>{b.ctrl&&x==="c"&&r()});let f=zf(()=>`Step ${o+1}/${ze.length}`,[o]);return g?St(_t,{flexDirection:"column",children:[xe(Ue,{bold:!0,children:"Memo setup"}),xe(Ue,{color:"gray",children:"No provider config found. Complete setup to continue."}),St(Ue,{color:"gray",children:["Config path: ",e]}),St(_t,{marginTop:1,flexDirection:"column",children:[xe(Ue,{color:"cyan",children:f}),xe(Ue,{children:g.label}),St(Ue,{color:"gray",children:["Default: ",g.defaultValue]}),g.hint?xe(Ue,{color:"gray",children:g.hint}):null]}),St(_t,{marginTop:1,children:[xe(Ue,{color:"gray",children:"> "}),xe(jf,{isDisabled:l,defaultValue:i[g.key]??"",placeholder:g.defaultValue,onSubmit:x=>{h(x)}},g.key)]}),xe(_t,{marginTop:1,children:xe(Ue,{color:"gray",children:"Enter to continue, Ctrl+C to exit"})}),l?xe(_t,{marginTop:1,children:xe(Bf,{label:"Saving config..."})}):null,p?xe(_t,{marginTop:1,children:St(Wf,{variant:"error",children:["Failed to save config: ",p]})}):null]}):null});function pa(t){let e=[],n=[],r=[],o=t.split(`
|
|
105
|
+
`).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,v=typeof p.thinking=="string"?p.thinking:"",f=(Array.isArray(p.toolBlocks)?p.toolBlocks:[]).map(b=>{let E=typeof b?.name=="string"?b.name:"";return E?{tool:E,input:b?.input}:null}).filter(Boolean),x=s.steps[s.steps.length-1];x&&(f.length>1?(x.action=f[0],x.parallelActions=f):u&&(x.action={tool:u,input:g}),v&&(x.thinking=v))}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(`
|
|
106
|
+
`),messages:e,turns:n,maxSequence:a}}function Vr(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function qf(t,e){return{index:t,userInput:"",steps:[],sequence:e}}function Kr(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(qf(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 Kf(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 da(t,e){switch(e.type){case"append_system_message":{let n=t.sequence+1;return{...t,sequence:n,systemMessages:[...t.systemMessages,Kf({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=Kr(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=Kr(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:$e.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=Kr(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 Vr();default:return t}}import{dirname as kn,join as fa,resolve as Vf}from"path";import{statSync as Xf,existsSync as ga,readFileSync as Jf}from"fs";import{readFile as Yf}from"fs/promises";import{get as Zf}from"https";import{fileURLToPath as Qf}from"url";function ma(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 eg(t,e){let n=ma(t),r=ma(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 ha(){try{let e=Qf(import.meta.url);return kn(e)}catch{}let t=Vf(process.argv[1]??process.cwd());try{return Xf(t).isFile()?kn(t):t}catch{return process.cwd()}}async function tg(t){let e=fa(t,"package.json");if(!ga(e))return null;let n=await Yf(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function ng(t){let e=fa(t,"package.json");if(!ga(e))return null;try{let n=Jf(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function rg(){let t=ha();for(;;){let e=await tg(t);if(e&&e.name==="@memo-code/memo")return e;let n=kn(t);if(n===t)break;t=n}return null}function Rn(){let t=ha();for(;;){let e=ng(t);if(e&&e.name==="@memo-code/memo")return e;let n=kn(t);if(n===t)break;t=n}return null}async function og(t,e=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(o=>{let s=Zf(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 ya(){let t=await rg();if(!t)return null;let e=await og(t.name);return!e||!eg(e,t.version)?null:{current:t.version,latest:e}}import{readFile as sg}from"fs/promises";import{dirname as ig,join as ag}from"path";import{fileURLToPath as lg}from"url";var cg=/{{\s*([\w.-]+)\s*}}/g;function ug(t,e){return t.replace(cg,(n,r)=>e[r]??"")}async function Xr(t,e={}){let n=ig(lg(import.meta.url)),r=ag(n,"task-prompts",`${t}.md`),o=await sg(r,"utf-8");return ug(o,e)}import{spawn as pg}from"child_process";var dg=12e3,mg=new Set(["WRITE","MAINTAIN","ADMIN"]),fg=["pull_request_read","list_pull_requests","search_pull_requests","add_issue_comment","add_comment_to_pending_review","issue_read","get_me"];function gg(t){return t.replace(/\\/g,"/").toLowerCase()}function hg(t,e){if(t.toLowerCase().includes("github"))return!0;if("command"in e){let o=gg(e.command),s=(e.args??[]).join(" ").toLowerCase();return!!(o.includes("github")||o.includes("gh-")||s.includes("github")||s.includes("gh-"))}let r=e.url.toLowerCase();return r.includes("github")||r.includes("api.github.com")}function yg(t,e){let n=new Set(e),r=Object.entries(t).filter(([i,a])=>hg(i,a)).map(([i])=>i),o=r.find(i=>n.has(i))??null,s=r.filter(i=>!n.has(i));return{active:o,inactiveCandidates:s}}function _g(t){let e=new Map;for(let n of t)for(let r of fg){let o=`_${r}`;if(!n.endsWith(o))continue;let s=n.slice(0,-o.length);s&&e.set(s,(e.get(s)??0)+1)}return Array.from(e.entries()).filter(([,n])=>n>=2).sort((n,r)=>r[1]-n[1]).map(([n])=>n)}async function Jr(t,e,n,r=dg){return new Promise(o=>{let s=pg(t,e,{cwd:n,env:process.env,stdio:["ignore","pipe","pipe"]}),i="",a="",l=!1,c=u=>{l||(l=!0,clearTimeout(p),o(u))},p=setTimeout(()=>{s.kill("SIGTERM"),c({ok:!1,stdout:i,stderr:a,code:null,errorMessage:`${t} ${e.join(" ")} timed out after ${r}ms`})},r);s.stdout.on("data",u=>{i+=u.toString()}),s.stderr.on("data",u=>{a+=u.toString()}),s.on("error",u=>{c({ok:!1,stdout:i,stderr:a,code:null,errorMessage:u.message})}),s.on("close",u=>{c({ok:u===0,stdout:i,stderr:a,code:u})})})}async function Sg(t){if(!(await Jr("gh",["--version"],t)).ok)return{ok:!1,reason:"GitHub MCP not available, and GitHub CLI (gh) is not installed or not executable. Install gh: https://cli.github.com/"};let n=await Jr("gh",["auth","status","-h","github.com"],t);if(!n.ok)return{ok:!1,reason:`GitHub CLI is installed but not authenticated for github.com. Run: gh auth login -h github.com (detail: ${n.stderr.trim()||n.stdout.trim()||n.errorMessage||"unknown error"})`};let r=await Jr("gh",["repo","view","--json","nameWithOwner,viewerPermission"],t);if(!r.ok)return{ok:!1,reason:`GitHub CLI authentication works, but this directory is not a readable GitHub repo for gh (detail: ${r.stderr.trim()||r.stdout.trim()||r.errorMessage||"unknown error"})`};let o;try{o=JSON.parse(r.stdout)}catch{return{ok:!1,reason:"Failed to parse `gh repo view` output. Try upgrading gh and retry."}}let s=o.nameWithOwner?.trim(),i=o.viewerPermission?.trim().toUpperCase();return!s||!i?{ok:!1,reason:"GitHub CLI did not return repository or permission info from `gh repo view`."}:mg.has(i)?{ok:!0,repository:s,viewerPermission:i}:{ok:!1,reason:`GitHub CLI connected to ${s}, but permission is ${i}. PR review comments require WRITE/MAINTAIN/ADMIN permission.`}}async function _a(t){let e=_g(t.availableToolNames??[]),n=t.activeMcpServerNames.find(c=>e.includes(c))??null,r=c=>{let p=t.availableToolNames;if(!p||p.length===0)return!0;let u=`${c}_`;return p.some(g=>g.startsWith(u))};if(n&&r(n))return{kind:"github_mcp",strategy:"github_mcp",details:`Using active GitHub MCP server \`${n}\` (detected from loaded MCP tool signatures).`,mcpServerPrefix:n};let{active:o,inactiveCandidates:s}=yg(t.mcpServers,t.activeMcpServerNames);if(o&&r(o))return{kind:"github_mcp",strategy:"github_mcp",details:`Using active GitHub MCP server \`${o}\`.`,mcpServerPrefix:o};let i=await Sg(t.cwd);if(i.ok){let c=s.length?` GitHub MCP server(s) configured but inactive in this session: ${s.join(", ")}.`:"";return{kind:"gh_cli",strategy:"gh_cli",details:`Using gh CLI on repo \`${i.repository}\` with permission \`${i.viewerPermission}\`.${c}`,repository:i.repository,viewerPermission:i.viewerPermission}}let a=s.length?` Also found configured but inactive GitHub MCP server(s): ${s.join(", ")}. Start a new session and activate one of them, or fix gh CLI access.`:"",l=o&&!r(o)?` Active MCP server \`${o}\` is configured, but no tools with prefix \`${o}_\` are currently loaded in this session.`:"";return{kind:"unavailable",reason:`${i.reason}${l}${a}`}}import{jsx as qe,jsxs as Eg}from"react/jsx-runtime";function xg(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 wg(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 Mg(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function Ta({sessionOptions:t,providerName:e,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:a,modelProfiles:l,dangerous:c=!1,needsSetup:p=!1}){let{exit:u}=Cg(),g=jt(()=>Object.keys(o??{}).sort(),[o]),v=jt(()=>xg(g,t.activeMcpServers),[g,t.activeMcpServers]),h=t.toolPermissionMode??(c?U.FULL:U.ONCE),[f,x]=vg(da,void 0,Vr),[b,E]=ee(e),[B,q]=ee(n),[fe,ce]=ee(a),[J,P]=ee(l),[Y,H]=ee(h),O=X(d=>ut({model_profiles:J},d),[J]),[K,V]=ee({...t,providerName:e,maxPromptTokens:O({name:e,model:n}),dangerous:h===U.FULL,toolPermissionMode:h}),[R,M]=ee(!1),[I,te]=ee([]),[ue,Ae]=ee(null),[_e,Se]=ee(null),[rt,He]=ee(O({name:e,model:n})),[Ke,A]=ee(0),[j,vt]=ee(p),[G,Gt]=ee(!p&&g.length>0),[ge,z]=ee(v),[L,bt]=ee(null),[D,Ve]=ee(null),ie=In(null),Fe=In(null),ot=In(null),[ne,Be]=ee(null),Xe=In(null),T=jt(()=>Rn(),[]),_=X(d=>{x(d)},[]);Wt(()=>{j||(z(v),Gt(g.length>0))},[j,v,g.length]);let y=X((d,S,w="info")=>{_({type:"append_system_message",title:d,content:S,tone:w})},[_]),Z=jt(()=>({onAssistantStep:(d,S)=>{let w=Fe.current;w&&_({type:"assistant_chunk",turn:w,step:S,chunk:d})},requestApproval:Y===U.FULL||Y===U.NONE?void 0:d=>new Promise(S=>{la(d),Be(d),Xe.current=S}),hooks:{onTurnStart:({turn:d,input:S,promptTokens:w})=>{Fe.current=d;let oe=ot.current;oe&&(ot.current=null);let ke=oe??S;w&&w>0&&A(w),_({type:"turn_start",turn:d,input:ke,promptTokens:w})},onAction:({turn:d,step:S,action:w,thinking:oe,parallelActions:ke})=>{_({type:"tool_action",turn:d,step:S,action:w,thinking:oe,parallelActions:ke})},onObservation:({turn:d,step:S,observation:w,resultStatus:oe,parallelResultStatuses:ke})=>{_({type:"tool_observation",turn:d,step:S,observation:w,toolStatus:Cr(oe),parallelToolStatuses:ei(ke)})},onFinal:({turn:d,finalText:S,status:w,errorMessage:oe,turnUsage:ke,tokenUsage:ka})=>{_({type:"turn_final",turn:d,finalText:S,status:w,errorMessage:oe,turnUsage:ke,tokenUsage:ka}),M(!1)}}}),[_,Y]);Wt(()=>{let d=!1;return(async()=>{if(!(j||G))try{let S=ie.current;S&&await S.close();let w=await dn(Z,K);if(d){await w.close();return}ie.current=w,Ve(w),Ae(w.historyFilePath??null)}catch(S){if(d)return;ie.current=null,Ve(null),Ae(null),M(!1),y("Session",`Failed to create session: ${S.message}`,"error")}})(),()=>{d=!0}},[y,Z,G,K,j]),Wt(()=>{let d=!1;return(async()=>{let S=await ya();d||!S||y("Update",`Update available: v${S.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{d=!0}},[y]),Wt(()=>()=>{ie.current&&ie.current.close()},[]);let re=X(async()=>{let d=Xe.current;d&&(d("deny"),Xe.current=null),ne&&Be(null),ie.current&&await ie.current.close(),bt("Bye!"),setTimeout(()=>u(),250)},[u,ne]),Pe=X(()=>{if(R){y("Clear","Cancel current run before clearing timeline.","warning");return}if(ne){y("Clear","Resolve current approval request before clearing timeline.","warning");return}_({type:"clear_current_timeline"}),Se(null),A(0),Mg()},[y,R,_,ne]),On=X(()=>{if(R){y("New Session","Cancel current run before starting a new session.","warning");return}if(ne){y("New Session","Resolve current approval request before starting a new session.","warning");return}_({type:"reset_all"}),Se(null),A(0),Fe.current=null,V(d=>({...d,sessionId:Tt()})),y("New Session","Started a fresh session.")},[y,R,_,ne]),Ct=X(async d=>{try{let S=await de();await Me(S.configPath,{...S.config,current_provider:d})}catch(S){y("Config",`Failed to persist provider: ${S.message}`,"warning")}},[y]),C=X(async d=>{if(R){y("Model switch","Cancel current run before switching models.","warning");return}if(d.name===b&&d.model===B){y("Model switch",`Already using ${d.name} (${d.model}).`);return}_({type:"reset_all"}),A(0),Fe.current=null;let S=O(d);E(d.name),q(d.model),He(S),V(w=>({...w,sessionId:Tt(),providerName:d.name,maxPromptTokens:S})),await Ct(d.name),y("Model switch",`Switched to ${d.name} (${d.model}).`)},[y,R,B,b,_,Ct,O]),k=X(d=>d===U.NONE?"none (no tools)":d===U.ONCE?"once (approval required)":"full (no approval)",[]),ae=X(d=>{if(R){y("Tools","Cancel current run before changing tool permission mode.","warning");return}if(ne){y("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(d===Y){y("Tools",`Already using ${k(d)}.`);return}H(d),V(S=>({...S,sessionId:Tt(),dangerous:d===U.FULL,toolPermissionMode:d})),y("Tools",`Tool permission set to ${k(d)}.`)},[y,R,ne,k,Y]),F=X(async d=>{try{let S=await de();await Me(S.configPath,{...S.config,active_mcp_servers:d})}catch(S){y("MCP",`Failed to persist active MCP servers: ${S.message}`,"warning")}},[y]),Te=X((d,S)=>{let w=wg(g,d);z(w),Gt(!1),V(oe=>({...oe,sessionId:Tt(),activeMcpServers:w})),S&&F(w)},[g,F]),Je=X(async d=>{if(R){y("History","Cancel current run before loading session history.","warning");return}if(ne){y("History","Resolve current approval request before loading session history.","warning");return}try{let S=await Tg(d.sessionFile,"utf8"),w=pa(S);_({type:"clear_current_timeline"}),_({type:"replace_history",turns:w.turns,maxSequence:w.maxSequence}),Se(w.messages),M(!1),Ve(null),Ae(null),A(0),Fe.current=null,V(oe=>({...oe,sessionId:Tt()})),y("History",w.summary||d.input)}catch(S){y("History",`Failed to load ${d.sessionFile}: ${S.message}`,"error")}},[y,R,_,ne]),st=X(()=>{R&&D?.cancelCurrentTurn?.()},[R,D]),xt=X(async()=>{if(!D||R)return;let d=ye($.INIT);try{let S=await Xr("init_agents");te(w=>[...w,d]),M(!0),ot.current=d,await D.runTurn(S)}catch(S){M(!1),y("Init",`Failed to run init task: ${S.message}`,"error")}},[y,R,D]),Ln=X(async d=>{if(!D||R)return;if(Y===U.NONE){y("Review",'Tool permission mode is "none". Set `/tools once` or `/tools full` before running `/review`.',"warning");return}let S=`${ye($.REVIEW)} ${d}`;try{let w=await _a({cwd:s,mcpServers:o,activeMcpServerNames:ge,availableToolNames:D.listToolNames?.()??[]});if(w.kind==="unavailable"){y("Review",w.reason,"error");return}let oe=await Xr("review_pull_request",{pr_number:String(d),backend_strategy:w.strategy,backend_details:w.details,mcp_server_prefix:w.kind==="github_mcp"?w.mcpServerPrefix:"github"});te(ke=>[...ke,S]),y("Review",w.details),M(!0),ot.current=S,await D.runTurn(oe)}catch(w){M(!1),y("Review",`Failed to run review task for PR #${d}: ${w.message}`,"error")}},[ge,y,R,s,o,D,Y]),wt=X(async d=>{let S=d.trim();if(S){if(S.toLowerCase()===yi){await re();return}if(S===ye($.INIT)){await xt();return}if(!(!D||R)){te(w=>[...w,S]),M(!0);try{await D.runTurn(S)}catch(w){M(!1),y("Run",`Turn failed: ${w.message}`,"error")}}}},[y,R,re,xt,D]),wa=X(async()=>{try{let d=await de(),S=Ze(d.config),w=ut(d.config,S);ce(d.config.providers),P(d.config.model_profiles),E(S.name),q(S.model),He(w),V(oe=>({...oe,sessionId:Tt(),providerName:S.name,maxPromptTokens:w})),vt(!1),y("Setup",`Config saved to ${d.configPath}`)}catch(d){y("Setup",`Failed to reload config: ${d.message}`,"error")}},[y]);Wt(()=>{if(!D||!_e?.length)return;let d=D.history[0];d&&(D.history.splice(0,D.history.length,d,..._e),Se(null))},[_e,D]);let Ma=X(d=>{let S=Xe.current;S&&(S(d),Xe.current=null),Be(null)},[]),Ea=ni(f.turns[f.turns.length-1]?.tokenUsage),Aa=ti(Ke,rt),Pa=jt(()=>({providerName:b,model:B,cwd:s,sessionId:K.sessionId??"unknown",mcpNames:ge,version:T?.version??"unknown"}),[ge,B,b,s,T?.version,K.sessionId]);return L?qe(Sa,{children:qe(bg,{color:"green",children:L})}):j?qe(ua,{configPath:r,onComplete:wa,onExit:re}):G?qe(ia,{serverNames:g,defaultSelected:v,onConfirm:Te,onExit:()=>{re()}}):Eg(Sa,{flexDirection:"column",children:[qe(hi,{header:Pa,systemMessages:f.systemMessages,turns:f.turns,historicalTurns:f.historicalTurns}),qe(ea,{disabled:!D||!!ne,busy:R,history:I,cwd:s,sessionsDir:i,currentSessionFile:ue??void 0,providers:fe,configPath:r,providerName:b,model:B,toolPermissionMode:Y,mcpServers:o,onSubmit:d=>{wt(d)},onExit:()=>{re()},onClear:Pe,onNewSession:On,onCancelRun:st,onHistorySelect:d=>{Je(d)},onModelSelect:d=>{C(d)},onSetToolPermission:ae,onReviewPullRequest:d=>{Ln(d)},onSystemMessage:y}),ne?qe(sa,{request:ne,onDecision:Ma}):null,qe(ra,{busy:R,pendingApproval:!!ne,contextPercent:Aa,tokenLine:Ea})]})}var Ag=`
|
|
116
107
|
Usage:
|
|
117
108
|
memo mcp list [--json]
|
|
118
109
|
memo mcp get <name> [--json]
|
|
@@ -121,14 +112,13 @@ Usage:
|
|
|
121
112
|
memo mcp remove <name>
|
|
122
113
|
memo mcp login <name> [--scopes scope1,scope2]
|
|
123
114
|
memo mcp logout <name>
|
|
124
|
-
`;function
|
|
125
|
-
`)}function
|
|
126
|
-
`),{...
|
|
127
|
-
[approval required] ${
|
|
128
|
-
[tool] ${
|
|
129
|
-
`);let
|
|
130
|
-
${
|
|
131
|
-
[tokens] prompt=${
|
|
132
|
-
provider=${n.name} model=${n.model}`)}catch(
|
|
133
|
-
`)),await
|
|
134
|
-
//# sourceMappingURL=index.js.map
|
|
115
|
+
`;function Yr(){console.log(Ag.trim())}function Pg(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 va(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(`
|
|
116
|
+
`)}function kg(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=Pg(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 Rg(t){let[e,...n]=t;return!e||e==="--help"||e==="-h"||e==="help"?{command:"help",rest:[]}:{command:e,rest:n}}function Zr(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 ba(t){let{command:e,rest:n}=Rg(t);if(e==="help"){Yr();return}if(e==="list"){let r=n.includes("--json"),s=(await de()).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(va(a,l))}return}if(e==="get"){let r=n.includes("--json"),o=Zr(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await de()).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(va(o,i));return}if(e==="add"){let r=kg(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),Yr();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 de(),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 Me(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(e==="remove"){let r=Zr(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await de(),s={...o.config.mcp_servers??{}};if(!s[r]){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}delete s[r],await Me(o.configPath,{...o.config,mcp_servers:s}),console.log(`Removed MCP server "${r}".`);return}if(e==="login"||e==="logout"){let r=Zr(n,["--scopes"]);if(!r){console.error("Missing server name."),process.exitCode=1;return}let s=(await de()).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}`),Yr(),process.exitCode=1}import{jsx as Bg}from"react/jsx-runtime";function $g(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 xa(t){let e=await de();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 Me(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=Ig({input:Og,output:Lg}),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 Me(e.configPath,u),console.log(`Config written to ${e.configPath}
|
|
117
|
+
`),{...e,config:u,needsSetup:!1}}finally{s.close()}}async function Dg(t){let e=await xa("plain"),n=Ze(e.config),r=ut(e.config,n),s={sessionId:Ca(),mode:"interactive",maxPromptTokens:r,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 i={requestApproval:t.options.dangerous?void 0:c=>(console.log(`
|
|
118
|
+
[approval required] ${c.toolName}: ${c.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:c})=>{console.log(`
|
|
119
|
+
[tool] ${c.tool}`),c.input!==void 0&&console.log(`[input] ${JSON.stringify(c.input)}`)},onObservation:()=>{}}},a=await dn(i,s),l=t.question;if(!l&&!process.stdin.isTTY&&(l=await Fg()),!l){console.error("No input provided. Pass a question or use stdin."),await a.close();return}try{console.log(`User: ${l}
|
|
120
|
+
`);let c=await a.runTurn(l);console.log(`
|
|
121
|
+
${c.finalText}`),console.log(`
|
|
122
|
+
[tokens] prompt=${c.tokenUsage.prompt} completion=${c.tokenUsage.completion} total=${c.tokenUsage.total}`),console.log(`
|
|
123
|
+
provider=${n.name} model=${n.model}`)}catch(c){console.error(`Run failed: ${c.message}`)}finally{await a.close()}}async function Ug(t){let e=await xa("tui"),n=Ze(e.config),r=ut(e.config,n),s={sessionId:Ca(),mode:"interactive",maxPromptTokens:r,activeMcpServers:e.config.active_mcp_servers,generateSessionTitle:!0,dangerous:t.options.dangerous},i=ln(e,s);t.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
|
|
124
|
+
`)),await Ng(Bg(Ta,{sessionOptions:s,providerName:n.name,model:n.model,configPath:e.configPath,mcpServers:e.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:i,providers:e.config.providers,modelProfiles:e.config.model_profiles,dangerous:t.options.dangerous,needsSetup:e.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function Hg(){let t=process.argv.slice(2);if(t[0]==="mcp"||t[0]==="--"&&t[1]==="mcp"){let r=t[0]==="--"?2:1;await ba(t.slice(r));return}let e=$g(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=Rn()?.version??"unknown";console.log(o);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await Dg(e);return}await Ug(e)}Hg();async function Fg(){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()})}
|