@memo-code/memo 0.8.56 → 0.8.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,37 +1,37 @@
1
1
  #!/usr/bin/env node
2
- var np=Object.create;var Br=Object.defineProperty;var rp=Object.getOwnPropertyDescriptor;var op=Object.getOwnPropertyNames;var sp=Object.getPrototypeOf,ip=Object.prototype.hasOwnProperty;var Ws=(t,e)=>()=>(t&&(e=t(t=0)),e);var js=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ap=(t,e)=>{for(var n in e)Br(t,n,{get:e[n],enumerable:!0})},cp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of op(e))!ip.call(t,o)&&o!==n&&Br(t,o,{get:()=>e[o],enumerable:!(r=rp(e,o))||r.enumerable});return t};var zs=(t,e,n)=>(n=t!=null?np(sp(t)):{},cp(e||!t||!t.__esModule?Br(n,"default",{value:t,enumerable:!0}):n,t));var gi=js(($T,Fn)=>{"use strict";function li(t){return Array.isArray(t)?t:[t]}var yd=void 0,Vr="",ai=" ",Kr="\\",Sd=/^\s+$/,wd=/(?:[^\\]|^)\\$/,_d=/^\\!/,vd=/^\\#/,Td=/\r?\n/g,Cd=/^\.{0,2}\/|^\.{1,2}$/,bd=/\/$/,Et="/",ui="node-ignore";typeof Symbol<"u"&&(ui=Symbol.for("node-ignore"));var pi=ui,Pt=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),xd=/([0-z])-([0-z])/g,di=()=>!1,Md=t=>t.replace(xd,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Vr),kd=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Ed=[[/^\uFEFF/,()=>Vr],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?ai:Vr)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+ai}],[/[\\$.|*+(){^]/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,()=>Kr],[/\\\\/g,()=>Kr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Kr?`\\[${n}${kd(r)}${o}`:o==="]"&&r.length%2===0?`[${Md(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],Pd=/(^|\\\/)?\\\*$/,rn="regex",$n="checkRegex",ci="_",Ad={[rn](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[$n](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Rd=t=>Ed.reduce((e,[n,r])=>e.replace(n,r.bind(t)),t),Dn=t=>typeof t=="string",Od=t=>t&&Dn(t)&&!Sd.test(t)&&!wd.test(t)&&t.indexOf("#")!==0,Id=t=>t.split(Td).filter(Boolean),Xr=class{constructor(e,n,r,o,s,i){this.pattern=e,this.mark=n,this.negative=s,Pt(this,"body",r),Pt(this,"ignoreCase",o),Pt(this,"regexPrefix",i)}get regex(){let e=ci+rn;return this[e]?this[e]:this._make(rn,e)}get checkRegex(){let e=ci+$n;return this[e]?this[e]:this._make($n,e)}_make(e,n){let r=this.regexPrefix.replace(Pd,Ad[e]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return Pt(this,n,o)}},Ld=({pattern:t,mark:e},n)=>{let r=!1,o=t;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(_d,"!").replace(vd,"#");let s=Rd(o);return new Xr(t,e,o,n,r,s)},Yr=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[pi]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Dn(e)&&(e={pattern:e}),Od(e.pattern)){let n=Ld(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,li(Dn(e)?Id(e):e).forEach(this._add,this),this._added}test(e,n,r){let o=!1,s=!1,i;this._rules.forEach(a=>{let{negative:l}=a;s===l&&o!==s||l&&!o&&!s&&!n||!a[r].test(e)||(o=!l,s=l,i=l?yd:a)});let c={ignored:o,unignored:s};return i&&(c.rule=i),c}},Nd=(t,e)=>{throw new e(t)},Ge=(t,e,n)=>Dn(t)?t?Ge.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),fi=t=>Cd.test(t);Ge.isNotRelative=fi;Ge.convert=t=>t;var Jr=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){Pt(this,pi,!0),this._rules=new Yr(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&&Ge.convert(e);return Ge(s,e,this._strictPathCheck?Nd:di),this._t(s,n,r,o)}checkIgnore(e){if(!bd.test(e))return this.test(e);let n=e.split(Et).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(Et)+Et,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(e,!1,$n)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(Et).filter(Boolean)),o.pop(),!o.length)return n[e]=this._rules.test(e,r,rn);let s=this._t(o.join(Et)+Et,n,r,o);return n[e]=s.ignored?s:this._rules.test(e,r,rn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return li(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Qr=t=>new Jr(t),$d=t=>Ge(t&&Ge.convert(t),t,di),mi=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ge.convert=t;let e=/^[a-z]:\//i;Ge.isNotRelative=n=>e.test(n)||fi(n)};typeof process<"u"&&process.platform==="win32"&&mi();Fn.exports=Qr;Qr.default=Qr;Fn.exports.isPathValid=$d;Pt(Fn.exports,Symbol.for("setupWindows"),mi)});var ya=js((ab,ha)=>{"use strict";function la(t){return Array.isArray(t)?t:[t]}var Mo="",ua=" ",bo="\\",Im=/^\s+$/,Lm=/(?:[^\\]|^)\\$/,Nm=/^\\!/,$m=/^\\#/,Dm=/\r?\n/g,Fm=/^\.*\/|^\.+$/,xo="/",fa="node-ignore";typeof Symbol<"u"&&(fa=Symbol.for("node-ignore"));var pa=fa,Um=(t,e,n)=>Object.defineProperty(t,e,{value:n}),Hm=/([0-z])-([0-z])/g,ma=()=>!1,Bm=t=>t.replace(Hm,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Mo),Wm=t=>{let{length:e}=t;return t.slice(0,e-e%2)},jm=[[/^\uFEFF/,()=>Mo],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?ua:Mo)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+ua}],[/[\\$.|*+(){^]/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,()=>bo],[/\\\\/g,()=>bo],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===bo?`\\[${n}${Wm(r)}${o}`:o==="]"&&r.length%2===0?`[${Bm(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],da=Object.create(null),zm=(t,e)=>{let n=da[t];return n||(n=jm.reduce((r,[o,s])=>r.replace(o,s.bind(t)),t),da[t]=n),e?new RegExp(n,"i"):new RegExp(n)},Po=t=>typeof t=="string",Gm=t=>t&&Po(t)&&!Im.test(t)&&!Lm.test(t)&&t.indexOf("#")!==0,qm=t=>t.split(Dm),ko=class{constructor(e,n,r,o){this.origin=e,this.pattern=n,this.negative=r,this.regex=o}},Km=(t,e)=>{let n=t,r=!1;t.indexOf("!")===0&&(r=!0,t=t.substr(1)),t=t.replace(Nm,"!").replace($m,"#");let o=zm(t,e);return new ko(n,t,r,o)},Vm=(t,e)=>{throw new e(t)},Ve=(t,e,n)=>Po(t)?t?Ve.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),ga=t=>Fm.test(t);Ve.isNotRelative=ga;Ve.convert=t=>t;var Eo=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){Um(this,pa,!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[pa]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Gm(e)){let n=Km(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,la(Po(e)?qm(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&&Ve.convert(e);return Ve(s,e,this._allowRelativePaths?ma:Vm),this._t(s,n,r,o)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(xo)),o.pop(),!o.length)return n[e]=this._testOne(e,r);let s=this._t(o.join(xo)+xo,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 la(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},qn=t=>new Eo(t),Xm=t=>Ve(t&&Ve.convert(t),t,ma);qn.isPathValid=Xm;qn.default=qn;ha.exports=qn;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,"/");Ve.convert=t;let e=/^[a-z]:\//i;Ve.isNotRelative=n=>e.test(n)||ga(n)}});function Nv(t){let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<=0||e>65535?null:e}function Bu(t){let e={open:!0};for(let n=0;n<t.length;n++){let r=t[n];if(r){if(r==="--open"){e.open=!0;continue}if(r==="--no-open"){e.open=!1;continue}if(r==="--host"){let o=t[n+1];o&&!o.startsWith("-")&&(e.host=o,n+=1);continue}if(r==="--port"){let o=t[n+1];if(o&&!o.startsWith("-")){let s=Nv(o);s!==null&&(e.port=s,n+=1)}continue}if(r==="--static-dir"){let o=t[n+1];o&&!o.startsWith("-")&&(e.staticDir=o,n+=1);continue}}}return e}var Wu=Ws(()=>{"use strict"});var qu={};ap(qu,{runWebCommand:()=>Xv});import{spawn as ju}from"child_process";import{existsSync as zu,readFileSync as $v}from"fs";import{createServer as Dv}from"net";import{dirname as xn,join as Q,resolve as He}from"path";import{fileURLToPath as $r}from"url";function dt(t){let e=He(t);for(;;){let n=Q(e,"package.json");if(zu(n))try{if(JSON.parse($v(n,"utf8")).name==="@memo-code/memo")return e}catch{}let r=xn(e);if(r===e)break;e=r}return null}function Dr(t){return zu(t)}function Hv(t){let e=[];t&&e.push(He(t)),process.env.MEMO_WEB_SERVER_ENTRY&&e.push(He(process.env.MEMO_WEB_SERVER_ENTRY));let n=xn($r(import.meta.url)),r=dt(n)??dt(process.cwd());r&&(e.push(Q(r,"dist/web/server/main.cjs")),e.push(Q(r,"dist/web/server/main.js")),e.push(Q(r,"packages/web-server/dist/main.cjs")),e.push(Q(r,"packages/web-server/dist/main.js"))),e.push(Q(process.cwd(),"dist/web/server/main.cjs")),e.push(Q(process.cwd(),"dist/web/server/main.js")),e.push(Q(process.cwd(),"packages/web-server/dist/main.cjs")),e.push(Q(process.cwd(),"packages/web-server/dist/main.js"));for(let o of e)if(Dr(o))return o;return null}function Bv(t){let e=[];t&&e.push(He(t)),process.env.MEMO_WEB_STATIC_DIR&&e.push(He(process.env.MEMO_WEB_STATIC_DIR));let n=xn($r(import.meta.url)),r=dt(n)??dt(process.cwd());r&&(e.push(Q(r,"dist/web/ui")),e.push(Q(r,"packages/web-ui/dist"))),e.push(Q(process.cwd(),"dist/web/ui")),e.push(Q(process.cwd(),"packages/web-ui/dist"));for(let o of e)if(Dr(Q(o,"index.html")))return o;return null}function Wv(){let t=xn($r(import.meta.url)),e=dt(t)??dt(process.cwd()),n=[];e&&(n.push(Q(e,"dist/task-prompts")),n.push(Q(e,"packages/tui/src/task-prompts"))),n.push(He(t,"../task-prompts")),n.push(He(t,"task-prompts"));for(let r of n)if(Dr(Q(r,"init_agents.md")))return r;return n[0]??He(t,"../task-prompts")}function jv(){let t=xn($r(import.meta.url)),e=dt(t)??dt(process.cwd()),n=[];process.env.MEMO_SYSTEM_PROMPT_PATH&&n.push(He(process.env.MEMO_SYSTEM_PROMPT_PATH)),e&&(n.push(Q(e,"dist/prompt.md")),n.push(Q(e,"packages/core/src/runtime/prompt.md"))),n.push(He(t,"../prompt.md")),n.push(He(t,"../../core/src/runtime/prompt.md"));for(let r of n)if(Dr(r))return r;return null}async function Gu(t,e){return new Promise(n=>{let r=Dv();r.unref(),r.once("error",()=>n(!1)),r.listen({host:t,port:e},()=>{r.close(()=>n(!0))})})}async function zv(t,e){for(let n=0;n<30;n++){let r=e+n;if(r>65535)break;if(await Gu(t,r))return r}throw new Error(`No available port found from ${e} to ${e+29}`)}function Gv(t,e){return e==="darwin"?{command:"open",args:[t]}:e==="win32"?{command:"cmd",args:["/c","start","",t]}:e==="linux"?{command:"xdg-open",args:[t]}:null}function qv(t){let e=Gv(t,process.platform);if(!e)return!1;try{return ju(e.command,e.args,{stdio:"ignore",detached:!0}).unref(),!0}catch{return!1}}function Kv(t,e){return`http://${t.includes(":")?`[${t}]`:t}:${e}`}async function Vv(t,e,n=8e3){let r=Date.now();for(;Date.now()-r<n;){if(!await Gu(t,e))return!0;await new Promise(o=>setTimeout(o,120))}return!1}async function Xv(t){let e=Bu(t),n=e.host??Fv,r=e.port??Uv,o=await zv(n,r),s=Hv();if(!s){console.error("web-server entry not found (main.js missing)."),console.error("Please run `pnpm run web:server:build` or `pnpm run build` first."),process.exitCode=1;return}let i=Bv(e.staticDir);if(!i){console.error("web-ui static assets not found (index.html missing)."),console.error("Please run `pnpm run web:ui:build` or `pnpm run build` first."),process.exitCode=1;return}o!==r&&console.log(`[memo web] Port ${r} is busy, using ${o}`);let c=Kv(n,o);console.log(`[memo web] Server: ${c}`),console.log(`[memo web] Entry: ${s}`),console.log(`[memo web] Static: ${i}`);let a=Wv(),l=jv(),u=ju(process.execPath,[s],{stdio:"inherit",env:{...process.env,MEMO_WEB_HOST:n,MEMO_WEB_PORT:String(o),MEMO_WEB_STATIC_DIR:i,MEMO_CLI_ENTRY:process.argv[1],MEMO_TASK_PROMPTS_DIR:a,...l?{MEMO_SYSTEM_PROMPT_PATH:l}:{}}});e.open&&(!await Vv(n,o)||!qv(c))&&console.warn(`[memo web] Failed to auto-open browser. Open manually: ${c}`);let p=d=>{u.killed||u.kill(d)};process.once("SIGINT",()=>{p("SIGINT")}),process.once("SIGTERM",()=>{p("SIGTERM")}),await new Promise(d=>{u.once("exit",(f,g)=>{if(g){process.exitCode=0,d();return}process.exitCode=f??0,d()})})}var Fv,Uv,Ku=Ws(()=>{"use strict";Wu();Fv="127.0.0.1",Uv=5494});import{randomUUID as Vu}from"crypto";import{readFile as Yv}from"fs/promises";import{createInterface as Jv}from"readline/promises";import{stdin as Qv,stdout as Zv}from"process";import{render as eT}from"ink";import Qs from"os";import{readFile as Wr}from"fs/promises";import{existsSync as Ip}from"fs";import{join as nt,dirname as Lp,resolve as en}from"path";import{fileURLToPath as Np}from"url";import{access as lp,readFile as up,readdir as pp,stat as dp}from"fs/promises";import{constants as fp}from"fs";import{homedir as qs}from"os";import{dirname as mp,isAbsolute as gp,join as kt,resolve as An}from"path";import hp from"fast-glob";var yp="SKILL.md",Sp=6,wp=200,_p=64,vp=1024,Tp="- 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 Ks(t){return t.trim().split(/\s+/).join(" ")}function Cp(t){let e=t.trim();return e.length>=2&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))?e.slice(1,-1):e}function bp(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 xp(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:Ks(o.join(" "))}function Gs(t,e){let n=xp(t,e);if(n)return n;let r=new RegExp(`^${e}\\s*:\\s*(.+?)\\s*$`,"m"),o=t.match(r);return o?.[1]?Ks(Cp(o[1])):null}function Mp(t,e){let n=bp(t);if(!n)return null;let r=Gs(n,"name"),o=Gs(n,"description");return!r||!o||r.length>_p||o.length>vp?null:{name:r,description:o,path:e}}function Vs(t,e){return t==="~"?e:t.startsWith("~/")?kt(e,t.slice(2)):t}async function kp(t){try{return(await dp(t)).isDirectory()}catch{return!1}}async function Ep(t){try{return await lp(kt(t,".git"),fp.F_OK),!0}catch{return!1}}async function Pp(t){let e=An(t),n=e;for(;;){if(await Ep(n))return n;let r=mp(n);if(r===n)break;n=r}return e}async function Ap(t){let e=[kt(t,".agents","skills")];try{let r=(await pp(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(kt(t,o,"skills"))}catch{return Pn(e)}return Pn(e)}function Pn(t){let e=[],n=new Set;for(let r of t){let o=An(r);n.has(o)||(n.add(o),e.push(o))}return e}async function Rp(t){let e=t.cwd??process.cwd(),n=t.homeDir??qs(),r=Vs(t.memoHome??process.env.MEMO_HOME??kt(n,".memo"),n),o=await Pp(e),s=await Ap(o);return s.push(kt(r,"skills")),Pn(s)}async function Op(t){if(t.skillRoots&&t.skillRoots.length>0){let e=t.homeDir??qs(),n=t.skillRoots.map(r=>{let o=Vs(r,e);return gp(o)?o:An(o)});return Pn(n)}return Rp(t)}async function Xs(t={}){let e=await Op(t),n=Math.max(1,t.maxSkills??wp),r=[],o=new Set;for(let s of e){if(!await kp(s))continue;let i=await hp(`**/${yp}`,{cwd:s,absolute:!0,onlyFiles:!0,deep:Sp,caseSensitiveMatch:!1,followSymbolicLinks:!0,suppressErrors:!0,unique:!0,ignore:["**/.git/**","**/node_modules/**"]});i.sort((c,a)=>c.localeCompare(a));for(let c of i){let a=An(c);if(o.has(a))continue;let l;try{l=await up(a,"utf-8")}catch{continue}let u=Mp(l,a);if(u&&(r.push(u),o.add(a),r.length>=n))return r}}return r}function Ys(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(Tp),e.join(`
4
- `)}var $p=/{{\s*([\w.-]+)\s*}}/g,Dp=/{{\s*soul_section\s*}}/;function Fp(t,e){return t.replace($p,(n,r)=>e[r]??"")}function Up(){try{return Qs.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}function Js(t){return en(t)}function Hp(t){let e=t.homeDir??Qs.homedir(),n=t.memoHome?.trim()||process.env.MEMO_HOME?.trim()||nt(e,".memo");return n==="~"?en(e):n.startsWith("~/")?en(nt(e,n.slice(2))):en(n)}function Bp(t,e){if(!Array.isArray(e))return t;let n=new Set(e.map(r=>Js(r)));return t.filter(r=>n.has(Js(r.path)))}async function Wp(t){let e=nt(t,"AGENTS.md");try{let n=await Wr(e,"utf-8");return n.trim()?{path:e,content:n}:null}catch{return null}}function jp(t,e){return`${t}
2
+ var tp=Object.create;var Br=Object.defineProperty;var np=Object.getOwnPropertyDescriptor;var rp=Object.getOwnPropertyNames;var op=Object.getPrototypeOf,sp=Object.prototype.hasOwnProperty;var Ws=(t,e)=>()=>(t&&(e=t(t=0)),e);var js=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ip=(t,e)=>{for(var n in e)Br(t,n,{get:e[n],enumerable:!0})},ap=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of rp(e))!sp.call(t,o)&&o!==n&&Br(t,o,{get:()=>e[o],enumerable:!(r=np(e,o))||r.enumerable});return t};var zs=(t,e,n)=>(n=t!=null?tp(op(t)):{},ap(e||!t||!t.__esModule?Br(n,"default",{value:t,enumerable:!0}):n,t));var gi=js(($T,Fn)=>{"use strict";function li(t){return Array.isArray(t)?t:[t]}var hd=void 0,Vr="",ai=" ",Kr="\\",yd=/^\s+$/,Sd=/(?:[^\\]|^)\\$/,wd=/^\\!/,_d=/^\\#/,vd=/\r?\n/g,Td=/^\.{0,2}\/|^\.{1,2}$/,Cd=/\/$/,Et="/",ui="node-ignore";typeof Symbol<"u"&&(ui=Symbol.for("node-ignore"));var pi=ui,Pt=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),bd=/([0-z])-([0-z])/g,di=()=>!1,xd=t=>t.replace(bd,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Vr),Md=t=>{let{length:e}=t;return t.slice(0,e-e%2)},kd=[[/^\uFEFF/,()=>Vr],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?ai:Vr)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+ai}],[/[\\$.|*+(){^]/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,()=>Kr],[/\\\\/g,()=>Kr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Kr?`\\[${n}${Md(r)}${o}`:o==="]"&&r.length%2===0?`[${xd(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],Ed=/(^|\\\/)?\\\*$/,rn="regex",$n="checkRegex",ci="_",Pd={[rn](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[$n](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Ad=t=>kd.reduce((e,[n,r])=>e.replace(n,r.bind(t)),t),Dn=t=>typeof t=="string",Rd=t=>t&&Dn(t)&&!yd.test(t)&&!Sd.test(t)&&t.indexOf("#")!==0,Od=t=>t.split(vd).filter(Boolean),Xr=class{constructor(e,n,r,o,s,i){this.pattern=e,this.mark=n,this.negative=s,Pt(this,"body",r),Pt(this,"ignoreCase",o),Pt(this,"regexPrefix",i)}get regex(){let e=ci+rn;return this[e]?this[e]:this._make(rn,e)}get checkRegex(){let e=ci+$n;return this[e]?this[e]:this._make($n,e)}_make(e,n){let r=this.regexPrefix.replace(Ed,Pd[e]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return Pt(this,n,o)}},Id=({pattern:t,mark:e},n)=>{let r=!1,o=t;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(wd,"!").replace(_d,"#");let s=Ad(o);return new Xr(t,e,o,n,r,s)},Yr=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[pi]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Dn(e)&&(e={pattern:e}),Rd(e.pattern)){let n=Id(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,li(Dn(e)?Od(e):e).forEach(this._add,this),this._added}test(e,n,r){let o=!1,s=!1,i;this._rules.forEach(a=>{let{negative:l}=a;s===l&&o!==s||l&&!o&&!s&&!n||!a[r].test(e)||(o=!l,s=l,i=l?hd:a)});let c={ignored:o,unignored:s};return i&&(c.rule=i),c}},Ld=(t,e)=>{throw new e(t)},Ge=(t,e,n)=>Dn(t)?t?Ge.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),fi=t=>Td.test(t);Ge.isNotRelative=fi;Ge.convert=t=>t;var Jr=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){Pt(this,pi,!0),this._rules=new Yr(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&&Ge.convert(e);return Ge(s,e,this._strictPathCheck?Ld:di),this._t(s,n,r,o)}checkIgnore(e){if(!Cd.test(e))return this.test(e);let n=e.split(Et).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(Et)+Et,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(e,!1,$n)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(Et).filter(Boolean)),o.pop(),!o.length)return n[e]=this._rules.test(e,r,rn);let s=this._t(o.join(Et)+Et,n,r,o);return n[e]=s.ignored?s:this._rules.test(e,r,rn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return li(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Qr=t=>new Jr(t),Nd=t=>Ge(t&&Ge.convert(t),t,di),mi=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ge.convert=t;let e=/^[a-z]:\//i;Ge.isNotRelative=n=>e.test(n)||fi(n)};typeof process<"u"&&process.platform==="win32"&&mi();Fn.exports=Qr;Qr.default=Qr;Fn.exports.isPathValid=Nd;Pt(Fn.exports,Symbol.for("setupWindows"),mi)});var ya=js((ab,ha)=>{"use strict";function la(t){return Array.isArray(t)?t:[t]}var Mo="",ua=" ",bo="\\",Om=/^\s+$/,Im=/(?:[^\\]|^)\\$/,Lm=/^\\!/,Nm=/^\\#/,$m=/\r?\n/g,Dm=/^\.*\/|^\.+$/,xo="/",fa="node-ignore";typeof Symbol<"u"&&(fa=Symbol.for("node-ignore"));var pa=fa,Fm=(t,e,n)=>Object.defineProperty(t,e,{value:n}),Um=/([0-z])-([0-z])/g,ma=()=>!1,Hm=t=>t.replace(Um,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Mo),Bm=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Wm=[[/^\uFEFF/,()=>Mo],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?ua:Mo)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+ua}],[/[\\$.|*+(){^]/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,()=>bo],[/\\\\/g,()=>bo],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===bo?`\\[${n}${Bm(r)}${o}`:o==="]"&&r.length%2===0?`[${Hm(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],da=Object.create(null),jm=(t,e)=>{let n=da[t];return n||(n=Wm.reduce((r,[o,s])=>r.replace(o,s.bind(t)),t),da[t]=n),e?new RegExp(n,"i"):new RegExp(n)},Po=t=>typeof t=="string",zm=t=>t&&Po(t)&&!Om.test(t)&&!Im.test(t)&&t.indexOf("#")!==0,Gm=t=>t.split($m),ko=class{constructor(e,n,r,o){this.origin=e,this.pattern=n,this.negative=r,this.regex=o}},qm=(t,e)=>{let n=t,r=!1;t.indexOf("!")===0&&(r=!0,t=t.substr(1)),t=t.replace(Lm,"!").replace(Nm,"#");let o=jm(t,e);return new ko(n,t,r,o)},Km=(t,e)=>{throw new e(t)},Ve=(t,e,n)=>Po(t)?t?Ve.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),ga=t=>Dm.test(t);Ve.isNotRelative=ga;Ve.convert=t=>t;var Eo=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){Fm(this,pa,!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[pa]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(zm(e)){let n=qm(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,la(Po(e)?Gm(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&&Ve.convert(e);return Ve(s,e,this._allowRelativePaths?ma:Km),this._t(s,n,r,o)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(xo)),o.pop(),!o.length)return n[e]=this._testOne(e,r);let s=this._t(o.join(xo)+xo,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 la(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},qn=t=>new Eo(t),Vm=t=>Ve(t&&Ve.convert(t),t,ma);qn.isPathValid=Vm;qn.default=qn;ha.exports=qn;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,"/");Ve.convert=t;let e=/^[a-z]:\//i;Ve.isNotRelative=n=>e.test(n)||ga(n)}});function Nv(t){let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<=0||e>65535?null:e}function Hu(t){let e={open:!0};for(let n=0;n<t.length;n++){let r=t[n];if(r){if(r==="--open"){e.open=!0;continue}if(r==="--no-open"){e.open=!1;continue}if(r==="--host"){let o=t[n+1];o&&!o.startsWith("-")&&(e.host=o,n+=1);continue}if(r==="--port"){let o=t[n+1];if(o&&!o.startsWith("-")){let s=Nv(o);s!==null&&(e.port=s,n+=1)}continue}if(r==="--static-dir"){let o=t[n+1];o&&!o.startsWith("-")&&(e.staticDir=o,n+=1);continue}}}return e}var Bu=Ws(()=>{"use strict"});var Gu={};ip(Gu,{runWebCommand:()=>Xv});import{spawn as Wu}from"child_process";import{existsSync as ju,readFileSync as $v}from"fs";import{createServer as Dv}from"net";import{dirname as xn,join as Q,resolve as He}from"path";import{fileURLToPath as $r}from"url";function dt(t){let e=He(t);for(;;){let n=Q(e,"package.json");if(ju(n))try{if(JSON.parse($v(n,"utf8")).name==="@memo-code/memo")return e}catch{}let r=xn(e);if(r===e)break;e=r}return null}function Dr(t){return ju(t)}function Hv(t){let e=[];t&&e.push(He(t)),process.env.MEMO_WEB_SERVER_ENTRY&&e.push(He(process.env.MEMO_WEB_SERVER_ENTRY));let n=xn($r(import.meta.url)),r=dt(n)??dt(process.cwd());r&&(e.push(Q(r,"dist/web/server/main.cjs")),e.push(Q(r,"dist/web/server/main.js")),e.push(Q(r,"packages/web-server/dist/main.cjs")),e.push(Q(r,"packages/web-server/dist/main.js"))),e.push(Q(process.cwd(),"dist/web/server/main.cjs")),e.push(Q(process.cwd(),"dist/web/server/main.js")),e.push(Q(process.cwd(),"packages/web-server/dist/main.cjs")),e.push(Q(process.cwd(),"packages/web-server/dist/main.js"));for(let o of e)if(Dr(o))return o;return null}function Bv(t){let e=[];t&&e.push(He(t)),process.env.MEMO_WEB_STATIC_DIR&&e.push(He(process.env.MEMO_WEB_STATIC_DIR));let n=xn($r(import.meta.url)),r=dt(n)??dt(process.cwd());r&&(e.push(Q(r,"dist/web/ui")),e.push(Q(r,"packages/web-ui/dist"))),e.push(Q(process.cwd(),"dist/web/ui")),e.push(Q(process.cwd(),"packages/web-ui/dist"));for(let o of e)if(Dr(Q(o,"index.html")))return o;return null}function Wv(){let t=xn($r(import.meta.url)),e=dt(t)??dt(process.cwd()),n=[];e&&(n.push(Q(e,"dist/task-prompts")),n.push(Q(e,"packages/tui/src/task-prompts"))),n.push(He(t,"../task-prompts")),n.push(He(t,"task-prompts"));for(let r of n)if(Dr(Q(r,"init_agents.md")))return r;return n[0]??He(t,"../task-prompts")}function jv(){let t=xn($r(import.meta.url)),e=dt(t)??dt(process.cwd()),n=[];process.env.MEMO_SYSTEM_PROMPT_PATH&&n.push(He(process.env.MEMO_SYSTEM_PROMPT_PATH)),e&&(n.push(Q(e,"dist/prompt.md")),n.push(Q(e,"packages/core/src/runtime/prompt.md"))),n.push(He(t,"../prompt.md")),n.push(He(t,"../../core/src/runtime/prompt.md"));for(let r of n)if(Dr(r))return r;return null}async function zu(t,e){return new Promise(n=>{let r=Dv();r.unref(),r.once("error",()=>n(!1)),r.listen({host:t,port:e},()=>{r.close(()=>n(!0))})})}async function zv(t,e){for(let n=0;n<30;n++){let r=e+n;if(r>65535)break;if(await zu(t,r))return r}throw new Error(`No available port found from ${e} to ${e+29}`)}function Gv(t,e){return e==="darwin"?{command:"open",args:[t]}:e==="win32"?{command:"cmd",args:["/c","start","",t]}:e==="linux"?{command:"xdg-open",args:[t]}:null}function qv(t){let e=Gv(t,process.platform);if(!e)return!1;try{return Wu(e.command,e.args,{stdio:"ignore",detached:!0}).unref(),!0}catch{return!1}}function Kv(t,e){return`http://${t.includes(":")?`[${t}]`:t}:${e}`}async function Vv(t,e,n=8e3){let r=Date.now();for(;Date.now()-r<n;){if(!await zu(t,e))return!0;await new Promise(o=>setTimeout(o,120))}return!1}async function Xv(t){let e=Hu(t),n=e.host??Fv,r=e.port??Uv,o=await zv(n,r),s=Hv();if(!s){console.error("web-server entry not found (main.js missing)."),console.error("Please run `pnpm run web:server:build` or `pnpm run build` first."),process.exitCode=1;return}let i=Bv(e.staticDir);if(!i){console.error("web-ui static assets not found (index.html missing)."),console.error("Please run `pnpm run web:ui:build` or `pnpm run build` first."),process.exitCode=1;return}o!==r&&console.log(`[memo web] Port ${r} is busy, using ${o}`);let c=Kv(n,o);console.log(`[memo web] Server: ${c}`),console.log(`[memo web] Entry: ${s}`),console.log(`[memo web] Static: ${i}`);let a=Wv(),l=jv(),u=Wu(process.execPath,[s],{stdio:"inherit",env:{...process.env,MEMO_WEB_HOST:n,MEMO_WEB_PORT:String(o),MEMO_WEB_STATIC_DIR:i,MEMO_CLI_ENTRY:process.argv[1],MEMO_TASK_PROMPTS_DIR:a,...l?{MEMO_SYSTEM_PROMPT_PATH:l}:{}}});e.open&&(!await Vv(n,o)||!qv(c))&&console.warn(`[memo web] Failed to auto-open browser. Open manually: ${c}`);let p=d=>{u.killed||u.kill(d)};process.once("SIGINT",()=>{p("SIGINT")}),process.once("SIGTERM",()=>{p("SIGTERM")}),await new Promise(d=>{u.once("exit",(f,g)=>{if(g){process.exitCode=0,d();return}process.exitCode=f??0,d()})})}var Fv,Uv,qu=Ws(()=>{"use strict";Bu();Fv="127.0.0.1",Uv=5494});import{randomUUID as Ku}from"crypto";import{readFile as Yv}from"fs/promises";import{createInterface as Jv}from"readline/promises";import{stdin as Qv,stdout as Zv}from"process";import{render as eT}from"ink";import Qs from"os";import{readFile as Wr}from"fs/promises";import{existsSync as Op}from"fs";import{join as nt,dirname as Ip,resolve as en}from"path";import{fileURLToPath as Lp}from"url";import{access as cp,readFile as lp,readdir as up,stat as pp}from"fs/promises";import{constants as dp}from"fs";import{homedir as qs}from"os";import{dirname as fp,isAbsolute as mp,join as kt,resolve as An}from"path";import gp from"fast-glob";var hp="SKILL.md",yp=6,Sp=200,wp=64,_p=1024,vp="- 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 Ks(t){return t.trim().split(/\s+/).join(" ")}function Tp(t){let e=t.trim();return e.length>=2&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))?e.slice(1,-1):e}function Cp(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 bp(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:Ks(o.join(" "))}function Gs(t,e){let n=bp(t,e);if(n)return n;let r=new RegExp(`^${e}\\s*:\\s*(.+?)\\s*$`,"m"),o=t.match(r);return o?.[1]?Ks(Tp(o[1])):null}function xp(t,e){let n=Cp(t);if(!n)return null;let r=Gs(n,"name"),o=Gs(n,"description");return!r||!o||r.length>wp||o.length>_p?null:{name:r,description:o,path:e}}function Vs(t,e){return t==="~"?e:t.startsWith("~/")?kt(e,t.slice(2)):t}async function Mp(t){try{return(await pp(t)).isDirectory()}catch{return!1}}async function kp(t){try{return await cp(kt(t,".git"),dp.F_OK),!0}catch{return!1}}async function Ep(t){let e=An(t),n=e;for(;;){if(await kp(n))return n;let r=fp(n);if(r===n)break;n=r}return e}async function Pp(t){let e=[kt(t,".agents","skills")];try{let r=(await up(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(kt(t,o,"skills"))}catch{return Pn(e)}return Pn(e)}function Pn(t){let e=[],n=new Set;for(let r of t){let o=An(r);n.has(o)||(n.add(o),e.push(o))}return e}async function Ap(t){let e=t.cwd??process.cwd(),n=t.homeDir??qs(),r=Vs(t.memoHome??process.env.MEMO_HOME??kt(n,".memo"),n),o=await Ep(e),s=await Pp(o);return s.push(kt(r,"skills")),Pn(s)}async function Rp(t){if(t.skillRoots&&t.skillRoots.length>0){let e=t.homeDir??qs(),n=t.skillRoots.map(r=>{let o=Vs(r,e);return mp(o)?o:An(o)});return Pn(n)}return Ap(t)}async function Xs(t={}){let e=await Rp(t),n=Math.max(1,t.maxSkills??Sp),r=[],o=new Set;for(let s of e){if(!await Mp(s))continue;let i=await gp(`**/${hp}`,{cwd:s,absolute:!0,onlyFiles:!0,deep:yp,caseSensitiveMatch:!1,followSymbolicLinks:!0,suppressErrors:!0,unique:!0,ignore:["**/.git/**","**/node_modules/**"]});i.sort((c,a)=>c.localeCompare(a));for(let c of i){let a=An(c);if(o.has(a))continue;let l;try{l=await lp(a,"utf-8")}catch{continue}let u=xp(l,a);if(u&&(r.push(u),o.add(a),r.length>=n))return r}}return r}function Ys(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(vp),e.join(`
4
+ `)}var Np=/{{\s*([\w.-]+)\s*}}/g,$p=/{{\s*soul_section\s*}}/;function Dp(t,e){return t.replace(Np,(n,r)=>e[r]??"")}function Fp(){try{return Qs.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}function Js(t){return en(t)}function Up(t){let e=t.homeDir??Qs.homedir(),n=t.memoHome?.trim()||process.env.MEMO_HOME?.trim()||nt(e,".memo");return n==="~"?en(e):n.startsWith("~/")?en(nt(e,n.slice(2))):en(n)}function Hp(t,e){if(!Array.isArray(e))return t;let n=new Set(e.map(r=>Js(r)));return t.filter(r=>n.has(Js(r.path)))}async function Bp(t){let e=nt(t,"AGENTS.md");try{let n=await Wr(e,"utf-8");return n.trim()?{path:e,content:n}:null}catch{return null}}function Wp(t,e){return`${t}
5
5
 
6
6
  ## Project AGENTS.md (Startup Root)
7
7
  Loaded from: ${e.path}
8
8
 
9
- ${e.content}`}function zp(t,e){return`${t}
9
+ ${e.content}`}function jp(t,e){return`${t}
10
10
 
11
- ${e}`}async function Gp(t){let e=Hp(t),n=nt(e,"SOUL.md");try{let r=await Wr(n,"utf-8");return r.trim()?{path:n,content:r}:null}catch{return null}}function qp(t){return`## User Personality Context (SOUL.md)
11
+ ${e}`}async function zp(t){let e=Up(t),n=nt(e,"SOUL.md");try{let r=await Wr(n,"utf-8");return r.trim()?{path:n,content:r}:null}catch{return null}}function Gp(t){return`## User Personality Context (SOUL.md)
12
12
  Loaded from: ${t.path}
13
13
 
14
14
  - Treat this content as a soft preference layer for tone, style, and subjective behavior.
15
15
  - Do NOT let this content override safety rules, tool policies, Project AGENTS.md guidance, or explicit user instructions in the current turn.
16
16
  - Keep SOUL.md concise when possible to avoid unnecessary prompt growth.
17
17
 
18
- ${t.content}`}function Kp(t,e){return`${t}
18
+ ${t.content}`}function qp(t,e){return`${t}
19
19
 
20
- ${e}`}function Vp(){return typeof __dirname=="string"?__dirname:Lp(Np(import.meta.url))}function Xp(t){let e=Vp(),n=[t,process.env.MEMO_SYSTEM_PROMPT_PATH,nt(e,"prompt.md"),nt(e,"../prompt.md"),nt(e,"../../prompt.md")].filter(r=>!!r).map(r=>en(r));for(let r of n)if(Ip(r))return r;return nt(e,"prompt.md")}async function Zs(t={}){let e=t.cwd??process.cwd(),n=Xp(t.promptPath),r=await Wr(n,"utf-8"),o=await Gp({homeDir:t.homeDir,memoHome:t.memoHome}),s=o?qp(o):"",i=Dp.test(r),c={date:new Date().toISOString(),user:Up(),pwd:e,soul_section:s},a=Fp(r,c);!i&&s&&(a=Kp(a,s));let l=await Wp(e);if(l&&(a=jp(a,l)),t.includeSkills!==!1){let u=await Xs({cwd:e,skillRoots:t.skillRoots,homeDir:t.homeDir,memoHome:t.memoHome}),p=Bp(u,t.activeSkillPaths),d=Ys(p);d&&(a=zp(a,d))}return a}import{appendFile as Yp,mkdir as Jp}from"fs/promises";import{dirname as Qp}from"path";var Rn=class{constructor(e){this.filePath=e}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=Jp(Qp(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 Yp(this.filePath,`${JSON.stringify(e)}
21
- `,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function ei(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{basename as oi}from"path";import{createHash as Zp}from"crypto";import{basename as MT,resolve as ed}from"path";function td(t){return t==="/"?t:t.replace(/\/+$/g,"")}function On(t){let n=ed(t.trim()).replace(/\\/g,"/");return n==="/"?n:td(n)}function ti(t){let e=On(t);return Zp("sha256").update(e).digest("hex").slice(0,16)}function ni(t,e){let n=On(t),r=On(e);return n===r?!0:n.startsWith(`${r}/`)}function jr(){return{prompt:0,completion:0,total:0}}function nd(){return{total:0,success:0,failed:0,denied:0,cancelled:0}}function fe(t){return typeof t!="string"?"":t.trim()}function zr(t){let e=fe(t);return e?e.replace(/<\s*(think|thinking)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi," ").replace(/<\s*\/?\s*(think|thinking)\b[^>]*>/gi," ").replace(/\s+/g," ").trim():""}function nn(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let e=Number.parseFloat(t);if(Number.isFinite(e))return e}return null}function yt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function rd(t,e){for(let s of e){let i=s.meta?.sessionId;if(typeof i=="string"&&i.trim())return i.trim()}let n=e.find(s=>{if(!s.meta)return!1;let i=s.meta.sessionId;return typeof i=="string"&&i.trim().length>0});if(n?.meta&&typeof n.meta.sessionId=="string")return n.meta.sessionId;let r=oi(t,".jsonl"),o=r.lastIndexOf("-");return o<=0||o>=r.length-1?r:r.slice(o+1)}function od(t,e){if(t){let r=t.replace(/\\/g,"/").split("/").filter(Boolean),o=r[r.length-1];if(o)return o}return oi(e,".jsonl")}function tn(t,e){let n=t.turnsById.get(e);if(n)return n;let r={turn:e,steps:[],byStep:new Map};return t.turnsById.set(e,r),r}function Gr(t,e){let n=t.byStep.get(e);if(n)return n;let r={step:e};return t.byStep.set(e,r),t.steps=Array.from(t.byStep.values()).sort((o,s)=>o.step-s.step),r}function sd(t,e){if(!t.trim())return null;let n;try{n=JSON.parse(t)}catch{return null}if(!yt(n))return null;let r=fe(n.ts),o=fe(n.type);if(!r||!o)return null;let s={index:e,ts:r,type:o},i=nn(n.turn),c=nn(n.step);i!==null&&(s.turn=Math.floor(i)),c!==null&&(s.step=Math.floor(c));let a=fe(n.role);return a&&(s.role=a),typeof n.content=="string"&&(s.content=n.content),yt(n.meta)&&(s.meta=n.meta),s}function In(t,e){if(!e)return;let n=nn(e.prompt),r=nn(e.completion),o=nn(e.total);n!==null&&(t.prompt+=Math.floor(n)),r!==null&&(t.completion+=Math.floor(r)),o!==null&&(t.total+=Math.floor(o))}function ri(t){if(!t)return"idle";let e=t.trim().toLowerCase();return e?e==="cancelled"?"cancelled":e==="error"||e==="prompt_limit"?"error":e==="running"?"running":"idle":"idle"}function id(t){if(!t)return[];let e=[],n=fe(t.tool);n&&e.push(n);let r=t.tools;if(Array.isArray(r))for(let s of r){let i=fe(s);i&&e.push(i)}let o=t.toolBlocks;if(Array.isArray(o))for(let s of o){if(!yt(s))continue;let i=fe(s.name);i&&e.push(i)}return Array.from(new Set(e))}function ad(t,e){if(!e)return;let n=e.trim().toLowerCase();if(n){if(n==="success"){t.toolUsage.success+=1;return}if(n==="approval_denied"){t.toolUsage.denied+=1,t.toolUsage.failed+=1,t.hasCancelled=!0;return}if(n==="cancelled"){t.toolUsage.cancelled+=1,t.hasCancelled=!0;return}t.toolUsage.failed+=1,t.hasError=!0}}function cd(t){let e=t.split(`
22
- `),n=[];for(let r=0;r<e.length;r+=1){let o=sd(e[r]??"",r);o&&n.push(o)}return n}function Ln(t,e){let n=cd(t),r=new Date().toISOString(),o={sessionId:"",title:"",project:"",cwd:"",startedAt:n[0]?.ts??r,updatedAt:n[n.length-1]?.ts??n[0]?.ts??r,status:"idle",turnCount:0,tokenUsage:jr(),toolUsage:nd(),turnsById:new Map,summaryParts:[],hasError:!1,hasCancelled:!1};for(let a of n){if(a.ts>o.updatedAt&&(o.updatedAt=a.ts),a.type==="session_start"&&a.meta){let l=fe(a.meta.cwd);l&&(o.cwd=l)}if(a.type==="session_title"){let l=zr(a.content);l&&(o.title=l)}if(a.type==="turn_start"){let l=a.turn??o.turnCount+1,u=tn(o,l);u.input=a.content,u.startedAt=a.ts,o.turnCount=Math.max(o.turnCount,l),a.content&&a.content.trim()&&(o.title||(o.title=zr(a.content)),o.summaryParts.push(`User: ${a.content.trim()}`))}if(a.type==="assistant"&&typeof a.turn=="number"){let l=tn(o,a.turn),u=Gr(l,a.step??l.steps.length),p=u.assistantText??"";u.assistantText=`${p}${a.content??""}`,a.content?.trim()&&o.summaryParts.push(`Assistant: ${a.content.trim()}`)}if(a.type==="action"&&typeof a.turn=="number"){let l=tn(o,a.turn),u=Gr(l,a.step??l.steps.length),p=id(a.meta);for(let g of p)o.toolUsage.total+=1;let d=fe(a.meta?.tool);d&&(u.action={tool:d,input:a.meta?.input});let f=fe(a.meta?.thinking);if(f&&(u.thinking=f),Array.isArray(a.meta?.toolBlocks)){let g=a.meta.toolBlocks.filter(yt).map(m=>{let _=fe(m.name);return _?{tool:_,input:m.input}:null}).filter(m=>!!m);g.length>1&&(u.parallelActions=g)}}if(a.type==="observation"&&typeof a.turn=="number"){let l=tn(o,a.turn),u=Gr(l,a.step??l.steps.length);u.observation=a.content;let p=fe(a.meta?.status);p&&(u.resultStatus=p),ad(o,p)}if(a.type==="final"&&typeof a.turn=="number"){let l=tn(o,a.turn);l.finalText=a.content;let u=fe(a.meta?.status);if(u){l.status=u;let d=ri(u);d==="error"&&(o.hasError=!0),d==="cancelled"&&(o.hasCancelled=!0)}let p=fe(a.meta?.errorMessage);if(p&&(l.errorMessage=p),yt(a.meta?.tokens)){let d=jr();In(d,a.meta.tokens),l.tokenUsage=d,In(o.tokenUsage,a.meta.tokens)}}if(a.type==="turn_end"){let l=fe(a.meta?.status);if(l){let u=ri(l);u==="error"&&(o.hasError=!0),u==="cancelled"&&(o.hasCancelled=!0)}yt(a.meta?.tokens)&&In(o.tokenUsage,a.meta.tokens)}a.type==="session_end"&&yt(a.meta?.tokens)&&(o.tokenUsage=jr(),In(o.tokenUsage,a.meta.tokens))}o.sessionId=rd(e,n),o.project=od(o.cwd,e),o.title=zr(o.title),o.title||(o.title=o.project||o.sessionId),o.hasError?o.status="error":o.hasCancelled?o.status="cancelled":o.status="idle";let s=o.startedAt.slice(0,10),i=Array.from(o.turnsById.values()).sort((a,l)=>a.turn-l.turn).map(a=>({turn:a.turn,input:a.input,startedAt:a.startedAt,finalText:a.finalText,status:a.status,errorMessage:a.errorMessage,tokenUsage:a.tokenUsage,steps:a.steps}));return{...{id:o.sessionId,sessionId:o.sessionId,filePath:e,title:o.title,project:o.project,workspaceId:o.cwd?ti(o.cwd):"",cwd:o.cwd,date:{day:/^\d{4}-\d{2}-\d{2}$/.test(s)?s:r.slice(0,10),startedAt:o.startedAt,updatedAt:o.updatedAt},status:o.status,turnCount:o.turnCount,tokenUsage:o.tokenUsage,toolUsage:o.toolUsage},summary:o.summaryParts.join(`
23
- `),turns:i,events:n}}import{readdir as ld,readFile as ud,stat as pd}from"fs/promises";import{join as dd,resolve as qr}from"path";function fd(t,e){if(typeof t!="number"||!Number.isFinite(t))return e;let n=Math.floor(t);return n>0?n:e}function si(t,e){if(typeof t!="number"||!Number.isFinite(t))return e;let n=Math.floor(t);return n<=0?e:Math.min(n,100)}function ii(t){if(!t)return null;let e=t.trim();return e&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:null}async function md(t){let e=[],n=async r=>{let o;try{o=await ld(r,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async s=>{if(s.isSymbolicLink())return;let i=dd(r,s.name);if(s.isDirectory()){await n(i);return}if(!(!s.isFile()||!s.name.endsWith(".jsonl")))try{let c=await pd(i);e.push({filePath:qr(i),mtimeMs:c.mtimeMs,size:c.size})}catch{}}))};return await n(qr(t)),e}function gd(t,e,n,r){let o=r==="asc"?1:-1;if(n==="project"){let s=t.project.localeCompare(e.project);return s===0?t.date.updatedAt.localeCompare(e.date.updatedAt)*o:s*o}if(n==="title"){let s=t.title.localeCompare(e.title);return s===0?t.date.updatedAt.localeCompare(e.date.updatedAt)*o:s*o}return n==="startedAt"?t.date.startedAt.localeCompare(e.date.startedAt)*o:t.date.updatedAt.localeCompare(e.date.updatedAt)*o}function hd(t,e){let n=t.project.trim(),r=t.cwd.trim(),o=/^\d{4}-\d{2}-\d{2}T\d{2}[-:]\d{2}[-:]\d{2}(?:\.\d+)?(?:Z)?-[A-Za-z0-9._-]+$/i.test(n)||/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)||n===t.sessionId;if(!n||!r||o||e.workspaceCwd&&!ni(r,e.workspaceCwd))return!1;if(e.project){let a=e.project.trim().toLowerCase();if(a&&n.toLowerCase()!==a)return!1}let s=ii(e.dateFrom),i=ii(e.dateTo);if(s&&t.date.day<s||i&&t.date.day>i)return!1;let c=e.q?.trim().toLowerCase();return!(c&&![t.title,n,r,t.sessionId,t.filePath].join(`
24
- `).toLowerCase().includes(c))}var Nn=class{sessionsDir;cache=new Map;sessionIdToPath=new Map;refreshInFlight=null;constructor(e){this.sessionsDir=qr(e.sessionsDir)}async refresh(){if(this.refreshInFlight){await this.refreshInFlight;return}let e=this.refreshInternal();this.refreshInFlight=e;try{await e}finally{this.refreshInFlight=null}}async list(e={}){await this.refresh();let n=fd(e.page,1),r=si(e.pageSize,20),o=e.sortBy??"updatedAt",s=e.order??"desc",i=Array.from(this.cache.values()).map(p=>p.summary).filter(p=>hd(p,e)).sort((p,d)=>gd(p,d,o,s)),c=i.length,a=c===0?0:Math.ceil(c/r),l=(n-1)*r;return{items:i.slice(l,l+r),page:n,pageSize:r,total:c,totalPages:a}}async getSessionDetail(e){await this.refresh();let n=this.sessionIdToPath.get(e);return n?this.cache.get(n)?.detail??null:null}async getSessionEvents(e,n,r){let o=await this.getSessionDetail(e);if(!o)return null;let s=Number.parseInt(n??"0",10),i=Number.isFinite(s)&&s>=0?s:0,c=si(r,100),a=o.events.slice(i,i+c),l=i+a.length;return{items:a,nextCursor:l>=o.events.length?null:String(l)}}async getAllSummaries(){return await this.refresh(),Array.from(this.cache.values()).map(e=>e.summary)}async refreshInternal(){let e=await md(this.sessionsDir),n=new Set(e.map(r=>r.filePath));for(let r of Array.from(this.cache.keys()))if(!n.has(r)){let o=this.cache.get(r);o&&this.sessionIdToPath.delete(o.summary.sessionId),this.cache.delete(r)}for(let r of e){let o=this.cache.get(r.filePath);if(!(o&&o.mtimeMs===r.mtimeMs&&o.size===r.size))try{let s=await ud(r.filePath,"utf8"),i=Ln(s,r.filePath),c=i,a={filePath:r.filePath,mtimeMs:r.mtimeMs,size:r.size,summary:c,detail:i};o&&this.sessionIdToPath.delete(o.summary.sessionId),this.cache.set(r.filePath,a),this.sessionIdToPath.set(c.sessionId,r.filePath)}catch{}}}};var wi=zs(gi(),1);import{existsSync as hi,statSync as Dd}from"fs";import{readFile as Fd,readdir as Ud}from"fs/promises";import{dirname as yi,join as Bn,relative as Si,resolve as Hd,sep as Bd}from"path";var Wd=6,jd=2500,_i=25,zd=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),Un=new Map,Zr=new Map,At=new Map,Gd=256;function Hn(t,e){if(At.size>=Gd&&!At.has(t)){let n=At.keys().next().value;typeof n=="string"&&At.delete(n)}At.set(t,e)}function vi(t){return t.split(Bd).join("/")}function qd(t){return{maxDepth:typeof t.maxDepth=="number"?Math.max(1,t.maxDepth):Wd,maxEntries:typeof t.maxEntries=="number"?Math.max(100,t.maxEntries):jd,limit:typeof t.limit=="number"?Math.max(1,t.limit):_i,respectGitIgnore:t.respectGitIgnore??!0,ignoreGlobs:t.ignoreGlobs?.length?t.ignoreGlobs:[]}}function Kd(t,e){let n=t.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>zd.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 Vd(t){return t.replace(/\\/g,"/")}function Xd(t){let e=Hd(t),n=At.get(e);if(n)return n;let r=e;try{Dd(r).isFile()&&(r=yi(r))}catch{r=process.cwd()}let o=r,s=[];for(;;){if(s.push(r),hi(Bn(r,".gitignore"))||hi(Bn(r,".git"))){for(let c of s)Hn(c,r);return Hn(e,r),r}let i=yi(r);if(i===r){for(let c of s)Hn(c,o);return Hn(e,o),o}r=i}}async function Yd(t){let e=Bn(t,".gitignore");try{return(await Fd(e,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#"))}catch{return[]}}function Jd(t){let e=(0,wi.default)();return t.length>0&&e.add(t),e}async function Qd(t){let e=Jd(await Yd(t));return{root:t,ignores:n=>{let r=Si(t,n);return!r||r.startsWith("..")?!1:e.ignores(Vd(r))}}}async function Zd(t){let e=Xd(t),n=Zr.get(e);if(n)return n;let r=Qd(e).catch(o=>{throw Zr.delete(e),o});return Zr.set(e,r),r}function ef(t){return JSON.stringify({maxDepth:t.maxDepth,maxEntries:t.maxEntries,respectGitIgnore:t.respectGitIgnore,ignoreGlobs:t.ignoreGlobs})}async function tf(t,e){let n=[],r=e.respectGitIgnore?await Zd(t):null,o=async(s,i)=>{if(n.length>=e.maxEntries)return;let c;try{c=await Ud(s,{withFileTypes:!0})}catch{return}for(let a of c){if(n.length>=e.maxEntries)break;if(a.isSymbolicLink())continue;let l=Bn(s,a.name);if(r?.ignores(l))continue;let u=Si(t,l);if(!u)continue;let p=vi(u);if(Kd(p,e))continue;let d=p.split("/").filter(Boolean),f=a.isDirectory();n.push({path:p,pathLower:p.toLowerCase(),segments:d,segmentsLower:d.map(g=>g.toLowerCase()),depth:i,isDir:f}),f&&i<e.maxDepth&&await o(l,i+1)}};return await o(t,0),n.sort((s,i)=>s.path.localeCompare(i.path)),n}async function nf(t,e){let n=qd(e),r=ef(n),o=Un.get(t);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=tf(t,n).then(i=>(Un.set(t,{entries:i,signature:r}),i)).catch(i=>{throw Un.delete(t),i});return Un.set(t,{entries:[],signature:r,pending:s}),s}function rf(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 c=t.segmentsLower[i];if(c.startsWith(o)){s=i,n+=(i-r)*1.2,n+=c.length-o.length;break}let a=c.indexOf(o);if(a!==-1){s=i,n+=(i-r)*2+a+2;break}}if(s===-1)return null;r=s+1}return t.isDir&&(n-=.5),n}function of(t,e,n){let o=e.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of t){let c=rf(i,o);c!==null&&s.push({entry:i,score:c})}return s.sort((i,c)=>{let a=i.score-c.score;return a!==0?a:i.entry.path.localeCompare(c.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 Ti(t){let e=await nf(t.cwd,t),n=typeof t.limit=="number"?Math.max(1,t.limit):_i;return of(e,t.query,n)}var z={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",COMPACT:"compact",MCP:"mcp",INIT:"init"},me={NONE:"none",ONCE:"once",FULL:"full"};function on(t){return`/${t}`}var sn=[{name:z.HELP,description:"Show command and shortcut help"},{name:z.EXIT,description:"Exit current session"},{name:z.NEW,description:"Start a fresh session"},{name:z.RESUME,description:"List and load session history"},{name:z.REVIEW,description:"Review a GitHub pull request and post comments"},{name:z.MODELS,description:"List or switch configured models"},{name:z.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:z.COMPACT,description:"Compact conversation context now"},{name:z.MCP,description:"Show configured MCP servers"},{name:z.INIT,description:"Generate AGENTS.md with agent instructions"}],sf={none:me.NONE,off:me.NONE,disabled:me.NONE,"no-tools":me.NONE,once:me.ONCE,ask:me.ONCE,single:me.ONCE,strict:me.ONCE,full:me.FULL,all:me.FULL,dangerous:me.FULL,"full-access":me.FULL};function af(t){if(!t)return null;let e=t.trim().toLowerCase();return e?sf[e]??null:null}function Ci(t){return t===me.NONE?"none (no tools)":t===me.ONCE?"once (approval required)":"full (no approval)"}function bi(){let t=sn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...sn.map(n=>` ${on(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(`
25
- `)}function cf(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 eo(t,e){let[n,...r]=t.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case z.HELP:return{kind:"message",title:"Help",content:bi()};case z.EXIT:return{kind:"exit"};case z.NEW:return{kind:"new"};case z.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case z.REVIEW:{let s=r.join(" ").trim(),i=cf(s);return i?{kind:"review_pr",prNumber:i}:{kind:"message",title:"Review",content:`Usage: ${on(z.REVIEW)} <prNumber>
20
+ ${e}`}function Kp(){return typeof __dirname=="string"?__dirname:Ip(Lp(import.meta.url))}function Vp(t){let e=Kp(),n=[t,process.env.MEMO_SYSTEM_PROMPT_PATH,nt(e,"prompt.md"),nt(e,"../prompt.md"),nt(e,"../../prompt.md")].filter(r=>!!r).map(r=>en(r));for(let r of n)if(Op(r))return r;return nt(e,"prompt.md")}async function Zs(t={}){let e=t.cwd??process.cwd(),n=Vp(t.promptPath),r=await Wr(n,"utf-8"),o=await zp({homeDir:t.homeDir,memoHome:t.memoHome}),s=o?Gp(o):"",i=$p.test(r),c={date:new Date().toISOString(),user:Fp(),pwd:e,soul_section:s},a=Dp(r,c);!i&&s&&(a=qp(a,s));let l=await Bp(e);if(l&&(a=Wp(a,l)),t.includeSkills!==!1){let u=await Xs({cwd:e,skillRoots:t.skillRoots,homeDir:t.homeDir,memoHome:t.memoHome}),p=Hp(u,t.activeSkillPaths),d=Ys(p);d&&(a=jp(a,d))}return a}import{appendFile as Xp,mkdir as Yp}from"fs/promises";import{dirname as Jp}from"path";var Rn=class{constructor(e){this.filePath=e}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=Yp(Jp(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 Xp(this.filePath,`${JSON.stringify(e)}
21
+ `,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function ei(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{basename as oi}from"path";import{createHash as Qp}from"crypto";import{basename as MT,resolve as Zp}from"path";function ed(t){return t==="/"?t:t.replace(/\/+$/g,"")}function On(t){let n=Zp(t.trim()).replace(/\\/g,"/");return n==="/"?n:ed(n)}function ti(t){let e=On(t);return Qp("sha256").update(e).digest("hex").slice(0,16)}function ni(t,e){let n=On(t),r=On(e);return n===r?!0:n.startsWith(`${r}/`)}function jr(){return{prompt:0,completion:0,total:0}}function td(){return{total:0,success:0,failed:0,denied:0,cancelled:0}}function fe(t){return typeof t!="string"?"":t.trim()}function zr(t){let e=fe(t);return e?e.replace(/<\s*(think|thinking)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi," ").replace(/<\s*\/?\s*(think|thinking)\b[^>]*>/gi," ").replace(/\s+/g," ").trim():""}function nn(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let e=Number.parseFloat(t);if(Number.isFinite(e))return e}return null}function yt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function nd(t,e){for(let s of e){let i=s.meta?.sessionId;if(typeof i=="string"&&i.trim())return i.trim()}let n=e.find(s=>{if(!s.meta)return!1;let i=s.meta.sessionId;return typeof i=="string"&&i.trim().length>0});if(n?.meta&&typeof n.meta.sessionId=="string")return n.meta.sessionId;let r=oi(t,".jsonl"),o=r.lastIndexOf("-");return o<=0||o>=r.length-1?r:r.slice(o+1)}function rd(t,e){if(t){let r=t.replace(/\\/g,"/").split("/").filter(Boolean),o=r[r.length-1];if(o)return o}return oi(e,".jsonl")}function tn(t,e){let n=t.turnsById.get(e);if(n)return n;let r={turn:e,steps:[],byStep:new Map};return t.turnsById.set(e,r),r}function Gr(t,e){let n=t.byStep.get(e);if(n)return n;let r={step:e};return t.byStep.set(e,r),t.steps=Array.from(t.byStep.values()).sort((o,s)=>o.step-s.step),r}function od(t,e){if(!t.trim())return null;let n;try{n=JSON.parse(t)}catch{return null}if(!yt(n))return null;let r=fe(n.ts),o=fe(n.type);if(!r||!o)return null;let s={index:e,ts:r,type:o},i=nn(n.turn),c=nn(n.step);i!==null&&(s.turn=Math.floor(i)),c!==null&&(s.step=Math.floor(c));let a=fe(n.role);return a&&(s.role=a),typeof n.content=="string"&&(s.content=n.content),yt(n.meta)&&(s.meta=n.meta),s}function In(t,e){if(!e)return;let n=nn(e.prompt),r=nn(e.completion),o=nn(e.total);n!==null&&(t.prompt+=Math.floor(n)),r!==null&&(t.completion+=Math.floor(r)),o!==null&&(t.total+=Math.floor(o))}function ri(t){if(!t)return"idle";let e=t.trim().toLowerCase();return e?e==="cancelled"?"cancelled":e==="error"||e==="prompt_limit"?"error":e==="running"?"running":"idle":"idle"}function sd(t){if(!t)return[];let e=[],n=fe(t.tool);n&&e.push(n);let r=t.tools;if(Array.isArray(r))for(let s of r){let i=fe(s);i&&e.push(i)}let o=t.toolBlocks;if(Array.isArray(o))for(let s of o){if(!yt(s))continue;let i=fe(s.name);i&&e.push(i)}return Array.from(new Set(e))}function id(t,e){if(!e)return;let n=e.trim().toLowerCase();if(n){if(n==="success"){t.toolUsage.success+=1;return}if(n==="approval_denied"){t.toolUsage.denied+=1,t.toolUsage.failed+=1,t.hasCancelled=!0;return}if(n==="cancelled"){t.toolUsage.cancelled+=1,t.hasCancelled=!0;return}t.toolUsage.failed+=1,t.hasError=!0}}function ad(t){let e=t.split(`
22
+ `),n=[];for(let r=0;r<e.length;r+=1){let o=od(e[r]??"",r);o&&n.push(o)}return n}function Ln(t,e){let n=ad(t),r=new Date().toISOString(),o={sessionId:"",title:"",project:"",cwd:"",startedAt:n[0]?.ts??r,updatedAt:n[n.length-1]?.ts??n[0]?.ts??r,status:"idle",turnCount:0,tokenUsage:jr(),toolUsage:td(),turnsById:new Map,summaryParts:[],hasError:!1,hasCancelled:!1};for(let a of n){if(a.ts>o.updatedAt&&(o.updatedAt=a.ts),a.type==="session_start"&&a.meta){let l=fe(a.meta.cwd);l&&(o.cwd=l)}if(a.type==="session_title"){let l=zr(a.content);l&&(o.title=l)}if(a.type==="turn_start"){let l=a.turn??o.turnCount+1,u=tn(o,l);u.input=a.content,u.startedAt=a.ts,o.turnCount=Math.max(o.turnCount,l),a.content&&a.content.trim()&&(o.title||(o.title=zr(a.content)),o.summaryParts.push(`User: ${a.content.trim()}`))}if(a.type==="assistant"&&typeof a.turn=="number"){let l=tn(o,a.turn),u=Gr(l,a.step??l.steps.length),p=u.assistantText??"";u.assistantText=`${p}${a.content??""}`,a.content?.trim()&&o.summaryParts.push(`Assistant: ${a.content.trim()}`)}if(a.type==="action"&&typeof a.turn=="number"){let l=tn(o,a.turn),u=Gr(l,a.step??l.steps.length),p=sd(a.meta);for(let g of p)o.toolUsage.total+=1;let d=fe(a.meta?.tool);d&&(u.action={tool:d,input:a.meta?.input});let f=fe(a.meta?.thinking);if(f&&(u.thinking=f),Array.isArray(a.meta?.toolBlocks)){let g=a.meta.toolBlocks.filter(yt).map(m=>{let _=fe(m.name);return _?{tool:_,input:m.input}:null}).filter(m=>!!m);g.length>1&&(u.parallelActions=g)}}if(a.type==="observation"&&typeof a.turn=="number"){let l=tn(o,a.turn),u=Gr(l,a.step??l.steps.length);u.observation=a.content;let p=fe(a.meta?.status);p&&(u.resultStatus=p),id(o,p)}if(a.type==="final"&&typeof a.turn=="number"){let l=tn(o,a.turn);l.finalText=a.content;let u=fe(a.meta?.status);if(u){l.status=u;let d=ri(u);d==="error"&&(o.hasError=!0),d==="cancelled"&&(o.hasCancelled=!0)}let p=fe(a.meta?.errorMessage);if(p&&(l.errorMessage=p),yt(a.meta?.tokens)){let d=jr();In(d,a.meta.tokens),l.tokenUsage=d,In(o.tokenUsage,a.meta.tokens)}}if(a.type==="turn_end"){let l=fe(a.meta?.status);if(l){let u=ri(l);u==="error"&&(o.hasError=!0),u==="cancelled"&&(o.hasCancelled=!0)}yt(a.meta?.tokens)&&In(o.tokenUsage,a.meta.tokens)}a.type==="session_end"&&yt(a.meta?.tokens)&&(o.tokenUsage=jr(),In(o.tokenUsage,a.meta.tokens))}o.sessionId=nd(e,n),o.project=rd(o.cwd,e),o.title=zr(o.title),o.title||(o.title=o.project||o.sessionId),o.hasError?o.status="error":o.hasCancelled?o.status="cancelled":o.status="idle";let s=o.startedAt.slice(0,10),i=Array.from(o.turnsById.values()).sort((a,l)=>a.turn-l.turn).map(a=>({turn:a.turn,input:a.input,startedAt:a.startedAt,finalText:a.finalText,status:a.status,errorMessage:a.errorMessage,tokenUsage:a.tokenUsage,steps:a.steps}));return{...{id:o.sessionId,sessionId:o.sessionId,filePath:e,title:o.title,project:o.project,workspaceId:o.cwd?ti(o.cwd):"",cwd:o.cwd,date:{day:/^\d{4}-\d{2}-\d{2}$/.test(s)?s:r.slice(0,10),startedAt:o.startedAt,updatedAt:o.updatedAt},status:o.status,turnCount:o.turnCount,tokenUsage:o.tokenUsage,toolUsage:o.toolUsage},summary:o.summaryParts.join(`
23
+ `),turns:i,events:n}}import{readdir as cd,readFile as ld,stat as ud}from"fs/promises";import{join as pd,resolve as qr}from"path";function dd(t,e){if(typeof t!="number"||!Number.isFinite(t))return e;let n=Math.floor(t);return n>0?n:e}function si(t,e){if(typeof t!="number"||!Number.isFinite(t))return e;let n=Math.floor(t);return n<=0?e:Math.min(n,100)}function ii(t){if(!t)return null;let e=t.trim();return e&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:null}async function fd(t){let e=[],n=async r=>{let o;try{o=await cd(r,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async s=>{if(s.isSymbolicLink())return;let i=pd(r,s.name);if(s.isDirectory()){await n(i);return}if(!(!s.isFile()||!s.name.endsWith(".jsonl")))try{let c=await ud(i);e.push({filePath:qr(i),mtimeMs:c.mtimeMs,size:c.size})}catch{}}))};return await n(qr(t)),e}function md(t,e,n,r){let o=r==="asc"?1:-1;if(n==="project"){let s=t.project.localeCompare(e.project);return s===0?t.date.updatedAt.localeCompare(e.date.updatedAt)*o:s*o}if(n==="title"){let s=t.title.localeCompare(e.title);return s===0?t.date.updatedAt.localeCompare(e.date.updatedAt)*o:s*o}return n==="startedAt"?t.date.startedAt.localeCompare(e.date.startedAt)*o:t.date.updatedAt.localeCompare(e.date.updatedAt)*o}function gd(t,e){let n=t.project.trim(),r=t.cwd.trim(),o=/^\d{4}-\d{2}-\d{2}T\d{2}[-:]\d{2}[-:]\d{2}(?:\.\d+)?(?:Z)?-[A-Za-z0-9._-]+$/i.test(n)||/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)||n===t.sessionId;if(!n||!r||o||e.workspaceCwd&&!ni(r,e.workspaceCwd))return!1;if(e.project){let a=e.project.trim().toLowerCase();if(a&&n.toLowerCase()!==a)return!1}let s=ii(e.dateFrom),i=ii(e.dateTo);if(s&&t.date.day<s||i&&t.date.day>i)return!1;let c=e.q?.trim().toLowerCase();return!(c&&![t.title,n,r,t.sessionId,t.filePath].join(`
24
+ `).toLowerCase().includes(c))}var Nn=class{sessionsDir;cache=new Map;sessionIdToPath=new Map;refreshInFlight=null;constructor(e){this.sessionsDir=qr(e.sessionsDir)}async refresh(){if(this.refreshInFlight){await this.refreshInFlight;return}let e=this.refreshInternal();this.refreshInFlight=e;try{await e}finally{this.refreshInFlight=null}}async list(e={}){await this.refresh();let n=dd(e.page,1),r=si(e.pageSize,20),o=e.sortBy??"updatedAt",s=e.order??"desc",i=Array.from(this.cache.values()).map(p=>p.summary).filter(p=>gd(p,e)).sort((p,d)=>md(p,d,o,s)),c=i.length,a=c===0?0:Math.ceil(c/r),l=(n-1)*r;return{items:i.slice(l,l+r),page:n,pageSize:r,total:c,totalPages:a}}async getSessionDetail(e){await this.refresh();let n=this.sessionIdToPath.get(e);return n?this.cache.get(n)?.detail??null:null}async getSessionEvents(e,n,r){let o=await this.getSessionDetail(e);if(!o)return null;let s=Number.parseInt(n??"0",10),i=Number.isFinite(s)&&s>=0?s:0,c=si(r,100),a=o.events.slice(i,i+c),l=i+a.length;return{items:a,nextCursor:l>=o.events.length?null:String(l)}}async getAllSummaries(){return await this.refresh(),Array.from(this.cache.values()).map(e=>e.summary)}async refreshInternal(){let e=await fd(this.sessionsDir),n=new Set(e.map(r=>r.filePath));for(let r of Array.from(this.cache.keys()))if(!n.has(r)){let o=this.cache.get(r);o&&this.sessionIdToPath.delete(o.summary.sessionId),this.cache.delete(r)}for(let r of e){let o=this.cache.get(r.filePath);if(!(o&&o.mtimeMs===r.mtimeMs&&o.size===r.size))try{let s=await ld(r.filePath,"utf8"),i=Ln(s,r.filePath),c=i,a={filePath:r.filePath,mtimeMs:r.mtimeMs,size:r.size,summary:c,detail:i};o&&this.sessionIdToPath.delete(o.summary.sessionId),this.cache.set(r.filePath,a),this.sessionIdToPath.set(c.sessionId,r.filePath)}catch{}}}};var wi=zs(gi(),1);import{existsSync as hi,statSync as $d}from"fs";import{readFile as Dd,readdir as Fd}from"fs/promises";import{dirname as yi,join as Bn,relative as Si,resolve as Ud,sep as Hd}from"path";var Bd=6,Wd=2500,_i=25,jd=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),Un=new Map,Zr=new Map,At=new Map,zd=256;function Hn(t,e){if(At.size>=zd&&!At.has(t)){let n=At.keys().next().value;typeof n=="string"&&At.delete(n)}At.set(t,e)}function vi(t){return t.split(Hd).join("/")}function Gd(t){return{maxDepth:typeof t.maxDepth=="number"?Math.max(1,t.maxDepth):Bd,maxEntries:typeof t.maxEntries=="number"?Math.max(100,t.maxEntries):Wd,limit:typeof t.limit=="number"?Math.max(1,t.limit):_i,respectGitIgnore:t.respectGitIgnore??!0,ignoreGlobs:t.ignoreGlobs?.length?t.ignoreGlobs:[]}}function qd(t,e){let n=t.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>jd.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 Kd(t){return t.replace(/\\/g,"/")}function Vd(t){let e=Ud(t),n=At.get(e);if(n)return n;let r=e;try{$d(r).isFile()&&(r=yi(r))}catch{r=process.cwd()}let o=r,s=[];for(;;){if(s.push(r),hi(Bn(r,".gitignore"))||hi(Bn(r,".git"))){for(let c of s)Hn(c,r);return Hn(e,r),r}let i=yi(r);if(i===r){for(let c of s)Hn(c,o);return Hn(e,o),o}r=i}}async function Xd(t){let e=Bn(t,".gitignore");try{return(await Dd(e,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#"))}catch{return[]}}function Yd(t){let e=(0,wi.default)();return t.length>0&&e.add(t),e}async function Jd(t){let e=Yd(await Xd(t));return{root:t,ignores:n=>{let r=Si(t,n);return!r||r.startsWith("..")?!1:e.ignores(Kd(r))}}}async function Qd(t){let e=Vd(t),n=Zr.get(e);if(n)return n;let r=Jd(e).catch(o=>{throw Zr.delete(e),o});return Zr.set(e,r),r}function Zd(t){return JSON.stringify({maxDepth:t.maxDepth,maxEntries:t.maxEntries,respectGitIgnore:t.respectGitIgnore,ignoreGlobs:t.ignoreGlobs})}async function ef(t,e){let n=[],r=e.respectGitIgnore?await Qd(t):null,o=async(s,i)=>{if(n.length>=e.maxEntries)return;let c;try{c=await Fd(s,{withFileTypes:!0})}catch{return}for(let a of c){if(n.length>=e.maxEntries)break;if(a.isSymbolicLink())continue;let l=Bn(s,a.name);if(r?.ignores(l))continue;let u=Si(t,l);if(!u)continue;let p=vi(u);if(qd(p,e))continue;let d=p.split("/").filter(Boolean),f=a.isDirectory();n.push({path:p,pathLower:p.toLowerCase(),segments:d,segmentsLower:d.map(g=>g.toLowerCase()),depth:i,isDir:f}),f&&i<e.maxDepth&&await o(l,i+1)}};return await o(t,0),n.sort((s,i)=>s.path.localeCompare(i.path)),n}async function tf(t,e){let n=Gd(e),r=Zd(n),o=Un.get(t);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=ef(t,n).then(i=>(Un.set(t,{entries:i,signature:r}),i)).catch(i=>{throw Un.delete(t),i});return Un.set(t,{entries:[],signature:r,pending:s}),s}function nf(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 c=t.segmentsLower[i];if(c.startsWith(o)){s=i,n+=(i-r)*1.2,n+=c.length-o.length;break}let a=c.indexOf(o);if(a!==-1){s=i,n+=(i-r)*2+a+2;break}}if(s===-1)return null;r=s+1}return t.isDir&&(n-=.5),n}function rf(t,e,n){let o=e.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of t){let c=nf(i,o);c!==null&&s.push({entry:i,score:c})}return s.sort((i,c)=>{let a=i.score-c.score;return a!==0?a:i.entry.path.localeCompare(c.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 Ti(t){let e=await tf(t.cwd,t),n=typeof t.limit=="number"?Math.max(1,t.limit):_i;return rf(e,t.query,n)}var z={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",COMPACT:"compact",MCP:"mcp",INIT:"init"},me={NONE:"none",ONCE:"once",FULL:"full"};function on(t){return`/${t}`}var sn=[{name:z.HELP,description:"Show command and shortcut help"},{name:z.EXIT,description:"Exit current session"},{name:z.NEW,description:"Start a fresh session"},{name:z.RESUME,description:"List and load session history"},{name:z.REVIEW,description:"Review a GitHub pull request and post comments"},{name:z.MODELS,description:"List or switch configured models"},{name:z.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:z.COMPACT,description:"Compact conversation context now"},{name:z.MCP,description:"Show configured MCP servers"},{name:z.INIT,description:"Generate AGENTS.md with agent instructions"}],of={none:me.NONE,off:me.NONE,disabled:me.NONE,"no-tools":me.NONE,once:me.ONCE,ask:me.ONCE,single:me.ONCE,strict:me.ONCE,full:me.FULL,all:me.FULL,dangerous:me.FULL,"full-access":me.FULL};function sf(t){if(!t)return null;let e=t.trim().toLowerCase();return e?of[e]??null:null}function Ci(t){return t===me.NONE?"none (no tools)":t===me.ONCE?"once (approval required)":"full (no approval)"}function bi(){let t=sn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...sn.map(n=>` ${on(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(`
25
+ `)}function af(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 eo(t,e){let[n,...r]=t.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case z.HELP:return{kind:"message",title:"Help",content:bi()};case z.EXIT:return{kind:"exit"};case z.NEW:return{kind:"new"};case z.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case z.REVIEW:{let s=r.join(" ").trim(),i=af(s);return i?{kind:"review_pr",prNumber:i}:{kind:"message",title:"Review",content:`Usage: ${on(z.REVIEW)} <prNumber>
26
26
  Examples: /review 999, /review #999`}}case z.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(l=>l.name===s)??e.providers.find(l=>l.model===s);if(i)return{kind:"switch_model",provider:i};let c=e.providers.map(l=>{let u=l.name===e.providerName&&l.model===e.model?" (current)":"",p=l.base_url?` @ ${l.base_url}`:"";return`- ${l.name}: ${l.model}${p}${u}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
27
27
 
28
28
  `:""}${c.join(`
29
- `)}`}}case z.TOOLS:{let s=r.join(" ").trim(),i=af(s),c=["none","once","full"].join(", ");return s?i?i===e.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${Ci(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
29
+ `)}`}}case z.TOOLS:{let s=r.join(" ").trim(),i=sf(s),c=["none","once","full"].join(", ");return s?i?i===e.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${Ci(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
30
30
  Choose one of: ${c}`}:{kind:"message",title:"Tools",content:`Current: ${Ci(e.toolPermissionMode)}
31
31
  Usage: ${on(z.TOOLS)} <mode>
32
32
  Modes: ${c}`}}case z.COMPACT:return{kind:"compact"};case z.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[c,a]of Object.entries(e.mcpServers))i.push(`- ${c}`),"url"in a?(i.push(` type: ${a.type??"streamable_http"}`),i.push(` url: ${a.url}`),a.bearer_token_env_var&&i.push(` bearer: ${a.bearer_token_env_var}`)):(i.push(` type: ${a.type??"stdio"}`),i.push(` command: ${a.command}`),a.args?.length&&i.push(` args: ${a.args.join(" ")}`)),i.push("");return{kind:"message",title:"MCP Servers",content:i.join(`
33
33
  `)}}case z.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${t}
34
- Type ${on(z.HELP)} for available commands.`}}}import{mkdir as lf,writeFile as uf,readFile as pf,access as df}from"fs/promises";import{homedir as Ei}from"os";import{dirname as ff,join as St,parse as mf,resolve as gf}from"path";import{randomUUID as JT}from"crypto";import{parse as hf}from"toml";var yf=St(Ei(),".memo"),Sf="sessions",xi=12e4,Pi=80,an={current_provider:"deepseek",mcp_oauth_credentials_store_mode:"auto",auto_compact_threshold_percent:Pi,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function Ai(t){return typeof t=="number"&&Number.isInteger(t)&&Number.isFinite(t)&&t>=1&&t<=100?t:Pi}function to(t){return t.trim().toLowerCase()}function Mi(t){if(typeof t?.context_window=="number"&&Number.isFinite(t.context_window)&&t.context_window>0)return Math.floor(t.context_window)}function Rt(t,e){let n=t.model_profiles;if(!n)return xi;let r=new Map;for(let[c,a]of Object.entries(n))r.set(to(c),a);let o=to(e.name),s=to(e.model),i=`${o}:${s}`;return Mi(r.get(i))??Mi(r.get(s))??xi}function ki(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function wf(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 _f(t){if(!Array.isArray(t))return;let e=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return Array.from(new Set(e))}function vf(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 Ri(t){return t.startsWith("~")?St(Ei(),t.slice(1)):t}function Tf(t){let e=t.providers.map(c=>{let a=typeof c?.name=="string"?c.name:"";if(!a)return"";let u=[`[[providers.${ki(a)}]]`,`name = ${JSON.stringify(a)}`,`env_api_key = ${JSON.stringify(String(c.env_api_key??""))}`,`model = ${JSON.stringify(String(c.model??""))}`];return c.base_url&&u.push(`base_url = ${JSON.stringify(String(c.base_url))}`),u.join(`
34
+ Type ${on(z.HELP)} for available commands.`}}}import{mkdir as cf,writeFile as lf,readFile as uf,access as pf}from"fs/promises";import{homedir as Ei}from"os";import{dirname as df,join as St,parse as ff,resolve as mf}from"path";import{randomUUID as JT}from"crypto";import{parse as gf}from"toml";var hf=St(Ei(),".memo"),yf="sessions",xi=12e4,Pi=80,an={current_provider:"deepseek",mcp_oauth_credentials_store_mode:"auto",auto_compact_threshold_percent:Pi,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function Ai(t){return typeof t=="number"&&Number.isInteger(t)&&Number.isFinite(t)&&t>=1&&t<=100?t:Pi}function to(t){return t.trim().toLowerCase()}function Mi(t){if(typeof t?.context_window=="number"&&Number.isFinite(t.context_window)&&t.context_window>0)return Math.floor(t.context_window)}function Rt(t,e){let n=t.model_profiles;if(!n)return xi;let r=new Map;for(let[c,a]of Object.entries(n))r.set(to(c),a);let o=to(e.name),s=to(e.model),i=`${o}:${s}`;return Mi(r.get(i))??Mi(r.get(s))??xi}function ki(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function Sf(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 wf(t){if(!Array.isArray(t))return;let e=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return Array.from(new Set(e))}function _f(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 Ri(t){return t.startsWith("~")?St(Ei(),t.slice(1)):t}function vf(t){let e=t.providers.map(c=>{let a=typeof c?.name=="string"?c.name:"";if(!a)return"";let u=[`[[providers.${ki(a)}]]`,`name = ${JSON.stringify(a)}`,`env_api_key = ${JSON.stringify(String(c.env_api_key??""))}`,`model = ${JSON.stringify(String(c.model??""))}`];return c.base_url&&u.push(`base_url = ${JSON.stringify(String(c.base_url))}`),u.join(`
35
35
  `)}).filter(Boolean).join(`
36
36
 
37
37
  `),n=t.model_profiles?Object.entries(t.model_profiles).map(([c,a])=>{let l=[],u=ki(c);return l.push(`[model_profiles.${u}]`),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(`
@@ -51,13 +51,13 @@ ${g}`}).join(`
51
51
  `));let o=[`current_provider = "${t.current_provider}"`];Array.isArray(t.active_mcp_servers)&&o.push(`active_mcp_servers = ${JSON.stringify(t.active_mcp_servers)}`),Array.isArray(t.active_skills)&&o.push(`active_skills = ${JSON.stringify(t.active_skills)}`);let s=t.mcp_oauth_credentials_store_mode;return(s==="auto"||s==="keyring"||s==="file")&&o.push(`mcp_oauth_credentials_store_mode = ${JSON.stringify(s)}`),typeof t.mcp_oauth_callback_port=="number"&&Number.isInteger(t.mcp_oauth_callback_port)&&t.mcp_oauth_callback_port>0&&t.mcp_oauth_callback_port<=65535&&o.push(`mcp_oauth_callback_port = ${t.mcp_oauth_callback_port}`),o.push(`auto_compact_threshold_percent = ${Ai(t.auto_compact_threshold_percent)}`),[o.join(`
52
52
  `),e,n,r].filter(Boolean).join(`
53
53
 
54
- `)}async function Me(t,e){await lf(ff(t),{recursive:!0}),await uf(t,Tf(e),"utf-8")}async function re(){let t=process.env.MEMO_HOME?Ri(process.env.MEMO_HOME):yf,e=St(t,"config.toml");try{await df(e);let n=await pf(e,"utf-8"),r=hf(n),o=wf(r.providers),s=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(f=>typeof f=="string"&&f.trim().length>0):void 0,i=_f(r.active_skills),c=r.mcp_oauth_credentials_store_mode==="auto"||r.mcp_oauth_credentials_store_mode==="keyring"||r.mcp_oauth_credentials_store_mode==="file"?r.mcp_oauth_credentials_store_mode:an.mcp_oauth_credentials_store_mode,a=typeof r.mcp_oauth_callback_port=="number"&&Number.isInteger(r.mcp_oauth_callback_port)&&r.mcp_oauth_callback_port>0&&r.mcp_oauth_callback_port<=65535?r.mcp_oauth_callback_port:void 0,l=Ai(r.auto_compact_threshold_percent),u=vf(r.model_profiles),p={current_provider:r.current_provider??an.current_provider,mcp_oauth_credentials_store_mode:c,mcp_oauth_callback_port:a,auto_compact_threshold_percent:l,providers:o,model_profiles:u,mcp_servers:r.mcp_servers??{},active_mcp_servers:s,active_skills:i},d=!p.providers.length;return{config:d?an:p,home:t,configPath:e,needsSetup:d}}catch{return{config:an,home:t,configPath:e,needsSetup:!0}}}function wt(t,e){let n=e||t.current_provider,r=t.providers.find(o=>o.name===n);return r||(t.providers?.[0]??an.providers[0])}function cn(t,e){let n=e.historyDir??St(t.home,Sf),r=Ri(n),o=gf(e.cwd??process.cwd()),s=mf(o).root,c=o.slice(s.length).split(/[\\/]+/).filter(Boolean);if(process.platform==="win32"){let l=/^([A-Za-z]):/.exec(s)?.[1];l&&c.unshift(l.toUpperCase())}if(c.length===0)return St(r,"-root");let a=`-${c.map(l=>l.replace(/[^A-Za-z0-9._-]/g,"_")).join("-")}`;return St(r,a)}function Oi(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"),c=String(n.getMinutes()).padStart(2,"0"),a=String(n.getSeconds()).padStart(2,"0"),l=`${r}-${o}-${s}T${i}-${c}-${a}`,u=e.replace(/[^A-Za-z0-9._-]/g,"_"),p=`${l}-${u}.jsonl`;return St(t,p)}import{createHash as Cf}from"crypto";import{spawn as bf}from"child_process";import{createServer as xf}from"http";import{mkdir as Mf,readFile as kf,rename as Ef,writeFile as Pf}from"fs/promises";import{homedir as oo}from"os";import{dirname as Af,join as ao}from"path";import{auth as Ii}from"@modelcontextprotocol/sdk/client/auth.js";var so=1,Rf="mcp-oauth.json",Of=3e5,If=5e3,Li="MCP-Protocol-Version",Lf="2024-11-05",co="memo-code.mcp.oauth",Nf=33333;function $f(t){return{client_name:"Memo Code CLI",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function Ni(t){return t instanceof Error?t.message:String(t)}function lo(t){return new URL(t).toString()}function uo(t){return t==="file"||t==="keyring"||t==="auto"?t:"auto"}function $i(t){return t==="~"?oo():t.startsWith("~/")?ao(oo(),t.slice(2)):t}function Df(t){return t?.memoHome?.trim()?$i(t.memoHome.trim()):process.env.MEMO_HOME?.trim()?$i(process.env.MEMO_HOME.trim()):ao(oo(),".memo")}function Bi(t){return ao(Df(t),"auth",Rf)}function Ot(t){return Cf("sha256").update(lo(t)).digest("hex")}function Di(){return{version:so,credentials:{}}}async function po(t){let e=Bi(t);try{let n=await kf(e,"utf8"),r=JSON.parse(n);return r.version!==so||!r.credentials?Di():{version:so,credentials:r.credentials}}catch{return Di()}}async function Wi(t,e){let n=Bi(t),r=`${n}.tmp`;await Mf(Af(n),{recursive:!0}),await Pf(r,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),await Ef(r,n)}var Wn=null;async function fo(){return Wn||(Wn=(async()=>{try{let e=await new Function("specifier","return import(specifier)")("keytar"),n=e.default??e;return n&&typeof n.getPassword=="function"&&typeof n.setPassword=="function"&&typeof n.deletePassword=="function"?n:null}catch{return null}})(),Wn)}async function no(t,e){let n=Ot(t);return(await po(e)).credentials[n]?.credential}async function ro(t,e,n){let r=Ot(t),o=await po(n);o.credentials[r]={url:lo(t),updatedAt:Date.now(),credential:e},await Wi(n,o)}async function io(t,e){let n=Ot(t),r=await po(e);return r.credentials[n]?(delete r.credentials[n],await Wi(e,r),!0):!1}async function Fi(t,e){let n=Ot(e),r=await t.getPassword(co,n);return r?JSON.parse(r).credential:void 0}async function Ui(t,e,n){let r=Ot(e),o={url:lo(e),updatedAt:Date.now(),credential:n};await t.setPassword(co,r,JSON.stringify(o))}async function Hi(t,e){let n=Ot(e);return t.deletePassword(co,n)}function Ff(t,e){return new URL(t).origin===e.origin}function ji(t){return{...t.http_headers??t.headers??{}}}function Uf(t){let e=t.replace(/^\/+|\/+$/g,"");if(!e)return["/.well-known/oauth-authorization-server"];let n=[],r=o=>{n.includes(o)||n.push(o)};return r(`/.well-known/oauth-authorization-server/${e}`),r(`/${e}/.well-known/oauth-authorization-server`),r("/.well-known/oauth-authorization-server"),n}function Hf(t){if(!t||t.length===0)return;let e=t.flatMap(n=>n.split(/[,\s]+/g)).map(n=>n.trim()).filter(Boolean);if(e.length!==0)return e.join(" ")}function zi(t){if(t!==void 0){if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`Invalid MCP OAuth callback port "${t}". Use an integer between 1 and 65535.`);return t}}function Bf(t){return process.platform==="darwin"?{command:"open",args:[t]}:process.platform==="win32"?{command:"cmd",args:["/c","start","",t]}:{command:"xdg-open",args:[t]}}async function Wf(t){let{command:e,args:n}=Bf(t);await new Promise((r,o)=>{let s=bf(e,n,{detached:!0,stdio:"ignore"}),i=!1,c=u=>{if(!i){if(i=!0,s.off("error",a),s.off("spawn",l),u){o(u);return}r()}},a=u=>{c(u)},l=()=>{c()};s.on("error",a),s.on("spawn",l),s.unref()})}function Gi(t,e){return async(n,r)=>{let o=typeof n=="string"||n instanceof URL?new URL(String(n),t):new URL(n.url),s=new Headers(r?.headers??{});if(Ff(t,o)){for(let[i,c]of Object.entries(e))s.has(i)||s.set(i,c);s.has(Li)||s.set(Li,Lf)}return fetch(o,{...r,headers:s})}}async function qi(t,e){let n=new URL(t),r=Gi(t,e),o=Uf(n.pathname);for(let s of o){let i=new URL(n.toString());i.pathname=s,i.search="",i.hash="";let c=new AbortController,a=setTimeout(()=>c.abort(),If);try{let l=await r(i,{method:"GET",signal:c.signal});if(!l.ok)continue;let u=await l.json();if(typeof u.authorization_endpoint=="string"&&typeof u.token_endpoint=="string")return!0}catch{continue}finally{clearTimeout(a)}}return!1}var jn=class{constructor(e,n,r,o,s){this.serverUrl=e;this.settings=n;this.redirectUrlValue=r;this.handleRedirect=o;this.clientMetadata=$f(r),s&&(this.credential=s,this.loaded=!0)}loaded=!1;credential={};verifier=null;clientMetadata;get redirectUrl(){return this.redirectUrlValue}async ensureLoaded(){if(this.loaded)return;let e=await zn(this.serverUrl,this.settings);this.credential=e.credential??{},this.loaded=!0}async persist(){await jf(this.serverUrl,this.credential,this.settings)}async clientInformation(){return await this.ensureLoaded(),this.credential.clientInformation}async saveClientInformation(e){await this.ensureLoaded(),this.credential={...this.credential,clientInformation:e},await this.persist()}async tokens(){return await this.ensureLoaded(),this.credential.tokens}async saveTokens(e){await this.ensureLoaded(),this.credential={...this.credential,tokens:e},await this.persist()}async redirectToAuthorization(e){await this.handleRedirect(e)}saveCodeVerifier(e){this.verifier=e}codeVerifier(){if(!this.verifier)throw new Error("OAuth code verifier is missing.");return this.verifier}async invalidateCredentials(e){if(await this.ensureLoaded(),e==="all")this.credential={};else if(e==="client")this.credential={...this.credential,clientInformation:void 0};else if(e==="tokens")this.credential={...this.credential,tokens:void 0};else if(e==="verifier"){this.verifier=null;return}await this.persist()}};async function zn(t,e){let n=uo(e?.storeMode);if(n==="file")return{backend:"file",credential:await no(t,e)};let r=await fo();if(n==="keyring"){if(!r)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return{backend:"keyring",credential:await Fi(r,t)}}if(!r)return{backend:"file",credential:await no(t,e)};try{let o=await Fi(r,t);if(o)return{backend:"keyring",credential:o}}catch{}return{backend:"file",credential:await no(t,e)}}async function jf(t,e,n){let r=uo(n?.storeMode);if(r==="file")return await ro(t,e,n),{backend:"file"};let o=await fo();if(r==="keyring"){if(!o)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return await Ui(o,t,e),{backend:"keyring"}}if(!o)return await ro(t,e,n),{backend:"file"};try{return await Ui(o,t,e),await io(t,n).catch(()=>{}),{backend:"keyring"}}catch{return await ro(t,e,n),{backend:"file"}}}async function zf(t,e){let n=uo(e?.storeMode);if(n==="file")return{backend:"file",removed:await io(t,e)};let r=await fo();if(n==="keyring"){if(!r)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return{backend:"keyring",removed:await Hi(r,t)}}let o=!1;if(r)try{o=await Hi(r,t)}catch{o=!1}let s=await io(t,e);return{backend:o?"keyring":"file",removed:o||s}}async function mo(t,e){return"url"in t?t.bearer_token_env_var?"bearer_token":(await zn(t.url,e)).credential?.tokens?.access_token?"oauth":await qi(t.url,ji(t))?"not_logged_in":"unsupported":"unsupported"}async function Gf(t,e){let n=zi(t),r="127.0.0.1",o=!1,s=null,i=null,c=null,a=new Promise((d,f)=>{i=d,c=f}),l=xf((d,f)=>{let g=new URL(d.url??"/",`http://${r}`);if(g.pathname!=="/callback"){f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not found");return}let m=g.searchParams.get("code"),_=g.searchParams.get("error"),A=g.searchParams.get("error_description");if(m){f.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),f.end("<html><body><h1>Authentication complete.</h1><p>You can close this window.</p></body></html>"),i?.(m);return}let h=A??_??"OAuth callback missing code.";f.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),f.end(`<html><body><h1>Authentication failed.</h1><p>${h}</p></body></html>`),c?.(new Error(h))});await new Promise((d,f)=>{l.once("error",f),l.listen(n??0,r,()=>{l.off("error",f),d()})});let u=l.address();if(!u||typeof u=="string")throw await new Promise(d=>l.close(()=>d())),new Error("Failed to resolve OAuth callback listener address.");s=setTimeout(()=>{c?.(new Error("Timed out waiting for OAuth callback."))},e),s.unref?.();let p=async()=>{o||(o=!0,s&&(clearTimeout(s),s=null),await new Promise(d=>l.close(()=>d())))};return{redirectUrl:`http://${r}:${u.port}/callback`,waitForCode:async()=>{try{return await a}finally{await p()}},close:p}}async function go(t){if(t.config.bearer_token_env_var)throw new Error(`Server "${t.serverName}" is configured with bearer_token_env_var. Remove it to use OAuth login.`);let e=ji(t.config);if(!await qi(t.config.url,e))throw new Error(`Server "${t.serverName}" does not advertise OAuth support. Configure --bearer-token-env-var instead.`);let r=await Gf(t.settings?.callbackPort,t.timeoutMs??Of),o=Gi(t.config.url,e),s=new jn(t.config.url,t.settings,r.redirectUrl,async i=>{let c=i.toString();t.onAuthorizationUrl?.(c);try{await Wf(c)}catch(a){t.onBrowserOpenFailure?.(new Error(Ni(a)),i.toString())}});try{let i=Hf(t.scopes);if(await Ii(s,{serverUrl:t.config.url,scope:i,fetchFn:o})==="REDIRECT"){let l=await r.waitForCode();if(await Ii(s,{serverUrl:t.config.url,authorizationCode:l,scope:i,fetchFn:o})!=="AUTHORIZED")throw new Error("OAuth authorization did not complete.")}let a=await zn(t.config.url,t.settings);if(!a.credential?.tokens?.access_token)throw new Error("OAuth login completed but no access token was stored.");return{backend:a.backend}}catch(i){throw new Error(`OAuth login failed: ${Ni(i)}`)}finally{await r.close()}}async function ho(t){return zf(t.config.url,t.settings)}async function Ki(t){if(t.config.bearer_token_env_var)return null;let e=await zn(t.config.url,t.settings);if(!e.credential?.tokens?.access_token)return null;let r=`http://127.0.0.1:${zi(t.settings?.callbackPort)??Nf}/callback`;return new jn(t.config.url,t.settings,r,async()=>{throw new Error(`MCP server "${t.serverName}" requires OAuth login. Run: memo mcp login ${t.serverName}`)},e.credential)}import{access as dC,mkdir as fC,readFile as mC,readdir as gC,rm as hC,writeFile as yC}from"fs/promises";import{homedir as wC}from"os";import{basename as vC,dirname as TC,join as CC,resolve as bC}from"path";import{z as qe}from"zod";function I(t){let{inputSchema:e,execute:n,...r}=t,o=e.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,source:"native",inputSchema:i,validateInput:c=>{let a=e.safeParse(c);if(!a.success){let l=a.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${t.name} invalid input: ${l}`}}return{ok:!0,data:a.data}},execute:n}}function S(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}import{spawn as gm}from"child_process";import{EventEmitter as hm}from"events";import{resolve as ym}from"path";import{posix as qf}from"path";var Vi=220,Xi=4096,Kf=/^\/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,Vf=/(?:^|[\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,Xf=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Yf=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function yo(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Jf(t){let e=t.replace(/\s+/g," ").trim();return e.length>Vi?`${e.slice(0,Vi)}\u2026`:e}function Yi(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return(e.split(/[\\/]/).at(-1)??e).toLowerCase()}function Qf(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 Zf(t){let e=[],n="",r=null,o=!1,s=()=>{let i=Qf(n).trim();i&&e.push(i),n=""};for(let i=0;i<t.length;i+=1){let c=t[i];if(o){n+=c,o=!1;continue}if(c==="\\"&&r!=="'"){n+=c,o=!0;continue}if(r){n+=c,c===r&&(r=null);continue}if(c==='"'||c==="'"){r=c,n+=c;continue}if(c===";"||c===`
55
- `){s();continue}if(c==="&"){t[i+1]==="&"&&(i+=1),s();continue}if(c==="|"){t[i+1]==="|"&&(i+=1),s();continue}n+=c}return s(),e}function em(t){let e=[],n="",r=null,o=!1,s=()=>{n&&e.push(n),n=""};for(let i=0;i<t.length;i+=1){let c=t[i];if(o){n+=c,o=!1;continue}if(c==="\\"&&r!=="'"){o=!0;continue}if(r){c===r?r=null:n+=c;continue}if(c==='"'||c==="'"){r=c;continue}if(/\s/.test(c)){s();continue}n+=c}return s(),e}function Ji(t){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t)}function tm(t,e){let n=e;for(;n<t.length;){let r=Yi(t[n]??"");if(r==="sudo"){for(n+=1;n<t.length;){let o=t[n]??"";if(!o.startsWith("-"))break;n+=1,Xf.has(o)&&n<t.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<t.length;){let o=t[n]??"";if(o.startsWith("-")||Ji(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function nm(t){let e=em(t);if(e.length===0)return null;let n=0;for(;n<e.length&&Ji(e[n]??"");)n+=1;if(n=tm(e,n),n>=e.length)return null;let r=Yi(e[n]??"");return r?{raw:t,commandName:r,args:e.slice(n+1)}:null}function So(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return Kf.test(e)}function rm(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)?qf.normalize(e)==="/":!1}function om(t){return t.startsWith("-")&&t!=="-"}function sm(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(!om(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(rm(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:t.raw};return null}function im(t){return t.commandName==="mkfs"||t.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:t.raw}:null}function am(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"&&So(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"&&So(r))return{ruleId:"dd_write_block_device",matchedSegment:t.raw}}return null}function cm(t){return!Yf.has(t.commandName)||!t.args.some(e=>So(e))?null:{ruleId:"disk_mutation_block_device",matchedSegment:t.raw}}function lm(t){return Vf.test(t)?{ruleId:"redirect_block_device",matchedSegment:t}:null}function um(t){for(let e of Zf(t)){let n=nm(e);if(n){let o=sm(n);if(o)return o;let s=im(n);if(s)return s;let i=am(n);if(i)return i;let c=cm(n);if(c)return c}let r=lm(e);if(r)return r}return null}function pm(t,e){let n=Jf(t.command),r=typeof t.sessionId=="number"?` session_id="${t.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${yo(t.toolName)}" reason="dangerous_command" policy="blacklist" rule="${yo(e.ruleId)}"${r} command="${yo(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function wo(t){let e=um(t.command);return e?{blocked:!0,xml:pm(t,e),match:e}:{blocked:!1}}function Qi(t){let n=t.replace(/\r\n/g,`
54
+ `)}async function Me(t,e){await cf(df(t),{recursive:!0}),await lf(t,vf(e),"utf-8")}async function re(){let t=process.env.MEMO_HOME?Ri(process.env.MEMO_HOME):hf,e=St(t,"config.toml");try{await pf(e);let n=await uf(e,"utf-8"),r=gf(n),o=Sf(r.providers),s=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(f=>typeof f=="string"&&f.trim().length>0):void 0,i=wf(r.active_skills),c=r.mcp_oauth_credentials_store_mode==="auto"||r.mcp_oauth_credentials_store_mode==="keyring"||r.mcp_oauth_credentials_store_mode==="file"?r.mcp_oauth_credentials_store_mode:an.mcp_oauth_credentials_store_mode,a=typeof r.mcp_oauth_callback_port=="number"&&Number.isInteger(r.mcp_oauth_callback_port)&&r.mcp_oauth_callback_port>0&&r.mcp_oauth_callback_port<=65535?r.mcp_oauth_callback_port:void 0,l=Ai(r.auto_compact_threshold_percent),u=_f(r.model_profiles),p={current_provider:r.current_provider??an.current_provider,mcp_oauth_credentials_store_mode:c,mcp_oauth_callback_port:a,auto_compact_threshold_percent:l,providers:o,model_profiles:u,mcp_servers:r.mcp_servers??{},active_mcp_servers:s,active_skills:i},d=!p.providers.length;return{config:d?an:p,home:t,configPath:e,needsSetup:d}}catch{return{config:an,home:t,configPath:e,needsSetup:!0}}}function wt(t,e){let n=e||t.current_provider,r=t.providers.find(o=>o.name===n);return r||(t.providers?.[0]??an.providers[0])}function cn(t,e){let n=e.historyDir??St(t.home,yf),r=Ri(n),o=mf(e.cwd??process.cwd()),s=ff(o).root,c=o.slice(s.length).split(/[\\/]+/).filter(Boolean);if(process.platform==="win32"){let l=/^([A-Za-z]):/.exec(s)?.[1];l&&c.unshift(l.toUpperCase())}if(c.length===0)return St(r,"-root");let a=`-${c.map(l=>l.replace(/[^A-Za-z0-9._-]/g,"_")).join("-")}`;return St(r,a)}function Oi(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"),c=String(n.getMinutes()).padStart(2,"0"),a=String(n.getSeconds()).padStart(2,"0"),l=`${r}-${o}-${s}T${i}-${c}-${a}`,u=e.replace(/[^A-Za-z0-9._-]/g,"_"),p=`${l}-${u}.jsonl`;return St(t,p)}import{createHash as Tf}from"crypto";import{spawn as Cf}from"child_process";import{createServer as bf}from"http";import{mkdir as xf,readFile as Mf,rename as kf,writeFile as Ef}from"fs/promises";import{homedir as oo}from"os";import{dirname as Pf,join as ao}from"path";import{auth as Ii}from"@modelcontextprotocol/sdk/client/auth.js";var so=1,Af="mcp-oauth.json",Rf=3e5,Of=5e3,Li="MCP-Protocol-Version",If="2024-11-05",co="memo-code.mcp.oauth",Lf=33333;function Nf(t){return{client_name:"Memo Code CLI",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function Ni(t){return t instanceof Error?t.message:String(t)}function lo(t){return new URL(t).toString()}function uo(t){return t==="file"||t==="keyring"||t==="auto"?t:"auto"}function $i(t){return t==="~"?oo():t.startsWith("~/")?ao(oo(),t.slice(2)):t}function $f(t){return t?.memoHome?.trim()?$i(t.memoHome.trim()):process.env.MEMO_HOME?.trim()?$i(process.env.MEMO_HOME.trim()):ao(oo(),".memo")}function Bi(t){return ao($f(t),"auth",Af)}function Ot(t){return Tf("sha256").update(lo(t)).digest("hex")}function Di(){return{version:so,credentials:{}}}async function po(t){let e=Bi(t);try{let n=await Mf(e,"utf8"),r=JSON.parse(n);return r.version!==so||!r.credentials?Di():{version:so,credentials:r.credentials}}catch{return Di()}}async function Wi(t,e){let n=Bi(t),r=`${n}.tmp`;await xf(Pf(n),{recursive:!0}),await Ef(r,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),await kf(r,n)}var Wn=null;async function fo(){return Wn||(Wn=(async()=>{try{let e=await new Function("specifier","return import(specifier)")("keytar"),n=e.default??e;return n&&typeof n.getPassword=="function"&&typeof n.setPassword=="function"&&typeof n.deletePassword=="function"?n:null}catch{return null}})(),Wn)}async function no(t,e){let n=Ot(t);return(await po(e)).credentials[n]?.credential}async function ro(t,e,n){let r=Ot(t),o=await po(n);o.credentials[r]={url:lo(t),updatedAt:Date.now(),credential:e},await Wi(n,o)}async function io(t,e){let n=Ot(t),r=await po(e);return r.credentials[n]?(delete r.credentials[n],await Wi(e,r),!0):!1}async function Fi(t,e){let n=Ot(e),r=await t.getPassword(co,n);return r?JSON.parse(r).credential:void 0}async function Ui(t,e,n){let r=Ot(e),o={url:lo(e),updatedAt:Date.now(),credential:n};await t.setPassword(co,r,JSON.stringify(o))}async function Hi(t,e){let n=Ot(e);return t.deletePassword(co,n)}function Df(t,e){return new URL(t).origin===e.origin}function ji(t){return{...t.http_headers??t.headers??{}}}function Ff(t){let e=t.replace(/^\/+|\/+$/g,"");if(!e)return["/.well-known/oauth-authorization-server"];let n=[],r=o=>{n.includes(o)||n.push(o)};return r(`/.well-known/oauth-authorization-server/${e}`),r(`/${e}/.well-known/oauth-authorization-server`),r("/.well-known/oauth-authorization-server"),n}function Uf(t){if(!t||t.length===0)return;let e=t.flatMap(n=>n.split(/[,\s]+/g)).map(n=>n.trim()).filter(Boolean);if(e.length!==0)return e.join(" ")}function zi(t){if(t!==void 0){if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`Invalid MCP OAuth callback port "${t}". Use an integer between 1 and 65535.`);return t}}function Hf(t){return process.platform==="darwin"?{command:"open",args:[t]}:process.platform==="win32"?{command:"cmd",args:["/c","start","",t]}:{command:"xdg-open",args:[t]}}async function Bf(t){let{command:e,args:n}=Hf(t);await new Promise((r,o)=>{let s=Cf(e,n,{detached:!0,stdio:"ignore"}),i=!1,c=u=>{if(!i){if(i=!0,s.off("error",a),s.off("spawn",l),u){o(u);return}r()}},a=u=>{c(u)},l=()=>{c()};s.on("error",a),s.on("spawn",l),s.unref()})}function Gi(t,e){return async(n,r)=>{let o=typeof n=="string"||n instanceof URL?new URL(String(n),t):new URL(n.url),s=new Headers(r?.headers??{});if(Df(t,o)){for(let[i,c]of Object.entries(e))s.has(i)||s.set(i,c);s.has(Li)||s.set(Li,If)}return fetch(o,{...r,headers:s})}}async function qi(t,e){let n=new URL(t),r=Gi(t,e),o=Ff(n.pathname);for(let s of o){let i=new URL(n.toString());i.pathname=s,i.search="",i.hash="";let c=new AbortController,a=setTimeout(()=>c.abort(),Of);try{let l=await r(i,{method:"GET",signal:c.signal});if(!l.ok)continue;let u=await l.json();if(typeof u.authorization_endpoint=="string"&&typeof u.token_endpoint=="string")return!0}catch{continue}finally{clearTimeout(a)}}return!1}var jn=class{constructor(e,n,r,o,s){this.serverUrl=e;this.settings=n;this.redirectUrlValue=r;this.handleRedirect=o;this.clientMetadata=Nf(r),s&&(this.credential=s,this.loaded=!0)}loaded=!1;credential={};verifier=null;clientMetadata;get redirectUrl(){return this.redirectUrlValue}async ensureLoaded(){if(this.loaded)return;let e=await zn(this.serverUrl,this.settings);this.credential=e.credential??{},this.loaded=!0}async persist(){await Wf(this.serverUrl,this.credential,this.settings)}async clientInformation(){return await this.ensureLoaded(),this.credential.clientInformation}async saveClientInformation(e){await this.ensureLoaded(),this.credential={...this.credential,clientInformation:e},await this.persist()}async tokens(){return await this.ensureLoaded(),this.credential.tokens}async saveTokens(e){await this.ensureLoaded(),this.credential={...this.credential,tokens:e},await this.persist()}async redirectToAuthorization(e){await this.handleRedirect(e)}saveCodeVerifier(e){this.verifier=e}codeVerifier(){if(!this.verifier)throw new Error("OAuth code verifier is missing.");return this.verifier}async invalidateCredentials(e){if(await this.ensureLoaded(),e==="all")this.credential={};else if(e==="client")this.credential={...this.credential,clientInformation:void 0};else if(e==="tokens")this.credential={...this.credential,tokens:void 0};else if(e==="verifier"){this.verifier=null;return}await this.persist()}};async function zn(t,e){let n=uo(e?.storeMode);if(n==="file")return{backend:"file",credential:await no(t,e)};let r=await fo();if(n==="keyring"){if(!r)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return{backend:"keyring",credential:await Fi(r,t)}}if(!r)return{backend:"file",credential:await no(t,e)};try{let o=await Fi(r,t);if(o)return{backend:"keyring",credential:o}}catch{}return{backend:"file",credential:await no(t,e)}}async function Wf(t,e,n){let r=uo(n?.storeMode);if(r==="file")return await ro(t,e,n),{backend:"file"};let o=await fo();if(r==="keyring"){if(!o)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return await Ui(o,t,e),{backend:"keyring"}}if(!o)return await ro(t,e,n),{backend:"file"};try{return await Ui(o,t,e),await io(t,n).catch(()=>{}),{backend:"keyring"}}catch{return await ro(t,e,n),{backend:"file"}}}async function jf(t,e){let n=uo(e?.storeMode);if(n==="file")return{backend:"file",removed:await io(t,e)};let r=await fo();if(n==="keyring"){if(!r)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return{backend:"keyring",removed:await Hi(r,t)}}let o=!1;if(r)try{o=await Hi(r,t)}catch{o=!1}let s=await io(t,e);return{backend:o?"keyring":"file",removed:o||s}}async function mo(t,e){return"url"in t?t.bearer_token_env_var?"bearer_token":(await zn(t.url,e)).credential?.tokens?.access_token?"oauth":await qi(t.url,ji(t))?"not_logged_in":"unsupported":"unsupported"}async function zf(t,e){let n=zi(t),r="127.0.0.1",o=!1,s=null,i=null,c=null,a=new Promise((d,f)=>{i=d,c=f}),l=bf((d,f)=>{let g=new URL(d.url??"/",`http://${r}`);if(g.pathname!=="/callback"){f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not found");return}let m=g.searchParams.get("code"),_=g.searchParams.get("error"),A=g.searchParams.get("error_description");if(m){f.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),f.end("<html><body><h1>Authentication complete.</h1><p>You can close this window.</p></body></html>"),i?.(m);return}let h=A??_??"OAuth callback missing code.";f.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),f.end(`<html><body><h1>Authentication failed.</h1><p>${h}</p></body></html>`),c?.(new Error(h))});await new Promise((d,f)=>{l.once("error",f),l.listen(n??0,r,()=>{l.off("error",f),d()})});let u=l.address();if(!u||typeof u=="string")throw await new Promise(d=>l.close(()=>d())),new Error("Failed to resolve OAuth callback listener address.");s=setTimeout(()=>{c?.(new Error("Timed out waiting for OAuth callback."))},e),s.unref?.();let p=async()=>{o||(o=!0,s&&(clearTimeout(s),s=null),await new Promise(d=>l.close(()=>d())))};return{redirectUrl:`http://${r}:${u.port}/callback`,waitForCode:async()=>{try{return await a}finally{await p()}},close:p}}async function go(t){if(t.config.bearer_token_env_var)throw new Error(`Server "${t.serverName}" is configured with bearer_token_env_var. Remove it to use OAuth login.`);let e=ji(t.config);if(!await qi(t.config.url,e))throw new Error(`Server "${t.serverName}" does not advertise OAuth support. Configure --bearer-token-env-var instead.`);let r=await zf(t.settings?.callbackPort,t.timeoutMs??Rf),o=Gi(t.config.url,e),s=new jn(t.config.url,t.settings,r.redirectUrl,async i=>{let c=i.toString();t.onAuthorizationUrl?.(c);try{await Bf(c)}catch(a){t.onBrowserOpenFailure?.(new Error(Ni(a)),i.toString())}});try{let i=Uf(t.scopes);if(await Ii(s,{serverUrl:t.config.url,scope:i,fetchFn:o})==="REDIRECT"){let l=await r.waitForCode();if(await Ii(s,{serverUrl:t.config.url,authorizationCode:l,scope:i,fetchFn:o})!=="AUTHORIZED")throw new Error("OAuth authorization did not complete.")}let a=await zn(t.config.url,t.settings);if(!a.credential?.tokens?.access_token)throw new Error("OAuth login completed but no access token was stored.");return{backend:a.backend}}catch(i){throw new Error(`OAuth login failed: ${Ni(i)}`)}finally{await r.close()}}async function ho(t){return jf(t.config.url,t.settings)}async function Ki(t){if(t.config.bearer_token_env_var)return null;let e=await zn(t.config.url,t.settings);if(!e.credential?.tokens?.access_token)return null;let r=`http://127.0.0.1:${zi(t.settings?.callbackPort)??Lf}/callback`;return new jn(t.config.url,t.settings,r,async()=>{throw new Error(`MCP server "${t.serverName}" requires OAuth login. Run: memo mcp login ${t.serverName}`)},e.credential)}import{access as dC,mkdir as fC,readFile as mC,readdir as gC,rm as hC,writeFile as yC}from"fs/promises";import{homedir as wC}from"os";import{basename as vC,dirname as TC,join as CC,resolve as bC}from"path";import{z as qe}from"zod";function I(t){let{inputSchema:e,execute:n,...r}=t,o=e.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,source:"native",inputSchema:i,validateInput:c=>{let a=e.safeParse(c);if(!a.success){let l=a.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${t.name} invalid input: ${l}`}}return{ok:!0,data:a.data}},execute:n}}function S(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}import{spawn as mm}from"child_process";import{EventEmitter as gm}from"events";import{resolve as hm}from"path";import{posix as Gf}from"path";var Vi=220,Xi=4096,qf=/^\/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,Kf=/(?:^|[\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,Vf=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Xf=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function yo(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Yf(t){let e=t.replace(/\s+/g," ").trim();return e.length>Vi?`${e.slice(0,Vi)}\u2026`:e}function Yi(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return(e.split(/[\\/]/).at(-1)??e).toLowerCase()}function Jf(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 Qf(t){let e=[],n="",r=null,o=!1,s=()=>{let i=Jf(n).trim();i&&e.push(i),n=""};for(let i=0;i<t.length;i+=1){let c=t[i];if(o){n+=c,o=!1;continue}if(c==="\\"&&r!=="'"){n+=c,o=!0;continue}if(r){n+=c,c===r&&(r=null);continue}if(c==='"'||c==="'"){r=c,n+=c;continue}if(c===";"||c===`
55
+ `){s();continue}if(c==="&"){t[i+1]==="&"&&(i+=1),s();continue}if(c==="|"){t[i+1]==="|"&&(i+=1),s();continue}n+=c}return s(),e}function Zf(t){let e=[],n="",r=null,o=!1,s=()=>{n&&e.push(n),n=""};for(let i=0;i<t.length;i+=1){let c=t[i];if(o){n+=c,o=!1;continue}if(c==="\\"&&r!=="'"){o=!0;continue}if(r){c===r?r=null:n+=c;continue}if(c==='"'||c==="'"){r=c;continue}if(/\s/.test(c)){s();continue}n+=c}return s(),e}function Ji(t){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t)}function em(t,e){let n=e;for(;n<t.length;){let r=Yi(t[n]??"");if(r==="sudo"){for(n+=1;n<t.length;){let o=t[n]??"";if(!o.startsWith("-"))break;n+=1,Vf.has(o)&&n<t.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<t.length;){let o=t[n]??"";if(o.startsWith("-")||Ji(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function tm(t){let e=Zf(t);if(e.length===0)return null;let n=0;for(;n<e.length&&Ji(e[n]??"");)n+=1;if(n=em(e,n),n>=e.length)return null;let r=Yi(e[n]??"");return r?{raw:t,commandName:r,args:e.slice(n+1)}:null}function So(t){let e=t.trim().replace(/^['"]|['"]$/g,"");return qf.test(e)}function nm(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)?Gf.normalize(e)==="/":!1}function rm(t){return t.startsWith("-")&&t!=="-"}function om(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(!rm(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(nm(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:t.raw};return null}function sm(t){return t.commandName==="mkfs"||t.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:t.raw}:null}function im(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"&&So(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"&&So(r))return{ruleId:"dd_write_block_device",matchedSegment:t.raw}}return null}function am(t){return!Xf.has(t.commandName)||!t.args.some(e=>So(e))?null:{ruleId:"disk_mutation_block_device",matchedSegment:t.raw}}function cm(t){return Kf.test(t)?{ruleId:"redirect_block_device",matchedSegment:t}:null}function lm(t){for(let e of Qf(t)){let n=tm(e);if(n){let o=om(n);if(o)return o;let s=sm(n);if(s)return s;let i=im(n);if(i)return i;let c=am(n);if(c)return c}let r=cm(e);if(r)return r}return null}function um(t,e){let n=Yf(t.command),r=typeof t.sessionId=="number"?` session_id="${t.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${yo(t.toolName)}" reason="dangerous_command" policy="blacklist" rule="${yo(e.ruleId)}"${r} command="${yo(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function wo(t){let e=lm(t.command);return e?{blocked:!0,xml:um(t,e),match:e}:{blocked:!1}}function Qi(t){let n=t.replace(/\r\n/g,`
56
56
  `).replace(/\r/g,`
57
57
  `).split(`
58
- `),r=n.pop()??"";return{completedLines:n,remainder:r}}function _o(t){return t.length<=Xi?t:t.slice(-Xi)}import{AsyncLocalStorage as dm}from"async_hooks";import{resolve as fm}from"path";var Zi=new dm;function ea(t){if(!(!t||!t.trim()))return fm(t)}function mm(){return Zi.getStore()??{}}function Fe(t=process.cwd()){return ea(mm().cwd)??t}async function ta(t,e){let n={cwd:ea(t.cwd)};return new Promise((r,o)=>{Zi.run(n,()=>{Promise.resolve(e()).then(r,o)})})}var Sm=1e4,wm=250,_m=2e3,Gn=64;function vm(t){return Math.ceil(t.length/4)}function Tm(){return Math.random().toString(16).slice(2)||String(Date.now())}function Cm(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 bm(t,e){let r=(typeof e=="number"&&e>0?Math.floor(e):_m)*4,o=vm(t);return t.length<=r?{output:t,originalTokenCount:o,deliveredChars:t.length}:{output:t.slice(0,r),originalTokenCount:o,deliveredChars:r}}function xm(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(`
59
- `)}function na(t,e){return typeof t!="number"||Number.isNaN(t)?e:t<0?0:Math.floor(t)}async function ra(t,e){e<=0||t.exited||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(c),i(),n())},s=()=>{o()},i=()=>{t.eventBus.off("exit",s)},c=setTimeout(()=>{o()},e);c.unref?.(),t.eventBus.on("exit",s)})}async function oa(t,e){t.exited||e<=0||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(c),i(),n())},s=()=>{o()},i=()=>{t.eventBus.off("exit",s)},c=setTimeout(()=>{o()},e);c.unref?.(),t.eventBus.on("exit",s)})}var vo=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Gn)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<=Gn)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){if(!e.exited){try{e.proc.kill("SIGTERM")}catch{}if(await oa(e,200),!e.exited){try{e.proc.kill("SIGKILL")}catch{}await oa(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()>=Gn)throw new Error(`too many active sessions (max ${Gn})`);let r=wo({toolName:e.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=Cm({cmd:n,shell:e.shell,login:e.login!==!1}),c=Fe(),a=e.workdir?.trim()?ym(c,e.workdir.trim()):c,l=gm(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),u={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new hm,proc:l},p=(m,_)=>{let A=typeof _=="string"?_:_.toString("utf8");u.output+=m?`${m}${A}`:A,u.eventBus.emit("output")};l.stdout?.on("data",m=>p("",m)),l.stderr?.on("data",m=>p("",m)),l.on("error",m=>{u.output+=`
60
- [exec error] ${m.message}`,u.eventBus.emit("output")}),l.on("close",m=>{u.exited=!0,u.exitCode=typeof m=="number"?m:-1,u.eventBus.emit("exit")}),this.sessions.set(o,u),this.cleanupSessions();let d=typeof e.execution_timeout_ms=="number"&&e.execution_timeout_ms>0?Math.floor(e.execution_timeout_ms):null,f=na(e.yield_time_ms,Sm),g=d!==null?Math.min(f,Math.max(0,d)):f;if(await ra(u,g),d!==null&&!u.exited&&Date.now()-s>=d)throw await this.terminateForTimeout(u),this.cleanupSessions(),new Error(`command timed out after ${d}ms`);return this.buildResponseText(u,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=_o(`${n.pendingStdinInput}${e.chars}`),{completedLines:s,remainder:i}=Qi(o);for(let c of s){if(!c.trim())continue;let a=wo({toolName:e.source_tool??"write_stdin",command:c,sessionId:n.id});if(a.blocked)return n.pendingStdinInput="",a.xml}n.pendingStdinInput=_o(i);try{let c=n.proc.stdin;c&&!c.destroyed&&!c.writableEnded&&c.write(e.chars)}catch{}}let r=na(e.yield_time_ms,wm);return await ra(n,r),this.buildResponseText(n,e.max_output_tokens)}buildResponseText(e,n){let r=e.output.slice(e.readOffset),o=bm(r,n);e.readOffset+=o.deliveredChars;let s={sessionId:e.id,chunkId:Tm(),wallTimeSeconds:(Date.now()-e.startedAtMs)/1e3,exitCode:e.exited?e.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return xm(s)}},sa=new vo;async function It(t){return sa.start(t)}async function ia(t){return sa.write(t)}var Mm=qe.object({command:qe.array(qe.string().min(1)).min(1,"command cannot be empty"),workdir:qe.string().optional(),timeout_ms:qe.number().int().positive().optional(),sandbox_permissions:qe.enum(["use_default","require_escalated"]).optional(),justification:qe.string().optional(),prefix_rule:qe.array(qe.string().min(1)).optional()}).strict(),km=/^[A-Za-z0-9_./:@%+-]+$/;function Em(t){return t.length===0?"''":km.test(t)?t:`'${t.replace(/'/g,`'"'"'`)}'`}function Pm(t){return t.map(e=>Em(e)).join(" ")}var aa=I({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:Mm,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,timeout_ms:n})=>{try{let r=await It({cmd:Pm(t),workdir:e,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return S(r)}catch(r){return S(`shell failed: ${r.message}`,!0)}}});import{z as Ke}from"zod";var Am=Ke.object({command:Ke.string().min(1,"command cannot be empty"),workdir:Ke.string().optional(),login:Ke.boolean().optional(),timeout_ms:Ke.number().int().positive().optional(),sandbox_permissions:Ke.enum(["use_default","require_escalated"]).optional(),justification:Ke.string().optional(),prefix_rule:Ke.array(Ke.string().min(1)).optional()}).strict(),ca=I({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:Am,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,login:n,timeout_ms:r})=>{try{let o=await It({cmd:t,workdir:e,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return S(o)}catch(o){return S(`shell_command failed: ${o.message}`,!0)}}});import{z as Ae}from"zod";var Rm=Ae.object({cmd:Ae.string().min(1,"cmd cannot be empty"),workdir:Ae.string().optional(),shell:Ae.string().optional(),login:Ae.boolean().optional(),tty:Ae.boolean().optional(),yield_time_ms:Ae.number().int().nonnegative().optional(),max_output_tokens:Ae.number().int().positive().optional(),sandbox_permissions:Ae.enum(["use_default","require_escalated"]).optional(),justification:Ae.string().optional(),prefix_rule:Ae.array(Ae.string().min(1)).optional()}).strict(),To=I({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:Rm,supportsParallelToolCalls:!0,isMutating:!0,execute:async t=>{try{let e=await It({...t,source_tool:"exec_command"});return S(e)}catch(e){return S(`exec_command failed: ${e.message}`,!0)}}});import{z as ln}from"zod";var Om=ln.object({session_id:ln.number().int().positive(),chars:ln.string().optional(),yield_time_ms:ln.number().int().nonnegative().optional(),max_output_tokens:ln.number().int().positive().optional()}).strict(),Co=I({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:Om,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await ia({...t,source_tool:"write_stdin"});return S(e)}catch(e){return S(`write_stdin failed: ${e.message}`,!0)}}});import{mkdir as _a,readFile as va,realpath as Ta,rm as Ca,writeFile as ba}from"fs/promises";import{basename as xa,dirname as Jn,isAbsolute as cg,join as Na}from"path";import{z as Ma}from"zod";var og=zs(ya(),1);import{normalize as Jm,resolve as Qm,dirname as pb,join as Zm,relative as eg,isAbsolute as tg}from"path";import{homedir as ng}from"os";import{existsSync as mb,statSync as gb,realpathSync as rg}from"fs";import{readFile as yb}from"fs/promises";function Ym(t){let e=t?.trim();if(!e)return null;let n=Number(e);return!Number.isFinite(n)||n<=0?null:Math.floor(n)}function Ao(){return Ym(process.env.MEMO_TOOL_RESULT_MAX_CHARS)??2e4}function rt(t){return Jm(Qm(t))}function Kn(t){let e=rt(t);try{return rt(rg(e))}catch{return e}}function sg(t,e){let n=eg(e,t);return n===""||!n.startsWith("..")&&!tg(n)}function ig(){let t=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>Kn(e)):[]}function Sa(){let t=new Set;t.add(Kn(Fe()));let e=process.env.MEMO_HOME?.trim()||Zm(ng(),".memo");t.add(Kn(e));for(let n of ig())t.add(n);return Array.from(t)}function ag(t){let e=Kn(t);return Sa().some(r=>sg(e,r))}function wa(t){if(ag(t))return null;let e=Sa();return`sandbox write denied: ${t} is not within allowed directories (${e.join(", ")})`}var Oo="*** Begin Patch",ka="*** End Patch",Ea="*** Add File: ",Pa="*** Delete File: ",Aa="*** Update File: ",Ra="*** Move to: ",lg="*** End of File",Oa="@@ ",ug="@@",Ia=Ma.object({input:Ma.string().min(1,"input cannot be empty")}).strict(),pg=`Use the \`apply_patch\` tool to edit files.
58
+ `),r=n.pop()??"";return{completedLines:n,remainder:r}}function _o(t){return t.length<=Xi?t:t.slice(-Xi)}import{AsyncLocalStorage as pm}from"async_hooks";import{resolve as dm}from"path";var Zi=new pm;function ea(t){if(!(!t||!t.trim()))return dm(t)}function fm(){return Zi.getStore()??{}}function Fe(t=process.cwd()){return ea(fm().cwd)??t}async function ta(t,e){let n={cwd:ea(t.cwd)};return new Promise((r,o)=>{Zi.run(n,()=>{Promise.resolve(e()).then(r,o)})})}var ym=1e4,Sm=250,wm=2e3,Gn=64;function _m(t){return Math.ceil(t.length/4)}function vm(){return Math.random().toString(16).slice(2)||String(Date.now())}function Tm(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 Cm(t,e){let r=(typeof e=="number"&&e>0?Math.floor(e):wm)*4,o=_m(t);return t.length<=r?{output:t,originalTokenCount:o,deliveredChars:t.length}:{output:t.slice(0,r),originalTokenCount:o,deliveredChars:r}}function bm(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(`
59
+ `)}function na(t,e){return typeof t!="number"||Number.isNaN(t)?e:t<0?0:Math.floor(t)}async function ra(t,e){e<=0||t.exited||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(c),i(),n())},s=()=>{o()},i=()=>{t.eventBus.off("exit",s)},c=setTimeout(()=>{o()},e);c.unref?.(),t.eventBus.on("exit",s)})}async function oa(t,e){t.exited||e<=0||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(c),i(),n())},s=()=>{o()},i=()=>{t.eventBus.off("exit",s)},c=setTimeout(()=>{o()},e);c.unref?.(),t.eventBus.on("exit",s)})}var vo=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Gn)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<=Gn)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){if(!e.exited){try{e.proc.kill("SIGTERM")}catch{}if(await oa(e,200),!e.exited){try{e.proc.kill("SIGKILL")}catch{}await oa(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()>=Gn)throw new Error(`too many active sessions (max ${Gn})`);let r=wo({toolName:e.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=Tm({cmd:n,shell:e.shell,login:e.login!==!1}),c=Fe(),a=e.workdir?.trim()?hm(c,e.workdir.trim()):c,l=mm(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),u={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new gm,proc:l},p=(m,_)=>{let A=typeof _=="string"?_:_.toString("utf8");u.output+=m?`${m}${A}`:A,u.eventBus.emit("output")};l.stdout?.on("data",m=>p("",m)),l.stderr?.on("data",m=>p("",m)),l.on("error",m=>{u.output+=`
60
+ [exec error] ${m.message}`,u.eventBus.emit("output")}),l.on("close",m=>{u.exited=!0,u.exitCode=typeof m=="number"?m:-1,u.eventBus.emit("exit")}),this.sessions.set(o,u),this.cleanupSessions();let d=typeof e.execution_timeout_ms=="number"&&e.execution_timeout_ms>0?Math.floor(e.execution_timeout_ms):null,f=na(e.yield_time_ms,ym),g=d!==null?Math.min(f,Math.max(0,d)):f;if(await ra(u,g),d!==null&&!u.exited&&Date.now()-s>=d)throw await this.terminateForTimeout(u),this.cleanupSessions(),new Error(`command timed out after ${d}ms`);return this.buildResponseText(u,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=_o(`${n.pendingStdinInput}${e.chars}`),{completedLines:s,remainder:i}=Qi(o);for(let c of s){if(!c.trim())continue;let a=wo({toolName:e.source_tool??"write_stdin",command:c,sessionId:n.id});if(a.blocked)return n.pendingStdinInput="",a.xml}n.pendingStdinInput=_o(i);try{let c=n.proc.stdin;c&&!c.destroyed&&!c.writableEnded&&c.write(e.chars)}catch{}}let r=na(e.yield_time_ms,Sm);return await ra(n,r),this.buildResponseText(n,e.max_output_tokens)}buildResponseText(e,n){let r=e.output.slice(e.readOffset),o=Cm(r,n);e.readOffset+=o.deliveredChars;let s={sessionId:e.id,chunkId:vm(),wallTimeSeconds:(Date.now()-e.startedAtMs)/1e3,exitCode:e.exited?e.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return bm(s)}},sa=new vo;async function It(t){return sa.start(t)}async function ia(t){return sa.write(t)}var xm=qe.object({command:qe.array(qe.string().min(1)).min(1,"command cannot be empty"),workdir:qe.string().optional(),timeout_ms:qe.number().int().positive().optional(),sandbox_permissions:qe.enum(["use_default","require_escalated"]).optional(),justification:qe.string().optional(),prefix_rule:qe.array(qe.string().min(1)).optional()}).strict(),Mm=/^[A-Za-z0-9_./:@%+-]+$/;function km(t){return t.length===0?"''":Mm.test(t)?t:`'${t.replace(/'/g,`'"'"'`)}'`}function Em(t){return t.map(e=>km(e)).join(" ")}var aa=I({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:xm,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,timeout_ms:n})=>{try{let r=await It({cmd:Em(t),workdir:e,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return S(r)}catch(r){return S(`shell failed: ${r.message}`,!0)}}});import{z as Ke}from"zod";var Pm=Ke.object({command:Ke.string().min(1,"command cannot be empty"),workdir:Ke.string().optional(),login:Ke.boolean().optional(),timeout_ms:Ke.number().int().positive().optional(),sandbox_permissions:Ke.enum(["use_default","require_escalated"]).optional(),justification:Ke.string().optional(),prefix_rule:Ke.array(Ke.string().min(1)).optional()}).strict(),ca=I({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:Pm,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,login:n,timeout_ms:r})=>{try{let o=await It({cmd:t,workdir:e,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return S(o)}catch(o){return S(`shell_command failed: ${o.message}`,!0)}}});import{z as Ae}from"zod";var Am=Ae.object({cmd:Ae.string().min(1,"cmd cannot be empty"),workdir:Ae.string().optional(),shell:Ae.string().optional(),login:Ae.boolean().optional(),tty:Ae.boolean().optional(),yield_time_ms:Ae.number().int().nonnegative().optional(),max_output_tokens:Ae.number().int().positive().optional(),sandbox_permissions:Ae.enum(["use_default","require_escalated"]).optional(),justification:Ae.string().optional(),prefix_rule:Ae.array(Ae.string().min(1)).optional()}).strict(),To=I({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:Am,supportsParallelToolCalls:!0,isMutating:!0,execute:async t=>{try{let e=await It({...t,source_tool:"exec_command"});return S(e)}catch(e){return S(`exec_command failed: ${e.message}`,!0)}}});import{z as ln}from"zod";var Rm=ln.object({session_id:ln.number().int().positive(),chars:ln.string().optional(),yield_time_ms:ln.number().int().nonnegative().optional(),max_output_tokens:ln.number().int().positive().optional()}).strict(),Co=I({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:Rm,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await ia({...t,source_tool:"write_stdin"});return S(e)}catch(e){return S(`write_stdin failed: ${e.message}`,!0)}}});import{mkdir as _a,readFile as va,realpath as Ta,rm as Ca,writeFile as ba}from"fs/promises";import{basename as xa,dirname as Jn,isAbsolute as ag,join as Na}from"path";import{z as Ma}from"zod";var rg=zs(ya(),1);import{normalize as Ym,resolve as Jm,dirname as pb,join as Qm,relative as Zm,isAbsolute as eg}from"path";import{homedir as tg}from"os";import{existsSync as mb,statSync as gb,realpathSync as ng}from"fs";import{readFile as yb}from"fs/promises";function Xm(t){let e=t?.trim();if(!e)return null;let n=Number(e);return!Number.isFinite(n)||n<=0?null:Math.floor(n)}function Ao(){return Xm(process.env.MEMO_TOOL_RESULT_MAX_CHARS)??2e4}function rt(t){return Ym(Jm(t))}function Kn(t){let e=rt(t);try{return rt(ng(e))}catch{return e}}function og(t,e){let n=Zm(e,t);return n===""||!n.startsWith("..")&&!eg(n)}function sg(){let t=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>Kn(e)):[]}function Sa(){let t=new Set;t.add(Kn(Fe()));let e=process.env.MEMO_HOME?.trim()||Qm(tg(),".memo");t.add(Kn(e));for(let n of sg())t.add(n);return Array.from(t)}function ig(t){let e=Kn(t);return Sa().some(r=>og(e,r))}function wa(t){if(ig(t))return null;let e=Sa();return`sandbox write denied: ${t} is not within allowed directories (${e.join(", ")})`}var Oo="*** Begin Patch",ka="*** End Patch",Ea="*** Add File: ",Pa="*** Delete File: ",Aa="*** Update File: ",Ra="*** Move to: ",cg="*** End of File",Oa="@@ ",lg="@@",Ia=Ma.object({input:Ma.string().min(1,"input cannot be empty")}).strict(),ug=`Use the \`apply_patch\` tool to edit files.
61
61
  Your patch language is a stripped\u2011down, file\u2011oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high\u2011level envelope:
62
62
 
63
63
  *** Begin Patch
@@ -124,33 +124,33 @@ It is important to remember:
124
124
  - You must include a header with your intended action (Add/Delete/Update)
125
125
  - You must prefix new lines with \`+\` even when creating a new file
126
126
  - File references can only be relative, NEVER ABSOLUTE.
127
- `,Lt=class extends Error{lineNumber;constructor(e,n){super(e),this.lineNumber=typeof n=="number"?n:null}};function Io(t){throw new Lt(t)}function Xe(t,e){throw new Lt(t,e)}function Vn(t,e){let n=t.trim();return n||Xe("path cannot be empty",e),cg(n)&&Xe(`File references must be relative, NEVER ABSOLUTE: ${n}`,e),n}function $a(t){let e=t[0]?.trim(),n=t[t.length-1]?.trim();e!==Oo&&Io(`The first line of the patch must be '${Oo}'`),n!==ka&&Io(`The last line of the patch must be '${ka}'`)}function dg(t,e){if(t.length<4)throw e;let n=t[0],r=t[t.length-1];if((n==="<<EOF"||n==="<<'EOF'"||n==='<<"EOF"')&&r.endsWith("EOF")){let o=t.slice(1,-1);return $a(o),o}throw e}function fg(t){let e=t.trim().split(/\r?\n/);(e.length===0||!e[0])&&Io(`The first line of the patch must be '${Oo}'`);let n=e;try{$a(n)}catch(i){if(!(i instanceof Lt)||i.lineNumber!==null)throw i;n=dg(e,i)}let r=[],o=n.slice(1,Math.max(n.length-1,1)),s=2;for(;o.length>0;){let i=mg(o,s);r.push(i.hunk),s+=i.parsedLines,o=o.slice(i.parsedLines)}return r}function mg(t,e){let n=t[0].trim();if(n.startsWith(Ea)){let r=Vn(n.slice(Ea.length),e),o="",s=1;for(let i=1;i<t.length;i+=1){let c=t[i];if(c.startsWith("+")){o+=`${c.slice(1)}
128
- `,s+=1;continue}break}return{hunk:{type:"add",path:r,contents:o},parsedLines:s}}if(n.startsWith(Pa))return{hunk:{type:"delete",path:Vn(n.slice(Pa.length),e)},parsedLines:1};if(n.startsWith(Aa)){let r=Vn(n.slice(Aa.length),e),o=t.slice(1),s=1,i=null,c=o[0]?.startsWith(Ra)?o[0].slice(Ra.length):null;typeof c=="string"&&(i=Vn(c,e+1),o=o.slice(1),s+=1);let a=[];for(;o.length>0;){if(o[0].trim().length===0){o=o.slice(1),s+=1;continue}if(o[0].startsWith("***"))break;let l=gg(o,e+s,a.length===0);a.push(l.chunk),o=o.slice(l.parsedLines),s+=l.parsedLines}return a.length===0&&Xe(`Update file hunk for path '${r}' is empty`,e),{hunk:{type:"update",path:r,movePath:i,chunks:a},parsedLines:s}}Xe(`'${n}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`,e)}function gg(t,e,n){t.length===0&&Xe("Update hunk does not contain any lines",e);let r=null,o=0;t[0]===ug?o=1:t[0].startsWith(Oa)?(r=t[0].slice(Oa.length),o=1):n||Xe(`Expected update hunk to start with a @@ context marker, got: '${t[0]}'`,e),o>=t.length&&Xe("Update hunk does not contain any lines",e+1);let s={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},i=0;for(let c=o;c<t.length;c+=1){let a=t[c];if(a===lg){i===0&&Xe("Update hunk does not contain any lines",e+1),s.isEndOfFile=!0,i+=1;break}let l=a[0];if(a.length===0){s.oldLines.push(""),s.newLines.push(""),i+=1;continue}if(l===" "){let u=a.slice(1);s.oldLines.push(u),s.newLines.push(u),i+=1;continue}if(l==="+"){s.newLines.push(a.slice(1)),i+=1;continue}if(l==="-"){s.oldLines.push(a.slice(1)),i+=1;continue}i===0&&Xe(`Unexpected line found in update hunk: '${a}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,e+1);break}return{chunk:s,parsedLines:i+o}}function La(t){return t.trim().replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u00A0\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000]/g," ")}function Ro(t,e,n,r){if(e.length===0)return n;if(e.length>t.length)return null;let o=r&&t.length>=e.length?t.length-e.length:n,s=t.length-e.length;for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(t[i+a]!==e[a]){c=!1;break}if(c)return i}for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(t[i+a].trimEnd()!==e[a].trimEnd()){c=!1;break}if(c)return i}for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(t[i+a].trim()!==e[a].trim()){c=!1;break}if(c)return i}for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(La(t[i+a])!==La(e[a])){c=!1;break}if(c)return i}return null}function hg(t,e,n){let r=[],o=0;for(let s of n){if(typeof s.changeContext=="string"){let l=Ro(t,[s.changeContext],o,!1);if(l===null)throw new Error(`Failed to find context '${s.changeContext}' in ${e}`);o=l+1}if(s.oldLines.length===0){let l=t.length>0&&t[t.length-1]===""?t.length-1:t.length;r.push({startIndex:l,oldLength:0,newLines:[...s.newLines]});continue}let i=[...s.oldLines],c=[...s.newLines],a=Ro(t,i,o,s.isEndOfFile);if(a===null&&i.length>0&&i[i.length-1]===""&&(i=i.slice(0,-1),c.length>0&&c[c.length-1]===""&&(c=c.slice(0,-1)),a=Ro(t,i,o,s.isEndOfFile)),a===null)throw new Error(`Failed to find expected lines in ${e}:
127
+ `,Lt=class extends Error{lineNumber;constructor(e,n){super(e),this.lineNumber=typeof n=="number"?n:null}};function Io(t){throw new Lt(t)}function Xe(t,e){throw new Lt(t,e)}function Vn(t,e){let n=t.trim();return n||Xe("path cannot be empty",e),ag(n)&&Xe(`File references must be relative, NEVER ABSOLUTE: ${n}`,e),n}function $a(t){let e=t[0]?.trim(),n=t[t.length-1]?.trim();e!==Oo&&Io(`The first line of the patch must be '${Oo}'`),n!==ka&&Io(`The last line of the patch must be '${ka}'`)}function pg(t,e){if(t.length<4)throw e;let n=t[0],r=t[t.length-1];if((n==="<<EOF"||n==="<<'EOF'"||n==='<<"EOF"')&&r.endsWith("EOF")){let o=t.slice(1,-1);return $a(o),o}throw e}function dg(t){let e=t.trim().split(/\r?\n/);(e.length===0||!e[0])&&Io(`The first line of the patch must be '${Oo}'`);let n=e;try{$a(n)}catch(i){if(!(i instanceof Lt)||i.lineNumber!==null)throw i;n=pg(e,i)}let r=[],o=n.slice(1,Math.max(n.length-1,1)),s=2;for(;o.length>0;){let i=fg(o,s);r.push(i.hunk),s+=i.parsedLines,o=o.slice(i.parsedLines)}return r}function fg(t,e){let n=t[0].trim();if(n.startsWith(Ea)){let r=Vn(n.slice(Ea.length),e),o="",s=1;for(let i=1;i<t.length;i+=1){let c=t[i];if(c.startsWith("+")){o+=`${c.slice(1)}
128
+ `,s+=1;continue}break}return{hunk:{type:"add",path:r,contents:o},parsedLines:s}}if(n.startsWith(Pa))return{hunk:{type:"delete",path:Vn(n.slice(Pa.length),e)},parsedLines:1};if(n.startsWith(Aa)){let r=Vn(n.slice(Aa.length),e),o=t.slice(1),s=1,i=null,c=o[0]?.startsWith(Ra)?o[0].slice(Ra.length):null;typeof c=="string"&&(i=Vn(c,e+1),o=o.slice(1),s+=1);let a=[];for(;o.length>0;){if(o[0].trim().length===0){o=o.slice(1),s+=1;continue}if(o[0].startsWith("***"))break;let l=mg(o,e+s,a.length===0);a.push(l.chunk),o=o.slice(l.parsedLines),s+=l.parsedLines}return a.length===0&&Xe(`Update file hunk for path '${r}' is empty`,e),{hunk:{type:"update",path:r,movePath:i,chunks:a},parsedLines:s}}Xe(`'${n}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`,e)}function mg(t,e,n){t.length===0&&Xe("Update hunk does not contain any lines",e);let r=null,o=0;t[0]===lg?o=1:t[0].startsWith(Oa)?(r=t[0].slice(Oa.length),o=1):n||Xe(`Expected update hunk to start with a @@ context marker, got: '${t[0]}'`,e),o>=t.length&&Xe("Update hunk does not contain any lines",e+1);let s={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},i=0;for(let c=o;c<t.length;c+=1){let a=t[c];if(a===cg){i===0&&Xe("Update hunk does not contain any lines",e+1),s.isEndOfFile=!0,i+=1;break}let l=a[0];if(a.length===0){s.oldLines.push(""),s.newLines.push(""),i+=1;continue}if(l===" "){let u=a.slice(1);s.oldLines.push(u),s.newLines.push(u),i+=1;continue}if(l==="+"){s.newLines.push(a.slice(1)),i+=1;continue}if(l==="-"){s.oldLines.push(a.slice(1)),i+=1;continue}i===0&&Xe(`Unexpected line found in update hunk: '${a}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,e+1);break}return{chunk:s,parsedLines:i+o}}function La(t){return t.trim().replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u00A0\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000]/g," ")}function Ro(t,e,n,r){if(e.length===0)return n;if(e.length>t.length)return null;let o=r&&t.length>=e.length?t.length-e.length:n,s=t.length-e.length;for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(t[i+a]!==e[a]){c=!1;break}if(c)return i}for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(t[i+a].trimEnd()!==e[a].trimEnd()){c=!1;break}if(c)return i}for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(t[i+a].trim()!==e[a].trim()){c=!1;break}if(c)return i}for(let i=o;i<=s;i+=1){let c=!0;for(let a=0;a<e.length;a+=1)if(La(t[i+a])!==La(e[a])){c=!1;break}if(c)return i}return null}function gg(t,e,n){let r=[],o=0;for(let s of n){if(typeof s.changeContext=="string"){let l=Ro(t,[s.changeContext],o,!1);if(l===null)throw new Error(`Failed to find context '${s.changeContext}' in ${e}`);o=l+1}if(s.oldLines.length===0){let l=t.length>0&&t[t.length-1]===""?t.length-1:t.length;r.push({startIndex:l,oldLength:0,newLines:[...s.newLines]});continue}let i=[...s.oldLines],c=[...s.newLines],a=Ro(t,i,o,s.isEndOfFile);if(a===null&&i.length>0&&i[i.length-1]===""&&(i=i.slice(0,-1),c.length>0&&c[c.length-1]===""&&(c=c.slice(0,-1)),a=Ro(t,i,o,s.isEndOfFile)),a===null)throw new Error(`Failed to find expected lines in ${e}:
129
129
  ${s.oldLines.join(`
130
- `)}`);r.push({startIndex:a,oldLength:i.length,newLines:c}),o=a+i.length}return r.sort((s,i)=>s.startIndex-i.startIndex),r}function yg(t,e){let n=[...t];for(let r=e.length-1;r>=0;r-=1){let o=e[r];n.splice(o.startIndex,o.oldLength,...o.newLines)}return n}function Sg(t,e,n){let r=t.split(`
131
- `);r.length>0&&r[r.length-1]===""&&r.pop();let o=hg(r,e,n),s=yg(r,o);return(s.length===0||s[s.length-1]!=="")&&s.push(""),s.join(`
132
- `)}function Xn(t,e){return rt(Na(t,e))}async function wg(t){let e=rt(t);try{return rt(await Ta(e))}catch(n){if(n.code!=="ENOENT")throw n;let o=[xa(e)],s=Jn(e);for(;;)try{let i=rt(await Ta(s));return rt(Na(i,...o))}catch(i){let c=i.code,a=Jn(s);if(c!=="ENOENT"||a===s)return e;o.unshift(xa(s)),s=a}}}async function Yn(t){let e=await wg(t),n=wa(e);if(n)throw new Error(n);return e}async function _g(t,e){let n=[];for(let r of t){if(r.type==="add"){let a=await Yn(Xn(e,r.path));n.push({type:"add",targetPath:a,displayPath:r.path,content:r.contents});continue}if(r.type==="delete"){let a=await Yn(Xn(e,r.path));try{await va(a,"utf8")}catch(l){throw new Error(`Failed to read ${r.path}: ${l.message}`)}n.push({type:"delete",targetPath:a,displayPath:r.path});continue}let o=await Yn(Xn(e,r.path)),s;try{s=await va(o,"utf8")}catch(a){throw new Error(`Failed to read file to update ${r.path}: ${a.message}`)}let i=Sg(s,r.path,r.chunks),c=r.movePath?await Yn(Xn(e,r.movePath)):o;n.push({type:"update",sourcePath:o,targetPath:c,displayPath:r.movePath??r.path,newContent:i})}return n}async function vg(t){if(t.length===0)throw new Error("No files were modified.");let e=[],n=[],r=[];for(let s of t){if(s.type==="add"){let c=Jn(s.targetPath);c&&await _a(c,{recursive:!0}),await ba(s.targetPath,s.content,"utf8"),e.push(s.displayPath);continue}if(s.type==="delete"){await Ca(s.targetPath),r.push(s.displayPath);continue}let i=Jn(s.targetPath);i&&await _a(i,{recursive:!0}),await ba(s.targetPath,s.newContent,"utf8"),s.targetPath!==s.sourcePath&&await Ca(s.sourcePath),n.push(s.displayPath)}let o=["Success. Updated the following files:"];for(let s of e)o.push(`A ${s}`);for(let s of n)o.push(`M ${s}`);for(let s of r)o.push(`D ${s}`);return o.join(`
133
- `)}function Tg(t){return typeof t.lineNumber=="number"?`Invalid patch hunk on line ${t.lineNumber}: ${t.message}`:`Invalid patch: ${t.message}`}var Da=I({name:"apply_patch",description:pg,inputSchema:Ia,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{let e=Ia.safeParse(t);if(!e.success){let n=e.error.issues[0]?.message??"invalid input";return S(`apply_patch invalid input: ${n}`,!0)}try{let n=fg(e.data.input),r=Fe(),o=await _g(n,r),s=await vg(o);return S(s)}catch(n){return n instanceof Lt?S(Tg(n),!0):S(n.message,!0)}}});import{z as nr}from"zod";import ge from"fs/promises";import st from"path";import{randomBytes as oc}from"crypto";var un=class{diff(e,n,r={}){let o;typeof r=="function"?(o=r,r={}):"callback"in r&&(o=r.callback);let s=this.castInput(e,r),i=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),a=this.removeEmpty(this.tokenize(i,r));return this.diffWithOptionsObj(c,a,r,o)}diffWithOptionsObj(e,n,r,o){var s;let i=h=>{if(h=this.postProcess(h,r),o){setTimeout(function(){o(h)},0);return}else return h},c=n.length,a=e.length,l=1,u=c+a;r.maxEditLength!=null&&(u=Math.min(u,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,d=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(f[0],n,e,0,r);if(f[0].oldPos+1>=a&&g+1>=c)return i(this.buildValues(f[0].lastComponent,n,e));let m=-1/0,_=1/0,A=()=>{for(let h=Math.max(m,-l);h<=Math.min(_,l);h+=2){let x,T=f[h-1],b=f[h+1];T&&(f[h-1]=void 0);let H=!1;if(b){let Se=b.oldPos-h;H=b&&0<=Se&&Se<c}let j=T&&T.oldPos+1<a;if(!H&&!j){f[h]=void 0;continue}if(!j||H&&T.oldPos<b.oldPos?x=this.addToPath(b,!0,!1,0,r):x=this.addToPath(T,!1,!0,1,r),g=this.extractCommon(x,n,e,h,r),x.oldPos+1>=a&&g+1>=c)return i(this.buildValues(x.lastComponent,n,e))||!0;f[h]=x,x.oldPos+1>=a&&(_=Math.min(_,h-1)),g+1>=c&&(m=Math.max(m,h+1))}l++};if(o)(function h(){setTimeout(function(){if(l>u||Date.now()>d)return o(void 0);A()||h()},0)})();else for(;l<=u&&Date.now()<=d;){let h=A();if(h)return h}}addToPath(e,n,r,o,s){let i=e.lastComponent;return i&&!s.oneChangePerToken&&i.added===n&&i.removed===r?{oldPos:e.oldPos+o,lastComponent:{count:i.count+1,added:n,removed:r,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:i}}}extractCommon(e,n,r,o,s){let i=n.length,c=r.length,a=e.oldPos,l=a-o,u=0;for(;l+1<i&&a+1<c&&this.equals(r[a+1],n[l+1],s);)l++,a++,u++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!s.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=a,l}equals(e,n,r){return r.comparator?r.comparator(e,n):e===n||!!r.ignoreCase&&e.toLowerCase()===n.toLowerCase()}removeEmpty(e){let n=[];for(let r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n}castInput(e,n){return e}tokenize(e,n){return Array.from(e)}join(e){return e.join("")}postProcess(e,n){return e}get useLongestToken(){return!1}buildValues(e,n,r){let o=[],s;for(;e;)o.push(e),s=e.previousComponent,delete e.previousComponent,e=s;o.reverse();let i=o.length,c=0,a=0,l=0;for(;c<i;c++){let u=o[c];if(u.removed)u.value=this.join(r.slice(l,l+u.count)),l+=u.count;else{if(!u.added&&this.useLongestToken){let p=n.slice(a,a+u.count);p=p.map(function(d,f){let g=r[l+f];return g.length>d.length?g:d}),u.value=this.join(p)}else u.value=this.join(n.slice(a,a+u.count));a+=u.count,u.added||(l+=u.count)}}return o}};var Lo=class extends un{constructor(){super(...arguments),this.tokenize=bg}equals(e,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!e.includes(`
130
+ `)}`);r.push({startIndex:a,oldLength:i.length,newLines:c}),o=a+i.length}return r.sort((s,i)=>s.startIndex-i.startIndex),r}function hg(t,e){let n=[...t];for(let r=e.length-1;r>=0;r-=1){let o=e[r];n.splice(o.startIndex,o.oldLength,...o.newLines)}return n}function yg(t,e,n){let r=t.split(`
131
+ `);r.length>0&&r[r.length-1]===""&&r.pop();let o=gg(r,e,n),s=hg(r,o);return(s.length===0||s[s.length-1]!=="")&&s.push(""),s.join(`
132
+ `)}function Xn(t,e){return rt(Na(t,e))}async function Sg(t){let e=rt(t);try{return rt(await Ta(e))}catch(n){if(n.code!=="ENOENT")throw n;let o=[xa(e)],s=Jn(e);for(;;)try{let i=rt(await Ta(s));return rt(Na(i,...o))}catch(i){let c=i.code,a=Jn(s);if(c!=="ENOENT"||a===s)return e;o.unshift(xa(s)),s=a}}}async function Yn(t){let e=await Sg(t),n=wa(e);if(n)throw new Error(n);return e}async function wg(t,e){let n=[];for(let r of t){if(r.type==="add"){let a=await Yn(Xn(e,r.path));n.push({type:"add",targetPath:a,displayPath:r.path,content:r.contents});continue}if(r.type==="delete"){let a=await Yn(Xn(e,r.path));try{await va(a,"utf8")}catch(l){throw new Error(`Failed to read ${r.path}: ${l.message}`)}n.push({type:"delete",targetPath:a,displayPath:r.path});continue}let o=await Yn(Xn(e,r.path)),s;try{s=await va(o,"utf8")}catch(a){throw new Error(`Failed to read file to update ${r.path}: ${a.message}`)}let i=yg(s,r.path,r.chunks),c=r.movePath?await Yn(Xn(e,r.movePath)):o;n.push({type:"update",sourcePath:o,targetPath:c,displayPath:r.movePath??r.path,newContent:i})}return n}async function _g(t){if(t.length===0)throw new Error("No files were modified.");let e=[],n=[],r=[];for(let s of t){if(s.type==="add"){let c=Jn(s.targetPath);c&&await _a(c,{recursive:!0}),await ba(s.targetPath,s.content,"utf8"),e.push(s.displayPath);continue}if(s.type==="delete"){await Ca(s.targetPath),r.push(s.displayPath);continue}let i=Jn(s.targetPath);i&&await _a(i,{recursive:!0}),await ba(s.targetPath,s.newContent,"utf8"),s.targetPath!==s.sourcePath&&await Ca(s.sourcePath),n.push(s.displayPath)}let o=["Success. Updated the following files:"];for(let s of e)o.push(`A ${s}`);for(let s of n)o.push(`M ${s}`);for(let s of r)o.push(`D ${s}`);return o.join(`
133
+ `)}function vg(t){return typeof t.lineNumber=="number"?`Invalid patch hunk on line ${t.lineNumber}: ${t.message}`:`Invalid patch: ${t.message}`}var Da=I({name:"apply_patch",description:ug,inputSchema:Ia,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{let e=Ia.safeParse(t);if(!e.success){let n=e.error.issues[0]?.message??"invalid input";return S(`apply_patch invalid input: ${n}`,!0)}try{let n=dg(e.data.input),r=Fe(),o=await wg(n,r),s=await _g(o);return S(s)}catch(n){return n instanceof Lt?S(vg(n),!0):S(n.message,!0)}}});import{z as nr}from"zod";import ge from"fs/promises";import st from"path";import{randomBytes as oc}from"crypto";var un=class{diff(e,n,r={}){let o;typeof r=="function"?(o=r,r={}):"callback"in r&&(o=r.callback);let s=this.castInput(e,r),i=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),a=this.removeEmpty(this.tokenize(i,r));return this.diffWithOptionsObj(c,a,r,o)}diffWithOptionsObj(e,n,r,o){var s;let i=h=>{if(h=this.postProcess(h,r),o){setTimeout(function(){o(h)},0);return}else return h},c=n.length,a=e.length,l=1,u=c+a;r.maxEditLength!=null&&(u=Math.min(u,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,d=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(f[0],n,e,0,r);if(f[0].oldPos+1>=a&&g+1>=c)return i(this.buildValues(f[0].lastComponent,n,e));let m=-1/0,_=1/0,A=()=>{for(let h=Math.max(m,-l);h<=Math.min(_,l);h+=2){let x,T=f[h-1],b=f[h+1];T&&(f[h-1]=void 0);let H=!1;if(b){let Se=b.oldPos-h;H=b&&0<=Se&&Se<c}let j=T&&T.oldPos+1<a;if(!H&&!j){f[h]=void 0;continue}if(!j||H&&T.oldPos<b.oldPos?x=this.addToPath(b,!0,!1,0,r):x=this.addToPath(T,!1,!0,1,r),g=this.extractCommon(x,n,e,h,r),x.oldPos+1>=a&&g+1>=c)return i(this.buildValues(x.lastComponent,n,e))||!0;f[h]=x,x.oldPos+1>=a&&(_=Math.min(_,h-1)),g+1>=c&&(m=Math.max(m,h+1))}l++};if(o)(function h(){setTimeout(function(){if(l>u||Date.now()>d)return o(void 0);A()||h()},0)})();else for(;l<=u&&Date.now()<=d;){let h=A();if(h)return h}}addToPath(e,n,r,o,s){let i=e.lastComponent;return i&&!s.oneChangePerToken&&i.added===n&&i.removed===r?{oldPos:e.oldPos+o,lastComponent:{count:i.count+1,added:n,removed:r,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:i}}}extractCommon(e,n,r,o,s){let i=n.length,c=r.length,a=e.oldPos,l=a-o,u=0;for(;l+1<i&&a+1<c&&this.equals(r[a+1],n[l+1],s);)l++,a++,u++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!s.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=a,l}equals(e,n,r){return r.comparator?r.comparator(e,n):e===n||!!r.ignoreCase&&e.toLowerCase()===n.toLowerCase()}removeEmpty(e){let n=[];for(let r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n}castInput(e,n){return e}tokenize(e,n){return Array.from(e)}join(e){return e.join("")}postProcess(e,n){return e}get useLongestToken(){return!1}buildValues(e,n,r){let o=[],s;for(;e;)o.push(e),s=e.previousComponent,delete e.previousComponent,e=s;o.reverse();let i=o.length,c=0,a=0,l=0;for(;c<i;c++){let u=o[c];if(u.removed)u.value=this.join(r.slice(l,l+u.count)),l+=u.count;else{if(!u.added&&this.useLongestToken){let p=n.slice(a,a+u.count);p=p.map(function(d,f){let g=r[l+f];return g.length>d.length?g:d}),u.value=this.join(p)}else u.value=this.join(n.slice(a,a+u.count));a+=u.count,u.added||(l+=u.count)}}return o}};var Lo=class extends un{constructor(){super(...arguments),this.tokenize=Cg}equals(e,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!e.includes(`
134
134
  `))&&(e=e.trim()),(!r.newlineIsToken||!n.includes(`
135
135
  `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(e.endsWith(`
136
136
  `)&&(e=e.slice(0,-1)),n.endsWith(`
137
- `)&&(n=n.slice(0,-1))),super.equals(e,n,r)}},Cg=new Lo;function No(t,e,n){return Cg.diff(t,e,n)}function bg(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
138
- `));let n=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let o=0;o<r.length;o++){let s=r[o];o%2&&!e.newlineIsToken?n[n.length-1]+=s:n.push(s)}return n}var Fa={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function $o(t,e,n,r,o,s,i){let c;i?typeof i=="function"?c={callback:i}:c=i:c={},typeof c.context>"u"&&(c.context=4);let a=c.context;if(c.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(c.callback){let{callback:u}=c;No(n,r,Object.assign(Object.assign({},c),{callback:p=>{let d=l(p);u(d)}}))}else return l(No(n,r,c));function l(u){if(!u)return;u.push({value:"",lines:[]});function p(h){return h.map(function(x){return" "+x})}let d=[],f=0,g=0,m=[],_=1,A=1;for(let h=0;h<u.length;h++){let x=u[h],T=x.lines||xg(x.value);if(x.lines=T,x.added||x.removed){if(!f){let b=u[h-1];f=_,g=A,b&&(m=a>0?p(b.lines.slice(-a)):[],f-=m.length,g-=m.length)}for(let b of T)m.push((x.added?"+":"-")+b);x.added?A+=T.length:_+=T.length}else{if(f)if(T.length<=a*2&&h<u.length-2)for(let b of p(T))m.push(b);else{let b=Math.min(T.length,a);for(let j of p(T.slice(0,b)))m.push(j);let H={oldStart:f,oldLines:_-f+b,newStart:g,newLines:A-g+b,lines:m};d.push(H),f=0,g=0,m=[]}_+=T.length,A+=T.length}}for(let h of d)for(let x=0;x<h.lines.length;x++)h.lines[x].endsWith(`
137
+ `)&&(n=n.slice(0,-1))),super.equals(e,n,r)}},Tg=new Lo;function No(t,e,n){return Tg.diff(t,e,n)}function Cg(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
138
+ `));let n=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let o=0;o<r.length;o++){let s=r[o];o%2&&!e.newlineIsToken?n[n.length-1]+=s:n.push(s)}return n}var Fa={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function $o(t,e,n,r,o,s,i){let c;i?typeof i=="function"?c={callback:i}:c=i:c={},typeof c.context>"u"&&(c.context=4);let a=c.context;if(c.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(c.callback){let{callback:u}=c;No(n,r,Object.assign(Object.assign({},c),{callback:p=>{let d=l(p);u(d)}}))}else return l(No(n,r,c));function l(u){if(!u)return;u.push({value:"",lines:[]});function p(h){return h.map(function(x){return" "+x})}let d=[],f=0,g=0,m=[],_=1,A=1;for(let h=0;h<u.length;h++){let x=u[h],T=x.lines||bg(x.value);if(x.lines=T,x.added||x.removed){if(!f){let b=u[h-1];f=_,g=A,b&&(m=a>0?p(b.lines.slice(-a)):[],f-=m.length,g-=m.length)}for(let b of T)m.push((x.added?"+":"-")+b);x.added?A+=T.length:_+=T.length}else{if(f)if(T.length<=a*2&&h<u.length-2)for(let b of p(T))m.push(b);else{let b=Math.min(T.length,a);for(let j of p(T.slice(0,b)))m.push(j);let H={oldStart:f,oldLines:_-f+b,newStart:g,newLines:A-g+b,lines:m};d.push(H),f=0,g=0,m=[]}_+=T.length,A+=T.length}}for(let h of d)for(let x=0;x<h.lines.length;x++)h.lines[x].endsWith(`
139
139
  `)?h.lines[x]=h.lines[x].slice(0,-1):(h.lines.splice(x+1,0,"\"),x++);return{oldFileName:t,newFileName:e,oldHeader:o,newHeader:s,hunks:d}}}function Qn(t,e){if(e||(e=Fa),Array.isArray(t)){if(t.length>1&&!e.includeFileHeaders)throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return t.map(r=>Qn(r,e)).join(`
140
140
  `)}let n=[];e.includeIndex&&t.oldFileName==t.newFileName&&n.push("Index: "+t.oldFileName),e.includeUnderline&&n.push("==================================================================="),e.includeFileHeaders&&(n.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),n.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader)));for(let r=0;r<t.hunks.length;r++){let o=t.hunks[r];o.oldLines===0&&(o.oldStart-=1),o.newLines===0&&(o.newStart-=1),n.push("@@ -"+o.oldStart+","+o.oldLines+" +"+o.newStart+","+o.newLines+" @@");for(let s of o.lines)n.push(s)}return n.join(`
141
141
  `)+`
142
- `}function Do(t,e,n,r,o,s,i){if(typeof i=="function"&&(i={callback:i}),i?.callback){let{callback:c}=i;$o(t,e,n,r,o,s,Object.assign(Object.assign({},i),{callback:a=>{c(a?Qn(a,i.headerOptions):void 0)}}))}else{let c=$o(t,e,n,r,o,s,i);return c?Qn(c,i?.headerOptions):void 0}}function xg(t){let e=t.endsWith(`
142
+ `}function Do(t,e,n,r,o,s,i){if(typeof i=="function"&&(i={callback:i}),i?.callback){let{callback:c}=i;$o(t,e,n,r,o,s,Object.assign(Object.assign({},i),{callback:a=>{c(a?Qn(a,i.headerOptions):void 0)}}))}else{let c=$o(t,e,n,r,o,s,i);return c?Qn(c,i?.headerOptions):void 0}}function bg(t){let e=t.endsWith(`
143
143
  `),n=t.split(`
144
144
  `).map(r=>r+`
145
- `);return e?n.pop():n.push(n.pop().slice(0,-1)),n}var Fo=(t,e,n)=>{let r=t instanceof RegExp?Ua(t,n):t,o=e instanceof RegExp?Ua(e,n):e,s=r!==null&&o!=null&&Mg(r,o,n);return s&&{start:s[0],end:s[1],pre:n.slice(0,s[0]),body:n.slice(s[0]+r.length,s[1]),post:n.slice(s[1]+o.length)}},Ua=(t,e)=>{let n=e.match(t);return n?n[0]:null},Mg=(t,e,n)=>{let r,o,s,i,c,a=n.indexOf(t),l=n.indexOf(e,a+1),u=a;if(a>=0&&l>0){if(t===e)return[a,l];for(r=[],s=n.length;u>=0&&!c;){if(u===a)r.push(u),a=n.indexOf(t,u+1);else if(r.length===1){let p=r.pop();p!==void 0&&(c=[p,l])}else o=r.pop(),o!==void 0&&o<s&&(s=o,i=l),l=n.indexOf(e,u+1);u=a<l&&a>=0?a:l}r.length&&i!==void 0&&(c=[s,i])}return c};var Ha="\0SLASH"+Math.random()+"\0",Ba="\0OPEN"+Math.random()+"\0",Ho="\0CLOSE"+Math.random()+"\0",Wa="\0COMMA"+Math.random()+"\0",ja="\0PERIOD"+Math.random()+"\0",kg=new RegExp(Ha,"g"),Eg=new RegExp(Ba,"g"),Pg=new RegExp(Ho,"g"),Ag=new RegExp(Wa,"g"),Rg=new RegExp(ja,"g"),Og=/\\\\/g,Ig=/\\{/g,Lg=/\\}/g,Ng=/\\,/g,$g=/\\./g,Dg=1e5;function Uo(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function Fg(t){return t.replace(Og,Ha).replace(Ig,Ba).replace(Lg,Ho).replace(Ng,Wa).replace($g,ja)}function Ug(t){return t.replace(kg,"\\").replace(Eg,"{").replace(Pg,"}").replace(Ag,",").replace(Rg,".")}function za(t){if(!t)return[""];let e=[],n=Fo("{","}",t);if(!n)return t.split(",");let{pre:r,body:o,post:s}=n,i=r.split(",");i[i.length-1]+="{"+o+"}";let c=za(s);return s.length&&(i[i.length-1]+=c.shift(),i.push.apply(i,c)),e.push.apply(e,i),e}function Ga(t,e={}){if(!t)return[];let{max:n=Dg}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),pn(Fg(t),n,!0).map(Ug)}function Hg(t){return"{"+t+"}"}function Bg(t){return/^-?0\d/.test(t)}function Wg(t,e){return t<=e}function jg(t,e){return t>=e}function pn(t,e,n){let r=[],o=Fo("{","}",t);if(!o)return[t];let s=o.pre,i=o.post.length?pn(o.post,e,!1):[""];if(/\$$/.test(o.pre))for(let c=0;c<i.length&&c<e;c++){let a=s+"{"+o.body+"}"+i[c];r.push(a)}else{let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(o.body),a=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(o.body),l=c||a,u=o.body.indexOf(",")>=0;if(!l&&!u)return o.post.match(/,(?!,).*\}/)?(t=o.pre+"{"+o.body+Ho+o.post,pn(t,e,!0)):[t];let p;if(l)p=o.body.split(/\.\./);else if(p=za(o.body),p.length===1&&p[0]!==void 0&&(p=pn(p[0],e,!1).map(Hg),p.length===1))return i.map(f=>o.pre+p[0]+f);let d;if(l&&p[0]!==void 0&&p[1]!==void 0){let f=Uo(p[0]),g=Uo(p[1]),m=Math.max(p[0].length,p[1].length),_=p.length===3&&p[2]!==void 0?Math.abs(Uo(p[2])):1,A=Wg;g<f&&(_*=-1,A=jg);let x=p.some(Bg);d=[];for(let T=f;A(T,g);T+=_){let b;if(a)b=String.fromCharCode(T),b==="\\"&&(b="");else if(b=String(T),x){let H=m-b.length;if(H>0){let j=new Array(H+1).join("0");T<0?b="-"+j+b.slice(1):b=j+b}}d.push(b)}}else{d=[];for(let f=0;f<p.length;f++)d.push.apply(d,pn(p[f],e,!1))}for(let f=0;f<d.length;f++)for(let g=0;g<i.length&&r.length<e;g++){let m=s+d[f]+i[g];(!n||l||m)&&r.push(m)}}return r}var dn=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")};var zg={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},fn=t=>t.replace(/[[\]\\-]/g,"\\$&"),Gg=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qa=t=>t.join(""),Ka=(t,e)=>{let n=e;if(t.charAt(n)!=="[")throw new Error("not in a brace expression");let r=[],o=[],s=n+1,i=!1,c=!1,a=!1,l=!1,u=n,p="";e:for(;s<t.length;){let m=t.charAt(s);if((m==="!"||m==="^")&&s===n+1){l=!0,s++;continue}if(m==="]"&&i&&!a){u=s+1;break}if(i=!0,m==="\\"&&!a){a=!0,s++;continue}if(m==="["&&!a){for(let[_,[A,h,x]]of Object.entries(zg))if(t.startsWith(_,s)){if(p)return["$.",!1,t.length-n,!0];s+=_.length,x?o.push(A):r.push(A),c=c||h;continue e}}if(a=!1,p){m>p?r.push(fn(p)+"-"+fn(m)):m===p&&r.push(fn(m)),p="",s++;continue}if(t.startsWith("-]",s+1)){r.push(fn(m+"-")),s+=2;continue}if(t.startsWith("-",s+1)){p=m,s+=2;continue}r.push(fn(m)),s++}if(u<s)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,t.length-n,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let m=r[0].length===2?r[0].slice(-1):r[0];return[Gg(m),!1,u-n,!1]}let d="["+(l?"^":"")+qa(r)+"]",f="["+(l?"":"^")+qa(o)+"]";return[r.length&&o.length?"("+d+"|"+f+")":r.length?d:f,c,u-n,!0]};var ot=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!0}={})=>n?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");var qg=new Set(["!","?","+","*","@"]),Va=t=>qg.has(t),Kg="(?!(?:^|/)\\.\\.?(?:$|/))",Zn="(?!\\.)",Vg=new Set(["[","."]),Xg=new Set(["..","."]),Yg=new Set("().*{}+?[]^$\\!"),Jg=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Bo="[^/]",Xa=Bo+"*?",Ya=Bo+"+?",Nt=class t{type;#n;#r;#s=!1;#e=[];#t;#i;#c;#a=!1;#o;#l;#p=!1;constructor(e,n,r={}){this.type=e,e&&(this.#r=!0),this.#t=n,this.#n=this.#t?this.#t.#n:this,this.#o=this.#n===this?r:this.#n.#o,this.#c=this.#n===this?[]:this.#n.#c,e==="!"&&!this.#n.#a&&this.#c.push(this),this.#i=this.#t?this.#t.#e.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#e)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#e.map(e=>String(e)).join("|")+")":this.#l=this.#e.map(e=>String(e)).join("")}#f(){if(this!==this.#n)throw new Error("should only call on root");if(this.#a)return this;this.toString(),this.#a=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let n=e,r=n.#t;for(;r;){for(let o=n.#i+1;!r.type&&o<r.#e.length;o++)for(let s of e.#e){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(r.#e[o])}n=r,r=n.#t}}return this}push(...e){for(let n of e)if(n!==""){if(typeof n!="string"&&!(n instanceof t&&n.#t===this))throw new Error("invalid part: "+n);this.#e.push(n)}}toJSON(){let e=this.type===null?this.#e.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#e.map(n=>n.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#n||this.#n.#a&&this.#t?.type==="!")&&e.push({}),e}isStart(){if(this.#n===this)return!0;if(!this.#t?.isStart())return!1;if(this.#i===0)return!0;let e=this.#t;for(let n=0;n<this.#i;n++){let r=e.#e[n];if(!(r instanceof t&&r.type==="!"))return!1}return!0}isEnd(){if(this.#n===this||this.#t?.type==="!")return!0;if(!this.#t?.isEnd())return!1;if(!this.type)return this.#t?.isEnd();let e=this.#t?this.#t.#e.length:0;return this.#i===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let n=new t(this.type,e);for(let r of this.#e)n.copyIn(r);return n}static#u(e,n,r,o){let s=!1,i=!1,c=-1,a=!1;if(n.type===null){let f=r,g="";for(;f<e.length;){let m=e.charAt(f++);if(s||m==="\\"){s=!s,g+=m;continue}if(i){f===c+1?(m==="^"||m==="!")&&(a=!0):m==="]"&&!(f===c+2&&a)&&(i=!1),g+=m;continue}else if(m==="["){i=!0,c=f,a=!1,g+=m;continue}if(!o.noext&&Va(m)&&e.charAt(f)==="("){n.push(g),g="";let _=new t(m,n);f=t.#u(e,_,f,o),n.push(_);continue}g+=m}return n.push(g),f}let l=r+1,u=new t(null,n),p=[],d="";for(;l<e.length;){let f=e.charAt(l++);if(s||f==="\\"){s=!s,d+=f;continue}if(i){l===c+1?(f==="^"||f==="!")&&(a=!0):f==="]"&&!(l===c+2&&a)&&(i=!1),d+=f;continue}else if(f==="["){i=!0,c=l,a=!1,d+=f;continue}if(Va(f)&&e.charAt(l)==="("){u.push(d),d="";let g=new t(f,u);u.push(g),l=t.#u(e,g,l,o);continue}if(f==="|"){u.push(d),d="",p.push(u),u=new t(null,n);continue}if(f===")")return d===""&&n.#e.length===0&&(n.#p=!0),u.push(d),d="",n.push(...p,u),l;d+=f}return n.type=null,n.#r=void 0,n.#e=[e.substring(r-1)],l}static fromGlob(e,n={}){let r=new t(null,void 0,n);return t.#u(e,r,0,n),r}toMMPattern(){if(this!==this.#n)return this.#n.toMMPattern();let e=this.toString(),[n,r,o,s]=this.toRegExpSource();if(!(o||this.#r||this.#o.nocase&&!this.#o.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let c=(this.#o.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${n}$`,c),{_src:n,_glob:e})}get options(){return this.#o}toRegExpSource(e){let n=e??!!this.#o.dot;if(this.#n===this&&this.#f(),!this.type){let a=this.isStart()&&this.isEnd()&&!this.#e.some(f=>typeof f!="string"),l=this.#e.map(f=>{let[g,m,_,A]=typeof f=="string"?t.#m(f,this.#r,a):f.toRegExpSource(e);return this.#r=this.#r||_,this.#s=this.#s||A,g}).join(""),u="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&Xg.has(this.#e[0]))){let g=Vg,m=n&&g.has(l.charAt(0))||l.startsWith("\\.")&&g.has(l.charAt(2))||l.startsWith("\\.\\.")&&g.has(l.charAt(4)),_=!n&&!e&&g.has(l.charAt(0));u=m?Kg:_?Zn:""}let p="";return this.isEnd()&&this.#n.#a&&this.#t?.type==="!"&&(p="(?:$|\\/)"),[u+l+p,ot(l),this.#r=!!this.#r,this.#s]}let r=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#d(n);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let a=this.toString();return this.#e=[a],this.type=null,this.#r=void 0,[a,ot(this.toString()),!1,!1]}let i=!r||e||n||!Zn?"":this.#d(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let c="";if(this.type==="!"&&this.#p)c=(this.isStart()&&!n?Zn:"")+Ya;else{let a=this.type==="!"?"))"+(this.isStart()&&!n&&!e?Zn:"")+Xa+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;c=o+s+a}return[c,ot(s),this.#r=!!this.#r,this.#s]}#d(e){return this.#e.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");let[r,o,s,i]=n.toRegExpSource(e);return this.#s=this.#s||i,r}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#m(e,n,r=!1){let o=!1,s="",i=!1;for(let c=0;c<e.length;c++){let a=e.charAt(c);if(o){o=!1,s+=(Yg.has(a)?"\\":"")+a;continue}if(a==="\\"){c===e.length-1?s+="\\\\":o=!0;continue}if(a==="["){let[l,u,p,d]=Ka(e,c);if(p){s+=l,i=i||u,c+=p-1,n=n||d;continue}}if(a==="*"){s+=r&&e==="*"?Ya:Xa,n=!0;continue}if(a==="?"){s+=Bo,n=!0;continue}s+=Jg(a)}return[s,ot(e),!!n,i]}};var Wo=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!1}={})=>n?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var te=(t,e,n={})=>(dn(e),!n.nocomment&&e.charAt(0)==="#"?!1:new $t(e,n).match(t)),Qg=/^\*+([^+@!?\*\[\(]*)$/,Zg=t=>e=>!e.startsWith(".")&&e.endsWith(t),eh=t=>e=>e.endsWith(t),th=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),nh=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),rh=/^\*+\.\*+$/,oh=t=>!t.startsWith(".")&&t.includes("."),sh=t=>t!=="."&&t!==".."&&t.includes("."),ih=/^\.\*+$/,ah=t=>t!=="."&&t!==".."&&t.startsWith("."),ch=/^\*+$/,lh=t=>t.length!==0&&!t.startsWith("."),uh=t=>t.length!==0&&t!=="."&&t!=="..",ph=/^\?+([^+@!?\*\[\(]*)?$/,dh=([t,e=""])=>{let n=Za([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},fh=([t,e=""])=>{let n=ec([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},mh=([t,e=""])=>{let n=ec([t]);return e?r=>n(r)&&r.endsWith(e):n},gh=([t,e=""])=>{let n=Za([t]);return e?r=>n(r)&&r.endsWith(e):n},Za=([t])=>{let e=t.length;return n=>n.length===e&&!n.startsWith(".")},ec=([t])=>{let e=t.length;return n=>n.length===e&&n!=="."&&n!==".."},tc=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ja={win32:{sep:"\\"},posix:{sep:"/"}},hh=tc==="win32"?Ja.win32.sep:Ja.posix.sep;te.sep=hh;var Oe=Symbol("globstar **");te.GLOBSTAR=Oe;var yh="[^/]",Sh=yh+"*?",wh="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",_h="(?:(?!(?:\\/|^)\\.).)*?",vh=(t,e={})=>n=>te(n,t,e);te.filter=vh;var Re=(t,e={})=>Object.assign({},t,e),Th=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return te;let e=te;return Object.assign((r,o,s={})=>e(r,o,Re(t,s)),{Minimatch:class extends e.Minimatch{constructor(o,s={}){super(o,Re(t,s))}static defaults(o){return e.defaults(Re(t,o)).Minimatch}},AST:class extends e.AST{constructor(o,s,i={}){super(o,s,Re(t,i))}static fromGlob(o,s={}){return e.AST.fromGlob(o,Re(t,s))}},unescape:(r,o={})=>e.unescape(r,Re(t,o)),escape:(r,o={})=>e.escape(r,Re(t,o)),filter:(r,o={})=>e.filter(r,Re(t,o)),defaults:r=>e.defaults(Re(t,r)),makeRe:(r,o={})=>e.makeRe(r,Re(t,o)),braceExpand:(r,o={})=>e.braceExpand(r,Re(t,o)),match:(r,o,s={})=>e.match(r,o,Re(t,s)),sep:e.sep,GLOBSTAR:Oe})};te.defaults=Th;var nc=(t,e={})=>(dn(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:Ga(t,{max:e.braceExpandMax}));te.braceExpand=nc;var Ch=(t,e={})=>new $t(t,e).makeRe();te.makeRe=Ch;var bh=(t,e,n={})=>{let r=new $t(e,n);return t=t.filter(o=>r.match(o)),r.options.nonull&&!t.length&&t.push(e),t};te.match=bh;var Qa=/[?*]|[+@!]\(.*?\)|\[|\]/,xh=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),$t=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,n={}){dn(e),n=n||{},this.options=n,this.pattern=e,this.platform=n.platform||tc,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let n of e)if(typeof n!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,n=this.options;if(!n.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,i,c)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=s[0]===""&&s[1]===""&&(s[2]==="?"||!Qa.test(s[2]))&&!Qa.test(s[3]),l=/^[a-z]:/i.test(s[0]);if(a)return[...s.slice(0,4),...s.slice(4).map(u=>this.parse(u))];if(l)return[s[0],...s.slice(1).map(u=>this.parse(u))]}return s.map(a=>this.parse(a))});if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let i=this.set[s];i[0]===""&&i[1]===""&&this.globParts[s][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let o=0;o<e[r].length;o++)e[r][o]==="**"&&(e[r][o]="*");let{optimizationLevel:n=1}=this.options;return n>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):n>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(n=>{let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let o=r;for(;n[o+1]==="**";)o++;o!==r&&n.splice(r,o-r)}return n})}levelOneOptimize(e){return e.map(n=>(n=n.reduce((r,o)=>{let s=r[r.length-1];return o==="**"&&s==="**"?r:o===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(r.pop(),r):(r.push(o),r)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let s=e[o];o===1&&s===""&&e[0]===""||(s==="."||s==="")&&(n=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(n=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];o&&o!=="."&&o!==".."&&o!=="**"&&(n=!0,e.splice(r-1,2),r-=2)}}while(n);return e.length===0?[""]:e}firstPhasePreProcess(e){let n=!1;do{n=!1;for(let r of e){let o=-1;for(;(o=r.indexOf("**",o+1))!==-1;){let i=o;for(;r[i+1]==="**";)i++;i>o&&r.splice(o+1,i-o);let c=r[o+1],a=r[o+2],l=r[o+3];if(c!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;n=!0,r.splice(o,1);let u=r.slice(0);u[o]="**",e.push(u),o--}if(!this.preserveMultipleSlashes){for(let i=1;i<r.length-1;i++){let c=r[i];i===1&&c===""&&r[0]===""||(c==="."||c==="")&&(n=!0,r.splice(i,1),i--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(n=!0,r.pop())}let s=0;for(;(s=r.indexOf("..",s+1))!==-1;){let i=r[s-1];if(i&&i!=="."&&i!==".."&&i!=="**"){n=!0;let a=s===1&&r[s+1]==="**"?["."]:[];r.splice(s-1,2,...a),r.length===0&&r.push(""),s-=2}}}}while(n);return e}secondPhasePreProcess(e){for(let n=0;n<e.length-1;n++)for(let r=n+1;r<e.length;r++){let o=this.partsMatch(e[n],e[r],!this.preserveMultipleSlashes);if(o){e[n]=[],e[r]=o;break}}return e.filter(n=>n.length)}partsMatch(e,n,r=!1){let o=0,s=0,i=[],c="";for(;o<e.length&&s<n.length;)if(e[o]===n[s])i.push(c==="b"?n[s]:e[o]),o++,s++;else if(r&&e[o]==="**"&&n[s]===e[o+1])i.push(e[o]),o++;else if(r&&n[s]==="**"&&e[o]===n[s+1])i.push(n[s]),s++;else if(e[o]==="*"&&n[s]&&(this.options.dot||!n[s].startsWith("."))&&n[s]!=="**"){if(c==="b")return!1;c="a",i.push(e[o]),o++,s++}else if(n[s]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(c==="a")return!1;c="b",i.push(n[s]),o++,s++}else return!1;return e.length===n.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,n=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)n=!n,r++;r&&(this.pattern=e.slice(r)),this.negate=n}matchOne(e,n,r=!1){let o=this.options;if(this.isWindows){let m=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),_=!m&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),A=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),h=!A&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),x=_?3:m?0:void 0,T=h?3:A?0:void 0;if(typeof x=="number"&&typeof T=="number"){let[b,H]=[e[x],n[T]];b.toLowerCase()===H.toLowerCase()&&(n[T]=b,T>x?n=n.slice(T):x>T&&(e=e.slice(x)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:n}),this.debug("matchOne",e.length,n.length);for(var i=0,c=0,a=e.length,l=n.length;i<a&&c<l;i++,c++){this.debug("matchOne loop");var u=n[c],p=e[i];if(this.debug(n,u,p),u===!1)return!1;if(u===Oe){this.debug("GLOBSTAR",[n,u,p]);var d=i,f=c+1;if(f===l){for(this.debug("** at the end");i<a;i++)if(e[i]==="."||e[i]===".."||!o.dot&&e[i].charAt(0)===".")return!1;return!0}for(;d<a;){var g=e[d];if(this.debug(`
145
+ `);return e?n.pop():n.push(n.pop().slice(0,-1)),n}var Fo=(t,e,n)=>{let r=t instanceof RegExp?Ua(t,n):t,o=e instanceof RegExp?Ua(e,n):e,s=r!==null&&o!=null&&xg(r,o,n);return s&&{start:s[0],end:s[1],pre:n.slice(0,s[0]),body:n.slice(s[0]+r.length,s[1]),post:n.slice(s[1]+o.length)}},Ua=(t,e)=>{let n=e.match(t);return n?n[0]:null},xg=(t,e,n)=>{let r,o,s,i,c,a=n.indexOf(t),l=n.indexOf(e,a+1),u=a;if(a>=0&&l>0){if(t===e)return[a,l];for(r=[],s=n.length;u>=0&&!c;){if(u===a)r.push(u),a=n.indexOf(t,u+1);else if(r.length===1){let p=r.pop();p!==void 0&&(c=[p,l])}else o=r.pop(),o!==void 0&&o<s&&(s=o,i=l),l=n.indexOf(e,u+1);u=a<l&&a>=0?a:l}r.length&&i!==void 0&&(c=[s,i])}return c};var Ha="\0SLASH"+Math.random()+"\0",Ba="\0OPEN"+Math.random()+"\0",Ho="\0CLOSE"+Math.random()+"\0",Wa="\0COMMA"+Math.random()+"\0",ja="\0PERIOD"+Math.random()+"\0",Mg=new RegExp(Ha,"g"),kg=new RegExp(Ba,"g"),Eg=new RegExp(Ho,"g"),Pg=new RegExp(Wa,"g"),Ag=new RegExp(ja,"g"),Rg=/\\\\/g,Og=/\\{/g,Ig=/\\}/g,Lg=/\\,/g,Ng=/\\./g,$g=1e5;function Uo(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function Dg(t){return t.replace(Rg,Ha).replace(Og,Ba).replace(Ig,Ho).replace(Lg,Wa).replace(Ng,ja)}function Fg(t){return t.replace(Mg,"\\").replace(kg,"{").replace(Eg,"}").replace(Pg,",").replace(Ag,".")}function za(t){if(!t)return[""];let e=[],n=Fo("{","}",t);if(!n)return t.split(",");let{pre:r,body:o,post:s}=n,i=r.split(",");i[i.length-1]+="{"+o+"}";let c=za(s);return s.length&&(i[i.length-1]+=c.shift(),i.push.apply(i,c)),e.push.apply(e,i),e}function Ga(t,e={}){if(!t)return[];let{max:n=$g}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),pn(Dg(t),n,!0).map(Fg)}function Ug(t){return"{"+t+"}"}function Hg(t){return/^-?0\d/.test(t)}function Bg(t,e){return t<=e}function Wg(t,e){return t>=e}function pn(t,e,n){let r=[],o=Fo("{","}",t);if(!o)return[t];let s=o.pre,i=o.post.length?pn(o.post,e,!1):[""];if(/\$$/.test(o.pre))for(let c=0;c<i.length&&c<e;c++){let a=s+"{"+o.body+"}"+i[c];r.push(a)}else{let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(o.body),a=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(o.body),l=c||a,u=o.body.indexOf(",")>=0;if(!l&&!u)return o.post.match(/,(?!,).*\}/)?(t=o.pre+"{"+o.body+Ho+o.post,pn(t,e,!0)):[t];let p;if(l)p=o.body.split(/\.\./);else if(p=za(o.body),p.length===1&&p[0]!==void 0&&(p=pn(p[0],e,!1).map(Ug),p.length===1))return i.map(f=>o.pre+p[0]+f);let d;if(l&&p[0]!==void 0&&p[1]!==void 0){let f=Uo(p[0]),g=Uo(p[1]),m=Math.max(p[0].length,p[1].length),_=p.length===3&&p[2]!==void 0?Math.abs(Uo(p[2])):1,A=Bg;g<f&&(_*=-1,A=Wg);let x=p.some(Hg);d=[];for(let T=f;A(T,g);T+=_){let b;if(a)b=String.fromCharCode(T),b==="\\"&&(b="");else if(b=String(T),x){let H=m-b.length;if(H>0){let j=new Array(H+1).join("0");T<0?b="-"+j+b.slice(1):b=j+b}}d.push(b)}}else{d=[];for(let f=0;f<p.length;f++)d.push.apply(d,pn(p[f],e,!1))}for(let f=0;f<d.length;f++)for(let g=0;g<i.length&&r.length<e;g++){let m=s+d[f]+i[g];(!n||l||m)&&r.push(m)}}return r}var dn=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")};var jg={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},fn=t=>t.replace(/[[\]\\-]/g,"\\$&"),zg=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),qa=t=>t.join(""),Ka=(t,e)=>{let n=e;if(t.charAt(n)!=="[")throw new Error("not in a brace expression");let r=[],o=[],s=n+1,i=!1,c=!1,a=!1,l=!1,u=n,p="";e:for(;s<t.length;){let m=t.charAt(s);if((m==="!"||m==="^")&&s===n+1){l=!0,s++;continue}if(m==="]"&&i&&!a){u=s+1;break}if(i=!0,m==="\\"&&!a){a=!0,s++;continue}if(m==="["&&!a){for(let[_,[A,h,x]]of Object.entries(jg))if(t.startsWith(_,s)){if(p)return["$.",!1,t.length-n,!0];s+=_.length,x?o.push(A):r.push(A),c=c||h;continue e}}if(a=!1,p){m>p?r.push(fn(p)+"-"+fn(m)):m===p&&r.push(fn(m)),p="",s++;continue}if(t.startsWith("-]",s+1)){r.push(fn(m+"-")),s+=2;continue}if(t.startsWith("-",s+1)){p=m,s+=2;continue}r.push(fn(m)),s++}if(u<s)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,t.length-n,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let m=r[0].length===2?r[0].slice(-1):r[0];return[zg(m),!1,u-n,!1]}let d="["+(l?"^":"")+qa(r)+"]",f="["+(l?"":"^")+qa(o)+"]";return[r.length&&o.length?"("+d+"|"+f+")":r.length?d:f,c,u-n,!0]};var ot=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!0}={})=>n?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");var Gg=new Set(["!","?","+","*","@"]),Va=t=>Gg.has(t),qg="(?!(?:^|/)\\.\\.?(?:$|/))",Zn="(?!\\.)",Kg=new Set(["[","."]),Vg=new Set(["..","."]),Xg=new Set("().*{}+?[]^$\\!"),Yg=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Bo="[^/]",Xa=Bo+"*?",Ya=Bo+"+?",Nt=class t{type;#n;#r;#s=!1;#e=[];#t;#i;#c;#a=!1;#o;#l;#p=!1;constructor(e,n,r={}){this.type=e,e&&(this.#r=!0),this.#t=n,this.#n=this.#t?this.#t.#n:this,this.#o=this.#n===this?r:this.#n.#o,this.#c=this.#n===this?[]:this.#n.#c,e==="!"&&!this.#n.#a&&this.#c.push(this),this.#i=this.#t?this.#t.#e.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#e)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#e.map(e=>String(e)).join("|")+")":this.#l=this.#e.map(e=>String(e)).join("")}#f(){if(this!==this.#n)throw new Error("should only call on root");if(this.#a)return this;this.toString(),this.#a=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let n=e,r=n.#t;for(;r;){for(let o=n.#i+1;!r.type&&o<r.#e.length;o++)for(let s of e.#e){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(r.#e[o])}n=r,r=n.#t}}return this}push(...e){for(let n of e)if(n!==""){if(typeof n!="string"&&!(n instanceof t&&n.#t===this))throw new Error("invalid part: "+n);this.#e.push(n)}}toJSON(){let e=this.type===null?this.#e.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#e.map(n=>n.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#n||this.#n.#a&&this.#t?.type==="!")&&e.push({}),e}isStart(){if(this.#n===this)return!0;if(!this.#t?.isStart())return!1;if(this.#i===0)return!0;let e=this.#t;for(let n=0;n<this.#i;n++){let r=e.#e[n];if(!(r instanceof t&&r.type==="!"))return!1}return!0}isEnd(){if(this.#n===this||this.#t?.type==="!")return!0;if(!this.#t?.isEnd())return!1;if(!this.type)return this.#t?.isEnd();let e=this.#t?this.#t.#e.length:0;return this.#i===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let n=new t(this.type,e);for(let r of this.#e)n.copyIn(r);return n}static#u(e,n,r,o){let s=!1,i=!1,c=-1,a=!1;if(n.type===null){let f=r,g="";for(;f<e.length;){let m=e.charAt(f++);if(s||m==="\\"){s=!s,g+=m;continue}if(i){f===c+1?(m==="^"||m==="!")&&(a=!0):m==="]"&&!(f===c+2&&a)&&(i=!1),g+=m;continue}else if(m==="["){i=!0,c=f,a=!1,g+=m;continue}if(!o.noext&&Va(m)&&e.charAt(f)==="("){n.push(g),g="";let _=new t(m,n);f=t.#u(e,_,f,o),n.push(_);continue}g+=m}return n.push(g),f}let l=r+1,u=new t(null,n),p=[],d="";for(;l<e.length;){let f=e.charAt(l++);if(s||f==="\\"){s=!s,d+=f;continue}if(i){l===c+1?(f==="^"||f==="!")&&(a=!0):f==="]"&&!(l===c+2&&a)&&(i=!1),d+=f;continue}else if(f==="["){i=!0,c=l,a=!1,d+=f;continue}if(Va(f)&&e.charAt(l)==="("){u.push(d),d="";let g=new t(f,u);u.push(g),l=t.#u(e,g,l,o);continue}if(f==="|"){u.push(d),d="",p.push(u),u=new t(null,n);continue}if(f===")")return d===""&&n.#e.length===0&&(n.#p=!0),u.push(d),d="",n.push(...p,u),l;d+=f}return n.type=null,n.#r=void 0,n.#e=[e.substring(r-1)],l}static fromGlob(e,n={}){let r=new t(null,void 0,n);return t.#u(e,r,0,n),r}toMMPattern(){if(this!==this.#n)return this.#n.toMMPattern();let e=this.toString(),[n,r,o,s]=this.toRegExpSource();if(!(o||this.#r||this.#o.nocase&&!this.#o.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let c=(this.#o.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${n}$`,c),{_src:n,_glob:e})}get options(){return this.#o}toRegExpSource(e){let n=e??!!this.#o.dot;if(this.#n===this&&this.#f(),!this.type){let a=this.isStart()&&this.isEnd()&&!this.#e.some(f=>typeof f!="string"),l=this.#e.map(f=>{let[g,m,_,A]=typeof f=="string"?t.#m(f,this.#r,a):f.toRegExpSource(e);return this.#r=this.#r||_,this.#s=this.#s||A,g}).join(""),u="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&Vg.has(this.#e[0]))){let g=Kg,m=n&&g.has(l.charAt(0))||l.startsWith("\\.")&&g.has(l.charAt(2))||l.startsWith("\\.\\.")&&g.has(l.charAt(4)),_=!n&&!e&&g.has(l.charAt(0));u=m?qg:_?Zn:""}let p="";return this.isEnd()&&this.#n.#a&&this.#t?.type==="!"&&(p="(?:$|\\/)"),[u+l+p,ot(l),this.#r=!!this.#r,this.#s]}let r=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#d(n);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let a=this.toString();return this.#e=[a],this.type=null,this.#r=void 0,[a,ot(this.toString()),!1,!1]}let i=!r||e||n||!Zn?"":this.#d(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let c="";if(this.type==="!"&&this.#p)c=(this.isStart()&&!n?Zn:"")+Ya;else{let a=this.type==="!"?"))"+(this.isStart()&&!n&&!e?Zn:"")+Xa+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;c=o+s+a}return[c,ot(s),this.#r=!!this.#r,this.#s]}#d(e){return this.#e.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");let[r,o,s,i]=n.toRegExpSource(e);return this.#s=this.#s||i,r}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#m(e,n,r=!1){let o=!1,s="",i=!1;for(let c=0;c<e.length;c++){let a=e.charAt(c);if(o){o=!1,s+=(Xg.has(a)?"\\":"")+a;continue}if(a==="\\"){c===e.length-1?s+="\\\\":o=!0;continue}if(a==="["){let[l,u,p,d]=Ka(e,c);if(p){s+=l,i=i||u,c+=p-1,n=n||d;continue}}if(a==="*"){s+=r&&e==="*"?Ya:Xa,n=!0;continue}if(a==="?"){s+=Bo,n=!0;continue}s+=Yg(a)}return[s,ot(e),!!n,i]}};var Wo=(t,{windowsPathsNoEscape:e=!1,magicalBraces:n=!1}={})=>n?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var te=(t,e,n={})=>(dn(e),!n.nocomment&&e.charAt(0)==="#"?!1:new $t(e,n).match(t)),Jg=/^\*+([^+@!?\*\[\(]*)$/,Qg=t=>e=>!e.startsWith(".")&&e.endsWith(t),Zg=t=>e=>e.endsWith(t),eh=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),th=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),nh=/^\*+\.\*+$/,rh=t=>!t.startsWith(".")&&t.includes("."),oh=t=>t!=="."&&t!==".."&&t.includes("."),sh=/^\.\*+$/,ih=t=>t!=="."&&t!==".."&&t.startsWith("."),ah=/^\*+$/,ch=t=>t.length!==0&&!t.startsWith("."),lh=t=>t.length!==0&&t!=="."&&t!=="..",uh=/^\?+([^+@!?\*\[\(]*)?$/,ph=([t,e=""])=>{let n=Za([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},dh=([t,e=""])=>{let n=ec([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},fh=([t,e=""])=>{let n=ec([t]);return e?r=>n(r)&&r.endsWith(e):n},mh=([t,e=""])=>{let n=Za([t]);return e?r=>n(r)&&r.endsWith(e):n},Za=([t])=>{let e=t.length;return n=>n.length===e&&!n.startsWith(".")},ec=([t])=>{let e=t.length;return n=>n.length===e&&n!=="."&&n!==".."},tc=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ja={win32:{sep:"\\"},posix:{sep:"/"}},gh=tc==="win32"?Ja.win32.sep:Ja.posix.sep;te.sep=gh;var Oe=Symbol("globstar **");te.GLOBSTAR=Oe;var hh="[^/]",yh=hh+"*?",Sh="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",wh="(?:(?!(?:\\/|^)\\.).)*?",_h=(t,e={})=>n=>te(n,t,e);te.filter=_h;var Re=(t,e={})=>Object.assign({},t,e),vh=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return te;let e=te;return Object.assign((r,o,s={})=>e(r,o,Re(t,s)),{Minimatch:class extends e.Minimatch{constructor(o,s={}){super(o,Re(t,s))}static defaults(o){return e.defaults(Re(t,o)).Minimatch}},AST:class extends e.AST{constructor(o,s,i={}){super(o,s,Re(t,i))}static fromGlob(o,s={}){return e.AST.fromGlob(o,Re(t,s))}},unescape:(r,o={})=>e.unescape(r,Re(t,o)),escape:(r,o={})=>e.escape(r,Re(t,o)),filter:(r,o={})=>e.filter(r,Re(t,o)),defaults:r=>e.defaults(Re(t,r)),makeRe:(r,o={})=>e.makeRe(r,Re(t,o)),braceExpand:(r,o={})=>e.braceExpand(r,Re(t,o)),match:(r,o,s={})=>e.match(r,o,Re(t,s)),sep:e.sep,GLOBSTAR:Oe})};te.defaults=vh;var nc=(t,e={})=>(dn(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:Ga(t,{max:e.braceExpandMax}));te.braceExpand=nc;var Th=(t,e={})=>new $t(t,e).makeRe();te.makeRe=Th;var Ch=(t,e,n={})=>{let r=new $t(e,n);return t=t.filter(o=>r.match(o)),r.options.nonull&&!t.length&&t.push(e),t};te.match=Ch;var Qa=/[?*]|[+@!]\(.*?\)|\[|\]/,bh=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),$t=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,n={}){dn(e),n=n||{},this.options=n,this.pattern=e,this.platform=n.platform||tc,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let n of e)if(typeof n!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,n=this.options;if(!n.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,i,c)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=s[0]===""&&s[1]===""&&(s[2]==="?"||!Qa.test(s[2]))&&!Qa.test(s[3]),l=/^[a-z]:/i.test(s[0]);if(a)return[...s.slice(0,4),...s.slice(4).map(u=>this.parse(u))];if(l)return[s[0],...s.slice(1).map(u=>this.parse(u))]}return s.map(a=>this.parse(a))});if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let i=this.set[s];i[0]===""&&i[1]===""&&this.globParts[s][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let o=0;o<e[r].length;o++)e[r][o]==="**"&&(e[r][o]="*");let{optimizationLevel:n=1}=this.options;return n>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):n>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(n=>{let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let o=r;for(;n[o+1]==="**";)o++;o!==r&&n.splice(r,o-r)}return n})}levelOneOptimize(e){return e.map(n=>(n=n.reduce((r,o)=>{let s=r[r.length-1];return o==="**"&&s==="**"?r:o===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(r.pop(),r):(r.push(o),r)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let s=e[o];o===1&&s===""&&e[0]===""||(s==="."||s==="")&&(n=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(n=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];o&&o!=="."&&o!==".."&&o!=="**"&&(n=!0,e.splice(r-1,2),r-=2)}}while(n);return e.length===0?[""]:e}firstPhasePreProcess(e){let n=!1;do{n=!1;for(let r of e){let o=-1;for(;(o=r.indexOf("**",o+1))!==-1;){let i=o;for(;r[i+1]==="**";)i++;i>o&&r.splice(o+1,i-o);let c=r[o+1],a=r[o+2],l=r[o+3];if(c!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;n=!0,r.splice(o,1);let u=r.slice(0);u[o]="**",e.push(u),o--}if(!this.preserveMultipleSlashes){for(let i=1;i<r.length-1;i++){let c=r[i];i===1&&c===""&&r[0]===""||(c==="."||c==="")&&(n=!0,r.splice(i,1),i--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(n=!0,r.pop())}let s=0;for(;(s=r.indexOf("..",s+1))!==-1;){let i=r[s-1];if(i&&i!=="."&&i!==".."&&i!=="**"){n=!0;let a=s===1&&r[s+1]==="**"?["."]:[];r.splice(s-1,2,...a),r.length===0&&r.push(""),s-=2}}}}while(n);return e}secondPhasePreProcess(e){for(let n=0;n<e.length-1;n++)for(let r=n+1;r<e.length;r++){let o=this.partsMatch(e[n],e[r],!this.preserveMultipleSlashes);if(o){e[n]=[],e[r]=o;break}}return e.filter(n=>n.length)}partsMatch(e,n,r=!1){let o=0,s=0,i=[],c="";for(;o<e.length&&s<n.length;)if(e[o]===n[s])i.push(c==="b"?n[s]:e[o]),o++,s++;else if(r&&e[o]==="**"&&n[s]===e[o+1])i.push(e[o]),o++;else if(r&&n[s]==="**"&&e[o]===n[s+1])i.push(n[s]),s++;else if(e[o]==="*"&&n[s]&&(this.options.dot||!n[s].startsWith("."))&&n[s]!=="**"){if(c==="b")return!1;c="a",i.push(e[o]),o++,s++}else if(n[s]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(c==="a")return!1;c="b",i.push(n[s]),o++,s++}else return!1;return e.length===n.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,n=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)n=!n,r++;r&&(this.pattern=e.slice(r)),this.negate=n}matchOne(e,n,r=!1){let o=this.options;if(this.isWindows){let m=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),_=!m&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),A=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),h=!A&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),x=_?3:m?0:void 0,T=h?3:A?0:void 0;if(typeof x=="number"&&typeof T=="number"){let[b,H]=[e[x],n[T]];b.toLowerCase()===H.toLowerCase()&&(n[T]=b,T>x?n=n.slice(T):x>T&&(e=e.slice(x)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:n}),this.debug("matchOne",e.length,n.length);for(var i=0,c=0,a=e.length,l=n.length;i<a&&c<l;i++,c++){this.debug("matchOne loop");var u=n[c],p=e[i];if(this.debug(n,u,p),u===!1)return!1;if(u===Oe){this.debug("GLOBSTAR",[n,u,p]);var d=i,f=c+1;if(f===l){for(this.debug("** at the end");i<a;i++)if(e[i]==="."||e[i]===".."||!o.dot&&e[i].charAt(0)===".")return!1;return!0}for(;d<a;){var g=e[d];if(this.debug(`
146
146
  globstar while`,e,d,n,f,g),this.matchOne(e.slice(d),n.slice(f),r))return this.debug("globstar found match!",d,a,g),!0;if(g==="."||g===".."||!o.dot&&g.charAt(0)==="."){this.debug("dot detected!",e,d,n,f);break}this.debug("globstar swallow a segment, and continue"),d++}return!!(r&&(this.debug(`
147
- >>> no match, partial?`,e,d,n,f),d===a))}let m;if(typeof u=="string"?(m=p===u,this.debug("string match",u,p,m)):(m=u.test(p),this.debug("pattern match",u,p,m)),!m)return!1}if(i===a&&c===l)return!0;if(i===a)return r;if(c===l)return i===a-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return nc(this.pattern,this.options)}parse(e){dn(e);let n=this.options;if(e==="**")return Oe;if(e==="")return"";let r,o=null;(r=e.match(ch))?o=n.dot?uh:lh:(r=e.match(Qg))?o=(n.nocase?n.dot?nh:th:n.dot?eh:Zg)(r[1]):(r=e.match(ph))?o=(n.nocase?n.dot?fh:dh:n.dot?mh:gh)(r):(r=e.match(rh))?o=n.dot?sh:oh:(r=e.match(ih))&&(o=ah);let s=Nt.fromGlob(e,this.options).toMMPattern();return o&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:o}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?Sh:n.dot?wh:_h,o=new Set(n.nocase?["i"]:[]),s=e.map(a=>{let l=a.map(p=>{if(p instanceof RegExp)for(let d of p.flags.split(""))o.add(d);return typeof p=="string"?xh(p):p===Oe?Oe:p._src});l.forEach((p,d)=>{let f=l[d+1],g=l[d-1];p!==Oe||g===Oe||(g===void 0?f!==void 0&&f!==Oe?l[d+1]="(?:\\/|"+r+"\\/)?"+f:l[d]=r:f===void 0?l[d-1]=g+"(?:\\/|\\/"+r+")?":f!==Oe&&(l[d-1]=g+"(?:\\/|\\/"+r+"\\/)"+f,l[d+1]=Oe))});let u=l.filter(p=>p!==Oe);if(this.partial&&u.length>=1){let p=[];for(let d=1;d<=u.length;d++)p.push(u.slice(0,d).join("/"));return"(?:"+p.join("|")+")"}return u.join("/")}).join("|"),[i,c]=e.length>1?["(?:",")"]:["",""];s="^"+i+s+c+"$",this.partial&&(s="^(?:\\/|"+i+s.slice(1,-1)+c+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let i=o[o.length-1];if(!i)for(let c=o.length-2;!i&&c>=0;c--)i=o[c];for(let c=0;c<s.length;c++){let a=s[c],l=o;if(r.matchBase&&a.length===1&&(l=[i]),this.matchOne(l,a,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return te.defaults(e).Minimatch}};te.AST=Nt;te.Minimatch=$t;te.escape=Wo;te.unescape=ot;import rc from"path";import Mh from"os";function kh(t){if(t.startsWith("/mnt/"))return t;if(t.match(/^\/[a-zA-Z]\//)&&process.platform==="win32"){let e=t.charAt(1).toUpperCase(),n=t.slice(2).replace(/\//g,"\\\\");return`${e}:${n}`}return t.match(/^[a-zA-Z]:/)?t.replace(/\//g,"\\\\"):t}function Ye(t){let e=t.trim().replace(/^["']|["']$/g,"");if(e.startsWith("/")&&(e.match(/^\/mnt\/[a-z]\//i)||process.platform!=="win32"||process.platform==="win32"&&!e.match(/^\/[a-zA-Z]\//)))return e.replace(/\/+/g,"/").replace(/(?<!^)\/$/,"")||"/";if(e=kh(e),e.startsWith("\\\\")?e=`\\\\${e.replace(/^\\{2,}/,"\\\\").substring(2).replace(/\\\\/g,"\\")}`:e=e.replace(/\\\\/g,"\\"),e=rc.normalize(e),t.startsWith("\\\\")&&!e.startsWith("\\\\")&&(e=`\\${e}`),e.match(/^[a-zA-Z]:/)){let r=e.replace(/\//g,"\\\\");return/^[a-z]:/.test(r)&&(r=r.charAt(0).toUpperCase()+r.slice(1)),r}return process.platform==="win32"?e.replace(/\//g,"\\\\"):e}function er(t){return t.startsWith("~/")||t==="~"?rc.join(Mh.homedir(),t.slice(1)):t}import Be from"path";function mn(t,e){if(typeof t!="string"||!Array.isArray(e)||!t||e.length===0||t.includes("\0"))return!1;let n;try{n=Be.resolve(Be.normalize(t))}catch{return!1}if(!Be.isAbsolute(n))throw new Error("Path must be absolute after normalization");return e.some(r=>{if(typeof r!="string"||!r||r.includes("\0"))return!1;let o;try{o=Be.resolve(Be.normalize(r))}catch{return!1}if(!Be.isAbsolute(o))throw new Error("Allowed directories must be absolute paths after normalization");if(n===o)return!0;if(o===Be.sep)return n.startsWith(Be.sep);if(Be.sep==="\\"&&o.match(/^[A-Za-z]:\\?$/)){let s=o.charAt(0).toLowerCase();return n.charAt(0).toLowerCase()===s&&n.startsWith(o.replace(/\\?$/,"\\"))}return n.startsWith(o+Be.sep)})}function Dt(t){return t.replace(/\r\n/g,`
148
- `)}function Eh(t,e,n="file"){let r=Dt(t),o=Dt(e);return Do(n,n,r,o,"original","modified")}function Ph(t,e){if(e.length===0)return st.resolve(process.cwd(),t);for(let n of e){let r=st.resolve(n,t),o=Ye(r);if(mn(o,e))return r}return st.resolve(e[0],t)}async function he(t,e){let n=er(t),r=st.isAbsolute(n)?st.resolve(n):Ph(n,e),o=Ye(r);if(!mn(o,e))throw new Error(`Access denied - path outside allowed directories: ${r} not in ${e.join(", ")}`);try{let s=await ge.realpath(r),i=Ye(s);if(!mn(i,e))throw new Error(`Access denied - symlink target outside allowed directories: ${s} not in ${e.join(", ")}`);return s}catch(s){if(s.code==="ENOENT"){let i=st.dirname(r);try{let c=await ge.realpath(i),a=Ye(c);if(!mn(a,e))throw new Error(`Access denied - parent directory outside allowed directories: ${c} not in ${e.join(", ")}`);return r}catch{throw new Error(`Parent directory does not exist: ${i}`)}}throw s}}async function tr(t,e="utf-8"){return await ge.readFile(t,e)}async function sc(t,e){try{await ge.writeFile(t,e,{encoding:"utf-8",flag:"wx"});return}catch(r){if(r.code!=="EEXIST")throw r}let n=`${t}.${oc(16).toString("hex")}.tmp`;try{await ge.writeFile(n,e,"utf-8"),await ge.rename(n,t)}catch(r){try{await ge.unlink(n)}catch{}throw r}}async function ic(t,e,n=!1){let r=Dt(await ge.readFile(t,"utf-8")),o=r;for(let a of e){let l=Dt(a.oldText),u=Dt(a.newText);if(o.includes(l)){o=o.replace(l,u);continue}let p=l.split(`
147
+ >>> no match, partial?`,e,d,n,f),d===a))}let m;if(typeof u=="string"?(m=p===u,this.debug("string match",u,p,m)):(m=u.test(p),this.debug("pattern match",u,p,m)),!m)return!1}if(i===a&&c===l)return!0;if(i===a)return r;if(c===l)return i===a-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return nc(this.pattern,this.options)}parse(e){dn(e);let n=this.options;if(e==="**")return Oe;if(e==="")return"";let r,o=null;(r=e.match(ah))?o=n.dot?lh:ch:(r=e.match(Jg))?o=(n.nocase?n.dot?th:eh:n.dot?Zg:Qg)(r[1]):(r=e.match(uh))?o=(n.nocase?n.dot?dh:ph:n.dot?fh:mh)(r):(r=e.match(nh))?o=n.dot?oh:rh:(r=e.match(sh))&&(o=ih);let s=Nt.fromGlob(e,this.options).toMMPattern();return o&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:o}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?yh:n.dot?Sh:wh,o=new Set(n.nocase?["i"]:[]),s=e.map(a=>{let l=a.map(p=>{if(p instanceof RegExp)for(let d of p.flags.split(""))o.add(d);return typeof p=="string"?bh(p):p===Oe?Oe:p._src});l.forEach((p,d)=>{let f=l[d+1],g=l[d-1];p!==Oe||g===Oe||(g===void 0?f!==void 0&&f!==Oe?l[d+1]="(?:\\/|"+r+"\\/)?"+f:l[d]=r:f===void 0?l[d-1]=g+"(?:\\/|\\/"+r+")?":f!==Oe&&(l[d-1]=g+"(?:\\/|\\/"+r+"\\/)"+f,l[d+1]=Oe))});let u=l.filter(p=>p!==Oe);if(this.partial&&u.length>=1){let p=[];for(let d=1;d<=u.length;d++)p.push(u.slice(0,d).join("/"));return"(?:"+p.join("|")+")"}return u.join("/")}).join("|"),[i,c]=e.length>1?["(?:",")"]:["",""];s="^"+i+s+c+"$",this.partial&&(s="^(?:\\/|"+i+s.slice(1,-1)+c+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let i=o[o.length-1];if(!i)for(let c=o.length-2;!i&&c>=0;c--)i=o[c];for(let c=0;c<s.length;c++){let a=s[c],l=o;if(r.matchBase&&a.length===1&&(l=[i]),this.matchOne(l,a,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return te.defaults(e).Minimatch}};te.AST=Nt;te.Minimatch=$t;te.escape=Wo;te.unescape=ot;import rc from"path";import xh from"os";function Mh(t){if(t.startsWith("/mnt/"))return t;if(t.match(/^\/[a-zA-Z]\//)&&process.platform==="win32"){let e=t.charAt(1).toUpperCase(),n=t.slice(2).replace(/\//g,"\\\\");return`${e}:${n}`}return t.match(/^[a-zA-Z]:/)?t.replace(/\//g,"\\\\"):t}function Ye(t){let e=t.trim().replace(/^["']|["']$/g,"");if(e.startsWith("/")&&(e.match(/^\/mnt\/[a-z]\//i)||process.platform!=="win32"||process.platform==="win32"&&!e.match(/^\/[a-zA-Z]\//)))return e.replace(/\/+/g,"/").replace(/(?<!^)\/$/,"")||"/";if(e=Mh(e),e.startsWith("\\\\")?e=`\\\\${e.replace(/^\\{2,}/,"\\\\").substring(2).replace(/\\\\/g,"\\")}`:e=e.replace(/\\\\/g,"\\"),e=rc.normalize(e),t.startsWith("\\\\")&&!e.startsWith("\\\\")&&(e=`\\${e}`),e.match(/^[a-zA-Z]:/)){let r=e.replace(/\//g,"\\\\");return/^[a-z]:/.test(r)&&(r=r.charAt(0).toUpperCase()+r.slice(1)),r}return process.platform==="win32"?e.replace(/\//g,"\\\\"):e}function er(t){return t.startsWith("~/")||t==="~"?rc.join(xh.homedir(),t.slice(1)):t}import Be from"path";function mn(t,e){if(typeof t!="string"||!Array.isArray(e)||!t||e.length===0||t.includes("\0"))return!1;let n;try{n=Be.resolve(Be.normalize(t))}catch{return!1}if(!Be.isAbsolute(n))throw new Error("Path must be absolute after normalization");return e.some(r=>{if(typeof r!="string"||!r||r.includes("\0"))return!1;let o;try{o=Be.resolve(Be.normalize(r))}catch{return!1}if(!Be.isAbsolute(o))throw new Error("Allowed directories must be absolute paths after normalization");if(n===o)return!0;if(o===Be.sep)return n.startsWith(Be.sep);if(Be.sep==="\\"&&o.match(/^[A-Za-z]:\\?$/)){let s=o.charAt(0).toLowerCase();return n.charAt(0).toLowerCase()===s&&n.startsWith(o.replace(/\\?$/,"\\"))}return n.startsWith(o+Be.sep)})}function Dt(t){return t.replace(/\r\n/g,`
148
+ `)}function kh(t,e,n="file"){let r=Dt(t),o=Dt(e);return Do(n,n,r,o,"original","modified")}function Eh(t,e){if(e.length===0)return st.resolve(process.cwd(),t);for(let n of e){let r=st.resolve(n,t),o=Ye(r);if(mn(o,e))return r}return st.resolve(e[0],t)}async function he(t,e){let n=er(t),r=st.isAbsolute(n)?st.resolve(n):Eh(n,e),o=Ye(r);if(!mn(o,e))throw new Error(`Access denied - path outside allowed directories: ${r} not in ${e.join(", ")}`);try{let s=await ge.realpath(r),i=Ye(s);if(!mn(i,e))throw new Error(`Access denied - symlink target outside allowed directories: ${s} not in ${e.join(", ")}`);return s}catch(s){if(s.code==="ENOENT"){let i=st.dirname(r);try{let c=await ge.realpath(i),a=Ye(c);if(!mn(a,e))throw new Error(`Access denied - parent directory outside allowed directories: ${c} not in ${e.join(", ")}`);return r}catch{throw new Error(`Parent directory does not exist: ${i}`)}}throw s}}async function tr(t,e="utf-8"){return await ge.readFile(t,e)}async function sc(t,e){try{await ge.writeFile(t,e,{encoding:"utf-8",flag:"wx"});return}catch(r){if(r.code!=="EEXIST")throw r}let n=`${t}.${oc(16).toString("hex")}.tmp`;try{await ge.writeFile(n,e,"utf-8"),await ge.rename(n,t)}catch(r){try{await ge.unlink(n)}catch{}throw r}}async function ic(t,e,n=!1){let r=Dt(await ge.readFile(t,"utf-8")),o=r;for(let a of e){let l=Dt(a.oldText),u=Dt(a.newText);if(o.includes(l)){o=o.replace(l,u);continue}let p=l.split(`
149
149
  `),d=o.split(`
150
150
  `),f=!1;for(let g=0;g<=d.length-p.length;g+=1){let m=d.slice(g,g+p.length);if(!p.every((x,T)=>{let b=m[T]??"";return x.trim()===b.trim()}))continue;let A=d[g]?.match(/^\s*/)?.[0]??"",h=u.split(`
151
151
  `).map((x,T)=>{if(T===0)return A+x.trimStart();let b=p[T]?.match(/^\s*/)?.[0]??"",H=x.match(/^\s*/)?.[0]??"";if(b&&H){let j=H.length-b.length;return A+" ".repeat(Math.max(0,j))+x.trimStart()}return x});d.splice(g,p.length,...h),o=d.join(`
152
152
  `),f=!0;break}if(!f)throw new Error(`Could not find exact match for edit:
153
- ${a.oldText}`)}let s=Eh(r,o,t),i=3;for(;s.includes("`".repeat(i));)i+=1;let c=`${"`".repeat(i)}diff
153
+ ${a.oldText}`)}let s=kh(r,o,t),i=3;for(;s.includes("`".repeat(i));)i+=1;let c=`${"`".repeat(i)}diff
154
154
  ${s}${"`".repeat(i)}
155
155
 
156
156
  `;if(!n){let a=`${t}.${oc(16).toString("hex")}.tmp`;try{await ge.writeFile(a,o,"utf-8"),await ge.rename(a,t)}catch(l){try{await ge.unlink(a)}catch{}throw l}}return c}async function ac(t,e){let o=(await ge.stat(t)).size;if(o===0)return"";let s=await ge.open(t,"r");try{let i=[],c=o,a=Buffer.alloc(1024),l=0,u="";for(;c>0&&l<e;){let p=Math.min(1024,c);c-=p;let{bytesRead:d}=await s.read(a,0,p,c);if(!d)break;let g=a.slice(0,d).toString("utf-8")+u,m=Dt(g).split(`
@@ -158,40 +158,40 @@ ${s}${"`".repeat(i)}
158
158
  `)}finally{await s.close()}}async function cc(t,e){let n=await ge.open(t,"r");try{let r=[],o="",s=0,i=Buffer.alloc(1024);for(;r.length<e;){let c=await n.read(i,0,i.length,s);if(c.bytesRead===0)break;s+=c.bytesRead,o+=i.slice(0,c.bytesRead).toString("utf-8");let a=o.lastIndexOf(`
159
159
  `);if(a!==-1){let l=o.slice(0,a).split(`
160
160
  `);o=o.slice(a+1);for(let u of l)if(r.push(u),r.length>=e)break}}return o.length>0&&r.length<e&&r.push(o),r.join(`
161
- `)}finally{await n.close()}}async function lc(t,e,n,r={}){let{excludePatterns:o=[]}=r,s=[];async function i(c){let a=await ge.readdir(c,{withFileTypes:!0});for(let l of a){let u=st.join(c,l.name);try{await he(u,n);let p=st.relative(t,u);if(o.some(f=>te(p,f,{dot:!0})))continue;te(p,e,{dot:!0})&&s.push(u),l.isDirectory()&&await i(u)}catch{continue}}}return await i(t),s}import{promises as uc}from"fs";import pc from"path";var Ah="MEMO_FS_ALLOWED_ROOTS";function Rh(t){return t?.trim()?t.split(",").map(e=>e.trim()).filter(Boolean):[]}async function Oh(t){let e=er(t),n=pc.resolve(e),r=Ye(n);try{let o=await uc.realpath(n),s=Ye(o);return r!==s?[r,s]:[s]}catch{return[r]}}async function Ih(t){let e=[];for(let n of t)try{(await uc.stat(n)).isDirectory()&&e.push(n)}catch{}return e}async function _e(){let t=Fe(),e=Rh(process.env[Ah]),n=[t,...e],r=new Set;for(let i of n){let c=await Oh(i);for(let a of c)r.add(a)}let o=Array.from(r),s=await Ih(o);return s.length>0?s:o.length>0?o:[Ye(pc.resolve(t))]}var Lh=nr.object({path:nr.string().min(1),head:nr.number().int().positive().optional(),tail:nr.number().int().positive().optional()}).strict(),dc=I({name:"read_text_file",description:"Read the complete file content as text, optionally with head/tail line limits.",inputSchema:Lh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{if(t.head&&t.tail)return S("Cannot specify both head and tail parameters simultaneously",!0);try{let e=await _e(),n=await he(t.path,e),r;return t.tail?r=await ac(n,t.tail):t.head?r=await cc(n,t.head):r=await tr(n),S(r)}catch(e){return S(`read_text_file failed: ${e.message}`,!0)}}});import{readFile as Nh}from"fs/promises";import $h from"path";import{z as fc}from"zod";var Dh=fc.object({path:fc.string().min(1)}).strict(),Fh={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac"},mc=I({name:"read_media_file",description:"Read an image or audio file and return base64 payload metadata as JSON text.",inputSchema:Dh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),r=$h.extname(n).toLowerCase(),o=Fh[r]??"application/octet-stream",s=(await Nh(n)).toString("base64"),i=o.startsWith("image/")?"image":o.startsWith("audio/")?"audio":"blob";return S(JSON.stringify({type:i,mimeType:o,data:s}))}catch(e){return S(`read_media_file failed: ${e.message}`,!0)}}});import{z as jo}from"zod";var Uh=jo.object({paths:jo.array(jo.string().min(1)).min(1)}).strict(),gc=I({name:"read_files",description:"Read multiple text files in one call. Per-file failures are returned inline without aborting the batch.",inputSchema:Uh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=[];for(let r of t.paths)try{let o=await he(r,e),s=await tr(o);n.push(`${r}:
161
+ `)}finally{await n.close()}}async function lc(t,e,n,r={}){let{excludePatterns:o=[]}=r,s=[];async function i(c){let a=await ge.readdir(c,{withFileTypes:!0});for(let l of a){let u=st.join(c,l.name);try{await he(u,n);let p=st.relative(t,u);if(o.some(f=>te(p,f,{dot:!0})))continue;te(p,e,{dot:!0})&&s.push(u),l.isDirectory()&&await i(u)}catch{continue}}}return await i(t),s}import{promises as uc}from"fs";import pc from"path";var Ph="MEMO_FS_ALLOWED_ROOTS";function Ah(t){return t?.trim()?t.split(",").map(e=>e.trim()).filter(Boolean):[]}async function Rh(t){let e=er(t),n=pc.resolve(e),r=Ye(n);try{let o=await uc.realpath(n),s=Ye(o);return r!==s?[r,s]:[s]}catch{return[r]}}async function Oh(t){let e=[];for(let n of t)try{(await uc.stat(n)).isDirectory()&&e.push(n)}catch{}return e}async function _e(){let t=Fe(),e=Ah(process.env[Ph]),n=[t,...e],r=new Set;for(let i of n){let c=await Rh(i);for(let a of c)r.add(a)}let o=Array.from(r),s=await Oh(o);return s.length>0?s:o.length>0?o:[Ye(pc.resolve(t))]}var Ih=nr.object({path:nr.string().min(1),head:nr.number().int().positive().optional(),tail:nr.number().int().positive().optional()}).strict(),dc=I({name:"read_text_file",description:"Read the complete file content as text, optionally with head/tail line limits.",inputSchema:Ih,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{if(t.head&&t.tail)return S("Cannot specify both head and tail parameters simultaneously",!0);try{let e=await _e(),n=await he(t.path,e),r;return t.tail?r=await ac(n,t.tail):t.head?r=await cc(n,t.head):r=await tr(n),S(r)}catch(e){return S(`read_text_file failed: ${e.message}`,!0)}}});import{readFile as Lh}from"fs/promises";import Nh from"path";import{z as fc}from"zod";var $h=fc.object({path:fc.string().min(1)}).strict(),Dh={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac"},mc=I({name:"read_media_file",description:"Read an image or audio file and return base64 payload metadata as JSON text.",inputSchema:$h,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),r=Nh.extname(n).toLowerCase(),o=Dh[r]??"application/octet-stream",s=(await Lh(n)).toString("base64"),i=o.startsWith("image/")?"image":o.startsWith("audio/")?"audio":"blob";return S(JSON.stringify({type:i,mimeType:o,data:s}))}catch(e){return S(`read_media_file failed: ${e.message}`,!0)}}});import{z as jo}from"zod";var Fh=jo.object({paths:jo.array(jo.string().min(1)).min(1)}).strict(),gc=I({name:"read_files",description:"Read multiple text files in one call. Per-file failures are returned inline without aborting the batch.",inputSchema:Fh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=[];for(let r of t.paths)try{let o=await he(r,e),s=await tr(o);n.push(`${r}:
162
162
  ${s}
163
163
  `)}catch(o){let s=o instanceof Error?o.message:String(o);n.push(`${r}: Error - ${s}`)}return S(n.join(`
164
164
  ---
165
- `))}catch(e){return S(`read_files failed: ${e.message}`,!0)}}});import{z as zo}from"zod";var Hh=zo.object({path:zo.string().min(1),content:zo.string()}).strict(),hc=I({name:"write_file",description:"Create or overwrite a file with UTF-8 content using atomic replace semantics.",inputSchema:Hh,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await _e(),n=await he(t.path,e);return await sc(n,t.content),S(`Successfully wrote to ${t.path}`)}catch(e){return S(`write_file failed: ${e.message}`,!0)}}});import{z as _t}from"zod";var Bh=_t.object({path:_t.string().min(1),edits:_t.array(_t.object({oldText:_t.string(),newText:_t.string()}).strict()).min(1),dryRun:_t.boolean().optional().default(!1)}).strict(),yc=I({name:"edit_file",description:"Apply ordered edit operations to a text file and return a unified diff (dryRun previews only).",inputSchema:Bh,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),r=await ic(n,t.edits,t.dryRun);return S(r)}catch(e){return S(`edit_file failed: ${e.message}`,!0)}}});import Wh from"fs/promises";import{z as Sc}from"zod";var jh=Sc.object({path:Sc.string().min(1)}).strict(),wc=I({name:"list_directory",description:"List direct children of a directory using [DIR]/[FILE] labels.",inputSchema:jh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),o=(await Wh.readdir(n,{withFileTypes:!0})).map(s=>`${s.isDirectory()?"[DIR]":"[FILE]"} ${s.name}`).join(`
166
- `);return S(o)}catch(e){return S(`list_directory failed: ${e.message}`,!0)}}});import{z as gn}from"zod";var zh=gn.object({path:gn.string().min(1),pattern:gn.string().min(1),excludePatterns:gn.array(gn.string()).optional().default([])}).strict(),_c=I({name:"search_files",description:"Recursively search files and directories by glob pattern within allowed directories.",inputSchema:zh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),r=await lc(n,t.pattern,e,{excludePatterns:t.excludePatterns});return S(r.length>0?r.join(`
167
- `):"No matches found")}catch(e){return S(`search_files failed: ${e.message}`,!0)}}});import{z as Je}from"zod";import{createHash as Gh}from"crypto";import{mkdir as qh,readFile as Kh,rename as Vh,writeFile as Xh}from"fs/promises";import{homedir as Ko}from"os";import{dirname as Yh,join as Yo}from"path";var Jh="mcp.json",or=2,Qh=120,Zh=600*1e3,vc=1440*60*1e3;function Go(){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 ey(t){return t==="~"?Ko():t.startsWith("~/")?Yo(Ko(),t.slice(2)):t}function ty(){let t=process.env.MEMO_HOME?.trim();return t?ey(t):Yo(Ko(),".memo")}function Tc(){return Yo(ty(),"cache",Jh)}function Vo(t){if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>Vo(r)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Vo(e[r])}`).join(",")}}`}function Cc(t){return Gh("sha256").update(Vo(t)).digest("hex")}function ny(t){return t instanceof Error?t.message:String(t)}function rr(){return{version:or,toolsByServer:{},responses:{}}}var Xo=class{data=rr();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>vc&&delete this.data.toolsByServer[n]}async ensureLoaded(){if(!Go()){this.loaded=!0;return}if(!this.loaded){if(this.loadPromise){await this.loadPromise;return}this.loadPromise=(async()=>{let e=Tc();try{let n=await Kh(e,"utf8"),r=JSON.parse(n);if(r.version===or){let o=r;this.data={version:or,toolsByServer:o.toolsByServer??{},responses:o.responses??{}}}else r.version===1&&r.entries?this.data={version:or,toolsByServer:{},responses:r.entries}:this.data=rr()}catch{this.data=rr()}finally{this.pruneExpiredResponses(),this.pruneExpiredTools(),this.loaded=!0}})(),await this.loadPromise}}async persistToDisk(){if(!Go())return;this.pruneExpiredResponses(),this.pruneExpiredTools();let e=Tc(),n=`${e}.tmp`,r=Yh(e);await qh(r,{recursive:!0}),await Xh(n,JSON.stringify(this.data,null,2),"utf8"),await Vh(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(){Go()&&(this.persistRequested=!0,!this.persistTimer&&(this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersistQueue()},Qh),this.persistTimer.unref?.()))}async getServerTools(e,n){await this.ensureLoaded();let r=this.data.toolsByServer[e];if(!r)return null;if(r.configHash!==Cc(n))return delete this.data.toolsByServer[e],this.schedulePersist(),null;let o=Date.now()-r.fetchedAt;return o>vc?(delete this.data.toolsByServer[e],this.schedulePersist(),null):{tools:r.tools,stale:o>Zh,ageMs:o}}async setServerTools(e,n,r){await this.ensureLoaded(),this.data.toolsByServer[e]={fetchedAt:Date.now(),configHash:Cc(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 c=await r();return this.data.responses[e]={expiresAt:Date.now()+n,value:c},this.schedulePersist(),c})();this.responseInflight.set(e,i);try{return await i}catch(c){throw new Error(ny(c))}finally{this.responseInflight.delete(e)}}async flushForTests(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.persistRequested=!0,await this.flushPersistQueue()}resetForTests(){this.data=rr(),this.loaded=!1,this.loadPromise=null,this.responseInflight.clear(),this.persistRequested=!1,this.persistRunning=!1,this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null)}},qo=null;function sr(){return qo||(qo=new Xo),qo}var bc=null,xc=null;function Jo(t){bc=t}function Mc(){return bc}function Qo(t){xc=t}function kc(){return xc}var ry=Je.object({server:Je.string().optional(),cursor:Je.string().optional()}).strict(),oy=Je.object({server:Je.string().optional(),cursor:Je.string().optional()}).strict(),sy=Je.object({server:Je.string().min(1),uri:Je.string().min(1)}).strict(),ir=15e3,iy=6e4;function Zo(){let t=Mc();if(!t)throw new Error("MCP pool is not initialized");return t}function es(){return kc()??sr()}function Ac(t){return t instanceof Error?t.message:String(t)}function Ec(t,e){return`list_resources:${t}:${e??""}`}function Pc(t,e){return`list_resource_templates:${t}:${e??""}`}function ay(t,e){return`read_resource:${t}:${e}`}function ts(t,e){return typeof t.hasServer=="function"?t.hasServer(e):typeof t.get=="function"?!!t.get(e):!1}async function ns(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 Rc(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 c=n[i];c&&o.push({name:c,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 Oc=I({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:ry,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=Zo(),r=es(),o=t?.trim();if(o){if(!ts(n,o))return S(`MCP server not found: ${t}`,!0);let a=await ns(n,o);if(!a)return S(`MCP server not found: ${t}`,!0);let l=await r.withResponseCache(Ec(a.name,e),ir,async()=>{let u=await a.client.listResources(e?{cursor:e}:void 0);return{server:a.name,resources:u.resources,nextCursor:u.nextCursor}});return S(JSON.stringify(l,null,2))}if(e)return S("cursor is only supported when server is specified",!0);let s=await Rc(n),i=`all:${s.map(a=>a.name).join(",")}`,c=await r.withResponseCache(Ec(i),ir,async()=>{let a=await Promise.allSettled(s.map(async p=>{if(!p.client)throw new Error(`MCP server '${p.name}' is not connected`);return{server:p.name,result:await p.client.listResources()}})),l=[],u=[];return a.forEach((p,d)=>{let f=s[d]?.name??"unknown";if(p.status==="rejected"){u.push({server:f,error:Ac(p.reason)});return}for(let g of p.value.result.resources)l.push({server:p.value.server,...g})}),{resources:l,...u.length>0?{errors:u}:{}}});return S(JSON.stringify(c,null,2))}catch(n){return S(`list_mcp_resources failed: ${n.message}`,!0)}}}),Ic=I({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:oy,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=Zo(),r=es(),o=t?.trim();if(o){if(!ts(n,o))return S(`MCP server not found: ${t}`,!0);let a=await ns(n,o);if(!a)return S(`MCP server not found: ${t}`,!0);let l=await r.withResponseCache(Pc(a.name,e),ir,async()=>{let u=await a.client.listResourceTemplates(e?{cursor:e}:void 0);return{server:a.name,resourceTemplates:u.resourceTemplates,nextCursor:u.nextCursor}});return S(JSON.stringify(l,null,2))}if(e)return S("cursor is only supported when server is specified",!0);let s=await Rc(n),i=`all:${s.map(a=>a.name).join(",")}`,c=await r.withResponseCache(Pc(i),ir,async()=>{let a=await Promise.allSettled(s.map(async p=>{if(!p.client)throw new Error(`MCP server '${p.name}' is not connected`);return{server:p.name,result:await p.client.listResourceTemplates()}})),l=[],u=[];return a.forEach((p,d)=>{let f=s[d]?.name??"unknown";if(p.status==="rejected"){u.push({server:f,error:Ac(p.reason)});return}for(let g of p.value.result.resourceTemplates)l.push({server:p.value.server,...g})}),{resourceTemplates:l,...u.length>0?{errors:u}:{}}});return S(JSON.stringify(c,null,2))}catch(n){return S(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Lc=I({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:sy,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let n=Zo(),r=es(),o=t.trim();if(!ts(n,o))return S(`MCP server not found: ${t}`,!0);let s=await ns(n,o);if(!s)return S(`MCP server not found: ${t}`,!0);let i=await r.withResponseCache(ay(o,e),iy,async()=>{let c=await s.client.readResource({uri:e});return{server:o,uri:e,...c}});return S(JSON.stringify(i,null,2))}catch(n){return S(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as Ft}from"zod";var cy=Ft.object({step:Ft.string().min(1),status:Ft.enum(["pending","in_progress","completed"])}).strict(),ly=Ft.object({explanation:Ft.string().optional(),plan:Ft.array(cy).min(1)}).strict(),Nc=[],$c=I({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:ly,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>{if(e.filter(r=>r.status==="in_progress").length>1)return S("At most one step can be in_progress at a time",!0);if(e.length<4){let r=e[0]?.step??"";return S(`<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 Nc=e,S(JSON.stringify({message:"Plan updated",explanation:t,plan:Nc},null,2))}});import{readFile as uy}from"fs/promises";import{homedir as py}from"os";import{join as Dc}from"path";import{z as Fc}from"zod";var dy=Fc.object({memory_id:Fc.string().min(1)}).strict();function fy(){let t=process.env.MEMO_HOME?.trim()||Dc(py(),".memo");return Dc(t,"Agents.md")}var Uc=I({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:dy,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=fy(),n=await uy(e,"utf8");return S(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return S(`memory not found for memory_id=${t}`,!0)}}});import{lookup as my}from"dns/promises";import{isIP as gy}from"net";import{Readability as hy}from"@mozilla/readability";import*as jc from"ipaddr.js";import{JSDOM as yy}from"jsdom";import Sy from"robots-parser";import wy from"turndown";import{ProxyAgent as _y}from"undici";import{z as Ut}from"zod";var vy=Ut.object({url:Ut.string().min(1),max_length:Ut.number().int().positive().lt(1e6).optional(),start_index:Ut.number().int().min(0).optional(),raw:Ut.boolean().optional(),proxy_url:Ut.string().min(1).optional()}).strict(),Ty=new Set(["http:","https:"]),Cy=new Set([301,302,303,307,308]),ar=10,by=1e6,xy="ModelContextProtocol/1.0 (Autonomous; +https://github.com/modelcontextprotocol/servers)",My=3e4,ky=5e6,Ey=5e3,Py=0,Ay=new wy({headingStyle:"atx"});function Hc(t,e){let n=t?.trim();if(!n)return e;let r=Number(n);return!Number.isFinite(r)||r<=0?e:Math.floor(r)}function Bc(t,e){let n=t?.trim().toLowerCase();return n?["1","true","yes","on"].includes(n)?!0:["0","false","no","off"].includes(n)?!1:e:e}function Ry(){return{userAgent:process.env.MEMO_WEBFETCH_USER_AGENT?.trim()||xy,ignoreRobotsTxt:Bc(process.env.MEMO_WEBFETCH_IGNORE_ROBOTS_TXT,!1),timeoutMs:Hc(process.env.MEMO_WEBFETCH_TIMEOUT_MS,My),maxBodyBytes:Hc(process.env.MEMO_WEBFETCH_MAX_BODY_BYTES,ky),blockPrivateNet:Bc(process.env.MEMO_WEBFETCH_BLOCK_PRIVATE_NET,!0)}}function Wc(t){return Ty.has(t.protocol)}function rs(t){let e=jc.parse(t);return e.kind()==="ipv6"?e.range()==="ipv4Mapped"?rs(e.toIPv4Address().toString()):new Set(["uniqueLocal","linkLocal","loopback","unspecified","reserved"]).has(e.range()):new Set(["private","loopback","linkLocal","broadcast","carrierGradeNat","reserved","unspecified"]).has(e.range())}async function Oy(t){let e=t.hostname.trim().toLowerCase();if(!e)throw new Error("URL host is empty");if(e==="localhost"||e.endsWith(".localhost"))throw new Error(`Blocked private or local network host: ${e}`);if(gy(e)){if(rs(e))throw new Error(`Blocked private or local network host: ${e}`);return}let n;try{n=await my(e,{all:!0,verbatim:!0})}catch(o){throw new Error(`Failed to resolve host for private network protection (${e}): ${o.message}`)}let r=Array.isArray(n)?n:[n];if(r.length===0)throw new Error(`Failed to resolve host for private network protection (${e})`);for(let o of r)if(rs(o.address))throw new Error(`Blocked private or local network host: ${e} (resolved to ${o.address})`)}async function Iy(t,e){let n=t.headers.get("content-length"),r=n?Number(n):0;if(r>e)throw new Error(`Request rejected: response body too large (${r} bytes)`);let o=0;if(t.body&&t.body.getReader){let i=t.body.getReader(),c=[];for(;;){let{done:u,value:p}=await i.read();if(u)break;if(p){if(o+=p.byteLength,o>e)throw new Error(`Request aborted: response body exceeds ${e} bytes`);c.push(p)}}let a=new Uint8Array(o),l=0;for(let u of c)a.set(u,l),l+=u.byteLength;return new TextDecoder().decode(a)}let s=await t.text();if(o=new TextEncoder().encode(s).byteLength,o>e)throw new Error(`Request rejected: response body exceeds ${e} bytes`);return s}function Ly(t,e,n){return{method:"GET",redirect:"manual",signal:t,headers:{"User-Agent":e},...n?{dispatcher:n}:{}}}async function zc(t,e){let n=new URL(t.toString());for(let r=0;r<=ar;r+=1){e.blockPrivateNet&&await Oy(n);let o=new AbortController,s=setTimeout(()=>o.abort(),e.timeoutMs),i;try{i=await globalThis.fetch(n,Ly(o.signal,e.userAgent,e.dispatcher))}catch(a){throw a.name==="AbortError"?new Error(`Request timeout or aborted (${e.timeoutMs}ms)`):a}finally{clearTimeout(s)}if(!Cy.has(i.status)){let a=await Iy(i,e.maxBodyBytes);return{response:i,bodyText:a,finalUrl:n}}if(r>=ar)throw new Error(`Too many redirects (max ${ar})`);let c=i.headers.get("location")?.trim();if(!c)throw new Error("Redirect response missing location header");n=new URL(c,n)}throw new Error(`Too many redirects (max ${ar})`)}function Ny(t,e){return/text\/html/i.test(t)||/^\s*<!doctype html/i.test(e)||/^\s*<html[\s>]/i.test(e)}function $y(t,e){let n=new yy(t,{url:e});try{let o=new hy(n.window.document).parse();return o?.content&&Ay.turndown(o.content).trim()||"<error>Page failed to be simplified from HTML</error>"}catch{return"<error>Page failed to be simplified from HTML</error>"}finally{n.window.close()}}function Dy(t){return new URL("/robots.txt",`${t.protocol}//${t.host}`)}async function Fy(t,e){let n=Dy(t),r;try{r=await zc(n,{userAgent:e.userAgent,timeoutMs:e.timeoutMs,maxBodyBytes:by,dispatcher:e.dispatcher,blockPrivateNet:e.blockPrivateNet})}catch(a){throw new Error(`Failed to fetch robots.txt ${n.toString()} due to a connection issue: ${a.message}`)}let o=r.response.status;if(o===401||o===403)throw new Error(`When fetching robots.txt (${n.toString()}), received status ${o} so assuming that autonomous fetching is not allowed, the user can try manually fetching by using the fetch prompt`);if(o>=400&&o<500)return;let s=r.bodyText.split(`
165
+ `))}catch(e){return S(`read_files failed: ${e.message}`,!0)}}});import{z as zo}from"zod";var Uh=zo.object({path:zo.string().min(1),content:zo.string()}).strict(),hc=I({name:"write_file",description:"Create or overwrite a file with UTF-8 content using atomic replace semantics.",inputSchema:Uh,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await _e(),n=await he(t.path,e);return await sc(n,t.content),S(`Successfully wrote to ${t.path}`)}catch(e){return S(`write_file failed: ${e.message}`,!0)}}});import{z as _t}from"zod";var Hh=_t.object({path:_t.string().min(1),edits:_t.array(_t.object({oldText:_t.string(),newText:_t.string()}).strict()).min(1),dryRun:_t.boolean().optional().default(!1)}).strict(),yc=I({name:"edit_file",description:"Apply ordered edit operations to a text file and return a unified diff (dryRun previews only).",inputSchema:Hh,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),r=await ic(n,t.edits,t.dryRun);return S(r)}catch(e){return S(`edit_file failed: ${e.message}`,!0)}}});import Bh from"fs/promises";import{z as Sc}from"zod";var Wh=Sc.object({path:Sc.string().min(1)}).strict(),wc=I({name:"list_directory",description:"List direct children of a directory using [DIR]/[FILE] labels.",inputSchema:Wh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),o=(await Bh.readdir(n,{withFileTypes:!0})).map(s=>`${s.isDirectory()?"[DIR]":"[FILE]"} ${s.name}`).join(`
166
+ `);return S(o)}catch(e){return S(`list_directory failed: ${e.message}`,!0)}}});import{z as gn}from"zod";var jh=gn.object({path:gn.string().min(1),pattern:gn.string().min(1),excludePatterns:gn.array(gn.string()).optional().default([])}).strict(),_c=I({name:"search_files",description:"Recursively search files and directories by glob pattern within allowed directories.",inputSchema:jh,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{try{let e=await _e(),n=await he(t.path,e),r=await lc(n,t.pattern,e,{excludePatterns:t.excludePatterns});return S(r.length>0?r.join(`
167
+ `):"No matches found")}catch(e){return S(`search_files failed: ${e.message}`,!0)}}});import{z as Je}from"zod";import{createHash as zh}from"crypto";import{mkdir as Gh,readFile as qh,rename as Kh,writeFile as Vh}from"fs/promises";import{homedir as Ko}from"os";import{dirname as Xh,join as Yo}from"path";var Yh="mcp.json",or=2,Jh=120,Qh=600*1e3,vc=1440*60*1e3;function Go(){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 Zh(t){return t==="~"?Ko():t.startsWith("~/")?Yo(Ko(),t.slice(2)):t}function ey(){let t=process.env.MEMO_HOME?.trim();return t?Zh(t):Yo(Ko(),".memo")}function Tc(){return Yo(ey(),"cache",Yh)}function Vo(t){if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>Vo(r)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Vo(e[r])}`).join(",")}}`}function Cc(t){return zh("sha256").update(Vo(t)).digest("hex")}function ty(t){return t instanceof Error?t.message:String(t)}function rr(){return{version:or,toolsByServer:{},responses:{}}}var Xo=class{data=rr();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>vc&&delete this.data.toolsByServer[n]}async ensureLoaded(){if(!Go()){this.loaded=!0;return}if(!this.loaded){if(this.loadPromise){await this.loadPromise;return}this.loadPromise=(async()=>{let e=Tc();try{let n=await qh(e,"utf8"),r=JSON.parse(n);if(r.version===or){let o=r;this.data={version:or,toolsByServer:o.toolsByServer??{},responses:o.responses??{}}}else r.version===1&&r.entries?this.data={version:or,toolsByServer:{},responses:r.entries}:this.data=rr()}catch{this.data=rr()}finally{this.pruneExpiredResponses(),this.pruneExpiredTools(),this.loaded=!0}})(),await this.loadPromise}}async persistToDisk(){if(!Go())return;this.pruneExpiredResponses(),this.pruneExpiredTools();let e=Tc(),n=`${e}.tmp`,r=Xh(e);await Gh(r,{recursive:!0}),await Vh(n,JSON.stringify(this.data,null,2),"utf8"),await Kh(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(){Go()&&(this.persistRequested=!0,!this.persistTimer&&(this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersistQueue()},Jh),this.persistTimer.unref?.()))}async getServerTools(e,n){await this.ensureLoaded();let r=this.data.toolsByServer[e];if(!r)return null;if(r.configHash!==Cc(n))return delete this.data.toolsByServer[e],this.schedulePersist(),null;let o=Date.now()-r.fetchedAt;return o>vc?(delete this.data.toolsByServer[e],this.schedulePersist(),null):{tools:r.tools,stale:o>Qh,ageMs:o}}async setServerTools(e,n,r){await this.ensureLoaded(),this.data.toolsByServer[e]={fetchedAt:Date.now(),configHash:Cc(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 c=await r();return this.data.responses[e]={expiresAt:Date.now()+n,value:c},this.schedulePersist(),c})();this.responseInflight.set(e,i);try{return await i}catch(c){throw new Error(ty(c))}finally{this.responseInflight.delete(e)}}async flushForTests(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.persistRequested=!0,await this.flushPersistQueue()}resetForTests(){this.data=rr(),this.loaded=!1,this.loadPromise=null,this.responseInflight.clear(),this.persistRequested=!1,this.persistRunning=!1,this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null)}},qo=null;function sr(){return qo||(qo=new Xo),qo}var bc=null,xc=null;function Jo(t){bc=t}function Mc(){return bc}function Qo(t){xc=t}function kc(){return xc}var ny=Je.object({server:Je.string().optional(),cursor:Je.string().optional()}).strict(),ry=Je.object({server:Je.string().optional(),cursor:Je.string().optional()}).strict(),oy=Je.object({server:Je.string().min(1),uri:Je.string().min(1)}).strict(),ir=15e3,sy=6e4;function Zo(){let t=Mc();if(!t)throw new Error("MCP pool is not initialized");return t}function es(){return kc()??sr()}function Ac(t){return t instanceof Error?t.message:String(t)}function Ec(t,e){return`list_resources:${t}:${e??""}`}function Pc(t,e){return`list_resource_templates:${t}:${e??""}`}function iy(t,e){return`read_resource:${t}:${e}`}function ts(t,e){return typeof t.hasServer=="function"?t.hasServer(e):typeof t.get=="function"?!!t.get(e):!1}async function ns(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 Rc(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 c=n[i];c&&o.push({name:c,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 Oc=I({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:ny,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=Zo(),r=es(),o=t?.trim();if(o){if(!ts(n,o))return S(`MCP server not found: ${t}`,!0);let a=await ns(n,o);if(!a)return S(`MCP server not found: ${t}`,!0);let l=await r.withResponseCache(Ec(a.name,e),ir,async()=>{let u=await a.client.listResources(e?{cursor:e}:void 0);return{server:a.name,resources:u.resources,nextCursor:u.nextCursor}});return S(JSON.stringify(l,null,2))}if(e)return S("cursor is only supported when server is specified",!0);let s=await Rc(n),i=`all:${s.map(a=>a.name).join(",")}`,c=await r.withResponseCache(Ec(i),ir,async()=>{let a=await Promise.allSettled(s.map(async p=>{if(!p.client)throw new Error(`MCP server '${p.name}' is not connected`);return{server:p.name,result:await p.client.listResources()}})),l=[],u=[];return a.forEach((p,d)=>{let f=s[d]?.name??"unknown";if(p.status==="rejected"){u.push({server:f,error:Ac(p.reason)});return}for(let g of p.value.result.resources)l.push({server:p.value.server,...g})}),{resources:l,...u.length>0?{errors:u}:{}}});return S(JSON.stringify(c,null,2))}catch(n){return S(`list_mcp_resources failed: ${n.message}`,!0)}}}),Ic=I({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:ry,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=Zo(),r=es(),o=t?.trim();if(o){if(!ts(n,o))return S(`MCP server not found: ${t}`,!0);let a=await ns(n,o);if(!a)return S(`MCP server not found: ${t}`,!0);let l=await r.withResponseCache(Pc(a.name,e),ir,async()=>{let u=await a.client.listResourceTemplates(e?{cursor:e}:void 0);return{server:a.name,resourceTemplates:u.resourceTemplates,nextCursor:u.nextCursor}});return S(JSON.stringify(l,null,2))}if(e)return S("cursor is only supported when server is specified",!0);let s=await Rc(n),i=`all:${s.map(a=>a.name).join(",")}`,c=await r.withResponseCache(Pc(i),ir,async()=>{let a=await Promise.allSettled(s.map(async p=>{if(!p.client)throw new Error(`MCP server '${p.name}' is not connected`);return{server:p.name,result:await p.client.listResourceTemplates()}})),l=[],u=[];return a.forEach((p,d)=>{let f=s[d]?.name??"unknown";if(p.status==="rejected"){u.push({server:f,error:Ac(p.reason)});return}for(let g of p.value.result.resourceTemplates)l.push({server:p.value.server,...g})}),{resourceTemplates:l,...u.length>0?{errors:u}:{}}});return S(JSON.stringify(c,null,2))}catch(n){return S(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Lc=I({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:oy,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let n=Zo(),r=es(),o=t.trim();if(!ts(n,o))return S(`MCP server not found: ${t}`,!0);let s=await ns(n,o);if(!s)return S(`MCP server not found: ${t}`,!0);let i=await r.withResponseCache(iy(o,e),sy,async()=>{let c=await s.client.readResource({uri:e});return{server:o,uri:e,...c}});return S(JSON.stringify(i,null,2))}catch(n){return S(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as Ft}from"zod";var ay=Ft.object({step:Ft.string().min(1),status:Ft.enum(["pending","in_progress","completed"])}).strict(),cy=Ft.object({explanation:Ft.string().optional(),plan:Ft.array(ay).min(1)}).strict(),Nc=[],$c=I({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:cy,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>{if(e.filter(r=>r.status==="in_progress").length>1)return S("At most one step can be in_progress at a time",!0);if(e.length<4){let r=e[0]?.step??"";return S(`<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 Nc=e,S(JSON.stringify({message:"Plan updated",explanation:t,plan:Nc},null,2))}});import{readFile as ly}from"fs/promises";import{homedir as uy}from"os";import{join as Dc}from"path";import{z as Fc}from"zod";var py=Fc.object({memory_id:Fc.string().min(1)}).strict();function dy(){let t=process.env.MEMO_HOME?.trim()||Dc(uy(),".memo");return Dc(t,"Agents.md")}var Uc=I({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:py,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=dy(),n=await ly(e,"utf8");return S(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return S(`memory not found for memory_id=${t}`,!0)}}});import{lookup as fy}from"dns/promises";import{isIP as my}from"net";import{Readability as gy}from"@mozilla/readability";import hy from"ipaddr.js";import{JSDOM as yy}from"jsdom";import Sy from"robots-parser";import wy from"turndown";import{ProxyAgent as _y}from"undici";import{z as Ut}from"zod";var vy=Ut.object({url:Ut.string().min(1),max_length:Ut.number().int().positive().lt(1e6).optional(),start_index:Ut.number().int().min(0).optional(),raw:Ut.boolean().optional(),proxy_url:Ut.string().min(1).optional()}).strict(),Ty=new Set(["http:","https:"]),Cy=new Set([301,302,303,307,308]),ar=10,by=1e6,xy="ModelContextProtocol/1.0 (Autonomous; +https://github.com/modelcontextprotocol/servers)",My=3e4,ky=5e6,Ey=5e3,Py=0,Ay=new wy({headingStyle:"atx"});function Hc(t,e){let n=t?.trim();if(!n)return e;let r=Number(n);return!Number.isFinite(r)||r<=0?e:Math.floor(r)}function Bc(t,e){let n=t?.trim().toLowerCase();return n?["1","true","yes","on"].includes(n)?!0:["0","false","no","off"].includes(n)?!1:e:e}function Ry(){return{userAgent:process.env.MEMO_WEBFETCH_USER_AGENT?.trim()||xy,ignoreRobotsTxt:Bc(process.env.MEMO_WEBFETCH_IGNORE_ROBOTS_TXT,!1),timeoutMs:Hc(process.env.MEMO_WEBFETCH_TIMEOUT_MS,My),maxBodyBytes:Hc(process.env.MEMO_WEBFETCH_MAX_BODY_BYTES,ky),blockPrivateNet:Bc(process.env.MEMO_WEBFETCH_BLOCK_PRIVATE_NET,!0)}}function Wc(t){return Ty.has(t.protocol)}function rs(t){let e=hy.parse(t);return e.kind()==="ipv6"?e.range()==="ipv4Mapped"?rs(e.toIPv4Address().toString()):new Set(["uniqueLocal","linkLocal","loopback","unspecified","reserved"]).has(e.range()):new Set(["private","loopback","linkLocal","broadcast","carrierGradeNat","reserved","unspecified"]).has(e.range())}async function Oy(t){let e=t.hostname.trim().toLowerCase();if(!e)throw new Error("URL host is empty");if(e==="localhost"||e.endsWith(".localhost"))throw new Error(`Blocked private or local network host: ${e}`);if(my(e)){if(rs(e))throw new Error(`Blocked private or local network host: ${e}`);return}let n;try{n=await fy(e,{all:!0,verbatim:!0})}catch(o){throw new Error(`Failed to resolve host for private network protection (${e}): ${o.message}`)}let r=Array.isArray(n)?n:[n];if(r.length===0)throw new Error(`Failed to resolve host for private network protection (${e})`);for(let o of r)if(rs(o.address))throw new Error(`Blocked private or local network host: ${e} (resolved to ${o.address})`)}async function Iy(t,e){let n=t.headers.get("content-length"),r=n?Number(n):0;if(r>e)throw new Error(`Request rejected: response body too large (${r} bytes)`);let o=0;if(t.body&&t.body.getReader){let i=t.body.getReader(),c=[];for(;;){let{done:u,value:p}=await i.read();if(u)break;if(p){if(o+=p.byteLength,o>e)throw new Error(`Request aborted: response body exceeds ${e} bytes`);c.push(p)}}let a=new Uint8Array(o),l=0;for(let u of c)a.set(u,l),l+=u.byteLength;return new TextDecoder().decode(a)}let s=await t.text();if(o=new TextEncoder().encode(s).byteLength,o>e)throw new Error(`Request rejected: response body exceeds ${e} bytes`);return s}function Ly(t,e,n){return{method:"GET",redirect:"manual",signal:t,headers:{"User-Agent":e},...n?{dispatcher:n}:{}}}async function jc(t,e){let n=new URL(t.toString());for(let r=0;r<=ar;r+=1){e.blockPrivateNet&&await Oy(n);let o=new AbortController,s=setTimeout(()=>o.abort(),e.timeoutMs),i;try{i=await globalThis.fetch(n,Ly(o.signal,e.userAgent,e.dispatcher))}catch(a){throw a.name==="AbortError"?new Error(`Request timeout or aborted (${e.timeoutMs}ms)`):a}finally{clearTimeout(s)}if(!Cy.has(i.status)){let a=await Iy(i,e.maxBodyBytes);return{response:i,bodyText:a,finalUrl:n}}if(r>=ar)throw new Error(`Too many redirects (max ${ar})`);let c=i.headers.get("location")?.trim();if(!c)throw new Error("Redirect response missing location header");n=new URL(c,n)}throw new Error(`Too many redirects (max ${ar})`)}function Ny(t,e){return/text\/html/i.test(t)||/^\s*<!doctype html/i.test(e)||/^\s*<html[\s>]/i.test(e)}function $y(t,e){let n=new yy(t,{url:e});try{let o=new gy(n.window.document).parse();return o?.content&&Ay.turndown(o.content).trim()||"<error>Page failed to be simplified from HTML</error>"}catch{return"<error>Page failed to be simplified from HTML</error>"}finally{n.window.close()}}function Dy(t){return new URL("/robots.txt",`${t.protocol}//${t.host}`)}async function Fy(t,e){let n=Dy(t),r;try{r=await jc(n,{userAgent:e.userAgent,timeoutMs:e.timeoutMs,maxBodyBytes:by,dispatcher:e.dispatcher,blockPrivateNet:e.blockPrivateNet})}catch(a){throw new Error(`Failed to fetch robots.txt ${n.toString()} due to a connection issue: ${a.message}`)}let o=r.response.status;if(o===401||o===403)throw new Error(`When fetching robots.txt (${n.toString()}), received status ${o} so assuming that autonomous fetching is not allowed, the user can try manually fetching by using the fetch prompt`);if(o>=400&&o<500)return;let s=r.bodyText.split(`
168
168
  `).filter(a=>!a.trim().startsWith("#")).join(`
169
169
  `);if(Sy(n.toString(),s).isAllowed(t.toString(),e.userAgent)===!1)throw new Error(`The site's robots.txt (${n.toString()}) specifies that autonomous fetching of this page is not allowed.`)}function Uy(t,e,n){let r=t.length;if(e>=r)return"<error>No more content available.</error>";let o=t.slice(e,e+n);if(!o)return"<error>No more content available.</error>";let s=o,i=o.length,c=r-(e+i);if(i===n&&c>0){let a=e+i;s+=`
170
170
 
171
- <error>Content truncated. Call the webfetch tool with a start_index of ${a} to get more content.</error>`}return s}function Hy(t){if(t)return new _y(t.toString())}function By(t){t&&typeof t.destroy=="function"&&t.destroy()}var Gc=I({name:"webfetch",description:"Fetch a URL, optionally simplify HTML to markdown, and return paged content with robots-aware policy checks.",inputSchema:vy,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return S(`Invalid URL: ${t.url}`,!0)}if(!Wc(e))return S(`Unsupported protocol: ${e.protocol}`,!0);let n=null;if(t.proxy_url){try{n=new URL(t.proxy_url)}catch{return S(`Invalid proxy URL: ${t.proxy_url}`,!0)}if(!Wc(n))return S(`Unsupported proxy protocol: ${n.protocol}`,!0)}let r=t.max_length??Ey,o=t.start_index??Py,s=Ry(),i=Hy(n);try{s.ignoreRobotsTxt||await Fy(e,{userAgent:s.userAgent,timeoutMs:s.timeoutMs,dispatcher:i,blockPrivateNet:s.blockPrivateNet});let c=await zc(e,{userAgent:s.userAgent,timeoutMs:s.timeoutMs,maxBodyBytes:s.maxBodyBytes,dispatcher:i,blockPrivateNet:s.blockPrivateNet});if(c.response.status>=400)return S(`Failed to fetch ${e.toString()} - status code ${c.response.status}`,!0);let a=c.response.headers.get("content-type")||"",l=Ny(a,c.bodyText),u=l&&!t.raw?$y(c.bodyText,c.finalUrl.toString()):c.bodyText,p=l&&!t.raw?"":`Content type ${a} cannot be simplified to markdown, but here is the raw content:
171
+ <error>Content truncated. Call the webfetch tool with a start_index of ${a} to get more content.</error>`}return s}function Hy(t){if(t)return new _y(t.toString())}function By(t){t&&typeof t.destroy=="function"&&t.destroy()}var zc=I({name:"webfetch",description:"Fetch a URL, optionally simplify HTML to markdown, and return paged content with robots-aware policy checks.",inputSchema:vy,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return S(`Invalid URL: ${t.url}`,!0)}if(!Wc(e))return S(`Unsupported protocol: ${e.protocol}`,!0);let n=null;if(t.proxy_url){try{n=new URL(t.proxy_url)}catch{return S(`Invalid proxy URL: ${t.proxy_url}`,!0)}if(!Wc(n))return S(`Unsupported proxy protocol: ${n.protocol}`,!0)}let r=t.max_length??Ey,o=t.start_index??Py,s=Ry(),i=Hy(n);try{s.ignoreRobotsTxt||await Fy(e,{userAgent:s.userAgent,timeoutMs:s.timeoutMs,dispatcher:i,blockPrivateNet:s.blockPrivateNet});let c=await jc(e,{userAgent:s.userAgent,timeoutMs:s.timeoutMs,maxBodyBytes:s.maxBodyBytes,dispatcher:i,blockPrivateNet:s.blockPrivateNet});if(c.response.status>=400)return S(`Failed to fetch ${e.toString()} - status code ${c.response.status}`,!0);let a=c.response.headers.get("content-type")||"",l=Ny(a,c.bodyText),u=l&&!t.raw?$y(c.bodyText,c.finalUrl.toString()):c.bodyText,p=l&&!t.raw?"":`Content type ${a} cannot be simplified to markdown, but here is the raw content:
172
172
  `,d=Uy(u,o,r);return S(`${p}Contents of ${e.toString()}:
173
- ${d}`)}catch(c){return S(`Request failed: ${c.message}`,!0)}finally{By(i)}}});import{spawn as Wy}from"child_process";import{existsSync as jy}from"fs";import{resolve as zy}from"path";import{z as ye}from"zod";var Gy=3e4,qy=1e4,Ky=3e5,qc=4,Vy=1500,Kc=2e3,it=new Map,Xy=ye.object({message:ye.string().min(1),agent_type:ye.string().optional()}).strict(),Yy=ye.object({id:ye.string().min(1),message:ye.string().min(1),interrupt:ye.boolean().optional()}).strict(),Jy=ye.object({id:ye.string().min(1)}).strict(),Qy=ye.object({ids:ye.array(ye.string().min(1)).min(1),timeout_ms:ye.number().int().positive().optional()}).strict(),Zy=ye.object({id:ye.string().min(1)}).strict();function Ht(){return new Date().toISOString()}function os(t){return S(`agent not found: ${t}`,!0)}function eS(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return qc;let e=Number(t);return!Number.isFinite(e)||e<=0?qc:Math.floor(e)}function tS(){let t=0;for(let e of it.values())e.running&&(t+=1);return t}function nS(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=zy(Fe(),"dist/index.js");return jy(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function rS(t){return t!=="running"}function oS(t){return new Promise(e=>{setTimeout(e,t)})}function sS(t){return t===void 0?Gy:t<=0?null:Math.max(qy,Math.min(Ky,t))}function iS(t){return t.length<=Kc?t:`${t.slice(0,Kc)}
173
+ ${d}`)}catch(c){return S(`Request failed: ${c.message}`,!0)}finally{By(i)}}});import{spawn as Wy}from"child_process";import{existsSync as jy}from"fs";import{resolve as zy}from"path";import{z as ye}from"zod";var Gy=3e4,qy=1e4,Ky=3e5,Gc=4,Vy=1500,qc=2e3,it=new Map,Xy=ye.object({message:ye.string().min(1),agent_type:ye.string().optional()}).strict(),Yy=ye.object({id:ye.string().min(1),message:ye.string().min(1),interrupt:ye.boolean().optional()}).strict(),Jy=ye.object({id:ye.string().min(1)}).strict(),Qy=ye.object({ids:ye.array(ye.string().min(1)).min(1),timeout_ms:ye.number().int().positive().optional()}).strict(),Zy=ye.object({id:ye.string().min(1)}).strict();function Ht(){return new Date().toISOString()}function os(t){return S(`agent not found: ${t}`,!0)}function eS(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return Gc;let e=Number(t);return!Number.isFinite(e)||e<=0?Gc:Math.floor(e)}function tS(){let t=0;for(let e of it.values())e.running&&(t+=1);return t}function nS(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=zy(Fe(),"dist/index.js");return jy(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function rS(t){return t!=="running"}function oS(t){return new Promise(e=>{setTimeout(e,t)})}function sS(t){return t===void 0?Gy:t<=0?null:Math.max(qy,Math.min(Ky,t))}function iS(t){return t.length<=qc?t:`${t.slice(0,qc)}
174
174
  ...[truncated]`}function aS(t,e){let n=[],r=t.trim(),o=e.trim();return r&&n.push(r),o&&n.push(`stderr:
175
175
  ${o}`),iS(n.join(`
176
176
 
177
- `))}async function Vc(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()}},Vy);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function cS(t){let e=it.get(t);return e?e.status:"not_found"}function lS(t){let e=it.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 uS(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 pS(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=Ht(),e.lastOutput=aS(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 Xc(t,e){let n=eS();if(tS()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=nS(),s=Wy(o,{cwd:Fe(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],c=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",a=>i.push(a)),s.stderr?.on("data",a=>c.push(a)),s.on("error",a=>{c.push(`[spawn error] ${a.message}`)}),t.running={id:r,message:e,process:s,startedAt:Ht(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=r,t.updatedAt=Ht(),s.on("close",a=>{let l=typeof a=="number"?a:-1,u=!!(t.running?.id===r&&t.running.interrupted);pS({record:t,submissionId:r,stdout:i.join(""),stderr:c.join(""),exitCode:l,interrupted:u})});try{s.stdin?.write(`${e.trim()}
178
- `)}catch{}try{s.stdin?.end()}catch{}return r}var Yc=I({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:Xy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return S("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=Ht(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:e,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};it.set(n,o);try{let s=await Xc(o,e);return S(JSON.stringify({...uS(o),submission_id:s},null,2))}catch(s){return it.delete(n),S(`spawn_agent failed: ${s.message}`,!0)}}}),Jc=I({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Yy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let r=it.get(t);if(!r)return os(t);let o=e.trim();if(!o)return S("send_input failed: message must not be empty",!0);if(r.status==="closed")return S(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(r.running){if(!n)return S(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await Vc(r)}try{let s=await Xc(r,o);return S(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return S(`send_input failed: ${s.message}`,!0)}}}),Qc=I({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Jy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=it.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=Ht()),S(JSON.stringify({agent_id:t,status:e.status},null,2))):os(t)}}),Zc=I({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Qy,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=sS(e);if(n===null)return S("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},c={};for(let a of t){let l=cS(a);rS(l)&&(i[a]=l,c[a]=lS(a))}return{status:i,details:c}},o=r();if(Object.keys(o.status).length>0)return S(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await oS(100),o=r(),Object.keys(o.status).length>0)return S(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return S(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),el=I({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Zy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=it.get(t);return e?e.status==="closed"?S(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=Ht(),await Vc(e),S(JSON.stringify({agent_id:t,status:"closed"},null,2))):os(t)}});var ss={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_text_file:"read",read_media_file:"read",read_files:"read",list_directory:"read",search_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",write_file:"write",edit_file:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},tl=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),cr={read:0,write:1,execute:2},nl=["exec","run","shell","command","stdin"],rl=["write","patch","create","delete","modify","update"],ol=["read","get","fetch","search","list","find"],sl=new Set(["write","execute"]);function as(t){let e={...ss,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let r=n.toLowerCase();return is(r,nl)?"execute":is(r,rl)?"write":is(r,ol)?"read":"write"},compareRisk(n,r){return cr[n]-cr[r]},needsApproval(n,r){return r==="strict"?!0:sl.has(n)}}}function is(t,e){return e.some(n=>t.includes(n))}import{createHash as dS}from"crypto";function lr(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>lr(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${lr(r)}`).join(",")}}`}function cs(t,e){let n=lr(e),r=`${t}:${n}`;return dS("sha256").update(r).digest("hex").slice(0,16)}function fS(t){return`Tool "${t}" requires approval.`}function ls(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=as({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(c){return s.getRiskLevel(c)},check(c,a){if(tl.has(c))return{needApproval:!1,decision:"auto-execute"};let l=s.getRiskLevel(c);if(!s.needsApproval(l,o))return{needApproval:!1,decision:"auto-execute"};let u=cs(c,a);return i.toolByFingerprint.set(u,c),i.sessionTools.has(c)||i.onceTools.has(c)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(c)?{needApproval:!0,fingerprint:u,riskLevel:l,reason:"This request was previously denied.",toolName:c,params:a}:{needApproval:!0,fingerprint:u,riskLevel:l,reason:fS(c),toolName:c,params:a}},recordDecision(c,a){let l=i.toolByFingerprint.get(c);if(l)switch(i.sessionTools.delete(l),i.onceTools.delete(l),i.deniedTools.delete(l),a){case"session":i.sessionTools.add(l);break;case"once":i.onceTools.add(l);break;case"deny":i.deniedTools.add(l);break}},isGranted(c){let a=i.toolByFingerprint.get(c);return a?i.sessionTools.has(a)||i.onceTools.has(a):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var il=1e5;function mS(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gS(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 hS(t,e,n){return`<system_hint type="tool_output_omitted" tool="${mS(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 yS(t,e){let n=Ao(),r=gS(e);return r<=n?e:{content:[{type:"text",text:hS(t,r,n)}],isError:!1}}function SS(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
179
- `)}function al(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wS(t,e){let n=e;if(typeof e=="string"){if(e.length>il)return{ok:!1,error:`${t.name} invalid input: input string too large (max ${il} chars)`};let r=e.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!al(n))return{ok:!1,error:`${t.name} invalid input: expected object`};if(typeof t.validateInput=="function"){let r=t.validateInput(n);return r.ok?al(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${t.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function _S(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 us=class{constructor(e){this.config=e;this.approvalManager=ls(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 c={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(c);let a=n?.requestApproval?await n.requestApproval(c):"deny";if(this.approvalManager.recordDecision(s.fingerprint,a),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:a}),a==="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 c=wS(i,e.input);if(!c.ok)return{actionId:o,tool:e.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:c.error,durationMs:Date.now()-r};let a=await i.execute(c.data),l=yS(e.name,a);return{actionId:o,tool:e.name,status:"success",success:!0,observation:SS(l)||"(no tool output)",durationMs:Date.now()-r}}catch(c){let a=_S(c);return{actionId:o,tool:e.name,status:a,errorType:a,success:!1,observation:`Tool execution failed: ${c.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 a=await Promise.all(e.map(l=>this.executeAction(l,n)));if(o==="fail_fast"){let l=a.findIndex(u=>u.rejected);s=l>=0?a.slice(0,l+1):a}else s=a}else for(let a of e){let l=await this.executeAction(a,n);if(s.push(l),l.rejected&&o==="fail_fast")break}let i=s.some(a=>a.rejected),c=s.map(a=>`[${a.tool}]: ${a.observation}`).join(`
177
+ `))}async function Kc(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()}},Vy);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function cS(t){let e=it.get(t);return e?e.status:"not_found"}function lS(t){let e=it.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 uS(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 pS(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=Ht(),e.lastOutput=aS(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 Vc(t,e){let n=eS();if(tS()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=nS(),s=Wy(o,{cwd:Fe(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],c=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",a=>i.push(a)),s.stderr?.on("data",a=>c.push(a)),s.on("error",a=>{c.push(`[spawn error] ${a.message}`)}),t.running={id:r,message:e,process:s,startedAt:Ht(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=r,t.updatedAt=Ht(),s.on("close",a=>{let l=typeof a=="number"?a:-1,u=!!(t.running?.id===r&&t.running.interrupted);pS({record:t,submissionId:r,stdout:i.join(""),stderr:c.join(""),exitCode:l,interrupted:u})});try{s.stdin?.write(`${e.trim()}
178
+ `)}catch{}try{s.stdin?.end()}catch{}return r}var Xc=I({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:Xy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return S("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=Ht(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:e,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};it.set(n,o);try{let s=await Vc(o,e);return S(JSON.stringify({...uS(o),submission_id:s},null,2))}catch(s){return it.delete(n),S(`spawn_agent failed: ${s.message}`,!0)}}}),Yc=I({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Yy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let r=it.get(t);if(!r)return os(t);let o=e.trim();if(!o)return S("send_input failed: message must not be empty",!0);if(r.status==="closed")return S(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(r.running){if(!n)return S(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await Kc(r)}try{let s=await Vc(r,o);return S(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return S(`send_input failed: ${s.message}`,!0)}}}),Jc=I({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Jy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=it.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=Ht()),S(JSON.stringify({agent_id:t,status:e.status},null,2))):os(t)}}),Qc=I({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Qy,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=sS(e);if(n===null)return S("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},c={};for(let a of t){let l=cS(a);rS(l)&&(i[a]=l,c[a]=lS(a))}return{status:i,details:c}},o=r();if(Object.keys(o.status).length>0)return S(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await oS(100),o=r(),Object.keys(o.status).length>0)return S(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return S(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),Zc=I({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Zy,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=it.get(t);return e?e.status==="closed"?S(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=Ht(),await Kc(e),S(JSON.stringify({agent_id:t,status:"closed"},null,2))):os(t)}});var ss={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_text_file:"read",read_media_file:"read",read_files:"read",list_directory:"read",search_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",write_file:"write",edit_file:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},el=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),cr={read:0,write:1,execute:2},tl=["exec","run","shell","command","stdin"],nl=["write","patch","create","delete","modify","update"],rl=["read","get","fetch","search","list","find"],ol=new Set(["write","execute"]);function as(t){let e={...ss,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let r=n.toLowerCase();return is(r,tl)?"execute":is(r,nl)?"write":is(r,rl)?"read":"write"},compareRisk(n,r){return cr[n]-cr[r]},needsApproval(n,r){return r==="strict"?!0:ol.has(n)}}}function is(t,e){return e.some(n=>t.includes(n))}import{createHash as dS}from"crypto";function lr(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>lr(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${lr(r)}`).join(",")}}`}function cs(t,e){let n=lr(e),r=`${t}:${n}`;return dS("sha256").update(r).digest("hex").slice(0,16)}function fS(t){return`Tool "${t}" requires approval.`}function ls(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=as({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(c){return s.getRiskLevel(c)},check(c,a){if(el.has(c))return{needApproval:!1,decision:"auto-execute"};let l=s.getRiskLevel(c);if(!s.needsApproval(l,o))return{needApproval:!1,decision:"auto-execute"};let u=cs(c,a);return i.toolByFingerprint.set(u,c),i.sessionTools.has(c)||i.onceTools.has(c)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(c)?{needApproval:!0,fingerprint:u,riskLevel:l,reason:"This request was previously denied.",toolName:c,params:a}:{needApproval:!0,fingerprint:u,riskLevel:l,reason:fS(c),toolName:c,params:a}},recordDecision(c,a){let l=i.toolByFingerprint.get(c);if(l)switch(i.sessionTools.delete(l),i.onceTools.delete(l),i.deniedTools.delete(l),a){case"session":i.sessionTools.add(l);break;case"once":i.onceTools.add(l);break;case"deny":i.deniedTools.add(l);break}},isGranted(c){let a=i.toolByFingerprint.get(c);return a?i.sessionTools.has(a)||i.onceTools.has(a):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var sl=1e5;function mS(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gS(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 hS(t,e,n){return`<system_hint type="tool_output_omitted" tool="${mS(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 yS(t,e){let n=Ao(),r=gS(e);return r<=n?e:{content:[{type:"text",text:hS(t,r,n)}],isError:!1}}function SS(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
179
+ `)}function il(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wS(t,e){let n=e;if(typeof e=="string"){if(e.length>sl)return{ok:!1,error:`${t.name} invalid input: input string too large (max ${sl} chars)`};let r=e.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!il(n))return{ok:!1,error:`${t.name} invalid input: expected object`};if(typeof t.validateInput=="function"){let r=t.validateInput(n);return r.ok?il(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${t.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function _S(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 us=class{constructor(e){this.config=e;this.approvalManager=ls(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 c={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(c);let a=n?.requestApproval?await n.requestApproval(c):"deny";if(this.approvalManager.recordDecision(s.fingerprint,a),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:a}),a==="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 c=wS(i,e.input);if(!c.ok)return{actionId:o,tool:e.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:c.error,durationMs:Date.now()-r};let a=await i.execute(c.data),l=yS(e.name,a);return{actionId:o,tool:e.name,status:"success",success:!0,observation:SS(l)||"(no tool output)",durationMs:Date.now()-r}}catch(c){let a=_S(c);return{actionId:o,tool:e.name,status:a,errorType:a,success:!1,observation:`Tool execution failed: ${c.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 a=await Promise.all(e.map(l=>this.executeAction(l,n)));if(o==="fail_fast"){let l=a.findIndex(u=>u.rejected);s=l>=0?a.slice(0,l+1):a}else s=a}else for(let a of e){let l=await this.executeAction(a,n);if(s.push(l),l.rejected&&o==="fail_fast")break}let i=s.some(a=>a.rejected),c=s.map(a=>`[${a.tool}]: ${a.observation}`).join(`
180
180
 
181
- `);return{results:s,combinedObservation:c,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function cl(t){return new us(t)}var ur=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 vS}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as TS}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as CS}from"@modelcontextprotocol/sdk/client/stdio.js";import{UnauthorizedError as bS}from"@modelcontextprotocol/sdk/client/auth.js";import{StreamableHTTPError as xS}from"@modelcontextprotocol/sdk/client/streamableHttp.js";function MS(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function ll(){return new vS({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function kS(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function ES(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 PS(t,e,n){let r=new URL(e.url),o=kS(ES(e)),s=await Ki({serverName:t,config:e,settings:n});try{let i=ll(),c=new TS(r,{requestInit:o,...s?{authProvider:s}:{}});return await i.connect(c),{client:i,transport:c}}catch(i){let c=RS(i)?` Run "memo mcp login ${t}".`:"",a=`Failed to connect via streamable_http (${i.message}).${c}`,l=new Error(a);throw l.cause=i,l}}async function AS(t,e,n){if("url"in e)return PS(t,e,n);let r={command:e.command,args:e.args,env:MS(e.env),stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},o=new CS(r),s=ll();return await s.connect(o),{client:s,transport:o}}var pr=class{connections=new Map;pendingConnections=new Map;serverConfigs=new Map;oauthSettings;setServerConfigs(e,n){this.serverConfigs=new Map(Object.entries(e)),this.oauthSettings=n}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:c,transport:a}=await AS(e,s,this.oauthSettings);try{let l=await c.listTools(),u={name:e,client:c,transport:a,tools:(l.tools||[]).map(p=>({name:`${e}_${p.name}`,description:p.description||`Tool from ${e}: ${p.name}`,source:"mcp",serverName:e,originalName:p.name,inputSchema:p.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(e,u),u}catch(l){try{await c.close()}catch{}throw l}})();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}};function RS(t){if(t instanceof bS)return!0;if(t instanceof xS)return t.code===401||t.code===403;let e=t?.message?.toLowerCase()??"";return e.includes("unauthorized")||e.includes("401")||e.includes("403")||e.includes("oauth")}var dr=class{pool;serverToolNames=new Map;refreshPromises=new Map;tools=new Map;cacheStore=sr();shouldLog;constructor(){this.pool=new pr,Jo(this.pool),Qo(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),c=this.connectionToDescriptors(e,i);await this.cacheStore.setServerTools(e,n,c);let a=c.map(l=>this.buildTool(e,n,l));this.replaceServerTools(e,a),this.shouldLog&&r==="background"&&console.log(`[MCP] Refreshed '${e}' tools in background (${a.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){return this.loadServersWithOptions(e)}async loadServersWithOptions(e,n){if(!e||Object.keys(e).length===0)return 0;let r=Object.entries(e);this.pool.setServerConfigs(e,n),this.removeToolsForMissingServers(new Set(r.map(([s])=>s)));let o=[];for(let[s,i]of r){let c=await this.cacheStore.getServerTools(s,i);if(c){let a=c.tools.map(l=>this.buildTool(s,i,l));this.replaceServerTools(s,a),this.shouldLog&&console.log(`[MCP] Loaded ${a.length} cached tools for '${s}' (${c.stale?"stale":"fresh"})`),c.stale&&this.refreshServer(s,i,"background");continue}o.push(this.refreshServer(s,i,"sync"))}return await Promise.all(o),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(),Jo(null),Qo(null)}getPool(){return this.pool}};var fr=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new ur,this.mcpRegistry=new dr}registerNativeTool(e){this.nativeRegistry.register(e)}registerNativeTools(e){for(let n of e)this.registerNativeTool(n)}async loadMcpServers(e,n){return this.mcpRegistry.loadServersWithOptions(e,n)}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,c]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let a of c)n.push(this.formatToolDescription(a));n.push("")}}return n.join(`
181
+ `);return{results:s,combinedObservation:c,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function al(t){return new us(t)}var ur=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 vS}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as TS}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as CS}from"@modelcontextprotocol/sdk/client/stdio.js";import{UnauthorizedError as bS}from"@modelcontextprotocol/sdk/client/auth.js";import{StreamableHTTPError as xS}from"@modelcontextprotocol/sdk/client/streamableHttp.js";function MS(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function cl(){return new vS({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function kS(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function ES(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 PS(t,e,n){let r=new URL(e.url),o=kS(ES(e)),s=await Ki({serverName:t,config:e,settings:n});try{let i=cl(),c=new TS(r,{requestInit:o,...s?{authProvider:s}:{}});return await i.connect(c),{client:i,transport:c}}catch(i){let c=RS(i)?` Run "memo mcp login ${t}".`:"",a=`Failed to connect via streamable_http (${i.message}).${c}`,l=new Error(a);throw l.cause=i,l}}async function AS(t,e,n){if("url"in e)return PS(t,e,n);let r={command:e.command,args:e.args,env:MS(e.env),stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},o=new CS(r),s=cl();return await s.connect(o),{client:s,transport:o}}var pr=class{connections=new Map;pendingConnections=new Map;serverConfigs=new Map;oauthSettings;setServerConfigs(e,n){this.serverConfigs=new Map(Object.entries(e)),this.oauthSettings=n}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:c,transport:a}=await AS(e,s,this.oauthSettings);try{let l=await c.listTools(),u={name:e,client:c,transport:a,tools:(l.tools||[]).map(p=>({name:`${e}_${p.name}`,description:p.description||`Tool from ${e}: ${p.name}`,source:"mcp",serverName:e,originalName:p.name,inputSchema:p.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(e,u),u}catch(l){try{await c.close()}catch{}throw l}})();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}};function RS(t){if(t instanceof bS)return!0;if(t instanceof xS)return t.code===401||t.code===403;let e=t?.message?.toLowerCase()??"";return e.includes("unauthorized")||e.includes("401")||e.includes("403")||e.includes("oauth")}var dr=class{pool;serverToolNames=new Map;refreshPromises=new Map;tools=new Map;cacheStore=sr();shouldLog;constructor(){this.pool=new pr,Jo(this.pool),Qo(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),c=this.connectionToDescriptors(e,i);await this.cacheStore.setServerTools(e,n,c);let a=c.map(l=>this.buildTool(e,n,l));this.replaceServerTools(e,a),this.shouldLog&&r==="background"&&console.log(`[MCP] Refreshed '${e}' tools in background (${a.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){return this.loadServersWithOptions(e)}async loadServersWithOptions(e,n){if(!e||Object.keys(e).length===0)return 0;let r=Object.entries(e);this.pool.setServerConfigs(e,n),this.removeToolsForMissingServers(new Set(r.map(([s])=>s)));let o=[];for(let[s,i]of r){let c=await this.cacheStore.getServerTools(s,i);if(c){let a=c.tools.map(l=>this.buildTool(s,i,l));this.replaceServerTools(s,a),this.shouldLog&&console.log(`[MCP] Loaded ${a.length} cached tools for '${s}' (${c.stale?"stale":"fresh"})`),c.stale&&this.refreshServer(s,i,"background");continue}o.push(this.refreshServer(s,i,"sync"))}return await Promise.all(o),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(),Jo(null),Qo(null)}getPool(){return this.pool}};var fr=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new ur,this.mcpRegistry=new dr}registerNativeTool(e){this.nativeRegistry.register(e)}registerNativeTools(e){for(let n of e)this.registerNativeTool(n)}async loadMcpServers(e,n){return this.mcpRegistry.loadServersWithOptions(e,n)}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,c]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let a of c)n.push(this.formatToolDescription(a));n.push("")}}return n.join(`
182
182
  `)}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(`
183
- `)}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 OS(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",r=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return e==="shell"?t.push(aa):e==="shell_command"?t.push(ca):e==="unified_exec"?t.push(To,Co):e!=="disabled"&&t.push(To,Co),t.push(Oc,Ic,Lc),t.push($c),t.push(Da),t.push(dc,mc,gc,hc,yc,wc,_c),r&&t.push(Uc),t.push(Gc),n&&t.push(Yc,Jc,Qc,Zc,el),t}function IS(t){let e={};for(let n of t)e[n.name]=n;return e}var LS=IS(OS()),NS=Object.values(LS),ul=NS;import zS from"openai";import{encoding_for_model as $S,get_encoding as DS}from"@dqbd/tiktoken";var pl="cl100k_base";function FS(t){let e=t?.trim()||pl;try{let n=()=>$S(e);return n().free(),{model:e,factory:n}}catch{let n=pl,r=()=>DS(n);return r().free(),{model:n,factory:r}}}function US(t){if(t.role==="assistant"){let e=t.reasoning_content?`
183
+ `)}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 OS(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",r=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return e==="shell"?t.push(aa):e==="shell_command"?t.push(ca):e==="unified_exec"?t.push(To,Co):e!=="disabled"&&t.push(To,Co),t.push(Oc,Ic,Lc),t.push($c),t.push(Da),t.push(dc,mc,gc,hc,yc,wc,_c),r&&t.push(Uc),t.push(zc),n&&t.push(Xc,Yc,Jc,Qc,Zc),t}function IS(t){let e={};for(let n of t)e[n.name]=n;return e}var LS=IS(OS()),NS=Object.values(LS),ll=NS;import zS from"openai";import{encoding_for_model as $S,get_encoding as DS}from"@dqbd/tiktoken";var ul="cl100k_base";function FS(t){let e=t?.trim()||ul;try{let n=()=>$S(e);return n().free(),{model:e,factory:n}}catch{let n=ul,r=()=>DS(n);return r().free(),{model:n,factory:r}}}function US(t){if(t.role==="assistant"){let e=t.reasoning_content?`
184
184
  ${t.reasoning_content}`:"";return t.tool_calls?.length?`${t.content}${e}
185
185
  ${JSON.stringify(t.tool_calls)}`:`${t.content}${e}`}return t.role==="tool"?`${t.content}
186
186
  ${t.tool_call_id}
187
- ${t.name??""}`:t.content}function dl(t){let{model:e,factory:n}=FS(t),r=n(),o=4,s=2,i=1,c=l=>l?r.encode(l).length:0;return{model:e,countText:c,countMessages:l=>{if(!l.length)return 0;let u=0;for(let p of l)u+=o,u+=c(US(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>r.free()}}import"openai";var HS={supportsParallelToolCalls:!1,supportsReasoningContent:!1};function ps(t){return t.trim().toLowerCase()}function BS(t,e,n){if(!n)return;let r=new Map;for(let[s,i]of Object.entries(n))r.set(ps(s),i);let o=r.get(`${t}:${e}`);return o||r.get(e)}function WS(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 fl(t,e){let n=ps(t.name),r=ps(t.model),{capabilities:o,usedOverride:s}=WS(HS,BS(n,r,e));return{profile:{wireApi:"chat_completions",...o,isFallback:!s}}}function jS(t){if(t.length!==0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}function ml(t){let e=jS(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 GS(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 qS(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function KS(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 VS(t){let e=t?.reasoning_content;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function XS(t){return!t||typeof t!="object"?!1:Array.isArray(t.choices)}async function gl(t,e,n){let r=await re(),o=r.config,s=new fr;if(s.registerNativeTools(ul),await s.loadMcpServers(GS(o.mcp_servers,e.activeMcpServers),{memoHome:r.home,storeMode:o.mcp_oauth_credentials_store_mode,callbackPort:o.mcp_oauth_callback_port}),t.tools)for(let[d,f]of Object.entries(t.tools))s.registerNativeTool({name:d,description:f.description,source:"native",inputSchema:{type:"object"},execute:f.execute});let i=s.toRegistry(),c=async()=>{let d=t.loadPrompt?await t.loadPrompt():await Zs({cwd:e.cwd,memoHome:r.home,activeSkillPaths:o.active_skills}),f=s.generateToolDescriptions();return f&&(d+=`
187
+ ${t.name??""}`:t.content}function pl(t){let{model:e,factory:n}=FS(t),r=n(),o=4,s=2,i=1,c=l=>l?r.encode(l).length:0;return{model:e,countText:c,countMessages:l=>{if(!l.length)return 0;let u=0;for(let p of l)u+=o,u+=c(US(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>r.free()}}import"openai";var HS={supportsParallelToolCalls:!1,supportsReasoningContent:!1};function ps(t){return t.trim().toLowerCase()}function BS(t,e,n){if(!n)return;let r=new Map;for(let[s,i]of Object.entries(n))r.set(ps(s),i);let o=r.get(`${t}:${e}`);return o||r.get(e)}function WS(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 dl(t,e){let n=ps(t.name),r=ps(t.model),{capabilities:o,usedOverride:s}=WS(HS,BS(n,r,e));return{profile:{wireApi:"chat_completions",...o,isFallback:!s}}}function jS(t){if(t.length!==0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}function fl(t){let e=jS(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 GS(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 qS(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function KS(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 VS(t){let e=t?.reasoning_content;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function XS(t){return!t||typeof t!="object"?!1:Array.isArray(t.choices)}async function ml(t,e,n){let r=await re(),o=r.config,s=new fr;if(s.registerNativeTools(ll),await s.loadMcpServers(GS(o.mcp_servers,e.activeMcpServers),{memoHome:r.home,storeMode:o.mcp_oauth_credentials_store_mode,callbackPort:o.mcp_oauth_callback_port}),t.tools)for(let[d,f]of Object.entries(t.tools))s.registerNativeTool({name:d,description:f.description,source:"native",inputSchema:{type:"object"},execute:f.execute});let i=s.toRegistry(),c=async()=>{let d=t.loadPrompt?await t.loadPrompt():await Zs({cwd:e.cwd,memoHome:r.home,activeSkillPaths:o.active_skills}),f=s.generateToolDescriptions();return f&&(d+=`
188
188
 
189
- ${f}`),d},a=s.generateToolDefinitions(),l=cn(r,e),u=Oi(l,n),p=new Rn(u);return{tools:i,dispose:async()=>{t.dispose&&await t.dispose(),await s.dispose()},callLLM:t.callLLM??(async(d,f,g)=>{let m=wt(o,e.providerName),_=process.env[m.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!_)throw new Error(`Missing env var ${m.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let A=new zS({apiKey:_,baseURL:m.base_url}),h=d.map(KS),{profile:x}=fl(m,o.model_profiles),T=g?.tools??a,b=ml({model:m.model,messages:h,toolDefinitions:T,profile:x}),H=await A.chat.completions.create(b,{signal:g?.signal});if(!XS(H))throw new Error("Streaming response is not supported in core callLLM");let j=H.choices?.[0]?.message,Se=VS(j);if(j?.tool_calls&&j.tool_calls.length>0){let q=[];j.content&&q.push({type:"text",text:j.content});for(let L of j.tool_calls)if(L.type==="function"){let oe=qS(L.function.arguments);oe.ok?q.push({type:"tool_use",id:L.id,name:L.function.name,input:oe.data}):q.push({type:"text",text:`[tool_use parse error] ${oe.error}; raw: ${oe.raw}`})}let P=q.some(L=>L.type==="tool_use");return{content:q,reasoning_content:Se,stop_reason:P?"tool_use":"end_turn",usage:{prompt:H.usage?.prompt_tokens??void 0,completion:H.usage?.completion_tokens??void 0,total:H.usage?.total_tokens??void 0}}}let ce=j?.content;if(typeof ce!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:ce}],reasoning_content:Se,stop_reason:"end_turn",usage:{prompt:H.usage?.prompt_tokens??void 0,completion:H.usage?.completion_tokens??void 0,total:H.usage?.total_tokens??void 0}}}),loadPrompt:c,historySinks:t.historySinks??[p],tokenCounter:t.tokenCounter??dl(e.tokenizerModel),historyFilePath:u}}function YS(t){let e=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=t.replace(n,(o,s,i)=>{let c=(i??"").trim();return c&&e.push(c),c});return{thinkingParts:e,cleaned:r.trim()}}function hl(t){if(t.length===0)return;let e=t.join(`
189
+ ${f}`),d},a=s.generateToolDefinitions(),l=cn(r,e),u=Oi(l,n),p=new Rn(u);return{tools:i,dispose:async()=>{t.dispose&&await t.dispose(),await s.dispose()},callLLM:t.callLLM??(async(d,f,g)=>{let m=wt(o,e.providerName),_=process.env[m.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!_)throw new Error(`Missing env var ${m.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let A=new zS({apiKey:_,baseURL:m.base_url}),h=d.map(KS),{profile:x}=dl(m,o.model_profiles),T=g?.tools??a,b=fl({model:m.model,messages:h,toolDefinitions:T,profile:x}),H=await A.chat.completions.create(b,{signal:g?.signal});if(!XS(H))throw new Error("Streaming response is not supported in core callLLM");let j=H.choices?.[0]?.message,Se=VS(j);if(j?.tool_calls&&j.tool_calls.length>0){let q=[];j.content&&q.push({type:"text",text:j.content});for(let L of j.tool_calls)if(L.type==="function"){let oe=qS(L.function.arguments);oe.ok?q.push({type:"tool_use",id:L.id,name:L.function.name,input:oe.data}):q.push({type:"text",text:`[tool_use parse error] ${oe.error}; raw: ${oe.raw}`})}let P=q.some(L=>L.type==="tool_use");return{content:q,reasoning_content:Se,stop_reason:P?"tool_use":"end_turn",usage:{prompt:H.usage?.prompt_tokens??void 0,completion:H.usage?.completion_tokens??void 0,total:H.usage?.total_tokens??void 0}}}let ce=j?.content;if(typeof ce!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:ce}],reasoning_content:Se,stop_reason:"end_turn",usage:{prompt:H.usage?.prompt_tokens??void 0,completion:H.usage?.completion_tokens??void 0,total:H.usage?.total_tokens??void 0}}}),loadPrompt:c,historySinks:t.historySinks??[p],tokenCounter:t.tokenCounter??pl(e.tokenizerModel),historyFilePath:u}}function YS(t){let e=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=t.replace(n,(o,s,i)=>{let c=(i??"").trim();return c&&e.push(c),c});return{thinkingParts:e,cleaned:r.trim()}}function gl(t){if(t.length===0)return;let e=t.join(`
190
190
  `),{thinkingParts:n,cleaned:r}=YS(e);return n.length>0?n.join(`
191
191
 
192
- `):r||void 0}import{randomUUID as aw}from"crypto";var mr="interactive";var fs="success",Bt="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.";var JS="Skipped tool execution after previous rejection.",yl="Tool execution skipped: tools are disabled in current permission mode.";function QS(t){process.stderr.write(`${JSON.stringify(t)}
193
- `)}function Sl(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 ms(){return{prompt:0,completion:0,total:0}}function gs(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 hs(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(`
194
- `),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 wl(t,e){for(let n of e)try{await n.append(t)}catch(r){QS({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function _l(t){if(!(t instanceof Error))return!1;if(t.name==="AbortError")return!0;let e=t.message?.toLowerCase?.()??"";return e.includes("request was aborted")||e.includes("operation was aborted")||e.includes("aborted")}function gr(t){return ds(t,new WeakSet,0)}var ZS=100;function ds(t,e,n){if(n>ZS)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=>ds(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)}:${ds(i,e,n+1)}`).join(",")}}`;return e.delete(t),o}function vl(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:gr(e.input)}}))}function Tl(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 c=i,a=typeof c.tool=="string"?c.tool.trim():"";if(!a||!Object.prototype.hasOwnProperty.call(e,a))continue;return{tool:a,input:c.input??{}}}catch{}return null}function ew(t){return t.length<=60?t:`${t.slice(0,57).trimEnd()}...`}function Cl(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 ew(r||e)}function ys(t){return{role:"tool",content:t.observation,tool_call_id:t.actionId,name:t.tool}}function bl(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?`${JS} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as ow}from"crypto";var xl=`You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
192
+ `):r||void 0}import{randomUUID as aw}from"crypto";var mr="interactive";var fs="success",Bt="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.";var JS="Skipped tool execution after previous rejection.",hl="Tool execution skipped: tools are disabled in current permission mode.";function QS(t){process.stderr.write(`${JSON.stringify(t)}
193
+ `)}function yl(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 ms(){return{prompt:0,completion:0,total:0}}function gs(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 hs(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(`
194
+ `),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 Sl(t,e){for(let n of e)try{await n.append(t)}catch(r){QS({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function wl(t){if(!(t instanceof Error))return!1;if(t.name==="AbortError")return!0;let e=t.message?.toLowerCase?.()??"";return e.includes("request was aborted")||e.includes("operation was aborted")||e.includes("aborted")}function gr(t){return ds(t,new WeakSet,0)}var ZS=100;function ds(t,e,n){if(n>ZS)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=>ds(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)}:${ds(i,e,n+1)}`).join(",")}}`;return e.delete(t),o}function _l(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:gr(e.input)}}))}function vl(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 c=i,a=typeof c.tool=="string"?c.tool.trim():"";if(!a||!Object.prototype.hasOwnProperty.call(e,a))continue;return{tool:a,input:c.input??{}}}catch{}return null}function ew(t){return t.length<=60?t:`${t.slice(0,57).trimEnd()}...`}function Tl(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 ew(r||e)}function ys(t){return{role:"tool",content:t.observation,tool_call_id:t.actionId,name:t.tool}}function Cl(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?`${JS} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as ow}from"crypto";var bl=`You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
195
195
 
196
196
  Include:
197
197
  - Current progress and key decisions made
@@ -203,34 +203,34 @@ Be concise, structured, and focused on helping the next LLM seamlessly continue
203
203
  `).trim();return e.length<=4e3?e:`${e.slice(0,4e3)}...`}function tw(t,e){let n=t.role.toUpperCase();if(t.role==="assistant"&&t.tool_calls?.length){let r=t.tool_calls.map(o=>o.function.name).join(", ");return`[${e}] ${n} (tool_calls: ${r})
204
204
  ${Ss(t.content)}`}if(t.role==="tool"){let r=t.name?` (${t.name})`:"";return`[${e}] ${n}${r}
205
205
  ${Ss(t.content)}`}return`[${e}] ${n}
206
- ${Ss(t.content)}`}function Ml(t){return t.role!=="user"?!1:t.content.startsWith(`${ws}
207
- `)}function kl(t){return["Conversation history to summarize:",t.length?t.map((n,r)=>tw(n,r)).join(`
206
+ ${Ss(t.content)}`}function xl(t){return t.role!=="user"?!1:t.content.startsWith(`${ws}
207
+ `)}function Ml(t){return["Conversation history to summarize:",t.length?t.map((n,r)=>tw(n,r)).join(`
208
208
 
209
209
  `):"(empty)","","Return only the summary body in plain text. Do not add markdown fences."].join(`
210
- `)}function nw(){return{onTurnStart:[],onContextUsage:[],onContextCompacted:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function El(t,e){e&&(e.onTurnStart&&t.onTurnStart.push(e.onTurnStart),e.onContextUsage&&t.onContextUsage.push(e.onContextUsage),e.onContextCompacted&&t.onContextCompacted.push(e.onContextCompacted),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 Pl(t){let e=nw();if(El(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)El(e,n);return e}async function X(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 Wt(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 sw=80,iw=2e4,hr=class{constructor(e,n,r,o,s){this.deps=e;this.options=n;this.id=n.sessionId||ow(),this.mode=n.mode||mr,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=e.historySinks??[],this.hooks=Pl(e),this.historyFilePath=s;let i=Sl(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=cl({tools:e.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=ms();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}:${gr(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=gr(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})}}resolveContextWindow(){let e=this.options.contextWindow;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):12e4}resolveSessionCwd(){let e=this.options.cwd?.trim();return e||process.cwd()}resolveAutoCompactThresholdPercent(){let e=this.options.autoCompactThresholdPercent;return typeof e=="number"&&Number.isInteger(e)&&Number.isFinite(e)&&e>=1&&e<=100?e:sw}resolveThresholdTokens(e){let n=Math.floor(e*this.resolveAutoCompactThresholdPercent()/100);return Math.max(1,n)}calculateUsagePercent(e,n){return e<=0||n<=0?0:Math.round(e/n*1e4)/100}async emitContextUsage(e,n,r,o,s,i){let c=this.calculateUsagePercent(r,o);await this.emitEvent("context_usage",{turn:e,step:n,meta:{phase:i,prompt_tokens:r,context_window:o,threshold_tokens:s,usage_percent:c}}),await X(this.hooks,"onContextUsage",{sessionId:this.id,turn:e,step:n,promptTokens:r,contextWindow:o,thresholdTokens:s,usagePercent:c,phase:i})}async emitContextCompacted(e,n,r){await this.emitEvent("context_compact",{turn:e,step:n,content:r.summary,meta:{reason:r.reason,status:r.status,before_tokens:r.beforeTokens,after_tokens:r.afterTokens,threshold_tokens:r.thresholdTokens,reduction_percent:r.reductionPercent,error_message:r.errorMessage}}),await X(this.hooks,"onContextCompacted",{sessionId:this.id,turn:e,step:n,reason:r.reason,status:r.status,beforeTokens:r.beforeTokens,afterTokens:r.afterTokens,thresholdTokens:r.thresholdTokens,reductionPercent:r.reductionPercent,summary:r.summary,errorMessage:r.errorMessage})}buildCompactedHistory(e){let n=this.history[0]?.role==="system"?this.history[0]:void 0,o=(n?this.history.slice(1):this.history).filter(c=>c.role==="user"&&!Ml(c)).map(c=>c.content),s=this.selectCompactionUserMessages(o).map(c=>({role:"user",content:c})),i={role:"user",content:`${ws}
210
+ `)}function nw(){return{onTurnStart:[],onContextUsage:[],onContextCompacted:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function kl(t,e){e&&(e.onTurnStart&&t.onTurnStart.push(e.onTurnStart),e.onContextUsage&&t.onContextUsage.push(e.onContextUsage),e.onContextCompacted&&t.onContextCompacted.push(e.onContextCompacted),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 El(t){let e=nw();if(kl(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)kl(e,n);return e}async function X(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 Wt(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 sw=80,iw=2e4,hr=class{constructor(e,n,r,o,s){this.deps=e;this.options=n;this.id=n.sessionId||ow(),this.mode=n.mode||mr,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=e.historySinks??[],this.hooks=El(e),this.historyFilePath=s;let i=yl(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=al({tools:e.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=ms();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}:${gr(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=gr(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})}}resolveContextWindow(){let e=this.options.contextWindow;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):12e4}resolveSessionCwd(){let e=this.options.cwd?.trim();return e||process.cwd()}resolveAutoCompactThresholdPercent(){let e=this.options.autoCompactThresholdPercent;return typeof e=="number"&&Number.isInteger(e)&&Number.isFinite(e)&&e>=1&&e<=100?e:sw}resolveThresholdTokens(e){let n=Math.floor(e*this.resolveAutoCompactThresholdPercent()/100);return Math.max(1,n)}calculateUsagePercent(e,n){return e<=0||n<=0?0:Math.round(e/n*1e4)/100}async emitContextUsage(e,n,r,o,s,i){let c=this.calculateUsagePercent(r,o);await this.emitEvent("context_usage",{turn:e,step:n,meta:{phase:i,prompt_tokens:r,context_window:o,threshold_tokens:s,usage_percent:c}}),await X(this.hooks,"onContextUsage",{sessionId:this.id,turn:e,step:n,promptTokens:r,contextWindow:o,thresholdTokens:s,usagePercent:c,phase:i})}async emitContextCompacted(e,n,r){await this.emitEvent("context_compact",{turn:e,step:n,content:r.summary,meta:{reason:r.reason,status:r.status,before_tokens:r.beforeTokens,after_tokens:r.afterTokens,threshold_tokens:r.thresholdTokens,reduction_percent:r.reductionPercent,error_message:r.errorMessage}}),await X(this.hooks,"onContextCompacted",{sessionId:this.id,turn:e,step:n,reason:r.reason,status:r.status,beforeTokens:r.beforeTokens,afterTokens:r.afterTokens,thresholdTokens:r.thresholdTokens,reductionPercent:r.reductionPercent,summary:r.summary,errorMessage:r.errorMessage})}buildCompactedHistory(e){let n=this.history[0]?.role==="system"?this.history[0]:void 0,o=(n?this.history.slice(1):this.history).filter(c=>c.role==="user"&&!xl(c)).map(c=>c.content),s=this.selectCompactionUserMessages(o).map(c=>({role:"user",content:c})),i={role:"user",content:`${ws}
211
211
  ${e}`};return n?[n,...s,i]:[...s,i]}selectCompactionUserMessages(e){if(!e.length)return[];let n=[],r=iw;for(let o=e.length-1;o>=0;o-=1){let s=e[o];if(!s)continue;let i=this.tokenCounter.countText(s);if(i<=r){if(n.push(s),r=Math.max(0,r-i),r===0)break;continue}r>0&&n.push(s.slice(0,r));break}return n.reverse(),n}normalizeCompactionSummary(e){return(e.replace(/<think>[\s\S]*?<\/think>/gi,"").trim()||e).replace(/\n{3,}/g,`
212
212
 
213
- `).trim()}async compactHistoryInternal(e,n,r){let o=this.resolveContextWindow(),s=this.resolveThresholdTokens(o),i=this.tokenCounter.countMessages(this.history),a=(this.history[0]?.role==="system"?this.history[0]:void 0)?this.history.slice(1):this.history.slice();if(!a.length){let l={reason:e,status:"skipped",beforeTokens:i,afterTokens:i,thresholdTokens:s,reductionPercent:0};return await this.emitContextCompacted(n,r,l),l}try{let l=await this.deps.callLLM([{role:"system",content:xl},{role:"user",content:kl(a)}],void 0,{tools:[]}),u=hs(l),p=this.normalizeCompactionSummary(u.textContent);if(!p)throw new Error("Compaction model returned an empty summary.");let d=this.buildCompactedHistory(p),f=this.tokenCounter.countMessages(d);this.history.splice(0,this.history.length,...d);let g=i>0?Math.max(0,Math.round((i-f)/i*1e4)/100):0,m={reason:e,status:"success",beforeTokens:i,afterTokens:f,thresholdTokens:s,reductionPercent:g,summary:p};return await this.emitContextCompacted(n,r,m),m}catch(l){let u={reason:e,status:"failed",beforeTokens:i,afterTokens:i,thresholdTokens:s,reductionPercent:0,errorMessage:l.message};return await this.emitContextCompacted(n,r,u),u}}buildToolApprovalHooks(e,n){return{onApprovalRequest:async r=>{await X(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 X(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){if(e!==1||this.title)return;let r=Cl(n);this.title=r,await this.emitEvent("session_title",{turn:e,content:r,meta:{source:"first_prompt",original_prompt:n}}),await X(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:e,title:r,originalPrompt:n})}async runTurn(e){return ta({cwd:this.resolveSessionCwd()},async()=>{let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=ms(),i=Date.now(),c=this.resolveContextWindow(),a=this.resolveThresholdTokens(c),l=this.resolveAutoCompactThresholdPercent(),u=!1;if(!this.sessionStartEmitted){let p=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:p,role:p?"system":void 0,meta:{mode:this.mode,cwd:this.resolveSessionCwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,contextWindow:c,autoCompactThresholdPercent:l,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:e});try{let p=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:e,meta:{tokens:{prompt:p}}}),await X(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:e,promptTokens:p,history:Wt(this.history)}),await this.emitContextUsage(r,0,p,c,a,"turn_start"),await this.maybeGenerateSessionTitle(r,e);let d="",f="ok",g,m=0,_=null,A=-1;for(let h=0;;h++){let x=this.tokenCounter.countMessages(this.history);if(await this.emitContextUsage(r,h,x,c,a,"step_start"),!u&&x>=a&&(u=!0,await this.compactHistoryInternal("auto",r,h),x=this.tokenCounter.countMessages(this.history),await this.emitContextUsage(r,h,x,c,a,"post_compact")),x>c){let O=`Context tokens (${x}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:O}),f="prompt_limit",d=O,g=O,await this.emitEvent("final",{turn:r,step:h,content:O,role:"assistant",meta:{tokens:{prompt:x}}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:O,status:f,errorMessage:g,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&x>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${x}`);let T="",b=[],H,j,Se,ce=!1;try{let O=await this.deps.callLLM(this.history,se=>{se&&(ce=!0),this.deps.onAssistantStep?.(se,h)},{signal:n.signal}),$=hs(O);T=$.textContent,b=$.toolUseBlocks,j=$.stopReason,H=$.usage,Se=$.reasoningContent,T.trim().length>0&&(_=T,A=h)}catch(O){if(this.cancelling&&_l(O)){f="cancelled",d="",g="Turn cancelled",await this.emitEvent("final",{turn:r,step:h,content:"",role:"assistant",meta:{cancelled:!0}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,errorMessage:g,turnUsage:{...s},steps:o});break}let $=`LLM call failed: ${O.message}`;this.history.push({role:"assistant",content:$}),f="error",d=$,g=$,await this.emitEvent("final",{turn:r,content:$,role:"assistant"}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,errorMessage:g,turnUsage:{...s},steps:o});break}!ce&&T&&this.deps.onAssistantStep?.(T,h);let q=b.length===0&&T?Tl(T,this.deps.tools):null,P,L=null;if(b.length>0){let O=b[0];if(O){let $=T?hl([T]):void 0;P={action:{tool:O.name,input:O.input},thinking:$},L={role:"assistant",content:T,reasoning_content:Se,tool_calls:vl(b)}}else P={}}else T?(P={final:T},L={role:"assistant",content:T,reasoning_content:Se}):P={};let oe=this.tokenCounter.countText(T),le=H?.prompt??x,B=H?.completion??oe,ue=H?.total??le+B,J={prompt:le,completion:B,total:ue};if(gs(s,J),gs(this.sessionUsage,J),o.push({index:h,assistantText:T,parsed:P,tokenUsage:J}),await this.emitEvent("assistant",{turn:r,step:h,content:T,role:"assistant",meta:{tokens:J,protocol_violation:!!q,protocol_violation_count:q?m+1:m||void 0}}),q){m+=1;let O=`Model protocol error: returned plain-text tool JSON for "${q.tool}" ${m} times. Structured tool calls are required.`;f="error",d=O,g=O,this.history.push({role:"assistant",content:O}),await this.emitEvent("final",{turn:r,step:h,content:O,role:"assistant",meta:{error_type:"model_protocol_error",tool:q.tool,protocol_violation:!0,protocol_violation_count:m,tokens:J}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,errorMessage:g,tokenUsage:J,turnUsage:{...s},steps:o});break}if(L&&this.history.push(L),b.length>0&&this.toolsDisabled){for(let O of b)this.history.push({role:"tool",content:yl,tool_call_id:O.id,name:O.name});f="error",d=Bt,g=Bt,this.history.push({role:"assistant",content:Bt}),await this.emitEvent("final",{turn:r,step:h,content:Bt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:b.length,tools:b.map(O=>O.name).join(","),tokens:J}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:Bt,status:f,errorMessage:g,tokenUsage:J,turnUsage:{...s},steps:o});break}if(b.length>1){for(let R of b)this.maybeWarnRepeatedAction(R.name,R.input);await this.emitEvent("action",{turn:r,step:h,meta:{tools:b.map(R=>R.name),action_ids:b.map(R=>R.id),action_id:b[0]?.id,parallel:!0,phase:"dispatch",thinking:P.thinking,toolBlocks:b.map(R=>({id:R.id,name:R.name,input:R.input}))}});let O=b[0];O&&await X(this.hooks,"onAction",{sessionId:this.id,turn:r,step:h,action:{tool:O.name,input:O.input},parallelActions:b.map(R=>({tool:R.name,input:R.input})),thinking:P.thinking,history:Wt(this.history)});let $=b.every(R=>!!this.deps.tools[R.name]?.supportsParallelToolCalls),se=b.some(R=>!!this.deps.tools[R.name]?.isMutating),Ce=$&&!se?"parallel":"sequential",we=await this.toolOrchestrator.executeActions(b.map(R=>({id:R.id,name:R.name,input:R.input})),{...this.buildToolApprovalHooks(r,h),executionMode:Ce,failurePolicy:"fail_fast"}),Ze=bl(b,we.results,we.hasRejection);for(let[R,D]of Ze.entries())this.history.push(ys(D)),await this.emitEvent("observation",{turn:r,step:h,content:D.observation,meta:{tool:D.tool,index:R,action_id:D.actionId,phase:"result",status:D.status,error_type:D.errorType,duration_ms:D.durationMs,execution_mode:Ce}});let je=Ze.map(R=>`[${R.tool}]: ${R.observation}`).join(`
213
+ `).trim()}async compactHistoryInternal(e,n,r){let o=this.resolveContextWindow(),s=this.resolveThresholdTokens(o),i=this.tokenCounter.countMessages(this.history),a=(this.history[0]?.role==="system"?this.history[0]:void 0)?this.history.slice(1):this.history.slice();if(!a.length){let l={reason:e,status:"skipped",beforeTokens:i,afterTokens:i,thresholdTokens:s,reductionPercent:0};return await this.emitContextCompacted(n,r,l),l}try{let l=await this.deps.callLLM([{role:"system",content:bl},{role:"user",content:Ml(a)}],void 0,{tools:[]}),u=hs(l),p=this.normalizeCompactionSummary(u.textContent);if(!p)throw new Error("Compaction model returned an empty summary.");let d=this.buildCompactedHistory(p),f=this.tokenCounter.countMessages(d);this.history.splice(0,this.history.length,...d);let g=i>0?Math.max(0,Math.round((i-f)/i*1e4)/100):0,m={reason:e,status:"success",beforeTokens:i,afterTokens:f,thresholdTokens:s,reductionPercent:g,summary:p};return await this.emitContextCompacted(n,r,m),m}catch(l){let u={reason:e,status:"failed",beforeTokens:i,afterTokens:i,thresholdTokens:s,reductionPercent:0,errorMessage:l.message};return await this.emitContextCompacted(n,r,u),u}}buildToolApprovalHooks(e,n){return{onApprovalRequest:async r=>{await X(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 X(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){if(e!==1||this.title)return;let r=Tl(n);this.title=r,await this.emitEvent("session_title",{turn:e,content:r,meta:{source:"first_prompt",original_prompt:n}}),await X(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:e,title:r,originalPrompt:n})}async runTurn(e){return ta({cwd:this.resolveSessionCwd()},async()=>{let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=ms(),i=Date.now(),c=this.resolveContextWindow(),a=this.resolveThresholdTokens(c),l=this.resolveAutoCompactThresholdPercent(),u=!1;if(!this.sessionStartEmitted){let p=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:p,role:p?"system":void 0,meta:{mode:this.mode,cwd:this.resolveSessionCwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,contextWindow:c,autoCompactThresholdPercent:l,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:e});try{let p=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:e,meta:{tokens:{prompt:p}}}),await X(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:e,promptTokens:p,history:Wt(this.history)}),await this.emitContextUsage(r,0,p,c,a,"turn_start"),await this.maybeGenerateSessionTitle(r,e);let d="",f="ok",g,m=0,_=null,A=-1;for(let h=0;;h++){let x=this.tokenCounter.countMessages(this.history);if(await this.emitContextUsage(r,h,x,c,a,"step_start"),!u&&x>=a&&(u=!0,await this.compactHistoryInternal("auto",r,h),x=this.tokenCounter.countMessages(this.history),await this.emitContextUsage(r,h,x,c,a,"post_compact")),x>c){let O=`Context tokens (${x}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:O}),f="prompt_limit",d=O,g=O,await this.emitEvent("final",{turn:r,step:h,content:O,role:"assistant",meta:{tokens:{prompt:x}}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:O,status:f,errorMessage:g,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&x>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${x}`);let T="",b=[],H,j,Se,ce=!1;try{let O=await this.deps.callLLM(this.history,se=>{se&&(ce=!0),this.deps.onAssistantStep?.(se,h)},{signal:n.signal}),$=hs(O);T=$.textContent,b=$.toolUseBlocks,j=$.stopReason,H=$.usage,Se=$.reasoningContent,T.trim().length>0&&(_=T,A=h)}catch(O){if(this.cancelling&&wl(O)){f="cancelled",d="",g="Turn cancelled",await this.emitEvent("final",{turn:r,step:h,content:"",role:"assistant",meta:{cancelled:!0}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,errorMessage:g,turnUsage:{...s},steps:o});break}let $=`LLM call failed: ${O.message}`;this.history.push({role:"assistant",content:$}),f="error",d=$,g=$,await this.emitEvent("final",{turn:r,content:$,role:"assistant"}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,errorMessage:g,turnUsage:{...s},steps:o});break}!ce&&T&&this.deps.onAssistantStep?.(T,h);let q=b.length===0&&T?vl(T,this.deps.tools):null,P,L=null;if(b.length>0){let O=b[0];if(O){let $=T?gl([T]):void 0;P={action:{tool:O.name,input:O.input},thinking:$},L={role:"assistant",content:T,reasoning_content:Se,tool_calls:_l(b)}}else P={}}else T?(P={final:T},L={role:"assistant",content:T,reasoning_content:Se}):P={};let oe=this.tokenCounter.countText(T),le=H?.prompt??x,B=H?.completion??oe,ue=H?.total??le+B,J={prompt:le,completion:B,total:ue};if(gs(s,J),gs(this.sessionUsage,J),o.push({index:h,assistantText:T,parsed:P,tokenUsage:J}),await this.emitEvent("assistant",{turn:r,step:h,content:T,role:"assistant",meta:{tokens:J,protocol_violation:!!q,protocol_violation_count:q?m+1:m||void 0}}),q){m+=1;let O=`Model protocol error: returned plain-text tool JSON for "${q.tool}" ${m} times. Structured tool calls are required.`;f="error",d=O,g=O,this.history.push({role:"assistant",content:O}),await this.emitEvent("final",{turn:r,step:h,content:O,role:"assistant",meta:{error_type:"model_protocol_error",tool:q.tool,protocol_violation:!0,protocol_violation_count:m,tokens:J}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,errorMessage:g,tokenUsage:J,turnUsage:{...s},steps:o});break}if(L&&this.history.push(L),b.length>0&&this.toolsDisabled){for(let O of b)this.history.push({role:"tool",content:hl,tool_call_id:O.id,name:O.name});f="error",d=Bt,g=Bt,this.history.push({role:"assistant",content:Bt}),await this.emitEvent("final",{turn:r,step:h,content:Bt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:b.length,tools:b.map(O=>O.name).join(","),tokens:J}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:Bt,status:f,errorMessage:g,tokenUsage:J,turnUsage:{...s},steps:o});break}if(b.length>1){for(let R of b)this.maybeWarnRepeatedAction(R.name,R.input);await this.emitEvent("action",{turn:r,step:h,meta:{tools:b.map(R=>R.name),action_ids:b.map(R=>R.id),action_id:b[0]?.id,parallel:!0,phase:"dispatch",thinking:P.thinking,toolBlocks:b.map(R=>({id:R.id,name:R.name,input:R.input}))}});let O=b[0];O&&await X(this.hooks,"onAction",{sessionId:this.id,turn:r,step:h,action:{tool:O.name,input:O.input},parallelActions:b.map(R=>({tool:R.name,input:R.input})),thinking:P.thinking,history:Wt(this.history)});let $=b.every(R=>!!this.deps.tools[R.name]?.supportsParallelToolCalls),se=b.some(R=>!!this.deps.tools[R.name]?.isMutating),Ce=$&&!se?"parallel":"sequential",we=await this.toolOrchestrator.executeActions(b.map(R=>({id:R.id,name:R.name,input:R.input})),{...this.buildToolApprovalHooks(r,h),executionMode:Ce,failurePolicy:"fail_fast"}),Ze=Cl(b,we.results,we.hasRejection);for(let[R,D]of Ze.entries())this.history.push(ys(D)),await this.emitEvent("observation",{turn:r,step:h,content:D.observation,meta:{tool:D.tool,index:R,action_id:D.actionId,phase:"result",status:D.status,error_type:D.errorType,duration_ms:D.durationMs,execution_mode:Ce}});let je=Ze.map(R=>`[${R.tool}]: ${R.observation}`).join(`
214
214
 
215
- `),ft=Ze.map(R=>R.status),be=ft.find(R=>R!==fs)??fs,Ee=o[o.length-1];if(Ee&&(Ee.observation=je),await X(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:h,tool:b.map(R=>R.name).join(", "),observation:je,resultStatus:be,parallelResultStatuses:ft,history:Wt(this.history)}),we.hasRejection){let R=Ze.find(D=>D.rejected);f="cancelled",d="\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:h,content:d,role:"assistant",meta:{rejected:!0,phase:"result",action_id:R?.actionId,error_type:R?.errorType??"approval_denied",duration_ms:R?.durationMs}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,tokenUsage:J,turnUsage:{...s},steps:o});break}continue}else if(P.action){this.maybeWarnRepeatedAction(P.action.tool,P.action.input);let O=b[0]?.id??`${r}:${h}:single:${P.action.tool}`;await this.emitEvent("action",{turn:r,step:h,meta:{tool:P.action.tool,input:P.action.input,action_id:O,phase:"dispatch",thinking:P.thinking}}),await X(this.hooks,"onAction",{sessionId:this.id,turn:r,step:h,action:P.action,thinking:P.thinking,history:Wt(this.history)});let $=await this.executeToolAction(O,P.action.tool,P.action.input,r,h);if($.rejected){this.history.push(ys({...$,observation:$.observation||`User denied tool execution: ${P.action.tool}`})),f="cancelled",d="\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:h,content:d,role:"assistant",meta:{rejected:!0,phase:"result",action_id:$.actionId,error_type:$.errorType??"approval_denied",duration_ms:$.durationMs}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,tokenUsage:J,turnUsage:{...s},steps:o});break}let se=$.observation;this.history.push({role:"tool",content:se,tool_call_id:$.actionId,name:P.action.tool});let Ce=o[o.length-1];Ce&&(Ce.observation=se),await this.emitEvent("observation",{turn:r,step:h,content:se,meta:{tool:P.action.tool,action_id:$.actionId,phase:"result",status:$.status,error_type:$.errorType,duration_ms:$.durationMs}}),await X(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:h,tool:P.action.tool,observation:se,resultStatus:$.status,history:Wt(this.history)});continue}if(j==="end_turn"||P.final){this.resetActionRepetition();let O=j==="end_turn"&&!P.final&&T.trim().length===0&&!!_&&A===h-1;d=O?_??"":P.final||T,P.final&&(P.final=d),await this.emitEvent("final",{turn:r,step:h,content:d,role:"assistant",meta:{tokens:J,fallback_from_previous_text:O||void 0}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,tokenUsage:J,turnUsage:{...s},steps:o});break}this.resetActionRepetition();break}return!d&&f!=="cancelled"&&(f==="ok"&&(f="error"),d="Unable to produce a final answer. Please retry or adjust the request.",g=d,this.history.push({role:"assistant",content:d}),await this.emitEvent("final",{turn:r,content:d,role:"assistant"}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:d,status:f,errorMessage:g,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:f,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:m||void 0}}),{finalText:d,steps:o,status:f,errorMessage:g,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}})}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async compactHistory(e="manual"){return this.compactHistoryInternal(e,this.turnIndex,0)}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=ei({sessionId:this.id,type:e,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await wl(r,this.sinks)}};async function yr(t,e={}){let n=e.sessionId||aw(),r=await gl(t,{...e,sessionId:n},n),o=await r.loadPrompt(),s=new hr({...t,...r},{...e,sessionId:n,mode:e.mode??mr},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as Xt}from"crypto";import{readFile as Sv}from"fs/promises";import{useCallback as Y,useEffect as Yt,useMemo as bn,useReducer as wv,useRef as Lr,useState as ne}from"react";import{Box as Lu,Text as _v,useApp as vv}from"ink";import{memo as Mw,useMemo as jl,useRef as zl,useEffect as kw}from"react";import{Box as Bl,Static as Ew,Text as Sr}from"ink";import{memo as Cs}from"react";import{Box as at,Text as ae}from"ink";var Ie={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import jt from"path";var cw="success",hn=".";function _s(t){return t?t===cw?Ie.SUCCESS:Ie.ERROR:Ie.SUCCESS}function Al(t){if(t?.length)return t.map(e=>_s(e))}function Rl(t,e){return!e||e<=0||!t||t<=0?0:Math.min(100,t/e*100)}function yn(t,e=80){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function Ol(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function vs(t,e){let n=t.trim();if(!n)return t;if(n===hn)return hn;if(jt.isAbsolute(n)){let r=jt.relative(jt.resolve(e),n);return r?jt.normalize(r):hn}if(n.startsWith("./")||n.startsWith("../")){let r=jt.normalize(n);return!r||r==="."||r==="./"?hn:r}return n}function Il(t){return t?t===hn||jt.isAbsolute(t)?!0:t.startsWith("./")||t.startsWith("../"):!1}import{memo as gw,useMemo as hw}from"react";import{Box as Ue,Text as ke}from"ink";import{marked as lw}from"marked";var uw=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Sn(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)?Sn(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Sn(r.tokens):"").filter(Boolean).join(`
216
- `):""}).join("")}function pw(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 dw(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 Nl(t){if(!t)return[];let e=[],n=0;for(let r of t.matchAll(uw)){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(dw(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 fw(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Sn(t.tokens):""}function mw(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Sn(t.tokens):typeof t.raw=="string"?t.raw.split(`
215
+ `),ft=Ze.map(R=>R.status),be=ft.find(R=>R!==fs)??fs,Ee=o[o.length-1];if(Ee&&(Ee.observation=je),await X(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:h,tool:b.map(R=>R.name).join(", "),observation:je,resultStatus:be,parallelResultStatuses:ft,history:Wt(this.history)}),we.hasRejection){let R=Ze.find(D=>D.rejected);f="cancelled",d="\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:h,content:d,role:"assistant",meta:{rejected:!0,phase:"result",action_id:R?.actionId,error_type:R?.errorType??"approval_denied",duration_ms:R?.durationMs}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,tokenUsage:J,turnUsage:{...s},steps:o});break}continue}else if(P.action){this.maybeWarnRepeatedAction(P.action.tool,P.action.input);let O=b[0]?.id??`${r}:${h}:single:${P.action.tool}`;await this.emitEvent("action",{turn:r,step:h,meta:{tool:P.action.tool,input:P.action.input,action_id:O,phase:"dispatch",thinking:P.thinking}}),await X(this.hooks,"onAction",{sessionId:this.id,turn:r,step:h,action:P.action,thinking:P.thinking,history:Wt(this.history)});let $=await this.executeToolAction(O,P.action.tool,P.action.input,r,h);if($.rejected){this.history.push(ys({...$,observation:$.observation||`User denied tool execution: ${P.action.tool}`})),f="cancelled",d="\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:h,content:d,role:"assistant",meta:{rejected:!0,phase:"result",action_id:$.actionId,error_type:$.errorType??"approval_denied",duration_ms:$.durationMs}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,tokenUsage:J,turnUsage:{...s},steps:o});break}let se=$.observation;this.history.push({role:"tool",content:se,tool_call_id:$.actionId,name:P.action.tool});let Ce=o[o.length-1];Ce&&(Ce.observation=se),await this.emitEvent("observation",{turn:r,step:h,content:se,meta:{tool:P.action.tool,action_id:$.actionId,phase:"result",status:$.status,error_type:$.errorType,duration_ms:$.durationMs}}),await X(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:h,tool:P.action.tool,observation:se,resultStatus:$.status,history:Wt(this.history)});continue}if(j==="end_turn"||P.final){this.resetActionRepetition();let O=j==="end_turn"&&!P.final&&T.trim().length===0&&!!_&&A===h-1;d=O?_??"":P.final||T,P.final&&(P.final=d),await this.emitEvent("final",{turn:r,step:h,content:d,role:"assistant",meta:{tokens:J,fallback_from_previous_text:O||void 0}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:h,finalText:d,status:f,tokenUsage:J,turnUsage:{...s},steps:o});break}this.resetActionRepetition();break}return!d&&f!=="cancelled"&&(f==="ok"&&(f="error"),d="Unable to produce a final answer. Please retry or adjust the request.",g=d,this.history.push({role:"assistant",content:d}),await this.emitEvent("final",{turn:r,content:d,role:"assistant"}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:d,status:f,errorMessage:g,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:f,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:m||void 0}}),{finalText:d,steps:o,status:f,errorMessage:g,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}})}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async compactHistory(e="manual"){return this.compactHistoryInternal(e,this.turnIndex,0)}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=ei({sessionId:this.id,type:e,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Sl(r,this.sinks)}};async function yr(t,e={}){let n=e.sessionId||aw(),r=await ml(t,{...e,sessionId:n},n),o=await r.loadPrompt(),s=new hr({...t,...r},{...e,sessionId:n,mode:e.mode??mr},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as Xt}from"crypto";import{readFile as Sv}from"fs/promises";import{useCallback as Y,useEffect as Yt,useMemo as bn,useReducer as wv,useRef as Lr,useState as ne}from"react";import{Box as Iu,Text as _v,useApp as vv}from"ink";import{memo as Mw,useMemo as Wl,useRef as jl,useEffect as kw}from"react";import{Box as Hl,Static as Ew,Text as Sr}from"ink";import{memo as Cs}from"react";import{Box as at,Text as ae}from"ink";var Ie={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import jt from"path";var cw="success",hn=".";function _s(t){return t?t===cw?Ie.SUCCESS:Ie.ERROR:Ie.SUCCESS}function Pl(t){if(t?.length)return t.map(e=>_s(e))}function Al(t,e){return!e||e<=0||!t||t<=0?0:Math.min(100,t/e*100)}function yn(t,e=80){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function Rl(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function vs(t,e){let n=t.trim();if(!n)return t;if(n===hn)return hn;if(jt.isAbsolute(n)){let r=jt.relative(jt.resolve(e),n);return r?jt.normalize(r):hn}if(n.startsWith("./")||n.startsWith("../")){let r=jt.normalize(n);return!r||r==="."||r==="./"?hn:r}return n}function Ol(t){return t?t===hn||jt.isAbsolute(t)?!0:t.startsWith("./")||t.startsWith("../"):!1}import{memo as gw,useMemo as hw}from"react";import{Box as Ue,Text as ke}from"ink";import{marked as lw}from"marked";var uw=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Sn(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)?Sn(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Sn(r.tokens):"").filter(Boolean).join(`
216
+ `):""}).join("")}function pw(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 dw(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 Ll(t){if(!t)return[];let e=[],n=0;for(let r of t.matchAll(uw)){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(dw(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 fw(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Sn(t.tokens):""}function mw(t){return typeof t.text=="string"&&t.text.length>0?t.text:Array.isArray(t.tokens)?Sn(t.tokens):typeof t.raw=="string"?t.raw.split(`
217
217
  `).map(e=>e.replace(/^>\s?/,"")).join(`
218
- `).trim():""}function Ll(t){return typeof t.text=="string"?t.text:Array.isArray(t.tokens)?Sn(t.tokens):typeof t.raw=="string"?t.raw:""}function $l(t){let{think:e,cleaned:n}=pw(t),r=[];e.length>0&&r.push({type:"think",content:e.join(`
218
+ `).trim():""}function Il(t){return typeof t.text=="string"?t.text:Array.isArray(t.tokens)?Sn(t.tokens):typeof t.raw=="string"?t.raw:""}function Nl(t){let{think:e,cleaned:n}=pw(t),r=[];e.length>0&&r.push({type:"think",content:e.join(`
219
219
 
220
- `)});let o=lw.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??Ll(s)});break}case"paragraph":case"text":{let i=Ll(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=mw(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(c=>fw(c)).filter(c=>c.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as bw,jsx as G,jsxs as zt}from"react/jsx-runtime";var yw="\u2014\u2014\u2014";function Sw(t,e){return t.repeat(Math.max(0,e))}function ww(t){let e=t.split(`
220
+ `)});let o=lw.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??Il(s)});break}case"paragraph":case"text":{let i=Il(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=mw(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(c=>fw(c)).filter(c=>c.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as bw,jsx as G,jsxs as zt}from"react/jsx-runtime";var yw="\u2014\u2014\u2014";function Sw(t,e){return t.repeat(Math.max(0,e))}function ww(t){let e=t.split(`
221
221
  `);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 _w(t){return t.split(`
222
- `)}function vw({content:t}){let e=_w(t);return G(Ue,{flexDirection:"column",marginY:1,children:e.map((n,r)=>G(ke,{children:n},r))})}function Tw({node:t}){switch(t.type){case"bold":return G(ke,{bold:!0,children:t.content});case"italic":return G(ke,{italic:!0,children:t.content});case"inlineCode":return G(ke,{color:"cyan",children:t.content});case"link":return zt(bw,{children:[G(ke,{color:"blue",underline:!0,children:t.label}),zt(ke,{color:"gray",children:[" (",t.href,")"]})]});case"text":return G(ke,{children:t.content});default:return null}}function Ts({content:t}){let e=Nl(t);return G(Ue,{flexWrap:"wrap",children:e.map((n,r)=>G(Tw,{node:n},r))})}function Cw(t,e){switch(t.type){case"html":return G(Ue,{children:G(ke,{color:"gray",dimColor:!0,children:t.content})},e);case"hr":return G(Ue,{marginY:1,children:G(ke,{color:"gray",dimColor:!0,children:yw})},e);case"think":return G(Ue,{flexDirection:"column",marginY:1,children:ww(t.content).map((n,r)=>G(ke,{color:"gray",dimColor:!0,children:n},r))},e);case"heading":return G(Ue,{children:zt(ke,{bold:!0,color:"cyan",children:[Sw("#",t.level)," ",t.content]})},e);case"paragraph":return G(Ts,{content:t.content},e);case"code":return G(vw,{content:t.content},e);case"blockquote":return G(Ue,{flexDirection:"column",children:t.content.split(`
223
- `).map((n,r)=>zt(Ue,{children:[G(ke,{color:"gray",dimColor:!0,children:"> "}),G(Ts,{content:n})]},r))},e);case"list":return G(Ue,{flexDirection:"column",children:t.items.map((n,r)=>zt(Ue,{children:[zt(ke,{color:"gray",children:[t.ordered?`${r+1}.`:"\u2022"," "]}),G(Ts,{content:n})]},r))},e);default:return null}}var Dl=gw(function({content:e}){let n=hw(()=>$l(e),[e]);return G(Ue,{flexDirection:"column",children:n.map((r,o)=>Cw(r,`${r.type}-${o}`))})});import{jsx as ve,jsxs as Le}from"react/jsx-runtime";function Fl(t){return t===Ie.ERROR?"red":t===Ie.EXECUTING?"yellow":"green"}function Ul(t,e){if(t==null)return null;if(typeof t=="string"){let s=Il(t)?vs(t,e):t;return yn(s,70)}if(typeof t!="object"||Array.isArray(t))return yn(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 c=String(i),a=o.has(s)?vs(c,e):c;return yn(a,70)}return yn(Ol(n),70)}var Hl=Cs(function({message:e}){let n=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return Le(at,{flexDirection:"column",children:[Le(ae,{color:n,children:["\u25CF ",e.title]}),ve(ae,{color:"gray",children:e.content})]})}),xw=Cs(function({step:e,cwd:n}){let r=!!(e.parallelActions&&e.parallelActions.length>1),o=!r&&e.action?Ul(e.action.input,n):null;return Le(at,{flexDirection:"column",children:[e.thinking?Le(at,{children:[ve(ae,{color:"gray",children:"\u25CF "}),ve(ae,{color:"gray",children:e.thinking})]}):null,r?e.parallelActions?.map((s,i)=>{let c=Ul(s.input,n);return Le(at,{children:[Le(ae,{color:Fl(e.parallelToolStatuses?.[i]??e.toolStatus),children:["\u25CF"," "]}),ve(ae,{color:"gray",children:"Used "}),ve(ae,{color:"cyan",children:s.tool}),c?Le(ae,{color:"gray",children:[" (",c,")"]}):null]},`${s.tool}-${i}`)}):null,!r&&e.action?Le(at,{children:[ve(ae,{color:Fl(e.toolStatus),children:"\u25CF "}),ve(ae,{color:"gray",children:"Used "}),ve(ae,{color:"cyan",children:e.action.tool}),o?Le(ae,{color:"gray",children:[" (",o,")"]}):null]}):null]})}),bs=Cs(function({turn:e,cwd:n}){return Le(at,{flexDirection:"column",children:[Le(at,{marginY:.5,children:[ve(ae,{color:"gray",children:"\u203A "}),ve(ae,{children:e.userInput})]}),e.steps.map(r=>ve(xw,{step:r,cwd:n},`${e.index}-${r.index}`)),e.finalText?ve(at,{marginTop:0,children:ve(Dl,{content:e.finalText})}):null,e.status&&e.status!=="ok"?Le(ae,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?ve(ae,{color:"red",children:e.errorMessage}):null]})});import{jsx as wn,jsxs as _n}from"react/jsx-runtime";function Wl(t){return t.sequence??0}function Pw(t){return t.type==="header"}function Aw(t){return t.id!==void 0}function Rw(t){let e=zl("");return jl(()=>{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 Gl=Mw(function({header:e,systemMessages:n,turns:r,historicalTurns:o}){let s=Rw(e),i=zl(e.cwd);kw(()=>{i.current=e.cwd},[e.cwd]);let{completedTurns:c,inProgressTurn:a,staticItems:l}=jl(()=>{let p=[...o,...r],d=p.length>0?p[p.length-1]:void 0,f=d&&!!(d.finalText||d.status&&d.status!=="ok"),g=f?p:p.slice(0,-1),m=f?void 0:d,_={type:"header",data:e},A=[...n,...g];A.sort((x,T)=>Wl(x)-Wl(T));let h=[_,...A];return{completedTurns:g,inProgressTurn:m,staticItems:h}},[e,o,r,n]),u=i.current;return _n(Bl,{flexDirection:"column",children:[wn(Ew,{items:l,children:p=>Pw(p)?_n(Bl,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[wn(Sr,{bold:!0,children:"Memo Code CLI"}),_n(Sr,{color:"gray",children:[p.data.providerName," / ",p.data.model," \u2022 v",p.data.version]}),_n(Sr,{color:"gray",children:["cwd: ",p.data.cwd]}),_n(Sr,{color:"gray",children:["mcp: ",p.data.mcpNames.join(", ")||"none"]})]},`header-${s}`):Aw(p)?wn(Hl,{message:p},p.id):wn(bs,{turn:p,cwd:u},`turn-${p.sequence??p.index}`)}),a?wn(bs,{turn:a,cwd:u}):null]})});import{memo as Xw,useCallback as Ct,useEffect as xr,useMemo as fu,useRef as Tn,useState as lt}from"react";import{Box as Es,Text as Mr,useInput as Yw,useStdout as Jw}from"ink";async function ql(t){return Ti(t)}import{basename as Ow,resolve as xs}from"path";var Kl=new Map;function Vl(t){let e=xs(t);return process.platform==="win32"?e.toLowerCase():e}function Xl(t){return xs(t)}function Iw(t){let e=xs(t),n=Kl.get(e);if(n)return n;let r=new Nn({sessionsDir:e});return Kl.set(e,r),r}function Lw(t){let e=Date.parse(t);return Number.isFinite(e)?e:0}function Nw(t){let e=t.title?.trim();return e||Ow(t.filePath).replace(/\.jsonl$/i,"")}async function wr(t){let e=t.limit??10;if(e<=0)return[];let r=await Iw(t.sessionsDir).getAllSummaries(),o=Vl(t.cwd),s=t.activeSessionFile?Xl(t.activeSessionFile):null,i=t.keyword?.trim().toLowerCase(),c=new Set,a=[],l=[...r].sort((u,p)=>p.date.updatedAt.localeCompare(u.date.updatedAt));for(let u of l){if(a.length>=e)break;if(Vl(u.cwd)!==o)continue;let p=Xl(u.filePath);if(s&&p===s||c.has(p))continue;let d=Nw(u);i&&!d.toLowerCase().includes(i)||(c.add(p),a.push({id:p,cwd:t.cwd,input:d,ts:Lw(u.date.updatedAt),sessionFile:p}))}return a}import{memo as $w}from"react";import{Box as _r,Text as vr}from"ink";import{jsx as vt,jsxs as Fw}from"react/jsx-runtime";var Dw="#3a3a3a",Tr="#262626",Yl=$w(function({items:e,activeIndex:n,loading:r}){return r?vt(_r,{paddingX:1,backgroundColor:Tr,children:vt(vr,{color:"gray",children:"Loading..."})}):e.length?vt(_r,{flexDirection:"column",backgroundColor:Tr,children:e.map((o,s)=>{let i=s===n;return Fw(_r,{paddingX:1,gap:2,backgroundColor:i?Dw:Tr,children:[vt(vr,{color:i?"cyan":"white",bold:i,children:o.title}),o.subtitle?vt(vr,{color:"gray",children:o.subtitle}):null]},o.id)})}):vt(_r,{paddingX:1,backgroundColor:Tr,children:vt(vr,{color:"gray",children:"No matches"})})});import Uw from"string-width";var Hw=55296,Bw=56319,Ww=56320,jw=57343;function Jl(t){return t>=Hw&&t<=Bw}function Ql(t){return t>=Ww&&t<=jw}function Ne(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 Ql(r)&&Jl(o)?n-1:n}function Zl(t,e){let n=Ne(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 Tt(t,e){let n=Ne(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 Ql(o)&&Jl(s)?r-1:r}function Cr(t,e){let n=Ne(t,e),r=t.lastIndexOf(`
222
+ `)}function vw({content:t}){let e=_w(t);return G(Ue,{flexDirection:"column",marginY:1,children:e.map((n,r)=>G(ke,{children:n},r))})}function Tw({node:t}){switch(t.type){case"bold":return G(ke,{bold:!0,children:t.content});case"italic":return G(ke,{italic:!0,children:t.content});case"inlineCode":return G(ke,{color:"cyan",children:t.content});case"link":return zt(bw,{children:[G(ke,{color:"blue",underline:!0,children:t.label}),zt(ke,{color:"gray",children:[" (",t.href,")"]})]});case"text":return G(ke,{children:t.content});default:return null}}function Ts({content:t}){let e=Ll(t);return G(Ue,{flexWrap:"wrap",children:e.map((n,r)=>G(Tw,{node:n},r))})}function Cw(t,e){switch(t.type){case"html":return G(Ue,{children:G(ke,{color:"gray",dimColor:!0,children:t.content})},e);case"hr":return G(Ue,{marginY:1,children:G(ke,{color:"gray",dimColor:!0,children:yw})},e);case"think":return G(Ue,{flexDirection:"column",marginY:1,children:ww(t.content).map((n,r)=>G(ke,{color:"gray",dimColor:!0,children:n},r))},e);case"heading":return G(Ue,{children:zt(ke,{bold:!0,color:"cyan",children:[Sw("#",t.level)," ",t.content]})},e);case"paragraph":return G(Ts,{content:t.content},e);case"code":return G(vw,{content:t.content},e);case"blockquote":return G(Ue,{flexDirection:"column",children:t.content.split(`
223
+ `).map((n,r)=>zt(Ue,{children:[G(ke,{color:"gray",dimColor:!0,children:"> "}),G(Ts,{content:n})]},r))},e);case"list":return G(Ue,{flexDirection:"column",children:t.items.map((n,r)=>zt(Ue,{children:[zt(ke,{color:"gray",children:[t.ordered?`${r+1}.`:"\u2022"," "]}),G(Ts,{content:n})]},r))},e);default:return null}}var $l=gw(function({content:e}){let n=hw(()=>Nl(e),[e]);return G(Ue,{flexDirection:"column",children:n.map((r,o)=>Cw(r,`${r.type}-${o}`))})});import{jsx as ve,jsxs as Le}from"react/jsx-runtime";function Dl(t){return t===Ie.ERROR?"red":t===Ie.EXECUTING?"yellow":"green"}function Fl(t,e){if(t==null)return null;if(typeof t=="string"){let s=Ol(t)?vs(t,e):t;return yn(s,70)}if(typeof t!="object"||Array.isArray(t))return yn(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 c=String(i),a=o.has(s)?vs(c,e):c;return yn(a,70)}return yn(Rl(n),70)}var Ul=Cs(function({message:e}){let n=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return Le(at,{flexDirection:"column",children:[Le(ae,{color:n,children:["\u25CF ",e.title]}),ve(ae,{color:"gray",children:e.content})]})}),xw=Cs(function({step:e,cwd:n}){let r=!!(e.parallelActions&&e.parallelActions.length>1),o=!r&&e.action?Fl(e.action.input,n):null;return Le(at,{flexDirection:"column",children:[e.thinking?Le(at,{children:[ve(ae,{color:"gray",children:"\u25CF "}),ve(ae,{color:"gray",children:e.thinking})]}):null,r?e.parallelActions?.map((s,i)=>{let c=Fl(s.input,n);return Le(at,{children:[Le(ae,{color:Dl(e.parallelToolStatuses?.[i]??e.toolStatus),children:["\u25CF"," "]}),ve(ae,{color:"gray",children:"Used "}),ve(ae,{color:"cyan",children:s.tool}),c?Le(ae,{color:"gray",children:[" (",c,")"]}):null]},`${s.tool}-${i}`)}):null,!r&&e.action?Le(at,{children:[ve(ae,{color:Dl(e.toolStatus),children:"\u25CF "}),ve(ae,{color:"gray",children:"Used "}),ve(ae,{color:"cyan",children:e.action.tool}),o?Le(ae,{color:"gray",children:[" (",o,")"]}):null]}):null]})}),bs=Cs(function({turn:e,cwd:n}){return Le(at,{flexDirection:"column",children:[Le(at,{marginY:.5,children:[ve(ae,{color:"gray",children:"\u203A "}),ve(ae,{children:e.userInput})]}),e.steps.map(r=>ve(xw,{step:r,cwd:n},`${e.index}-${r.index}`)),e.finalText?ve(at,{marginTop:0,children:ve($l,{content:e.finalText})}):null,e.status&&e.status!=="ok"?Le(ae,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?ve(ae,{color:"red",children:e.errorMessage}):null]})});import{jsx as wn,jsxs as _n}from"react/jsx-runtime";function Bl(t){return t.sequence??0}function Pw(t){return t.type==="header"}function Aw(t){return t.id!==void 0}function Rw(t){let e=jl("");return Wl(()=>{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 zl=Mw(function({header:e,systemMessages:n,turns:r,historicalTurns:o}){let s=Rw(e),i=jl(e.cwd);kw(()=>{i.current=e.cwd},[e.cwd]);let{completedTurns:c,inProgressTurn:a,staticItems:l}=Wl(()=>{let p=[...o,...r],d=p.length>0?p[p.length-1]:void 0,f=d&&!!(d.finalText||d.status&&d.status!=="ok"),g=f?p:p.slice(0,-1),m=f?void 0:d,_={type:"header",data:e},A=[...n,...g];A.sort((x,T)=>Bl(x)-Bl(T));let h=[_,...A];return{completedTurns:g,inProgressTurn:m,staticItems:h}},[e,o,r,n]),u=i.current;return _n(Hl,{flexDirection:"column",children:[wn(Ew,{items:l,children:p=>Pw(p)?_n(Hl,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[wn(Sr,{bold:!0,children:"Memo Code CLI"}),_n(Sr,{color:"gray",children:[p.data.providerName," / ",p.data.model," \u2022 v",p.data.version]}),_n(Sr,{color:"gray",children:["cwd: ",p.data.cwd]}),_n(Sr,{color:"gray",children:["mcp: ",p.data.mcpNames.join(", ")||"none"]})]},`header-${s}`):Aw(p)?wn(Ul,{message:p},p.id):wn(bs,{turn:p,cwd:u},`turn-${p.sequence??p.index}`)}),a?wn(bs,{turn:a,cwd:u}):null]})});import{memo as Xw,useCallback as Ct,useEffect as xr,useMemo as du,useRef as Tn,useState as lt}from"react";import{Box as Es,Text as Mr,useInput as Yw,useStdout as Jw}from"ink";async function Gl(t){return Ti(t)}import{basename as Ow,resolve as xs}from"path";var ql=new Map;function Kl(t){let e=xs(t);return process.platform==="win32"?e.toLowerCase():e}function Vl(t){return xs(t)}function Iw(t){let e=xs(t),n=ql.get(e);if(n)return n;let r=new Nn({sessionsDir:e});return ql.set(e,r),r}function Lw(t){let e=Date.parse(t);return Number.isFinite(e)?e:0}function Nw(t){let e=t.title?.trim();return e||Ow(t.filePath).replace(/\.jsonl$/i,"")}async function wr(t){let e=t.limit??10;if(e<=0)return[];let r=await Iw(t.sessionsDir).getAllSummaries(),o=Kl(t.cwd),s=t.activeSessionFile?Vl(t.activeSessionFile):null,i=t.keyword?.trim().toLowerCase(),c=new Set,a=[],l=[...r].sort((u,p)=>p.date.updatedAt.localeCompare(u.date.updatedAt));for(let u of l){if(a.length>=e)break;if(Kl(u.cwd)!==o)continue;let p=Vl(u.filePath);if(s&&p===s||c.has(p))continue;let d=Nw(u);i&&!d.toLowerCase().includes(i)||(c.add(p),a.push({id:p,cwd:t.cwd,input:d,ts:Lw(u.date.updatedAt),sessionFile:p}))}return a}import{memo as $w}from"react";import{Box as _r,Text as vr}from"ink";import{jsx as vt,jsxs as Fw}from"react/jsx-runtime";var Dw="#3a3a3a",Tr="#262626",Xl=$w(function({items:e,activeIndex:n,loading:r}){return r?vt(_r,{paddingX:1,backgroundColor:Tr,children:vt(vr,{color:"gray",children:"Loading..."})}):e.length?vt(_r,{flexDirection:"column",backgroundColor:Tr,children:e.map((o,s)=>{let i=s===n;return Fw(_r,{paddingX:1,gap:2,backgroundColor:i?Dw:Tr,children:[vt(vr,{color:i?"cyan":"white",bold:i,children:o.title}),o.subtitle?vt(vr,{color:"gray",children:o.subtitle}):null]},o.id)})}):vt(_r,{paddingX:1,backgroundColor:Tr,children:vt(vr,{color:"gray",children:"No matches"})})});import Uw from"string-width";var Hw=55296,Bw=56319,Ww=56320,jw=57343;function Yl(t){return t>=Hw&&t<=Bw}function Jl(t){return t>=Ww&&t<=jw}function Ne(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 Jl(r)&&Yl(o)?n-1:n}function Ql(t,e){let n=Ne(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 Tt(t,e){let n=Ne(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 Jl(o)&&Yl(s)?r-1:r}function Cr(t,e){let n=Ne(t,e),r=t.lastIndexOf(`
224
224
  `,Math.max(0,n-1));return r===-1?0:r+1}function br(t,e){let n=Ne(t,e),r=t.indexOf(`
225
- `,n);return r===-1?t.length:r}function zw(t){return/[\p{L}\p{N}_]/u.test(t)}function eu(t,e,n){let r=Ne(t,e);if(!n)return{value:t,cursor:r};let o=n.replace(/\r\n?/g,`
226
- `);return o?{value:`${t.slice(0,r)}${o}${t.slice(r)}`,cursor:r+o.length}:{value:t,cursor:r}}function tu(t,e){let n=Ne(t,e);if(n<=0)return{value:t,cursor:n};let r=Tt(t,n);return{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function Ms(t,e){let n=Ne(t,e);if(n>=t.length)return{value:t,cursor:n};let r=Zl(t,n);return{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function nu(t,e){let n=Ne(t,e);if(n<=0)return{value:t,cursor:n};let r=n;for(;r>0;){let s=Tt(t,r);if(t.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=Tt(t,r),i=t.slice(s,r);if(!zw(i))break;r=s}return r===n&&(r=Tt(t,n)),{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function ru(t,e){let n=Ne(t,e),r=Cr(t,n);return r>=n?{value:t,cursor:n}:{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function ou(t,e){let n=Ne(t,e),r=br(t,n);return r<=n?{value:t,cursor:n}:{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function su(t,e){return Tt(t,e)}function iu(t,e){return Zl(t,e)}function au(t,e){return Cr(t,e)}function cu(t,e){return br(t,e)}function ks(t,e,n,r){let o=Ne(t,e),s=Cr(t,o),i=br(t,o),c=o-s,a=r??c;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:a,changed:!1};let d=s-1,f=Cr(t,d),g=Math.min(f+a,d);return{cursor:g,preferredColumn:a,changed:g!==o}}if(i>=t.length)return{cursor:o,preferredColumn:a,changed:!1};let l=i+1,u=br(t,l),p=Math.min(l+a,u);return{cursor:p,preferredColumn:a,changed:p!==o}}function lu(t,e,n){let r=Ne(t,e),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,c=0,a="",l=0,u=()=>{s.push({text:a,start:i,end:c})},p=0;for(let g of t){let m=p;if(p+=g.length,g===`
227
- `){c=m,u(),i=p,c=p,a="",l=0;continue}let _=Math.max(0,Uw(g));a.length>0&&l+_>o&&(u(),i=m,c=m,a="",l=0),a+=g,c=p,l+=_}if(u(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let d=Math.max(0,s.length-1),f=(s[d]?.text??"").length;for(let g=0;g<s.length;g+=1){let m=s[g];if(m&&!(r<m.start)&&r<=m.end){d=g,f=r-m.start;break}}return{lines:s,row:d,cursorInRow:f}}function uu(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 Gw=3,pu=8,qw=120,Kw=process.platform==="win32"?60:8,vn=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(e={}){this.minChars=e.minChars??Gw,this.charIntervalMs=e.charIntervalMs??pu,this.enterSuppressWindowMs=e.enterSuppressWindowMs??qw,this.activeIdleTimeoutMs=e.activeIdleTimeoutMs??Kw}static recommendedFlushDelayMs(){return pu+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+=`
228
- `,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=Vw(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 Vw(t,e){if(e<=0)return t.length;let n=t.length,r=e;for(;r>0&&n>0;)n=Tt(t,n),r-=1;return n}var We={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",COMPACT:"compact",MCP:"mcp",INIT:"init"},Te={NONE:"none",ONCE:"once",FULL:"full"};function ct(t){return`/${t}`}var du="exit";import{jsx as Gt,jsxs as mu}from"react/jsx-runtime";var Qw=400,Ps=ct(We.MODELS),As=ct(We.TOOLS),Zw=ct(We.INIT),e_=[{mode:Te.NONE,description:"Disable all tool calls"},{mode:Te.ONCE,description:"Require approval when needed"},{mode:Te.FULL,description:"Run tools without approval"}];function t_(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 n_(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(We.RESUME)||t.slice(0,n).trim().length>0)return null;let s=r.slice(We.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function r_(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 o_(t){let e=t.trimStart();if(!e.startsWith(Ps))return null;let n=e.slice(Ps.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function s_(t){let e=t.trimStart();if(!e.startsWith(As))return null;let n=e.slice(As.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function i_(t){return s_(t)??o_(t)??r_(t)??t_(t)??n_(t)}function a_(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 c_(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:`${Ps} ${r.name}`,meta:{type:"model",provider:r}}))}}function l_(t){return{mode:"tools",items:e_.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===t?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${As} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function u_(t){return{mode:"slash",items:sn.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 p_({trigger:t,cwd:e,sessionsDir:n,currentSessionFile:r,providers:o,toolPermissionMode:s}){switch(t.type){case"file":return{mode:"file",items:(await ql({cwd:e,query:t.query,limit:8,respectGitIgnore:!0})).map(a=>({id:a.id,title:a.isDir?`${a.path}/`:a.path,kind:"file",value:a.isDir?`${a.path}/`:a.path,meta:{type:"file",isDir:a.isDir}}))};case"history":return{mode:"history",items:(await wr({sessionsDir:n,cwd:e,keyword:t.keyword,activeSessionFile:r})).map(a=>({id:a.id,title:a.input,subtitle:a_(a.ts),kind:"history",value:a.input,meta:{type:"history",entry:a}}))};case"models":return c_(o,t.keyword);case"tools":return l_(s);case"slash":return u_(t.keyword)}}var gu=Xw(function({disabled:e,busy:n,history:r,cwd:o,sessionsDir:s,currentSessionFile:i,providers:c,configPath:a,providerName:l,model:u,toolPermissionMode:p,mcpServers:d,onSubmit:f,onExit:g,onClear:m,onNewSession:_,onCancelRun:A,onCompact:h,onHistorySelect:x,onModelSelect:T,onSetToolPermission:b,onReviewPullRequest:H,onSystemMessage:j}){let{stdout:Se}=Jw(),[ce,q]=lt({value:"",cursor:0}),P=Tn(ce),L=Tn(null),[oe,le]=lt(null),[B,ue]=lt(""),[J,O]=lt("none"),[$,se]=lt([]),[Ce,we]=lt(0),[Ze,je]=lt(!1),[ft,be]=lt(!1),Ee=Tn(0),R=Tn(0),D=Tn(new vn);xr(()=>{P.current=ce,be(!1)},[ce]);let Mn=fu(()=>({configPath:a,providerName:l,model:u,mcpServers:d,providers:c,toolPermissionMode:p}),[a,l,u,d,c,p]),xe=fu(()=>e||ft?null:i_(ce.value),[e,ce.value,ft]),K=Ct((M=!0)=>{M&&be(!0),O("none"),se([]),we(0),je(!1)},[]),U=Ct((M,v=!1)=>{P.current=M,q(M),v&&(le(null),ue(""))},[]),Jt=Ct(()=>{U({value:"",cursor:0},!0)},[U]),F=Ct((M,v=!0)=>{if(!M)return;let w=P.current;L.current=null;let ee=eu(w.value,w.cursor,M);U(ee,v),M.includes(`
229
- `)&&K(!1)},[U,K]),mt=Ct(M=>M.type==="none"?!1:M.type==="paste"?(M.text&&F(M.text,!0),!0):(F(M.text,!0),!0),[F]),pe=Ct((M=!0)=>{let v=D.current.flushBeforeModifiedInput();return v&&F(v,!0),M&&D.current.clearWindowAfterNonChar(),!!v},[F]);xr(()=>{let M=setInterval(()=>{let v=D.current.flushIfDue(Date.now());mt(v)},vn.recommendedFlushDelayMs());return()=>{clearInterval(M)}},[mt]),xr(()=>{e&&K(!1)},[e,K]),xr(()=>{if(!xe){K(!1);return}let M=!1,v=++Ee.current;return je(!0),(async()=>{try{let{mode:w,items:ee}=await p_({trigger:xe,cwd:o,sessionsDir:s,currentSessionFile:i,providers:c,toolPermissionMode:p});if(M||v!==Ee.current)return;O(w),se(ee),we(ie=>ee.length?Math.min(ie,ee.length-1):0)}finally{!M&&v===Ee.current&&je(!1)}})(),()=>{M=!0}},[xe,o,s,i,c,p,K]);let et=Ct(M=>{if(M){if(J==="file"&&xe?.type==="file"){let v=P.current.value,w=v.slice(0,xe.tokenStart),ee=v.slice(xe.tokenStart+xe.query.length),ie=`${w}${M.value}${ee}`,ze=w.length+M.value.length;U({value:ie,cursor:ze},!0),M.meta?.type==="file"&&M.meta.isDir||K();return}switch(M.meta?.type){case"history":x(M.meta.entry),U({value:M.value,cursor:M.value.length},!1),K();return;case"model":T(M.meta.provider),Jt(),K();return;case"tools":b(M.meta.mode),Jt(),K();return;case"slash":U({value:`${M.value} `,cursor:`${M.value} `.length},!0),K(!1);return;default:U({value:M.value,cursor:M.value.length},!0),K()}}},[U,J,xe,K,Jt,x,T,b]);Yw((M,v)=>{if(v.ctrl&&M==="c"){g();return}if(e)return;let w=Date.now();mt(D.current.flushIfDue(w));let ee=J!=="none",ie=ee&&$.length>0,ze=uu(M,v),Fr=!!(v.ctrl||v.meta),Qt=!!M&&!Fr&&!v.return&&!v.tab&&ze==="none"&&!v.escape&&!v.upArrow&&!v.downArrow&&!v.leftArrow&&!v.rightArrow;if(!Qt&&!v.return&&pe(!0),v.ctrl&&M==="a"){let E=P.current,N=au(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.ctrl&&M==="e"){let E=P.current,N=cu(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.ctrl&&M==="u"){let E=P.current,N=ru(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="k"){let E=P.current,N=ou(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="w"){let E=P.current,N=nu(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="d"){let E=P.current;if(!E.value){g();return}let N=Ms(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="l"){U({value:"",cursor:0},!0),K(),m(),_();return}if(v.escape){if(w-R.current<=Qw){R.current=0,n?A():(L.current=null,U({value:"",cursor:0},!0),K());return}R.current=w,ee&&K();return}if(v.upArrow){if(ie){we(W=>W<=0?$.length-1:W-1);return}let E=P.current;if(E.value.includes(`
225
+ `,n);return r===-1?t.length:r}function zw(t){return/[\p{L}\p{N}_]/u.test(t)}function Zl(t,e,n){let r=Ne(t,e);if(!n)return{value:t,cursor:r};let o=n.replace(/\r\n?/g,`
226
+ `);return o?{value:`${t.slice(0,r)}${o}${t.slice(r)}`,cursor:r+o.length}:{value:t,cursor:r}}function eu(t,e){let n=Ne(t,e);if(n<=0)return{value:t,cursor:n};let r=Tt(t,n);return{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function Ms(t,e){let n=Ne(t,e);if(n>=t.length)return{value:t,cursor:n};let r=Ql(t,n);return{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function tu(t,e){let n=Ne(t,e);if(n<=0)return{value:t,cursor:n};let r=n;for(;r>0;){let s=Tt(t,r);if(t.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=Tt(t,r),i=t.slice(s,r);if(!zw(i))break;r=s}return r===n&&(r=Tt(t,n)),{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function nu(t,e){let n=Ne(t,e),r=Cr(t,n);return r>=n?{value:t,cursor:n}:{value:`${t.slice(0,r)}${t.slice(n)}`,cursor:r}}function ru(t,e){let n=Ne(t,e),r=br(t,n);return r<=n?{value:t,cursor:n}:{value:`${t.slice(0,n)}${t.slice(r)}`,cursor:n}}function ou(t,e){return Tt(t,e)}function su(t,e){return Ql(t,e)}function iu(t,e){return Cr(t,e)}function au(t,e){return br(t,e)}function ks(t,e,n,r){let o=Ne(t,e),s=Cr(t,o),i=br(t,o),c=o-s,a=r??c;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:a,changed:!1};let d=s-1,f=Cr(t,d),g=Math.min(f+a,d);return{cursor:g,preferredColumn:a,changed:g!==o}}if(i>=t.length)return{cursor:o,preferredColumn:a,changed:!1};let l=i+1,u=br(t,l),p=Math.min(l+a,u);return{cursor:p,preferredColumn:a,changed:p!==o}}function cu(t,e,n){let r=Ne(t,e),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,c=0,a="",l=0,u=()=>{s.push({text:a,start:i,end:c})},p=0;for(let g of t){let m=p;if(p+=g.length,g===`
227
+ `){c=m,u(),i=p,c=p,a="",l=0;continue}let _=Math.max(0,Uw(g));a.length>0&&l+_>o&&(u(),i=m,c=m,a="",l=0),a+=g,c=p,l+=_}if(u(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let d=Math.max(0,s.length-1),f=(s[d]?.text??"").length;for(let g=0;g<s.length;g+=1){let m=s[g];if(m&&!(r<m.start)&&r<=m.end){d=g,f=r-m.start;break}}return{lines:s,row:d,cursorInRow:f}}function lu(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 Gw=3,uu=8,qw=120,Kw=process.platform==="win32"?60:8,vn=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(e={}){this.minChars=e.minChars??Gw,this.charIntervalMs=e.charIntervalMs??uu,this.enterSuppressWindowMs=e.enterSuppressWindowMs??qw,this.activeIdleTimeoutMs=e.activeIdleTimeoutMs??Kw}static recommendedFlushDelayMs(){return uu+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+=`
228
+ `,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=Vw(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 Vw(t,e){if(e<=0)return t.length;let n=t.length,r=e;for(;r>0&&n>0;)n=Tt(t,n),r-=1;return n}var We={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",COMPACT:"compact",MCP:"mcp",INIT:"init"},Te={NONE:"none",ONCE:"once",FULL:"full"};function ct(t){return`/${t}`}var pu="exit";import{jsx as Gt,jsxs as fu}from"react/jsx-runtime";var Qw=400,Ps=ct(We.MODELS),As=ct(We.TOOLS),Zw=ct(We.INIT),e_=[{mode:Te.NONE,description:"Disable all tool calls"},{mode:Te.ONCE,description:"Require approval when needed"},{mode:Te.FULL,description:"Run tools without approval"}];function t_(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 n_(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(We.RESUME)||t.slice(0,n).trim().length>0)return null;let s=r.slice(We.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function r_(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 o_(t){let e=t.trimStart();if(!e.startsWith(Ps))return null;let n=e.slice(Ps.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function s_(t){let e=t.trimStart();if(!e.startsWith(As))return null;let n=e.slice(As.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function i_(t){return s_(t)??o_(t)??r_(t)??t_(t)??n_(t)}function a_(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 c_(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:`${Ps} ${r.name}`,meta:{type:"model",provider:r}}))}}function l_(t){return{mode:"tools",items:e_.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===t?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${As} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function u_(t){return{mode:"slash",items:sn.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 p_({trigger:t,cwd:e,sessionsDir:n,currentSessionFile:r,providers:o,toolPermissionMode:s}){switch(t.type){case"file":return{mode:"file",items:(await Gl({cwd:e,query:t.query,limit:8,respectGitIgnore:!0})).map(a=>({id:a.id,title:a.isDir?`${a.path}/`:a.path,kind:"file",value:a.isDir?`${a.path}/`:a.path,meta:{type:"file",isDir:a.isDir}}))};case"history":return{mode:"history",items:(await wr({sessionsDir:n,cwd:e,keyword:t.keyword,activeSessionFile:r})).map(a=>({id:a.id,title:a.input,subtitle:a_(a.ts),kind:"history",value:a.input,meta:{type:"history",entry:a}}))};case"models":return c_(o,t.keyword);case"tools":return l_(s);case"slash":return u_(t.keyword)}}var mu=Xw(function({disabled:e,busy:n,history:r,cwd:o,sessionsDir:s,currentSessionFile:i,providers:c,configPath:a,providerName:l,model:u,toolPermissionMode:p,mcpServers:d,onSubmit:f,onExit:g,onClear:m,onNewSession:_,onCancelRun:A,onCompact:h,onHistorySelect:x,onModelSelect:T,onSetToolPermission:b,onReviewPullRequest:H,onSystemMessage:j}){let{stdout:Se}=Jw(),[ce,q]=lt({value:"",cursor:0}),P=Tn(ce),L=Tn(null),[oe,le]=lt(null),[B,ue]=lt(""),[J,O]=lt("none"),[$,se]=lt([]),[Ce,we]=lt(0),[Ze,je]=lt(!1),[ft,be]=lt(!1),Ee=Tn(0),R=Tn(0),D=Tn(new vn);xr(()=>{P.current=ce,be(!1)},[ce]);let Mn=du(()=>({configPath:a,providerName:l,model:u,mcpServers:d,providers:c,toolPermissionMode:p}),[a,l,u,d,c,p]),xe=du(()=>e||ft?null:i_(ce.value),[e,ce.value,ft]),K=Ct((M=!0)=>{M&&be(!0),O("none"),se([]),we(0),je(!1)},[]),U=Ct((M,v=!1)=>{P.current=M,q(M),v&&(le(null),ue(""))},[]),Jt=Ct(()=>{U({value:"",cursor:0},!0)},[U]),F=Ct((M,v=!0)=>{if(!M)return;let w=P.current;L.current=null;let ee=Zl(w.value,w.cursor,M);U(ee,v),M.includes(`
229
+ `)&&K(!1)},[U,K]),mt=Ct(M=>M.type==="none"?!1:M.type==="paste"?(M.text&&F(M.text,!0),!0):(F(M.text,!0),!0),[F]),pe=Ct((M=!0)=>{let v=D.current.flushBeforeModifiedInput();return v&&F(v,!0),M&&D.current.clearWindowAfterNonChar(),!!v},[F]);xr(()=>{let M=setInterval(()=>{let v=D.current.flushIfDue(Date.now());mt(v)},vn.recommendedFlushDelayMs());return()=>{clearInterval(M)}},[mt]),xr(()=>{e&&K(!1)},[e,K]),xr(()=>{if(!xe){K(!1);return}let M=!1,v=++Ee.current;return je(!0),(async()=>{try{let{mode:w,items:ee}=await p_({trigger:xe,cwd:o,sessionsDir:s,currentSessionFile:i,providers:c,toolPermissionMode:p});if(M||v!==Ee.current)return;O(w),se(ee),we(ie=>ee.length?Math.min(ie,ee.length-1):0)}finally{!M&&v===Ee.current&&je(!1)}})(),()=>{M=!0}},[xe,o,s,i,c,p,K]);let et=Ct(M=>{if(M){if(J==="file"&&xe?.type==="file"){let v=P.current.value,w=v.slice(0,xe.tokenStart),ee=v.slice(xe.tokenStart+xe.query.length),ie=`${w}${M.value}${ee}`,ze=w.length+M.value.length;U({value:ie,cursor:ze},!0),M.meta?.type==="file"&&M.meta.isDir||K();return}switch(M.meta?.type){case"history":x(M.meta.entry),U({value:M.value,cursor:M.value.length},!1),K();return;case"model":T(M.meta.provider),Jt(),K();return;case"tools":b(M.meta.mode),Jt(),K();return;case"slash":U({value:`${M.value} `,cursor:`${M.value} `.length},!0),K(!1);return;default:U({value:M.value,cursor:M.value.length},!0),K()}}},[U,J,xe,K,Jt,x,T,b]);Yw((M,v)=>{if(v.ctrl&&M==="c"){g();return}if(e)return;let w=Date.now();mt(D.current.flushIfDue(w));let ee=J!=="none",ie=ee&&$.length>0,ze=lu(M,v),Fr=!!(v.ctrl||v.meta),Qt=!!M&&!Fr&&!v.return&&!v.tab&&ze==="none"&&!v.escape&&!v.upArrow&&!v.downArrow&&!v.leftArrow&&!v.rightArrow;if(!Qt&&!v.return&&pe(!0),v.ctrl&&M==="a"){let E=P.current,N=iu(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.ctrl&&M==="e"){let E=P.current,N=au(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.ctrl&&M==="u"){let E=P.current,N=nu(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="k"){let E=P.current,N=ru(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="w"){let E=P.current,N=tu(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="d"){let E=P.current;if(!E.value){g();return}let N=Ms(E.value,E.cursor);L.current=null,U(N,!0);return}if(v.ctrl&&M==="l"){U({value:"",cursor:0},!0),K(),m(),_();return}if(v.escape){if(w-R.current<=Qw){R.current=0,n?A():(L.current=null,U({value:"",cursor:0},!0),K());return}R.current=w,ee&&K();return}if(v.upArrow){if(ie){we(W=>W<=0?$.length-1:W-1);return}let E=P.current;if(E.value.includes(`
230
230
  `)){let W=ks(E.value,E.cursor,"up",L.current??void 0);if(W.changed){L.current=W.preferredColumn,U({value:E.value,cursor:W.cursor},!1);return}}if(!r.length)return;if(oe===null){ue(E.value);let W=r.length-1;le(W);let Pe=r[W]??"";L.current=null,U({value:Pe,cursor:Pe.length},!1);return}let N=Math.max(0,oe-1);le(N);let de=r[N]??"";L.current=null,U({value:de,cursor:de.length},!1);return}if(v.downArrow){if(ie){we(W=>(W+1)%$.length);return}let E=P.current;if(E.value.includes(`
231
- `)){let W=ks(E.value,E.cursor,"down",L.current??void 0);if(W.changed){L.current=W.preferredColumn,U({value:E.value,cursor:W.cursor},!1);return}}if(oe===null)return;let N=oe+1;if(N>=r.length){le(null),L.current=null,U({value:B,cursor:B.length},!1),ue("");return}le(N);let de=r[N]??"";L.current=null,U({value:de,cursor:de.length},!1);return}if(v.leftArrow){let E=P.current,N=su(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.rightArrow){let E=P.current,N=iu(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.tab&&ie){et($[Ce]);return}if(v.return){if(ie){et($[Ce]);return}D.current.hasPendingFirstChar()&&!D.current.isBuffering()&&pe(!1);let E=P.current.value.trimStart().startsWith("/");if(!v.shift&&!E){if(D.current.appendNewlineIfActive(w))return;if(D.current.newlineShouldInsertInsteadOfSubmit(w)){pe(!1),F(`
231
+ `)){let W=ks(E.value,E.cursor,"down",L.current??void 0);if(W.changed){L.current=W.preferredColumn,U({value:E.value,cursor:W.cursor},!1);return}}if(oe===null)return;let N=oe+1;if(N>=r.length){le(null),L.current=null,U({value:B,cursor:B.length},!1),ue("");return}le(N);let de=r[N]??"";L.current=null,U({value:de,cursor:de.length},!1);return}if(v.leftArrow){let E=P.current,N=ou(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.rightArrow){let E=P.current,N=su(E.value,E.cursor);L.current=null,U({value:E.value,cursor:N},!1);return}if(v.tab&&ie){et($[Ce]);return}if(v.return){if(ie){et($[Ce]);return}D.current.hasPendingFirstChar()&&!D.current.isBuffering()&&pe(!1);let E=P.current.value.trimStart().startsWith("/");if(!v.shift&&!E){if(D.current.appendNewlineIfActive(w))return;if(D.current.newlineShouldInsertInsteadOfSubmit(w)){pe(!1),F(`
232
232
  `,!0),D.current.extendWindow(w);return}}if(pe(!0),v.shift){F(`
233
- `,!0);return}let de=P.current.value.trim();if(!de)return;if(de.startsWith("/")){let W=eo(de,Mn);switch(W.kind){case"message":j(W.title,W.content);break;case"new":_();break;case"exit":g();break;case"switch_model":T(W.provider);break;case"set_tool_permission":b(W.mode);break;case"compact":h();break;case"review_pr":H(W.prNumber);break;case"init_agents_md":f(Zw);break;default:{let Pe=W}}L.current=null,U({value:"",cursor:0},!0),K(!1);return}f(de),L.current=null,U({value:"",cursor:0},!0),K(!1);return}if(ze!=="none"){let E=P.current,N=ze==="backspace"?tu(E.value,E.cursor):Ms(E.value,E.cursor);L.current=null,U(N,!0);return}if(M&&Qt){let E=Array.from(M);if(E.length!==1){pe(!1),F(M,!0),D.current.clearAfterExplicitPaste();return}let N=E[0]??"";if(!N)return;let de=ht=>{let Mt=P.current,kn=Mt.value.slice(0,Mt.cursor),En=Mt.value.slice(Mt.cursor),Zt=D.current.decideBeginBuffer(w,kn,ht);return Zt?(L.current=null,U({value:`${kn.slice(0,Zt.start)}${En}`,cursor:Zt.start},!0),D.current.appendCharToBuffer(N,w),!0):!1};if(!((N.codePointAt(0)??0)<=127)){let ht=D.current.onPlainCharNoHold(w);if(ht?.type==="buffer_append"){D.current.appendCharToBuffer(N,w);return}if(ht?.type==="begin_buffer"&&de(ht.retroChars))return;pe(!1),F(N,!0);return}let Pe=D.current.onPlainChar(N,w);if(Pe.type==="retain_first_char")return;if(Pe.type==="buffer_append"||Pe.type==="begin_buffer_from_pending"){D.current.appendCharToBuffer(N,w);return}if(Pe.type==="begin_buffer"&&de(Pe.retroChars))return;pe(!1),F(N,!0);return}M&&(F(M,!0),D.current.clearWindowAfterNonChar())});let xt=Se?.columns??process.stdout?.columns??80,Z=Math.max(1,xt-3),tt=lu(ce.value,ce.cursor,Z),gt=tt.lines;return mu(Es,{flexDirection:"column",gap:1,children:[Gt(Es,{flexDirection:"column",paddingY:1,children:gt.map((M,v)=>{let w=M.text,ee=!e&&v===tt.row,ie=ee?w.slice(0,tt.cursorInRow):w,ze=ee?w.slice(tt.cursorInRow):"";return mu(Es,{children:[Gt(Mr,{color:"gray",children:v===0?"\u203A ":" "}),Gt(Mr,{children:ie}),ee?Gt(Mr,{color:"cyan",children:"\u258A"}):null,ee?Gt(Mr,{children:ze}):null]},`line-${v}`)})}),J!=="none"?Gt(Yl,{items:$.map(({value:M,meta:v,...w})=>w),activeIndex:Ce,loading:Ze}):null]})});import{memo as d_}from"react";import{Box as hu,Text as Rs}from"ink";import{jsx as Os,jsxs as yu}from"react/jsx-runtime";var Su=d_(function({busy:e,pendingApproval:n=!1,contextPercent:r}){let o=`${r.toFixed(1)}%`;return yu(hu,{justifyContent:"space-between",children:[Os(hu,{children:e?Os(Rs,{color:"yellow",children:"Working..."}):Os(Rs,{color:"gray",children:n?"Approval pending \u2022 Enter confirm \u2022 Esc deny":"Enter send \u2022 Shift+Enter newline \u2022 /help"})}),yu(Rs,{color:"gray",children:["context: ",o]})]})});import{memo as f_}from"react";import{Box as kr,Text as Is,useInput as m_}from"ink";import{Select as g_,StatusMessage as h_}from"@inkjs/ui";import{jsx as bt,jsxs as wu}from"react/jsx-runtime";var y_=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function S_(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 _u=f_(function({request:e,onDecision:n}){m_((o,s)=>{(s.escape||s.ctrl&&o==="c")&&n("deny")});let r=S_(e.params);return wu(kr,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[bt(Is,{bold:!0,color:"yellow",children:"Tool Approval Required"}),wu(Is,{children:[e.toolName,r?` (${r})`:""]}),bt(kr,{marginTop:1,children:bt(h_,{variant:"warning",children:e.reason})}),bt(kr,{marginTop:1,flexDirection:"column",children:bt(g_,{options:y_.map(o=>({label:o.label,value:o.decision})),onChange:o=>{n(o)}})}),bt(kr,{marginTop:1,children:bt(Is,{color:"gray",children:"Enter confirm \u2022 Esc deny"})})]})});import{memo as w_,useMemo as __,useState as v_}from"react";import{Box as Ls,Text as Er,useInput as T_}from"ink";import{MultiSelect as C_}from"@inkjs/ui";import{jsx as Cn,jsxs as Ns}from"react/jsx-runtime";function b_(t,e){let n=new Set(t);return e.filter(r=>n.has(r))}var vu=w_(function({serverNames:e,defaultSelected:n,onConfirm:r,onExit:o}){let s=__(()=>{let l=b_(e,n);return n.length===0?[]:l.length>0?l:[...e]},[n,e]),[i,c]=v_(s),a=i.length===e.length;return T_((l,u)=>{if(u.ctrl&&l==="c"){o();return}u.escape&&r(i,!1)}),Ns(Ls,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[Cn(Er,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),Cn(Er,{color:"gray",children:"Select servers to load for this run."}),Cn(Ls,{marginTop:1,flexDirection:"column",children:Cn(C_,{options:e.map(l=>({label:l,value:l})),defaultValue:s,onChange:c,onSubmit:l=>{r(l,!0)}})}),Ns(Ls,{marginTop:1,flexDirection:"column",children:[Ns(Er,{color:"gray",children:["Selected: ",i.length,"/",e.length,a?" (all)":""]}),Cn(Er,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, Enter confirm"})]})]})});import{spawn as x_}from"child_process";var $s="\x07",M_="Memo: Approval required",k_="Memo CLI",E_=2e3;function P_(t){return t.replace(/\s+/g," ").trim()}function A_(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function R_(t){let e=P_(t.reason),n=`Tool ${t.toolName} is waiting for your approval.`;return e?A_(`${n} ${e}`,220):n}function Tu(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function O_(t,e=process.platform){let n=M_,r=R_(t);return e==="darwin"?{command:"osascript",args:["-e",`display notification "${Tu(r)}" with title "${Tu(n)}"`]}:e==="linux"?{command:"notify-send",args:["--app-name",k_,n,r]}:null}async function I_(t,e){await new Promise((n,r)=>{let o=x_(t,e,{stdio:"ignore"}),s=!1,i=a=>{if(!s){if(s=!0,a){r(a);return}n()}},c=setTimeout(()=>{try{o.kill()}catch{}i()},E_);o.once("error",a=>{clearTimeout(c),i(a)}),o.once("exit",a=>{if(clearTimeout(c),a===0||a===null){i();return}i(new Error(`${t} exited with code ${a}`))})})}function L_(t){if(t){t($s);return}try{if(process.stdout?.isTTY){process.stdout.write($s);return}process.stderr?.isTTY&&process.stderr.write($s)}catch{}}async function Cu(t,e={}){L_(e.writeBell);let n=O_(t,e.platform??process.platform);if(!n)return;let r=e.runCommand??I_;try{await r(n.command,n.args)}catch{}}import{Box as qt,Text as Qe,useInput as N_}from"ink";import{Spinner as $_,StatusMessage as D_,TextInput as F_}from"@inkjs/ui";import{memo as U_,useCallback as bu,useMemo as H_,useState as Pr}from"react";import{jsx as $e,jsxs as Kt}from"react/jsx-runtime";var ut=[{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"}],xu=U_(function({configPath:e,onComplete:n,onExit:r}){let[o,s]=Pr(0),[i,c]=Pr({}),[a,l]=Pr(!1),[u,p]=Pr(null),d=ut[o]??ut[0],f=bu(async _=>{l(!0),p(null);try{let A={current_provider:_.name,providers:[{name:_.name,env_api_key:_.envKey,model:_.model,base_url:_.baseUrl||void 0}]};await Me(e,A),n()}catch(A){p(A.message),l(!1)}},[e,n]),g=bu(async _=>{if(!d)return;let A=_.trim()||d.defaultValue,h={...i,[d.key]:A};if(c(h),o<ut.length-1){s(o+1);return}let x={name:h.name||ut[0].defaultValue,envKey:h.envKey||ut[1].defaultValue,model:h.model||ut[2].defaultValue,baseUrl:h.baseUrl||ut[3].defaultValue};await f(x)},[f,d,o,i]);N_((_,A)=>{A.ctrl&&_==="c"&&r()});let m=H_(()=>`Step ${o+1}/${ut.length}`,[o]);return d?Kt(qt,{flexDirection:"column",children:[$e(Qe,{bold:!0,children:"Memo setup"}),$e(Qe,{color:"gray",children:"No provider config found. Complete setup to continue."}),Kt(Qe,{color:"gray",children:["Config path: ",e]}),Kt(qt,{marginTop:1,flexDirection:"column",children:[$e(Qe,{color:"cyan",children:m}),$e(Qe,{children:d.label}),Kt(Qe,{color:"gray",children:["Default: ",d.defaultValue]}),d.hint?$e(Qe,{color:"gray",children:d.hint}):null]}),Kt(qt,{marginTop:1,children:[$e(Qe,{color:"gray",children:"> "}),$e(F_,{isDisabled:a,defaultValue:i[d.key]??"",placeholder:d.defaultValue,onSubmit:_=>{g(_)}},d.key)]}),$e(qt,{marginTop:1,children:$e(Qe,{color:"gray",children:"Enter to continue, Ctrl+C to exit"})}),a?$e(qt,{marginTop:1,children:$e($_,{label:"Saving config..."})}):null,u?$e(qt,{marginTop:1,children:Kt(D_,{variant:"error",children:["Failed to save config: ",u]})}):null]}):null});function Mu(t){let e=t.finalText?.trim();return e||t.steps.map(n=>n.assistantText??"").join("").trim()}function B_(t){return t==="ok"||t==="error"||t==="cancelled"?t:void 0}function W_(t){if(t.resultStatus)return t.resultStatus==="success"?Ie.SUCCESS:Ie.ERROR}function j_(t,e,n){return{index:-(n+1),userInput:t.input??"",steps:(t.steps??[]).map(r=>({index:r.step,assistantText:r.assistantText??"",thinking:r.thinking,action:r.action,parallelActions:r.parallelActions,observation:r.observation,toolStatus:W_(r)})),status:B_(t.status),errorMessage:t.errorMessage,tokenUsage:t.tokenUsage,finalText:Mu(t),sequence:e}}function Ar(t){let e=Ln(t,"history.log"),n=[...e.turns].sort((i,c)=>i.turn-c.turn),r=[];for(let i of n){let c=(i.input??"").trim();c&&r.push({role:"user",content:c});let a=Mu(i);a&&r.push({role:"assistant",content:a})}let o=0,s=n.map((i,c)=>(o+=1,j_(i,o,c)));return{summary:e.summary,messages:r,turns:s,maxSequence:o}}function Ds(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function z_(t,e){return{index:t,userInput:"",steps:[],sequence:e}}function Rr(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 Vt(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(z_(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 G_(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 ku(t,e){switch(e.type){case"append_system_message":{let n=t.sequence+1;return{...t,sequence:n,systemMessages:[...t.systemMessages,G_({title:e.title,content:e.content,tone:e.tone,sequence:n})]}}case"turn_start":{let n=Vt(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"context_usage":{let n=Vt(t,e.turn,r=>{let o=Rr(r.steps,e.step),s=o[e.step];return s?(o[e.step]={...s,contextPromptTokens:e.promptTokens},{...r,contextPromptTokens:e.promptTokens,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Vt(t,e.turn,r=>{let o=Rr(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=Vt(t,e.turn,r=>{let o=Rr(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:Ie.EXECUTING},{...r,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Vt(t,e.turn,r=>{let o=Rr(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=Vt(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 Ds();default:return t}}import{dirname as Or,join as Pu,resolve as q_}from"path";import{statSync as K_,existsSync as Au,readFileSync as V_}from"fs";import{readFile as X_}from"fs/promises";import{get as Y_}from"https";import{fileURLToPath as J_}from"url";function Eu(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 Q_(t,e){let n=Eu(t),r=Eu(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 Ru(){try{let e=J_(import.meta.url);return Or(e)}catch{}let t=q_(process.argv[1]??process.cwd());try{return K_(t).isFile()?Or(t):t}catch{return process.cwd()}}async function Z_(t){let e=Pu(t,"package.json");if(!Au(e))return null;let n=await X_(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function ev(t){let e=Pu(t,"package.json");if(!Au(e))return null;try{let n=V_(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function tv(){let t=Ru();for(;;){let e=await Z_(t);if(e&&e.name==="@memo-code/memo")return e;let n=Or(t);if(n===t)break;t=n}return null}function Ir(){let t=Ru();for(;;){let e=ev(t);if(e&&e.name==="@memo-code/memo")return e;let n=Or(t);if(n===t)break;t=n}return null}async function nv(t,e=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(o=>{let s=Y_(r,{timeout:e},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let c=[];i.on("data",a=>c.push(a)),i.on("end",()=>{try{let a=JSON.parse(Buffer.concat(c).toString("utf8"));o(a.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function Ou(){let t=await tv();if(!t)return null;let e=await nv(t.name);return!e||!Q_(e,t.version)?null:{current:t.version,latest:e}}import{readFile as rv}from"fs/promises";import{dirname as ov,join as sv}from"path";import{fileURLToPath as iv}from"url";var av=/{{\s*([\w.-]+)\s*}}/g;function cv(t,e){return t.replace(av,(n,r)=>e[r]??"")}async function Fs(t,e={}){let n=ov(iv(import.meta.url)),r=sv(n,"task-prompts",`${t}.md`),o=await rv(r,"utf-8");return cv(o,e)}import{spawn as lv}from"child_process";var uv=12e3,pv=new Set(["WRITE","MAINTAIN","ADMIN"]),dv=["pull_request_read","list_pull_requests","search_pull_requests","add_issue_comment","add_comment_to_pending_review","issue_read","get_me"];function fv(t){return t.replace(/\\/g,"/").toLowerCase()}function mv(t,e){if(t.toLowerCase().includes("github"))return!0;if("command"in e){let o=fv(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 gv(t,e){let n=new Set(e),r=Object.entries(t).filter(([i,c])=>mv(i,c)).map(([i])=>i),o=r.find(i=>n.has(i))??null,s=r.filter(i=>!n.has(i));return{active:o,inactiveCandidates:s}}function hv(t){let e=new Map;for(let n of t)for(let r of dv){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 Us(t,e,n,r=uv){return new Promise(o=>{let s=lv(t,e,{cwd:n,env:process.env,stdio:["ignore","pipe","pipe"]}),i="",c="",a=!1,l=p=>{a||(a=!0,clearTimeout(u),o(p))},u=setTimeout(()=>{s.kill("SIGTERM"),l({ok:!1,stdout:i,stderr:c,code:null,errorMessage:`${t} ${e.join(" ")} timed out after ${r}ms`})},r);s.stdout.on("data",p=>{i+=p.toString()}),s.stderr.on("data",p=>{c+=p.toString()}),s.on("error",p=>{l({ok:!1,stdout:i,stderr:c,code:null,errorMessage:p.message})}),s.on("close",p=>{l({ok:p===0,stdout:i,stderr:c,code:p})})})}async function yv(t){if(!(await Us("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 Us("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 Us("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`."}:pv.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 Iu(t){let e=hv(t.availableToolNames??[]),n=t.activeMcpServerNames.find(l=>e.includes(l))??null,r=l=>{let u=t.availableToolNames;if(!u||u.length===0)return!0;let p=`${l}_`;return u.some(d=>d.startsWith(p))};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}=gv(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 yv(t.cwd);if(i.ok){let l=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}\`.${l}`,repository:i.repository,viewerPermission:i.viewerPermission}}let c=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.`:"",a=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}${a}${c}`}}import{jsx as pt,jsxs as xv}from"react/jsx-runtime";function Tv(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 Cv(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 bv(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function Nu({sessionOptions:t,providerName:e,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:c,modelProfiles:a,dangerous:l=!1,needsSetup:u=!1,initialHistory:p}){let{exit:d}=vv(),f=bn(()=>Object.keys(o??{}).sort(),[o]),g=bn(()=>Tv(f,t.activeMcpServers),[f,t.activeMcpServers]),m=t.toolPermissionMode??(l?Te.FULL:Te.ONCE),[_,A]=wv(ku,void 0,Ds),[h,x]=ne(e),[T,b]=ne(n),[H,j]=ne(c),[Se,ce]=ne(a),[q,P]=ne(m),L=Y(y=>Rt({model_profiles:Se},y),[Se]),[oe,le]=ne({...t,providerName:e,contextWindow:L({name:e,model:n}),dangerous:m===Te.FULL,toolPermissionMode:m}),[B,ue]=ne(!1),[J,O]=ne([]),[$,se]=ne(null),[Ce,we]=ne(null),[Ze,je]=ne(L({name:e,model:n})),[ft,be]=ne(0),[Ee,R]=ne(u),[D,Mn]=ne(!u&&f.length>0),[xe,K]=ne(g),[U,Jt]=ne(null),[F,mt]=ne(null),pe=Lr(null),et=Lr(null),xt=Lr(null),[Z,tt]=ne(null),gt=Lr(null),M=bn(()=>Ir(),[]),v=Y(y=>{A(y)},[]);Yt(()=>{p&&(v({type:"clear_current_timeline"}),v({type:"replace_history",turns:p.turns,maxSequence:p.maxSequence}),we(p.messages),p.summary.trim()&&v({type:"append_system_message",title:"History",content:p.summary,tone:"info"}))},[v,p]),Yt(()=>{Ee||(K(g),Mn(f.length>0))},[Ee,g,f.length]);let w=Y((y,C,k="info")=>{v({type:"append_system_message",title:y,content:C,tone:k})},[v]),ee=bn(()=>({onAssistantStep:(y,C)=>{let k=et.current;k&&v({type:"assistant_chunk",turn:k,step:C,chunk:y})},requestApproval:q===Te.FULL||q===Te.NONE?void 0:y=>new Promise(C=>{Cu(y),tt(y),gt.current=C}),hooks:{onTurnStart:({turn:y,input:C,promptTokens:k})=>{et.current=y;let V=xt.current;V&&(xt.current=null);let De=V??C;k&&k>0&&be(k),v({type:"turn_start",turn:y,input:De,promptTokens:k})},onContextUsage:({turn:y,step:C,promptTokens:k,phase:V})=>{be(k),v({type:"context_usage",turn:y,step:C,promptTokens:k,phase:V})},onContextCompacted:({reason:y,status:C,beforeTokens:k,afterTokens:V,reductionPercent:De,errorMessage:Ur})=>{C==="success"&&be(V);let Hr=y==="manual"?"manual command":"auto trigger";if(C==="success"){w("Context compacted",`Compacted by ${Hr}: ${k} -> ${V} tokens (${De.toFixed(2)}% reduced).`);return}if(C==="skipped"){w("Context compacted",`Skipped (${Hr}): nothing to compact.`,"warning");return}w("Context compacted",`Failed (${Hr}): ${Ur??"unknown error"}`,"warning")},onAction:({turn:y,step:C,action:k,thinking:V,parallelActions:De})=>{v({type:"tool_action",turn:y,step:C,action:k,thinking:V,parallelActions:De})},onObservation:({turn:y,step:C,observation:k,resultStatus:V,parallelResultStatuses:De})=>{v({type:"tool_observation",turn:y,step:C,observation:k,toolStatus:_s(V),parallelToolStatuses:Al(De)})},onFinal:({turn:y,finalText:C,status:k,errorMessage:V,turnUsage:De,tokenUsage:Ur})=>{v({type:"turn_final",turn:y,finalText:C,status:k,errorMessage:V,turnUsage:De,tokenUsage:Ur}),ue(!1)}}}),[w,v,q]);Yt(()=>{let y=!1;return(async()=>{if(!(Ee||D))try{let C=pe.current;C&&await C.close();let k=await yr(ee,oe);if(y){await k.close();return}pe.current=k,mt(k),se(k.historyFilePath??null)}catch(C){if(y)return;pe.current=null,mt(null),se(null),ue(!1),w("Session",`Failed to create session: ${C.message}`,"error")}})(),()=>{y=!0}},[w,ee,D,oe,Ee]),Yt(()=>{let y=!1;return(async()=>{let C=await Ou();y||!C||w("Update",`Update available: v${C.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{y=!0}},[w]),Yt(()=>()=>{pe.current&&pe.current.close()},[]);let ie=Y(async()=>{let y=gt.current;y&&(y("deny"),gt.current=null),Z&&tt(null),pe.current&&await pe.current.close(),Jt("Bye!"),setTimeout(()=>d(),250)},[d,Z]),ze=Y(()=>{if(B){w("Clear","Cancel current run before clearing timeline.","warning");return}if(Z){w("Clear","Resolve current approval request before clearing timeline.","warning");return}v({type:"clear_current_timeline"}),we(null),be(0),bv()},[w,B,v,Z]),Fr=Y(()=>{if(B){w("New Session","Cancel current run before starting a new session.","warning");return}if(Z){w("New Session","Resolve current approval request before starting a new session.","warning");return}v({type:"reset_all"}),we(null),be(0),et.current=null,le(y=>({...y,sessionId:Xt()})),w("New Session","Started a fresh session.")},[w,B,v,Z]),Qt=Y(async y=>{try{let C=await re();await Me(C.configPath,{...C.config,current_provider:y})}catch(C){w("Config",`Failed to persist provider: ${C.message}`,"warning")}},[w]),E=Y(async y=>{if(B){w("Model switch","Cancel current run before switching models.","warning");return}if(y.name===h&&y.model===T){w("Model switch",`Already using ${y.name} (${y.model}).`);return}v({type:"reset_all"}),be(0),et.current=null;let C=L(y);x(y.name),b(y.model),je(C),le(k=>({...k,sessionId:Xt(),providerName:y.name,contextWindow:C})),await Qt(y.name),w("Model switch",`Switched to ${y.name} (${y.model}).`)},[w,B,T,h,v,Qt,L]),N=Y(y=>y===Te.NONE?"none (no tools)":y===Te.ONCE?"once (approval required)":"full (no approval)",[]),de=Y(y=>{if(B){w("Tools","Cancel current run before changing tool permission mode.","warning");return}if(Z){w("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(y===q){w("Tools",`Already using ${N(y)}.`);return}P(y),le(C=>({...C,sessionId:Xt(),dangerous:y===Te.FULL,toolPermissionMode:y})),w("Tools",`Tool permission set to ${N(y)}.`)},[w,B,Z,N,q]),W=Y(async y=>{try{let C=await re();await Me(C.configPath,{...C.config,active_mcp_servers:y})}catch(C){w("MCP",`Failed to persist active MCP servers: ${C.message}`,"warning")}},[w]),Pe=Y((y,C)=>{let k=Cv(f,y);K(k),Mn(!1),le(V=>({...V,sessionId:Xt(),activeMcpServers:k})),C&&W(k)},[f,W]),ht=Y(async y=>{if(B){w("History","Cancel current run before loading session history.","warning");return}if(Z){w("History","Resolve current approval request before loading session history.","warning");return}try{let C=await Sv(y.sessionFile,"utf8"),k=Ar(C);v({type:"clear_current_timeline"}),v({type:"replace_history",turns:k.turns,maxSequence:k.maxSequence}),we(k.messages),ue(!1),mt(null),se(null),be(0),et.current=null,le(V=>({...V,sessionId:Xt()})),w("History",k.summary||y.input)}catch(C){w("History",`Failed to load ${y.sessionFile}: ${C.message}`,"error")}},[w,B,v,Z]),Mt=Y(()=>{B&&F?.cancelCurrentTurn?.()},[B,F]),kn=Y(async()=>{if(B){w("Compact","Cancel current run before compacting context.","warning");return}if(Z){w("Compact","Resolve current approval request before compacting context.","warning");return}if(F)try{let y=await F.compactHistory("manual");be(y.afterTokens)}catch(y){w("Compact",`Failed to compact context: ${y.message}`,"error")}},[w,B,Z,F]),En=Y(async()=>{if(!F||B)return;let y=ct(We.INIT);try{let C=await Fs("init_agents");O(k=>[...k,y]),ue(!0),xt.current=y,await F.runTurn(C)}catch(C){ue(!1),w("Init",`Failed to run init task: ${C.message}`,"error")}},[w,B,F]),Zt=Y(async y=>{if(!F||B)return;if(q===Te.NONE){w("Review",'Tool permission mode is "none". Set `/tools once` or `/tools full` before running `/review`.',"warning");return}let C=`${ct(We.REVIEW)} ${y}`;try{let k=await Iu({cwd:s,mcpServers:o,activeMcpServerNames:xe,availableToolNames:F.listToolNames?.()??[]});if(k.kind==="unavailable"){w("Review",k.reason,"error");return}let V=await Fs("review_pull_request",{pr_number:String(y),backend_strategy:k.strategy,backend_details:k.details,mcp_server_prefix:k.kind==="github_mcp"?k.mcpServerPrefix:"github"});O(De=>[...De,C]),w("Review",k.details),ue(!0),xt.current=C,await F.runTurn(V)}catch(k){ue(!1),w("Review",`Failed to run review task for PR #${y}: ${k.message}`,"error")}},[xe,w,B,s,o,F,q]),Ju=Y(async y=>{let C=y.trim();if(C){if(C.toLowerCase()===du){await ie();return}if(C===ct(We.INIT)){await En();return}if(!(!F||B)){O(k=>[...k,C]),ue(!0);try{await F.runTurn(C)}catch(k){ue(!1),w("Run",`Turn failed: ${k.message}`,"error")}}}},[w,B,ie,En,F]),Qu=Y(async()=>{try{let y=await re(),C=wt(y.config),k=Rt(y.config,C);j(y.config.providers),ce(y.config.model_profiles),x(C.name),b(C.model),je(k),le(V=>({...V,sessionId:Xt(),providerName:C.name,contextWindow:k,autoCompactThresholdPercent:y.config.auto_compact_threshold_percent})),R(!1),w("Setup",`Config saved to ${y.configPath}`)}catch(y){w("Setup",`Failed to reload config: ${y.message}`,"error")}},[w]);Yt(()=>{if(!F||!Ce?.length)return;let y=F.history[0];y&&(F.history.splice(0,F.history.length,y,...Ce),we(null))},[Ce,F]);let Zu=Y(y=>{let C=gt.current;C&&(C(y),gt.current=null),tt(null)},[]),ep=Rl(ft,Ze),tp=bn(()=>({providerName:h,model:T,cwd:s,sessionId:oe.sessionId??"unknown",mcpNames:xe,version:M?.version??"unknown"}),[xe,T,h,s,M?.version,oe.sessionId]);return U?pt(Lu,{children:pt(_v,{color:"green",children:U})}):Ee?pt(xu,{configPath:r,onComplete:Qu,onExit:ie}):D?pt(vu,{serverNames:f,defaultSelected:g,onConfirm:Pe,onExit:()=>{ie()}}):xv(Lu,{flexDirection:"column",children:[pt(Gl,{header:tp,systemMessages:_.systemMessages,turns:_.turns,historicalTurns:_.historicalTurns}),pt(gu,{disabled:!F||!!Z,busy:B,history:J,cwd:s,sessionsDir:i,currentSessionFile:$??void 0,providers:H,configPath:r,providerName:h,model:T,toolPermissionMode:q,mcpServers:o,onSubmit:y=>{Ju(y)},onExit:()=>{ie()},onClear:ze,onNewSession:Fr,onCancelRun:Mt,onCompact:()=>{kn()},onHistorySelect:y=>{ht(y)},onModelSelect:y=>{E(y)},onSetToolPermission:de,onReviewPullRequest:y=>{Zt(y)},onSystemMessage:w}),Z?pt(_u,{request:Z,onDecision:Zu}):null,pt(Su,{busy:B,pendingApproval:!!Z,contextPercent:ep})]})}var Mv=`
233
+ `,!0);return}let de=P.current.value.trim();if(!de)return;if(de.startsWith("/")){let W=eo(de,Mn);switch(W.kind){case"message":j(W.title,W.content);break;case"new":_();break;case"exit":g();break;case"switch_model":T(W.provider);break;case"set_tool_permission":b(W.mode);break;case"compact":h();break;case"review_pr":H(W.prNumber);break;case"init_agents_md":f(Zw);break;default:{let Pe=W}}L.current=null,U({value:"",cursor:0},!0),K(!1);return}f(de),L.current=null,U({value:"",cursor:0},!0),K(!1);return}if(ze!=="none"){let E=P.current,N=ze==="backspace"?eu(E.value,E.cursor):Ms(E.value,E.cursor);L.current=null,U(N,!0);return}if(M&&Qt){let E=Array.from(M);if(E.length!==1){pe(!1),F(M,!0),D.current.clearAfterExplicitPaste();return}let N=E[0]??"";if(!N)return;let de=ht=>{let Mt=P.current,kn=Mt.value.slice(0,Mt.cursor),En=Mt.value.slice(Mt.cursor),Zt=D.current.decideBeginBuffer(w,kn,ht);return Zt?(L.current=null,U({value:`${kn.slice(0,Zt.start)}${En}`,cursor:Zt.start},!0),D.current.appendCharToBuffer(N,w),!0):!1};if(!((N.codePointAt(0)??0)<=127)){let ht=D.current.onPlainCharNoHold(w);if(ht?.type==="buffer_append"){D.current.appendCharToBuffer(N,w);return}if(ht?.type==="begin_buffer"&&de(ht.retroChars))return;pe(!1),F(N,!0);return}let Pe=D.current.onPlainChar(N,w);if(Pe.type==="retain_first_char")return;if(Pe.type==="buffer_append"||Pe.type==="begin_buffer_from_pending"){D.current.appendCharToBuffer(N,w);return}if(Pe.type==="begin_buffer"&&de(Pe.retroChars))return;pe(!1),F(N,!0);return}M&&(F(M,!0),D.current.clearWindowAfterNonChar())});let xt=Se?.columns??process.stdout?.columns??80,Z=Math.max(1,xt-3),tt=cu(ce.value,ce.cursor,Z),gt=tt.lines;return fu(Es,{flexDirection:"column",gap:1,children:[Gt(Es,{flexDirection:"column",paddingY:1,children:gt.map((M,v)=>{let w=M.text,ee=!e&&v===tt.row,ie=ee?w.slice(0,tt.cursorInRow):w,ze=ee?w.slice(tt.cursorInRow):"";return fu(Es,{children:[Gt(Mr,{color:"gray",children:v===0?"\u203A ":" "}),Gt(Mr,{children:ie}),ee?Gt(Mr,{color:"cyan",children:"\u258A"}):null,ee?Gt(Mr,{children:ze}):null]},`line-${v}`)})}),J!=="none"?Gt(Xl,{items:$.map(({value:M,meta:v,...w})=>w),activeIndex:Ce,loading:Ze}):null]})});import{memo as d_}from"react";import{Box as gu,Text as Rs}from"ink";import{jsx as Os,jsxs as hu}from"react/jsx-runtime";var yu=d_(function({busy:e,pendingApproval:n=!1,contextPercent:r}){let o=`${r.toFixed(1)}%`;return hu(gu,{justifyContent:"space-between",children:[Os(gu,{children:e?Os(Rs,{color:"yellow",children:"Working..."}):Os(Rs,{color:"gray",children:n?"Approval pending \u2022 Enter confirm \u2022 Esc deny":"Enter send \u2022 Shift+Enter newline \u2022 /help"})}),hu(Rs,{color:"gray",children:["context: ",o]})]})});import{memo as f_}from"react";import{Box as kr,Text as Is,useInput as m_}from"ink";import{Select as g_,StatusMessage as h_}from"@inkjs/ui";import{jsx as bt,jsxs as Su}from"react/jsx-runtime";var y_=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function S_(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 wu=f_(function({request:e,onDecision:n}){m_((o,s)=>{(s.escape||s.ctrl&&o==="c")&&n("deny")});let r=S_(e.params);return Su(kr,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[bt(Is,{bold:!0,color:"yellow",children:"Tool Approval Required"}),Su(Is,{children:[e.toolName,r?` (${r})`:""]}),bt(kr,{marginTop:1,children:bt(h_,{variant:"warning",children:e.reason})}),bt(kr,{marginTop:1,flexDirection:"column",children:bt(g_,{options:y_.map(o=>({label:o.label,value:o.decision})),onChange:o=>{n(o)}})}),bt(kr,{marginTop:1,children:bt(Is,{color:"gray",children:"Enter confirm \u2022 Esc deny"})})]})});import{memo as w_,useMemo as __,useState as v_}from"react";import{Box as Ls,Text as Er,useInput as T_}from"ink";import{MultiSelect as C_}from"@inkjs/ui";import{jsx as Cn,jsxs as Ns}from"react/jsx-runtime";function b_(t,e){let n=new Set(t);return e.filter(r=>n.has(r))}var _u=w_(function({serverNames:e,defaultSelected:n,onConfirm:r,onExit:o}){let s=__(()=>{let l=b_(e,n);return n.length===0?[]:l.length>0?l:[...e]},[n,e]),[i,c]=v_(s),a=i.length===e.length;return T_((l,u)=>{if(u.ctrl&&l==="c"){o();return}u.escape&&r(i,!1)}),Ns(Ls,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[Cn(Er,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),Cn(Er,{color:"gray",children:"Select servers to load for this run."}),Cn(Ls,{marginTop:1,flexDirection:"column",children:Cn(C_,{options:e.map(l=>({label:l,value:l})),defaultValue:s,onChange:c,onSubmit:l=>{r(l,!0)}})}),Ns(Ls,{marginTop:1,flexDirection:"column",children:[Ns(Er,{color:"gray",children:["Selected: ",i.length,"/",e.length,a?" (all)":""]}),Cn(Er,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, Enter confirm"})]})]})});import{spawn as x_}from"child_process";var $s="\x07",M_="Memo: Approval required",k_="Memo CLI",E_=2e3;function P_(t){return t.replace(/\s+/g," ").trim()}function A_(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}function R_(t){let e=P_(t.reason),n=`Tool ${t.toolName} is waiting for your approval.`;return e?A_(`${n} ${e}`,220):n}function vu(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function O_(t,e=process.platform){let n=M_,r=R_(t);return e==="darwin"?{command:"osascript",args:["-e",`display notification "${vu(r)}" with title "${vu(n)}"`]}:e==="linux"?{command:"notify-send",args:["--app-name",k_,n,r]}:null}async function I_(t,e){await new Promise((n,r)=>{let o=x_(t,e,{stdio:"ignore"}),s=!1,i=a=>{if(!s){if(s=!0,a){r(a);return}n()}},c=setTimeout(()=>{try{o.kill()}catch{}i()},E_);o.once("error",a=>{clearTimeout(c),i(a)}),o.once("exit",a=>{if(clearTimeout(c),a===0||a===null){i();return}i(new Error(`${t} exited with code ${a}`))})})}function L_(t){if(t){t($s);return}try{if(process.stdout?.isTTY){process.stdout.write($s);return}process.stderr?.isTTY&&process.stderr.write($s)}catch{}}async function Tu(t,e={}){L_(e.writeBell);let n=O_(t,e.platform??process.platform);if(!n)return;let r=e.runCommand??I_;try{await r(n.command,n.args)}catch{}}import{Box as qt,Text as Qe,useInput as N_}from"ink";import{Spinner as $_,StatusMessage as D_,TextInput as F_}from"@inkjs/ui";import{memo as U_,useCallback as Cu,useMemo as H_,useState as Pr}from"react";import{jsx as $e,jsxs as Kt}from"react/jsx-runtime";var ut=[{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"}],bu=U_(function({configPath:e,onComplete:n,onExit:r}){let[o,s]=Pr(0),[i,c]=Pr({}),[a,l]=Pr(!1),[u,p]=Pr(null),d=ut[o]??ut[0],f=Cu(async _=>{l(!0),p(null);try{let A={current_provider:_.name,providers:[{name:_.name,env_api_key:_.envKey,model:_.model,base_url:_.baseUrl||void 0}]};await Me(e,A),n()}catch(A){p(A.message),l(!1)}},[e,n]),g=Cu(async _=>{if(!d)return;let A=_.trim()||d.defaultValue,h={...i,[d.key]:A};if(c(h),o<ut.length-1){s(o+1);return}let x={name:h.name||ut[0].defaultValue,envKey:h.envKey||ut[1].defaultValue,model:h.model||ut[2].defaultValue,baseUrl:h.baseUrl||ut[3].defaultValue};await f(x)},[f,d,o,i]);N_((_,A)=>{A.ctrl&&_==="c"&&r()});let m=H_(()=>`Step ${o+1}/${ut.length}`,[o]);return d?Kt(qt,{flexDirection:"column",children:[$e(Qe,{bold:!0,children:"Memo setup"}),$e(Qe,{color:"gray",children:"No provider config found. Complete setup to continue."}),Kt(Qe,{color:"gray",children:["Config path: ",e]}),Kt(qt,{marginTop:1,flexDirection:"column",children:[$e(Qe,{color:"cyan",children:m}),$e(Qe,{children:d.label}),Kt(Qe,{color:"gray",children:["Default: ",d.defaultValue]}),d.hint?$e(Qe,{color:"gray",children:d.hint}):null]}),Kt(qt,{marginTop:1,children:[$e(Qe,{color:"gray",children:"> "}),$e(F_,{isDisabled:a,defaultValue:i[d.key]??"",placeholder:d.defaultValue,onSubmit:_=>{g(_)}},d.key)]}),$e(qt,{marginTop:1,children:$e(Qe,{color:"gray",children:"Enter to continue, Ctrl+C to exit"})}),a?$e(qt,{marginTop:1,children:$e($_,{label:"Saving config..."})}):null,u?$e(qt,{marginTop:1,children:Kt(D_,{variant:"error",children:["Failed to save config: ",u]})}):null]}):null});function xu(t){let e=t.finalText?.trim();return e||t.steps.map(n=>n.assistantText??"").join("").trim()}function B_(t){return t==="ok"||t==="error"||t==="cancelled"?t:void 0}function W_(t){if(t.resultStatus)return t.resultStatus==="success"?Ie.SUCCESS:Ie.ERROR}function j_(t,e,n){return{index:-(n+1),userInput:t.input??"",steps:(t.steps??[]).map(r=>({index:r.step,assistantText:r.assistantText??"",thinking:r.thinking,action:r.action,parallelActions:r.parallelActions,observation:r.observation,toolStatus:W_(r)})),status:B_(t.status),errorMessage:t.errorMessage,tokenUsage:t.tokenUsage,finalText:xu(t),sequence:e}}function Ar(t){let e=Ln(t,"history.log"),n=[...e.turns].sort((i,c)=>i.turn-c.turn),r=[];for(let i of n){let c=(i.input??"").trim();c&&r.push({role:"user",content:c});let a=xu(i);a&&r.push({role:"assistant",content:a})}let o=0,s=n.map((i,c)=>(o+=1,j_(i,o,c)));return{summary:e.summary,messages:r,turns:s,maxSequence:o}}function Ds(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function z_(t,e){return{index:t,userInput:"",steps:[],sequence:e}}function Rr(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 Vt(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(z_(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 G_(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 Mu(t,e){switch(e.type){case"append_system_message":{let n=t.sequence+1;return{...t,sequence:n,systemMessages:[...t.systemMessages,G_({title:e.title,content:e.content,tone:e.tone,sequence:n})]}}case"turn_start":{let n=Vt(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"context_usage":{let n=Vt(t,e.turn,r=>{let o=Rr(r.steps,e.step),s=o[e.step];return s?(o[e.step]={...s,contextPromptTokens:e.promptTokens},{...r,contextPromptTokens:e.promptTokens,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Vt(t,e.turn,r=>{let o=Rr(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=Vt(t,e.turn,r=>{let o=Rr(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:Ie.EXECUTING},{...r,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Vt(t,e.turn,r=>{let o=Rr(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=Vt(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 Ds();default:return t}}import{dirname as Or,join as Eu,resolve as q_}from"path";import{statSync as K_,existsSync as Pu,readFileSync as V_}from"fs";import{readFile as X_}from"fs/promises";import{get as Y_}from"https";import{fileURLToPath as J_}from"url";function ku(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 Q_(t,e){let n=ku(t),r=ku(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 Au(){try{let e=J_(import.meta.url);return Or(e)}catch{}let t=q_(process.argv[1]??process.cwd());try{return K_(t).isFile()?Or(t):t}catch{return process.cwd()}}async function Z_(t){let e=Eu(t,"package.json");if(!Pu(e))return null;let n=await X_(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function ev(t){let e=Eu(t,"package.json");if(!Pu(e))return null;try{let n=V_(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function tv(){let t=Au();for(;;){let e=await Z_(t);if(e&&e.name==="@memo-code/memo")return e;let n=Or(t);if(n===t)break;t=n}return null}function Ir(){let t=Au();for(;;){let e=ev(t);if(e&&e.name==="@memo-code/memo")return e;let n=Or(t);if(n===t)break;t=n}return null}async function nv(t,e=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(o=>{let s=Y_(r,{timeout:e},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let c=[];i.on("data",a=>c.push(a)),i.on("end",()=>{try{let a=JSON.parse(Buffer.concat(c).toString("utf8"));o(a.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function Ru(){let t=await tv();if(!t)return null;let e=await nv(t.name);return!e||!Q_(e,t.version)?null:{current:t.version,latest:e}}import{readFile as rv}from"fs/promises";import{dirname as ov,join as sv}from"path";import{fileURLToPath as iv}from"url";var av=/{{\s*([\w.-]+)\s*}}/g;function cv(t,e){return t.replace(av,(n,r)=>e[r]??"")}async function Fs(t,e={}){let n=ov(iv(import.meta.url)),r=sv(n,"task-prompts",`${t}.md`),o=await rv(r,"utf-8");return cv(o,e)}import{spawn as lv}from"child_process";var uv=12e3,pv=new Set(["WRITE","MAINTAIN","ADMIN"]),dv=["pull_request_read","list_pull_requests","search_pull_requests","add_issue_comment","add_comment_to_pending_review","issue_read","get_me"];function fv(t){return t.replace(/\\/g,"/").toLowerCase()}function mv(t,e){if(t.toLowerCase().includes("github"))return!0;if("command"in e){let o=fv(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 gv(t,e){let n=new Set(e),r=Object.entries(t).filter(([i,c])=>mv(i,c)).map(([i])=>i),o=r.find(i=>n.has(i))??null,s=r.filter(i=>!n.has(i));return{active:o,inactiveCandidates:s}}function hv(t){let e=new Map;for(let n of t)for(let r of dv){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 Us(t,e,n,r=uv){return new Promise(o=>{let s=lv(t,e,{cwd:n,env:process.env,stdio:["ignore","pipe","pipe"]}),i="",c="",a=!1,l=p=>{a||(a=!0,clearTimeout(u),o(p))},u=setTimeout(()=>{s.kill("SIGTERM"),l({ok:!1,stdout:i,stderr:c,code:null,errorMessage:`${t} ${e.join(" ")} timed out after ${r}ms`})},r);s.stdout.on("data",p=>{i+=p.toString()}),s.stderr.on("data",p=>{c+=p.toString()}),s.on("error",p=>{l({ok:!1,stdout:i,stderr:c,code:null,errorMessage:p.message})}),s.on("close",p=>{l({ok:p===0,stdout:i,stderr:c,code:p})})})}async function yv(t){if(!(await Us("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 Us("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 Us("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`."}:pv.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 Ou(t){let e=hv(t.availableToolNames??[]),n=t.activeMcpServerNames.find(l=>e.includes(l))??null,r=l=>{let u=t.availableToolNames;if(!u||u.length===0)return!0;let p=`${l}_`;return u.some(d=>d.startsWith(p))};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}=gv(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 yv(t.cwd);if(i.ok){let l=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}\`.${l}`,repository:i.repository,viewerPermission:i.viewerPermission}}let c=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.`:"",a=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}${a}${c}`}}import{jsx as pt,jsxs as xv}from"react/jsx-runtime";function Tv(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 Cv(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 bv(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function Lu({sessionOptions:t,providerName:e,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:c,modelProfiles:a,dangerous:l=!1,needsSetup:u=!1,initialHistory:p}){let{exit:d}=vv(),f=bn(()=>Object.keys(o??{}).sort(),[o]),g=bn(()=>Tv(f,t.activeMcpServers),[f,t.activeMcpServers]),m=t.toolPermissionMode??(l?Te.FULL:Te.ONCE),[_,A]=wv(Mu,void 0,Ds),[h,x]=ne(e),[T,b]=ne(n),[H,j]=ne(c),[Se,ce]=ne(a),[q,P]=ne(m),L=Y(y=>Rt({model_profiles:Se},y),[Se]),[oe,le]=ne({...t,providerName:e,contextWindow:L({name:e,model:n}),dangerous:m===Te.FULL,toolPermissionMode:m}),[B,ue]=ne(!1),[J,O]=ne([]),[$,se]=ne(null),[Ce,we]=ne(null),[Ze,je]=ne(L({name:e,model:n})),[ft,be]=ne(0),[Ee,R]=ne(u),[D,Mn]=ne(!u&&f.length>0),[xe,K]=ne(g),[U,Jt]=ne(null),[F,mt]=ne(null),pe=Lr(null),et=Lr(null),xt=Lr(null),[Z,tt]=ne(null),gt=Lr(null),M=bn(()=>Ir(),[]),v=Y(y=>{A(y)},[]);Yt(()=>{p&&(v({type:"clear_current_timeline"}),v({type:"replace_history",turns:p.turns,maxSequence:p.maxSequence}),we(p.messages),p.summary.trim()&&v({type:"append_system_message",title:"History",content:p.summary,tone:"info"}))},[v,p]),Yt(()=>{Ee||(K(g),Mn(f.length>0))},[Ee,g,f.length]);let w=Y((y,C,k="info")=>{v({type:"append_system_message",title:y,content:C,tone:k})},[v]),ee=bn(()=>({onAssistantStep:(y,C)=>{let k=et.current;k&&v({type:"assistant_chunk",turn:k,step:C,chunk:y})},requestApproval:q===Te.FULL||q===Te.NONE?void 0:y=>new Promise(C=>{Tu(y),tt(y),gt.current=C}),hooks:{onTurnStart:({turn:y,input:C,promptTokens:k})=>{et.current=y;let V=xt.current;V&&(xt.current=null);let De=V??C;k&&k>0&&be(k),v({type:"turn_start",turn:y,input:De,promptTokens:k})},onContextUsage:({turn:y,step:C,promptTokens:k,phase:V})=>{be(k),v({type:"context_usage",turn:y,step:C,promptTokens:k,phase:V})},onContextCompacted:({reason:y,status:C,beforeTokens:k,afterTokens:V,reductionPercent:De,errorMessage:Ur})=>{C==="success"&&be(V);let Hr=y==="manual"?"manual command":"auto trigger";if(C==="success"){w("Context compacted",`Compacted by ${Hr}: ${k} -> ${V} tokens (${De.toFixed(2)}% reduced).`);return}if(C==="skipped"){w("Context compacted",`Skipped (${Hr}): nothing to compact.`,"warning");return}w("Context compacted",`Failed (${Hr}): ${Ur??"unknown error"}`,"warning")},onAction:({turn:y,step:C,action:k,thinking:V,parallelActions:De})=>{v({type:"tool_action",turn:y,step:C,action:k,thinking:V,parallelActions:De})},onObservation:({turn:y,step:C,observation:k,resultStatus:V,parallelResultStatuses:De})=>{v({type:"tool_observation",turn:y,step:C,observation:k,toolStatus:_s(V),parallelToolStatuses:Pl(De)})},onFinal:({turn:y,finalText:C,status:k,errorMessage:V,turnUsage:De,tokenUsage:Ur})=>{v({type:"turn_final",turn:y,finalText:C,status:k,errorMessage:V,turnUsage:De,tokenUsage:Ur}),ue(!1)}}}),[w,v,q]);Yt(()=>{let y=!1;return(async()=>{if(!(Ee||D))try{let C=pe.current;C&&await C.close();let k=await yr(ee,oe);if(y){await k.close();return}pe.current=k,mt(k),se(k.historyFilePath??null)}catch(C){if(y)return;pe.current=null,mt(null),se(null),ue(!1),w("Session",`Failed to create session: ${C.message}`,"error")}})(),()=>{y=!0}},[w,ee,D,oe,Ee]),Yt(()=>{let y=!1;return(async()=>{let C=await Ru();y||!C||w("Update",`Update available: v${C.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{y=!0}},[w]),Yt(()=>()=>{pe.current&&pe.current.close()},[]);let ie=Y(async()=>{let y=gt.current;y&&(y("deny"),gt.current=null),Z&&tt(null),pe.current&&await pe.current.close(),Jt("Bye!"),setTimeout(()=>d(),250)},[d,Z]),ze=Y(()=>{if(B){w("Clear","Cancel current run before clearing timeline.","warning");return}if(Z){w("Clear","Resolve current approval request before clearing timeline.","warning");return}v({type:"clear_current_timeline"}),we(null),be(0),bv()},[w,B,v,Z]),Fr=Y(()=>{if(B){w("New Session","Cancel current run before starting a new session.","warning");return}if(Z){w("New Session","Resolve current approval request before starting a new session.","warning");return}v({type:"reset_all"}),we(null),be(0),et.current=null,le(y=>({...y,sessionId:Xt()})),w("New Session","Started a fresh session.")},[w,B,v,Z]),Qt=Y(async y=>{try{let C=await re();await Me(C.configPath,{...C.config,current_provider:y})}catch(C){w("Config",`Failed to persist provider: ${C.message}`,"warning")}},[w]),E=Y(async y=>{if(B){w("Model switch","Cancel current run before switching models.","warning");return}if(y.name===h&&y.model===T){w("Model switch",`Already using ${y.name} (${y.model}).`);return}v({type:"reset_all"}),be(0),et.current=null;let C=L(y);x(y.name),b(y.model),je(C),le(k=>({...k,sessionId:Xt(),providerName:y.name,contextWindow:C})),await Qt(y.name),w("Model switch",`Switched to ${y.name} (${y.model}).`)},[w,B,T,h,v,Qt,L]),N=Y(y=>y===Te.NONE?"none (no tools)":y===Te.ONCE?"once (approval required)":"full (no approval)",[]),de=Y(y=>{if(B){w("Tools","Cancel current run before changing tool permission mode.","warning");return}if(Z){w("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(y===q){w("Tools",`Already using ${N(y)}.`);return}P(y),le(C=>({...C,sessionId:Xt(),dangerous:y===Te.FULL,toolPermissionMode:y})),w("Tools",`Tool permission set to ${N(y)}.`)},[w,B,Z,N,q]),W=Y(async y=>{try{let C=await re();await Me(C.configPath,{...C.config,active_mcp_servers:y})}catch(C){w("MCP",`Failed to persist active MCP servers: ${C.message}`,"warning")}},[w]),Pe=Y((y,C)=>{let k=Cv(f,y);K(k),Mn(!1),le(V=>({...V,sessionId:Xt(),activeMcpServers:k})),C&&W(k)},[f,W]),ht=Y(async y=>{if(B){w("History","Cancel current run before loading session history.","warning");return}if(Z){w("History","Resolve current approval request before loading session history.","warning");return}try{let C=await Sv(y.sessionFile,"utf8"),k=Ar(C);v({type:"clear_current_timeline"}),v({type:"replace_history",turns:k.turns,maxSequence:k.maxSequence}),we(k.messages),ue(!1),mt(null),se(null),be(0),et.current=null,le(V=>({...V,sessionId:Xt()})),w("History",k.summary||y.input)}catch(C){w("History",`Failed to load ${y.sessionFile}: ${C.message}`,"error")}},[w,B,v,Z]),Mt=Y(()=>{B&&F?.cancelCurrentTurn?.()},[B,F]),kn=Y(async()=>{if(B){w("Compact","Cancel current run before compacting context.","warning");return}if(Z){w("Compact","Resolve current approval request before compacting context.","warning");return}if(F)try{let y=await F.compactHistory("manual");be(y.afterTokens)}catch(y){w("Compact",`Failed to compact context: ${y.message}`,"error")}},[w,B,Z,F]),En=Y(async()=>{if(!F||B)return;let y=ct(We.INIT);try{let C=await Fs("init_agents");O(k=>[...k,y]),ue(!0),xt.current=y,await F.runTurn(C)}catch(C){ue(!1),w("Init",`Failed to run init task: ${C.message}`,"error")}},[w,B,F]),Zt=Y(async y=>{if(!F||B)return;if(q===Te.NONE){w("Review",'Tool permission mode is "none". Set `/tools once` or `/tools full` before running `/review`.',"warning");return}let C=`${ct(We.REVIEW)} ${y}`;try{let k=await Ou({cwd:s,mcpServers:o,activeMcpServerNames:xe,availableToolNames:F.listToolNames?.()??[]});if(k.kind==="unavailable"){w("Review",k.reason,"error");return}let V=await Fs("review_pull_request",{pr_number:String(y),backend_strategy:k.strategy,backend_details:k.details,mcp_server_prefix:k.kind==="github_mcp"?k.mcpServerPrefix:"github"});O(De=>[...De,C]),w("Review",k.details),ue(!0),xt.current=C,await F.runTurn(V)}catch(k){ue(!1),w("Review",`Failed to run review task for PR #${y}: ${k.message}`,"error")}},[xe,w,B,s,o,F,q]),Yu=Y(async y=>{let C=y.trim();if(C){if(C.toLowerCase()===pu){await ie();return}if(C===ct(We.INIT)){await En();return}if(!(!F||B)){O(k=>[...k,C]),ue(!0);try{await F.runTurn(C)}catch(k){ue(!1),w("Run",`Turn failed: ${k.message}`,"error")}}}},[w,B,ie,En,F]),Ju=Y(async()=>{try{let y=await re(),C=wt(y.config),k=Rt(y.config,C);j(y.config.providers),ce(y.config.model_profiles),x(C.name),b(C.model),je(k),le(V=>({...V,sessionId:Xt(),providerName:C.name,contextWindow:k,autoCompactThresholdPercent:y.config.auto_compact_threshold_percent})),R(!1),w("Setup",`Config saved to ${y.configPath}`)}catch(y){w("Setup",`Failed to reload config: ${y.message}`,"error")}},[w]);Yt(()=>{if(!F||!Ce?.length)return;let y=F.history[0];y&&(F.history.splice(0,F.history.length,y,...Ce),we(null))},[Ce,F]);let Qu=Y(y=>{let C=gt.current;C&&(C(y),gt.current=null),tt(null)},[]),Zu=Al(ft,Ze),ep=bn(()=>({providerName:h,model:T,cwd:s,sessionId:oe.sessionId??"unknown",mcpNames:xe,version:M?.version??"unknown"}),[xe,T,h,s,M?.version,oe.sessionId]);return U?pt(Iu,{children:pt(_v,{color:"green",children:U})}):Ee?pt(bu,{configPath:r,onComplete:Ju,onExit:ie}):D?pt(_u,{serverNames:f,defaultSelected:g,onConfirm:Pe,onExit:()=>{ie()}}):xv(Iu,{flexDirection:"column",children:[pt(zl,{header:ep,systemMessages:_.systemMessages,turns:_.turns,historicalTurns:_.historicalTurns}),pt(mu,{disabled:!F||!!Z,busy:B,history:J,cwd:s,sessionsDir:i,currentSessionFile:$??void 0,providers:H,configPath:r,providerName:h,model:T,toolPermissionMode:q,mcpServers:o,onSubmit:y=>{Yu(y)},onExit:()=>{ie()},onClear:ze,onNewSession:Fr,onCancelRun:Mt,onCompact:()=>{kn()},onHistorySelect:y=>{ht(y)},onModelSelect:y=>{E(y)},onSetToolPermission:de,onReviewPullRequest:y=>{Zt(y)},onSystemMessage:w}),Z?pt(wu,{request:Z,onDecision:Qu}):null,pt(yu,{busy:B,pendingApproval:!!Z,contextPercent:Zu})]})}var Mv=`
234
234
  Usage:
235
235
  memo mcp list [--json]
236
236
  memo mcp get <name> [--json]
@@ -239,14 +239,14 @@ Usage:
239
239
  memo mcp remove <name>
240
240
  memo mcp login <name> [--scopes scope1,scope2]
241
241
  memo mcp logout <name>
242
- `;function Nr(){console.log(Mv.trim())}function $u(t){return t instanceof Error?t.message:String(t)}function kv(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 Du(t,e,n){let r=[];if(r.push(`${t}`),n&&r.push(` auth_status: ${n}`),"url"in e){r.push(` type: ${e.type??"streamable_http"}`),r.push(` url: ${e.url}`),e.bearer_token_env_var&&r.push(` bearer_token_env_var: ${e.bearer_token_env_var}`);let o=e.http_headers??e.headers;o&&Object.keys(o).length>0&&r.push(` headers: ${Object.entries(o).map(([s,i])=>`${s}=${i}`).join(", ")}`)}else r.push(` type: ${e.type??"stdio"}`),r.push(` command: ${e.command}`),e.args&&e.args.length>0&&r.push(` args: ${e.args.join(" ")}`),e.env&&Object.keys(e.env).length>0&&r.push(` env: ${Object.entries(e.env).map(([o,s])=>`${o}=${s}`).join(", ")}`);return r.join(`
243
- `)}function Ev(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 c=t[i];if(c){if(c==="--"){s=t.slice(i+1);break}if(c==="--url"){let a=t[i+1];if(!a)return{error:"Missing value for --url."};n=a,i+=1;continue}if(c==="--bearer-token-env-var"){let a=t[i+1];if(!a)return{error:"Missing value for --bearer-token-env-var."};r=a,i+=1;continue}if(c==="--env"){let a=t[i+1];if(!a)return{error:"Missing value for --env (KEY=VALUE)."};let l=kv(a);if(!l)return{error:"Invalid --env format. Use KEY=VALUE."};o[l.key]=l.value,i+=1;continue}return c==="--help"||c==="-h"?{error:""}:{error:`Unknown option: ${c}`}}}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 Pv(t){let[e,...n]=t;return!e||e==="--help"||e==="-h"||e==="help"?{command:"help",rest:[]}:{command:e,rest:n}}function Hs(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}function Av(t){return t.split(/[,\s]+/g).map(e=>e.trim()).filter(Boolean)}function Rv(t){let e,n;for(let r=0;r<t.length;r+=1){let o=t[r];if(o){if(o==="--help"||o==="-h")return{showHelp:!0};if(o==="--scopes"){let s=t[r+1];if(!s)return{error:"Missing value for --scopes."};let i=Av(s);if(i.length===0)return{error:"Invalid --scopes value. Use comma-separated scopes."};n=i,r+=1;continue}if(o.startsWith("--"))return{error:`Unknown option: ${o}`};if(!e){e=o;continue}return{error:`Unexpected argument: ${o}`}}}return{name:e,scopes:n}}function Bs(t){return{memoHome:t.home,storeMode:t.config.mcp_oauth_credentials_store_mode,callbackPort:t.config.mcp_oauth_callback_port}}async function Fu(t){let{command:e,rest:n}=Pv(t);if(e==="help"){Nr();return}if(e==="list"){let r=n.includes("--json"),o=await re(),s=o.config.mcp_servers??{},i=Object.keys(s),c=Bs(o),a=new Map;if(await Promise.all(i.map(async l=>{let u=s[l];if(u)try{let p=await mo(u,c);a.set(l,p)}catch{a.set(l,"unsupported")}})),r){let l={};for(let u of i){let p=s[u];p&&(l[u]={...p,auth_status:a.get(u)??"unsupported"})}console.log(JSON.stringify(l,null,2));return}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 l of i){let u=s[l];u&&console.log(Du(l,u,a.get(l)??"unsupported"))}return}if(e==="get"){let r=n.includes("--json"),o=Hs(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await re()).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(Du(o,i));return}if(e==="add"){let r=Ev(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),Nr();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 re(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let c;o.url?c={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:c={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=c,await Me(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(e==="remove"){let r=Hs(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await re(),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"){let r=Rv(n);if(r.showHelp){Nr();return}if(r.error){console.error(r.error),process.exitCode=1;return}let o=r.name;if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=await re(),i=s.config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(!("url"in i)){console.error("OAuth login only applies to streamable HTTP servers."),process.exitCode=1;return}console.log(`Starting OAuth login for "${o}"...`);try{let c=await go({serverName:o,config:i,scopes:r.scopes,settings:Bs(s),onAuthorizationUrl:a=>{console.log(`Open this URL to authorize:
244
- ${a}`)},onBrowserOpenFailure:()=>{console.log("Browser launch failed. Open the URL above manually.")}});console.log(`OAuth login completed for "${o}" (credentials stored in ${c.backend}).`)}catch(c){console.error($u(c)),process.exitCode=1}return}if(e==="logout"){let r=Hs(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await re(),s=o.config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth logout only applies to streamable HTTP servers."),process.exitCode=1;return}try{(await ho({config:s,settings:Bs(o)})).removed?console.log(`Removed OAuth credentials for "${r}".`):console.log(`No OAuth credentials stored for "${r}".`)}catch(i){console.error($u(i)),process.exitCode=1}return}console.error(`Unknown subcommand: ${e}`),Nr(),process.exitCode=1}function Uu(t){let e={dangerous:!1,showVersion:!1,once:!1,prev:!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"||o==="-once"){e.once=!0;continue}if(o==="--prev"||o==="-prev"){e.prev=!0;continue}if(o==="--dangerous"||o==="-d"){e.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:e}}var Ov=["mcp","web"];function Iv(t){return t.length===0?{token:null,offset:0}:t[0]==="--"?{token:t[1]??null,offset:2}:{token:t[0]??null,offset:1}}function Lv(t){return Ov.includes(t)}function Hu(t){let{token:e,offset:n}=Iv(t);return e&&Lv(e)?{kind:"subcommand",name:e,args:t.slice(n)}:{kind:"default",args:t}}import{jsx as iT}from"react/jsx-runtime";async function Xu(t){let e=await re();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(c=>!!process.env[c]);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=Jv({input:Qv,output:Zv}),i=async(c,a)=>(await s.question(c)).trim()||a;try{console.log("No provider config found. Please answer the prompts:");let c=await i("Provider name [deepseek]: ","deepseek"),a=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),l=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),p={current_provider:c,providers:[{name:c,env_api_key:a,model:l,base_url:u||void 0}]};return await Me(e.configPath,p),console.log(`Config written to ${e.configPath}
245
- `),{...e,config:p,needsSetup:!1}}finally{s.close()}}async function Yu(t,e){let r=(await wr({sessionsDir:t,cwd:e,limit:1}))[0];if(!r)return null;let o=await Yv(r.sessionFile,"utf8");return Ar(o)}function tT(t,e){if(!e.length)return;let n=t.history[0];n&&t.history.splice(0,t.history.length,n,...e)}async function nT(t){let e=await Xu("plain"),n=wt(e.config),r=Rt(e.config,n),s={sessionId:Vu(),mode:"interactive",contextWindow:r,autoCompactThresholdPercent:e.config.auto_compact_threshold_percent,activeMcpServers:e.config.active_mcp_servers,dangerous:t.options.dangerous},i=cn(e,s),c=t.options.prev?await Yu(i,process.cwd()):null;if(t.options.prev&&!c){console.error("No previous session found for current directory."),process.exitCode=1;return}t.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let a={requestApproval:t.options.dangerous?void 0:p=>(console.log(`
242
+ `;function Nr(){console.log(Mv.trim())}function Nu(t){return t instanceof Error?t.message:String(t)}function kv(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 $u(t,e,n){let r=[];if(r.push(`${t}`),n&&r.push(` auth_status: ${n}`),"url"in e){r.push(` type: ${e.type??"streamable_http"}`),r.push(` url: ${e.url}`),e.bearer_token_env_var&&r.push(` bearer_token_env_var: ${e.bearer_token_env_var}`);let o=e.http_headers??e.headers;o&&Object.keys(o).length>0&&r.push(` headers: ${Object.entries(o).map(([s,i])=>`${s}=${i}`).join(", ")}`)}else r.push(` type: ${e.type??"stdio"}`),r.push(` command: ${e.command}`),e.args&&e.args.length>0&&r.push(` args: ${e.args.join(" ")}`),e.env&&Object.keys(e.env).length>0&&r.push(` env: ${Object.entries(e.env).map(([o,s])=>`${o}=${s}`).join(", ")}`);return r.join(`
243
+ `)}function Ev(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 c=t[i];if(c){if(c==="--"){s=t.slice(i+1);break}if(c==="--url"){let a=t[i+1];if(!a)return{error:"Missing value for --url."};n=a,i+=1;continue}if(c==="--bearer-token-env-var"){let a=t[i+1];if(!a)return{error:"Missing value for --bearer-token-env-var."};r=a,i+=1;continue}if(c==="--env"){let a=t[i+1];if(!a)return{error:"Missing value for --env (KEY=VALUE)."};let l=kv(a);if(!l)return{error:"Invalid --env format. Use KEY=VALUE."};o[l.key]=l.value,i+=1;continue}return c==="--help"||c==="-h"?{error:""}:{error:`Unknown option: ${c}`}}}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 Pv(t){let[e,...n]=t;return!e||e==="--help"||e==="-h"||e==="help"?{command:"help",rest:[]}:{command:e,rest:n}}function Hs(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}function Av(t){return t.split(/[,\s]+/g).map(e=>e.trim()).filter(Boolean)}function Rv(t){let e,n;for(let r=0;r<t.length;r+=1){let o=t[r];if(o){if(o==="--help"||o==="-h")return{showHelp:!0};if(o==="--scopes"){let s=t[r+1];if(!s)return{error:"Missing value for --scopes."};let i=Av(s);if(i.length===0)return{error:"Invalid --scopes value. Use comma-separated scopes."};n=i,r+=1;continue}if(o.startsWith("--"))return{error:`Unknown option: ${o}`};if(!e){e=o;continue}return{error:`Unexpected argument: ${o}`}}}return{name:e,scopes:n}}function Bs(t){return{memoHome:t.home,storeMode:t.config.mcp_oauth_credentials_store_mode,callbackPort:t.config.mcp_oauth_callback_port}}async function Du(t){let{command:e,rest:n}=Pv(t);if(e==="help"){Nr();return}if(e==="list"){let r=n.includes("--json"),o=await re(),s=o.config.mcp_servers??{},i=Object.keys(s),c=Bs(o),a=new Map;if(await Promise.all(i.map(async l=>{let u=s[l];if(u)try{let p=await mo(u,c);a.set(l,p)}catch{a.set(l,"unsupported")}})),r){let l={};for(let u of i){let p=s[u];p&&(l[u]={...p,auth_status:a.get(u)??"unsupported"})}console.log(JSON.stringify(l,null,2));return}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 l of i){let u=s[l];u&&console.log($u(l,u,a.get(l)??"unsupported"))}return}if(e==="get"){let r=n.includes("--json"),o=Hs(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await re()).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($u(o,i));return}if(e==="add"){let r=Ev(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),Nr();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 re(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let c;o.url?c={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:c={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=c,await Me(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(e==="remove"){let r=Hs(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await re(),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"){let r=Rv(n);if(r.showHelp){Nr();return}if(r.error){console.error(r.error),process.exitCode=1;return}let o=r.name;if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=await re(),i=s.config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(!("url"in i)){console.error("OAuth login only applies to streamable HTTP servers."),process.exitCode=1;return}console.log(`Starting OAuth login for "${o}"...`);try{let c=await go({serverName:o,config:i,scopes:r.scopes,settings:Bs(s),onAuthorizationUrl:a=>{console.log(`Open this URL to authorize:
244
+ ${a}`)},onBrowserOpenFailure:()=>{console.log("Browser launch failed. Open the URL above manually.")}});console.log(`OAuth login completed for "${o}" (credentials stored in ${c.backend}).`)}catch(c){console.error(Nu(c)),process.exitCode=1}return}if(e==="logout"){let r=Hs(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await re(),s=o.config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth logout only applies to streamable HTTP servers."),process.exitCode=1;return}try{(await ho({config:s,settings:Bs(o)})).removed?console.log(`Removed OAuth credentials for "${r}".`):console.log(`No OAuth credentials stored for "${r}".`)}catch(i){console.error(Nu(i)),process.exitCode=1}return}console.error(`Unknown subcommand: ${e}`),Nr(),process.exitCode=1}function Fu(t){let e={dangerous:!1,showVersion:!1,once:!1,prev:!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"||o==="-once"){e.once=!0;continue}if(o==="--prev"||o==="-prev"){e.prev=!0;continue}if(o==="--dangerous"||o==="-d"){e.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:e}}var Ov=["mcp","web"];function Iv(t){return t.length===0?{token:null,offset:0}:t[0]==="--"?{token:t[1]??null,offset:2}:{token:t[0]??null,offset:1}}function Lv(t){return Ov.includes(t)}function Uu(t){let{token:e,offset:n}=Iv(t);return e&&Lv(e)?{kind:"subcommand",name:e,args:t.slice(n)}:{kind:"default",args:t}}import{jsx as iT}from"react/jsx-runtime";async function Vu(t){let e=await re();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(c=>!!process.env[c]);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=Jv({input:Qv,output:Zv}),i=async(c,a)=>(await s.question(c)).trim()||a;try{console.log("No provider config found. Please answer the prompts:");let c=await i("Provider name [deepseek]: ","deepseek"),a=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),l=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),p={current_provider:c,providers:[{name:c,env_api_key:a,model:l,base_url:u||void 0}]};return await Me(e.configPath,p),console.log(`Config written to ${e.configPath}
245
+ `),{...e,config:p,needsSetup:!1}}finally{s.close()}}async function Xu(t,e){let r=(await wr({sessionsDir:t,cwd:e,limit:1}))[0];if(!r)return null;let o=await Yv(r.sessionFile,"utf8");return Ar(o)}function tT(t,e){if(!e.length)return;let n=t.history[0];n&&t.history.splice(0,t.history.length,n,...e)}async function nT(t){let e=await Vu("plain"),n=wt(e.config),r=Rt(e.config,n),s={sessionId:Ku(),mode:"interactive",contextWindow:r,autoCompactThresholdPercent:e.config.auto_compact_threshold_percent,activeMcpServers:e.config.active_mcp_servers,dangerous:t.options.dangerous},i=cn(e,s),c=t.options.prev?await Xu(i,process.cwd()):null;if(t.options.prev&&!c){console.error("No previous session found for current directory."),process.exitCode=1;return}t.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let a={requestApproval:t.options.dangerous?void 0:p=>(console.log(`
246
246
  [approval required] ${p.toolName}: ${p.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:p})=>{console.log(`
247
247
  [tool] ${p.tool}`),p.input!==void 0&&console.log(`[input] ${JSON.stringify(p.input)}`)},onObservation:()=>{}}},l=await yr(a,s);c&&(tT(l,c.messages),console.log("[session] Continued from previous session context."));let u=t.question;if(!u&&!process.stdin.isTTY&&(u=await sT()),!u){console.error("No input provided. Pass a question or use stdin."),await l.close();return}try{console.log(`User: ${u}
248
248
  `);let p=await l.runTurn(u);console.log(`
249
249
  ${p.finalText}`),console.log(`
250
250
  [tokens] prompt=${p.tokenUsage.prompt} completion=${p.tokenUsage.completion} total=${p.tokenUsage.total}`),console.log(`
251
- provider=${n.name} model=${n.model}`)}catch(p){console.error(`Run failed: ${p.message}`)}finally{await l.close()}}async function rT(t){let e=await Xu("tui"),n=wt(e.config),r=Rt(e.config,n),s={sessionId:Vu(),mode:"interactive",contextWindow:r,autoCompactThresholdPercent:e.config.auto_compact_threshold_percent,activeMcpServers:e.config.active_mcp_servers,dangerous:t.options.dangerous},i=cn(e,s),c=t.options.prev?await Yu(i,process.cwd()):null;if(t.options.prev&&!c){console.error("No previous session found for current directory."),process.exitCode=1;return}t.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
252
- `)),await eT(iT(Nu,{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,initialHistory:c??void 0}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function oT(){let t=process.argv.slice(2),e=Hu(t);if(e.kind==="subcommand"){if(e.name==="mcp"){await Fu(e.args);return}if(e.name==="web"){let{runWebCommand:o}=await Promise.resolve().then(()=>(Ku(),qu));await o(e.args);return}}let n=Uu(e.args);if(n.options.showVersion){let s=Ir()?.version??"unknown";console.log(s);return}let r=process.stdin.isTTY&&process.stdout.isTTY;if(n.options.once||!r){await nT(n);return}await rT(n)}oT();async function sT(){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()})}
251
+ provider=${n.name} model=${n.model}`)}catch(p){console.error(`Run failed: ${p.message}`)}finally{await l.close()}}async function rT(t){let e=await Vu("tui"),n=wt(e.config),r=Rt(e.config,n),s={sessionId:Ku(),mode:"interactive",contextWindow:r,autoCompactThresholdPercent:e.config.auto_compact_threshold_percent,activeMcpServers:e.config.active_mcp_servers,dangerous:t.options.dangerous},i=cn(e,s),c=t.options.prev?await Xu(i,process.cwd()):null;if(t.options.prev&&!c){console.error("No previous session found for current directory."),process.exitCode=1;return}t.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
252
+ `)),await eT(iT(Lu,{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,initialHistory:c??void 0}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function oT(){let t=process.argv.slice(2),e=Uu(t);if(e.kind==="subcommand"){if(e.name==="mcp"){await Du(e.args);return}if(e.name==="web"){let{runWebCommand:o}=await Promise.resolve().then(()=>(qu(),Gu));await o(e.args);return}}let n=Fu(e.args);if(n.options.showVersion){let s=Ir()?.version??"unknown";console.log(s);return}let r=process.stdin.isTTY&&process.stdout.isTTY;if(n.options.once||!r){await nT(n);return}await rT(n)}oT();async function sT(){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()})}