@memo-code/memo 0.7.0 → 0.7.1

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.
Files changed (2) hide show
  1. package/dist/index.js +62 -61
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,48 +1,48 @@
1
1
  #!/usr/bin/env node
2
- var ii=Object.create;var dr=Object.defineProperty;var ai=Object.getOwnPropertyDescriptor;var li=Object.getOwnPropertyNames;var ci=Object.getPrototypeOf,ui=Object.prototype.hasOwnProperty;var pi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var mi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of li(t))!ui.call(e,o)&&o!==n&&dr(e,o,{get:()=>t[o],enumerable:!(r=ai(t,o))||r.enumerable});return e};var di=(e,t,n)=>(n=e!=null?ii(ci(e)):{},mi(t||!e||!e.__esModule?dr(n,"default",{value:e,enumerable:!0}):n,e));var Ur=pi((rd,Dr)=>{"use strict";function Pr(e){return Array.isArray(e)?e:[e]}var kn="",Ir=" ",Mn="\\",aa=/^\s+$/,la=/(?:[^\\]|^)\\$/,ca=/^\\!/,ua=/^\\#/,pa=/\r?\n/g,ma=/^\.*\/|^\.+$/,wn="/",Lr="node-ignore";typeof Symbol<"u"&&(Lr=Symbol.for("node-ignore"));var Rr=Lr,da=(e,t,n)=>Object.defineProperty(e,t,{value:n}),fa=/([0-z])-([0-z])/g,Nr=()=>!1,ga=e=>e.replace(fa,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:kn),ha=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ya=[[/^\uFEFF/,()=>kn],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Ir:kn)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Ir}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Mn],[/\\\\/g,()=>Mn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Mn?`\\[${n}${ha(r)}${o}`:o==="]"&&r.length%2===0?`[${ga(n)}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Or=Object.create(null),Ta=(e,t)=>{let n=Or[e];return n||(n=ya.reduce((r,[o,s])=>r.replace(o,s.bind(e)),e),Or[e]=n),t?new RegExp(n,"i"):new RegExp(n)},Rn=e=>typeof e=="string",_a=e=>e&&Rn(e)&&!aa.test(e)&&!la.test(e)&&e.indexOf("#")!==0,Sa=e=>e.split(pa),Pn=class{constructor(t,n,r,o){this.origin=t,this.pattern=n,this.negative=r,this.regex=o}},va=(e,t)=>{let n=e,r=!1;e.indexOf("!")===0&&(r=!0,e=e.substr(1)),e=e.replace(ca,"!").replace(ua,"#");let o=Ta(e,t);return new Pn(n,e,r,o)},xa=(e,t)=>{throw new t(e)},De=(e,t,n)=>Rn(e)?e?De.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),$r=e=>ma.test(e);De.isNotRelative=$r;De.convert=e=>e;var In=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){da(this,Rr,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(t){if(t&&t[Rr]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(_a(t)){let n=va(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Pr(Rn(t)?Sa(t):t).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(t){return this.add(t)}_testOne(t,n){let r=!1,o=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(o===i&&r!==o||i&&!r&&!o&&!n)return;s.regex.test(t)&&(r=!i,o=i)}),{ignored:r,unignored:o}}_test(t,n,r,o){let s=t&&De.convert(t);return De(s,t,this._allowRelativePaths?Nr:xa),this._t(s,n,r,o)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(wn)),o.pop(),!o.length)return n[t]=this._testOne(t,r);let s=this._t(o.join(wn)+wn,n,r,o);return n[t]=s.ignored?s:this._testOne(t,r)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return Pr(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},Wt=e=>new In(e),Ca=e=>De(e&&De.convert(e),e,Nr);Wt.isPathValid=Ca;Wt.default=Wt;Dr.exports=Wt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");De.convert=e;let t=/^[a-z]:\//i;De.isNotRelative=n=>t.test(n)||$r(n)}});import{randomUUID as ti}from"crypto";import{createInterface as cm}from"readline/promises";import{stdin as um,stdout as pm}from"process";import{render as mm}from"ink";import fi from"os";import{readFile as fr}from"fs/promises";import{join as gr,dirname as gi}from"path";import{fileURLToPath as hi}from"url";var yi=/{{\s*([\w.-]+)\s*}}/g;function Ti(e,t){return e.replace(yi,(n,r)=>t[r]??"")}function _i(){try{return fi.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function Si(e){let t=gr(e,"AGENTS.md");try{let n=await fr(t,"utf-8");return n.trim()?{path:t,content:n}:null}catch{return null}}function vi(e,t){return`${e}
2
+ var pi=Object.create;var hr=Object.defineProperty;var di=Object.getOwnPropertyDescriptor;var mi=Object.getOwnPropertyNames;var fi=Object.getPrototypeOf,gi=Object.prototype.hasOwnProperty;var hi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var yi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mi(t))!gi.call(e,o)&&o!==n&&hr(e,o,{get:()=>t[o],enumerable:!(r=di(t,o))||r.enumerable});return e};var Ti=(e,t,n)=>(n=e!=null?pi(fi(e)):{},yi(t||!e||!e.__esModule?hr(n,"default",{value:e,enumerable:!0}):n,e));var Br=hi((fm,Fr)=>{"use strict";function Or(e){return Array.isArray(e)?e:[e]}var In="",Lr=" ",kn="\\",fa=/^\s+$/,ga=/(?:[^\\]|^)\\$/,ha=/^\\!/,ya=/^\\#/,Ta=/\r?\n/g,_a=/^\.*\/|^\.+$/,Pn="/",Dr="node-ignore";typeof Symbol<"u"&&(Dr=Symbol.for("node-ignore"));var Nr=Dr,Sa=(e,t,n)=>Object.defineProperty(e,t,{value:n}),va=/([0-z])-([0-z])/g,Ur=()=>!1,xa=e=>e.replace(va,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:In),Ca=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ba=[[/^\uFEFF/,()=>In],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Lr:In)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Lr}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>kn],[/\\\\/g,()=>kn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===kn?`\\[${n}${Ca(r)}${o}`:o==="]"&&r.length%2===0?`[${xa(n)}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],$r=Object.create(null),Ea=(e,t)=>{let n=$r[e];return n||(n=ba.reduce((r,[o,s])=>r.replace(o,s.bind(e)),e),$r[e]=n),t?new RegExp(n,"i"):new RegExp(n)},Ln=e=>typeof e=="string",Aa=e=>e&&Ln(e)&&!fa.test(e)&&!ga.test(e)&&e.indexOf("#")!==0,wa=e=>e.split(Ta),Rn=class{constructor(t,n,r,o){this.origin=t,this.pattern=n,this.negative=r,this.regex=o}},Ma=(e,t)=>{let n=e,r=!1;e.indexOf("!")===0&&(r=!0,e=e.substr(1)),e=e.replace(ha,"!").replace(ya,"#");let o=Ea(e,t);return new Rn(n,e,r,o)},ka=(e,t)=>{throw new t(e)},De=(e,t,n)=>Ln(e)?e?De.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),Hr=e=>_a.test(e);De.isNotRelative=Hr;De.convert=e=>e;var On=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){Sa(this,Nr,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(t){if(t&&t[Nr]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(Aa(t)){let n=Ma(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Or(Ln(t)?wa(t):t).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(t){return this.add(t)}_testOne(t,n){let r=!1,o=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(o===i&&r!==o||i&&!r&&!o&&!n)return;s.regex.test(t)&&(r=!i,o=i)}),{ignored:r,unignored:o}}_test(t,n,r,o){let s=t&&De.convert(t);return De(s,t,this._allowRelativePaths?Ur:ka),this._t(s,n,r,o)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(Pn)),o.pop(),!o.length)return n[t]=this._testOne(t,r);let s=this._t(o.join(Pn)+Pn,n,r,o);return n[t]=s.ignored?s:this._testOne(t,r)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return Or(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},Wt=e=>new On(e),Pa=e=>De(e&&De.convert(e),e,Ur);Wt.isPathValid=Pa;Wt.default=Wt;Fr.exports=Wt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");De.convert=e;let t=/^[a-z]:\//i;De.isNotRelative=n=>t.test(n)||Hr(n)}});import{randomUUID as ii}from"crypto";import{createInterface as Sd}from"readline/promises";import{stdin as vd,stdout as xd}from"process";import{render as Cd}from"ink";import _i from"os";import{readFile as yr}from"fs/promises";import{join as Tr,dirname as Si}from"path";import{fileURLToPath as vi}from"url";var xi=/{{\s*([\w.-]+)\s*}}/g;function Ci(e,t){return e.replace(xi,(n,r)=>t[r]??"")}function bi(){try{return _i.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function Ei(e){let t=Tr(e,"AGENTS.md");try{let n=await yr(t,"utf-8");return n.trim()?{path:t,content:n}:null}catch{return null}}function Ai(e,t){return`${e}
3
3
 
4
4
  ## Project AGENTS.md (Startup Root)
5
5
  Loaded from: ${t.path}
6
6
 
7
- ${t.content}`}async function hr(e={}){let t=e.cwd??process.cwd(),n=gi(hi(import.meta.url)),r=gr(n,"prompt.md"),o=await fr(r,"utf-8"),s={date:new Date().toISOString(),user:_i(),pwd:t},i=Ti(o,s),a=await Si(t);return a?vi(i,a):i}import{appendFile as xi,mkdir as Ci}from"fs/promises";import{dirname as bi}from"path";var Bt=class{constructor(t){this.filePath=t}ready=!1;async append(t){this.ready||(await Ci(bi(this.filePath),{recursive:!0}),this.ready=!0),await xi(this.filePath,`${JSON.stringify(t)}
8
- `,"utf8")}async flush(){return Promise.resolve()}};function yr(e){return{ts:new Date().toISOString(),sessionId:e.sessionId,turn:e.turn,step:e.step,type:e.type,content:e.content,role:e.role,meta:e.meta}}import{z as Ne}from"zod";function N(e){let{inputSchema:t,execute:n,...r}=e,o=t.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,source:"native",inputSchema:i,validateInput:a=>{let l=t.safeParse(a);if(!l.success){let c=l.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${e.name} invalid input: ${c}`}}return{ok:!0,data:l.data}},execute:n}}function f(e,t=!1){return{content:[{type:"text",text:e}],isError:t}}import{spawn as qi}from"child_process";import{EventEmitter as Gi}from"events";import{resolve as Ki}from"path";import{posix as Ai}from"path";var Tr=220,_r=4096,Ei=/^\/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,Mi=/(?:^|[\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,wi=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),ki=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function Sn(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Pi(e){let t=e.replace(/\s+/g," ").trim();return t.length>Tr?`${t.slice(0,Tr)}\u2026`:t}function Sr(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return(t.split(/[\\/]/).at(-1)??t).toLowerCase()}function Ii(e){let t=null,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){n=!1;continue}if(o==="\\"&&t!=="'"){n=!0;continue}if(t){o===t&&(t=null);continue}if(o==='"'||o==="'"){t=o;continue}if(o==="#")return e.slice(0,r)}return e}function Ri(e){let t=[],n="",r=null,o=!1,s=()=>{let i=Ii(n).trim();i&&t.push(i),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){n+=a,o=!0;continue}if(r){n+=a,a===r&&(r=null);continue}if(a==='"'||a==="'"){r=a,n+=a;continue}if(a===";"||a===`
9
- `){s();continue}if(a==="&"){e[i+1]==="&"&&(i+=1),s();continue}if(a==="|"){e[i+1]==="|"&&(i+=1),s();continue}n+=a}return s(),t}function Oi(e){let t=[],n="",r=null,o=!1,s=()=>{n&&t.push(n),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){o=!0;continue}if(r){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(/\s/.test(a)){s();continue}n+=a}return s(),t}function vr(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function Li(e,t){let n=t;for(;n<e.length;){let r=Sr(e[n]??"");if(r==="sudo"){for(n+=1;n<e.length;){let o=e[n]??"";if(!o.startsWith("-"))break;n+=1,wi.has(o)&&n<e.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<e.length;){let o=e[n]??"";if(o.startsWith("-")||vr(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function Ni(e){let t=Oi(e);if(t.length===0)return null;let n=0;for(;n<t.length&&vr(t[n]??"");)n+=1;if(n=Li(t,n),n>=t.length)return null;let r=Sr(t[n]??"");return r?{raw:e,commandName:r,args:t.slice(n+1)}:null}function vn(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return Ei.test(t)}function $i(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.toLowerCase();return n==="/"||n==="/*"||n==="/.*"||n==="~"||n==="~/"||n==="~/*"||n==="$home"||n==="$home/"||n==="$home/*"||n==="${home}"||n==="${home}/"||n==="${home}/*"?!0:t.startsWith("/")&&!/[*?[\]{}$]/.test(t)?Ai.normalize(t)==="/":!1}function Di(e){return e.startsWith("-")&&e!=="-"}function Ui(e){if(e.commandName!=="rm")return null;let t=!1,n=0;for(;n<e.args.length;){let o=e.args[n]??"";if(o==="--"){n+=1;break}if(!Di(o))break;if(o==="--recursive"){t=!0,n+=1;continue}if(o.startsWith("--")){n+=1;continue}let s=o.slice(1);(s.includes("r")||s.includes("R"))&&(t=!0),n+=1}if(!t)return null;let r=e.args.slice(n);for(let o of r)if($i(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:e.raw};return null}function Hi(e){return e.commandName==="mkfs"||e.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:e.raw}:null}function Fi(e){if(e.commandName!=="dd")return null;for(let t=0;t<e.args.length;t+=1){let n=e.args[t]??"",r=n.indexOf("=");if(r<=0)continue;let o=n.slice(0,r).toLowerCase(),s=n.slice(r+1);if(o==="of"&&vn(s))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}for(let t=0;t<e.args.length-1;t+=1){let n=(e.args[t]??"").toLowerCase(),r=e.args[t+1]??"";if(n==="of"&&vn(r))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}return null}function Bi(e){return!ki.has(e.commandName)||!e.args.some(t=>vn(t))?null:{ruleId:"disk_mutation_block_device",matchedSegment:e.raw}}function Wi(e){return Mi.test(e)?{ruleId:"redirect_block_device",matchedSegment:e}:null}function ji(e){for(let t of Ri(e)){let n=Ni(t);if(n){let o=Ui(n);if(o)return o;let s=Hi(n);if(s)return s;let i=Fi(n);if(i)return i;let a=Bi(n);if(a)return a}let r=Wi(t);if(r)return r}return null}function zi(e,t){let n=Pi(e.command),r=typeof e.sessionId=="number"?` session_id="${e.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${Sn(e.toolName)}" reason="dangerous_command" policy="blacklist" rule="${Sn(t.ruleId)}"${r} command="${Sn(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function xn(e){let t=ji(e.command);return t?{blocked:!0,xml:zi(e,t),match:t}:{blocked:!1}}function xr(e){let n=e.replace(/\r\n/g,`
7
+ ${t.content}`}async function _r(e={}){let t=e.cwd??process.cwd(),n=Si(vi(import.meta.url)),r=Tr(n,"prompt.md"),o=await yr(r,"utf-8"),s={date:new Date().toISOString(),user:bi(),pwd:t},i=Ci(o,s),a=await Ei(t);return a?Ai(i,a):i}import{appendFile as wi,mkdir as Mi}from"fs/promises";import{dirname as ki}from"path";var Ft=class{constructor(t){this.filePath=t}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=Mi(ki(this.filePath),{recursive:!0}).then(()=>{})),this.ensureDirPromise}async append(t){if(this.closed)throw new Error("History sink is closed");return this.writeQueue=this.writeQueue.then(async()=>{await this.ensureDirectory(),await wi(this.filePath,`${JSON.stringify(t)}
8
+ `,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function Sr(e){return{ts:new Date().toISOString(),sessionId:e.sessionId,turn:e.turn,step:e.step,type:e.type,content:e.content,role:e.role,meta:e.meta}}import{z as Ne}from"zod";function N(e){let{inputSchema:t,execute:n,...r}=e,o=t.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,source:"native",inputSchema:i,validateInput:a=>{let l=t.safeParse(a);if(!l.success){let c=l.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${e.name} invalid input: ${c}`}}return{ok:!0,data:l.data}},execute:n}}function f(e,t=!1){return{content:[{type:"text",text:e}],isError:t}}import{spawn as Ji}from"child_process";import{EventEmitter as Yi}from"events";import{resolve as Zi}from"path";import{posix as Pi}from"path";var vr=220,xr=4096,Ii=/^\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)$/i,Ri=/(?:^|[\s(])(?:\d?>>?|>>|>\||&>)\s*\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)(?:\s|$)/i,Oi=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Li=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function xn(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ni(e){let t=e.replace(/\s+/g," ").trim();return t.length>vr?`${t.slice(0,vr)}\u2026`:t}function Cr(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return(t.split(/[\\/]/).at(-1)??t).toLowerCase()}function $i(e){let t=null,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){n=!1;continue}if(o==="\\"&&t!=="'"){n=!0;continue}if(t){o===t&&(t=null);continue}if(o==='"'||o==="'"){t=o;continue}if(o==="#")return e.slice(0,r)}return e}function Di(e){let t=[],n="",r=null,o=!1,s=()=>{let i=$i(n).trim();i&&t.push(i),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){n+=a,o=!0;continue}if(r){n+=a,a===r&&(r=null);continue}if(a==='"'||a==="'"){r=a,n+=a;continue}if(a===";"||a===`
9
+ `){s();continue}if(a==="&"){e[i+1]==="&"&&(i+=1),s();continue}if(a==="|"){e[i+1]==="|"&&(i+=1),s();continue}n+=a}return s(),t}function Ui(e){let t=[],n="",r=null,o=!1,s=()=>{n&&t.push(n),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(o){n+=a,o=!1;continue}if(a==="\\"&&r!=="'"){o=!0;continue}if(r){a===r?r=null:n+=a;continue}if(a==='"'||a==="'"){r=a;continue}if(/\s/.test(a)){s();continue}n+=a}return s(),t}function br(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function Hi(e,t){let n=t;for(;n<e.length;){let r=Cr(e[n]??"");if(r==="sudo"){for(n+=1;n<e.length;){let o=e[n]??"";if(!o.startsWith("-"))break;n+=1,Oi.has(o)&&n<e.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<e.length;){let o=e[n]??"";if(o.startsWith("-")||br(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function Fi(e){let t=Ui(e);if(t.length===0)return null;let n=0;for(;n<t.length&&br(t[n]??"");)n+=1;if(n=Hi(t,n),n>=t.length)return null;let r=Cr(t[n]??"");return r?{raw:e,commandName:r,args:t.slice(n+1)}:null}function Cn(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return Ii.test(t)}function Bi(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.toLowerCase();return n==="/"||n==="/*"||n==="/.*"||n==="~"||n==="~/"||n==="~/*"||n==="$home"||n==="$home/"||n==="$home/*"||n==="${home}"||n==="${home}/"||n==="${home}/*"?!0:t.startsWith("/")&&!/[*?[\]{}$]/.test(t)?Pi.normalize(t)==="/":!1}function Wi(e){return e.startsWith("-")&&e!=="-"}function ji(e){if(e.commandName!=="rm")return null;let t=!1,n=0;for(;n<e.args.length;){let o=e.args[n]??"";if(o==="--"){n+=1;break}if(!Wi(o))break;if(o==="--recursive"){t=!0,n+=1;continue}if(o.startsWith("--")){n+=1;continue}let s=o.slice(1);(s.includes("r")||s.includes("R"))&&(t=!0),n+=1}if(!t)return null;let r=e.args.slice(n);for(let o of r)if(Bi(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:e.raw};return null}function zi(e){return e.commandName==="mkfs"||e.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:e.raw}:null}function qi(e){if(e.commandName!=="dd")return null;for(let t=0;t<e.args.length;t+=1){let n=e.args[t]??"",r=n.indexOf("=");if(r<=0)continue;let o=n.slice(0,r).toLowerCase(),s=n.slice(r+1);if(o==="of"&&Cn(s))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}for(let t=0;t<e.args.length-1;t+=1){let n=(e.args[t]??"").toLowerCase(),r=e.args[t+1]??"";if(n==="of"&&Cn(r))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}return null}function Gi(e){return!Li.has(e.commandName)||!e.args.some(t=>Cn(t))?null:{ruleId:"disk_mutation_block_device",matchedSegment:e.raw}}function Ki(e){return Ri.test(e)?{ruleId:"redirect_block_device",matchedSegment:e}:null}function Vi(e){for(let t of Di(e)){let n=Fi(t);if(n){let o=ji(n);if(o)return o;let s=zi(n);if(s)return s;let i=qi(n);if(i)return i;let a=Gi(n);if(a)return a}let r=Ki(t);if(r)return r}return null}function Xi(e,t){let n=Ni(e.command),r=typeof e.sessionId=="number"?` session_id="${e.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${xn(e.toolName)}" reason="dangerous_command" policy="blacklist" rule="${xn(t.ruleId)}"${r} command="${xn(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function bn(e){let t=Vi(e.command);return t?{blocked:!0,xml:Xi(e,t),match:t}:{blocked:!1}}function Er(e){let n=e.replace(/\r\n/g,`
10
10
  `).replace(/\r/g,`
11
11
  `).split(`
12
- `),r=n.pop()??"";return{completedLines:n,remainder:r}}function Cn(e){return e.length<=_r?e:e.slice(-_r)}var Vi=1e4,Xi=250,Ji=2e3,Cr=64;function Yi(e){return Math.ceil(e.length/4)}function Zi(){return Math.random().toString(16).slice(2)||String(Date.now())}function Qi(e){let t=e.login,n=e.shell?.trim();if(process.platform==="win32"){let o=n||"powershell.exe";return o.toLowerCase().includes("powershell")?{file:o,args:["-NoProfile","-Command",e.cmd]}:{file:o,args:[t?"-lc":"-c",e.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[t?"-lc":"-c",e.cmd]}}function ea(e,t){let r=(typeof t=="number"&&t>0?Math.floor(t):Ji)*4,o=Yi(e);return e.length<=r?{output:e,originalTokenCount:o}:{output:e.slice(0,r),originalTokenCount:o}}function ta(e){let t=[];return t.push(`Chunk ID: ${e.chunkId}`),t.push(`Wall time: ${e.wallTimeSeconds.toFixed(4)} seconds`),e.exitCode!==null?t.push(`Process exited with code ${e.exitCode}`):t.push(`Process running with session ID ${e.sessionId}`),t.push(`Original token count: ${e.originalTokenCount}`),t.push("Output:"),t.push(e.output),t.join(`
13
- `)}function br(e,t){return typeof e!="number"||Number.isNaN(e)?t:e<0?0:Math.floor(e)}async function Ar(e,t){t<=0||e.exited||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},t),o=()=>{clearTimeout(r),s(),n()},s=()=>{e.eventBus.off("exit",o)};e.eventBus.on("exit",o)})])}var bn=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Cr)return;let t=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,r)=>n.startedAtMs-r.startedAtMs);for(let n of t){if(this.sessions.size<=Cr)break;this.sessions.delete(n.id)}}async start(t){let n=t.cmd.trim();if(!n)throw new Error("cmd must not be empty");let r=xn({toolName:t.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=Qi({cmd:n,shell:t.shell,login:t.login!==!1}),a=t.workdir?.trim()?Ki(process.cwd(),t.workdir.trim()):process.cwd(),l=qi(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),c={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new Gi,proc:l},u=(y,p)=>{let h=typeof p=="string"?p:p.toString("utf8");c.output+=y?`${y}${h}`:h,c.eventBus.emit("output")};l.stdout?.on("data",y=>u("",y)),l.stderr?.on("data",y=>u("",y)),l.on("error",y=>{c.output+=`
14
- [exec error] ${y.message}`,c.eventBus.emit("output")}),l.on("close",y=>{c.exited=!0,c.exitCode=typeof y=="number"?y:-1,c.eventBus.emit("exit")}),this.sessions.set(o,c),this.cleanupSessions();let d=br(t.yield_time_ms,Vi);return await Ar(c,d),this.buildResponseText(c,t.max_output_tokens)}async write(t){let n=this.sessions.get(t.session_id);if(!n)throw new Error(`session_id ${t.session_id} not found`);if(!n.exited&&t.chars&&t.chars.length>0){let o=Cn(`${n.pendingStdinInput}${t.chars}`),{completedLines:s,remainder:i}=xr(o);for(let a of s){if(!a.trim())continue;let l=xn({toolName:t.source_tool??"write_stdin",command:a,sessionId:n.id});if(l.blocked)return n.pendingStdinInput="",l.xml}n.pendingStdinInput=Cn(i),n.proc.stdin?.write(t.chars)}let r=br(t.yield_time_ms,Xi);return await Ar(n,r),this.buildResponseText(n,t.max_output_tokens)}buildResponseText(t,n){let r=t.output.slice(t.readOffset);t.readOffset=t.output.length;let o=ea(r,n),s={sessionId:t.id,chunkId:Zi(),wallTimeSeconds:(Date.now()-t.startedAtMs)/1e3,exitCode:t.exited?t.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return ta(s)}},Er=new bn;async function st(e){return Er.start(e)}async function Mr(e){return Er.write(e)}var na=Ne.object({command:Ne.array(Ne.string().min(1)).min(1,"command cannot be empty"),workdir:Ne.string().optional(),timeout_ms:Ne.number().int().positive().optional(),sandbox_permissions:Ne.enum(["use_default","require_escalated"]).optional(),justification:Ne.string().optional(),prefix_rule:Ne.array(Ne.string().min(1)).optional()}).strict();function ra(e){return e.map(t=>/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)).join(" ")}var wr=N({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:na,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,timeout_ms:n})=>{try{let r=await st({cmd:ra(e),workdir:t,login:!1,yield_time_ms:n,source_tool:"shell"});return f(r)}catch(r){return f(`shell failed: ${r.message}`,!0)}}});import{z as $e}from"zod";var oa=$e.object({command:$e.string().min(1,"command cannot be empty"),workdir:$e.string().optional(),login:$e.boolean().optional(),timeout_ms:$e.number().int().positive().optional(),sandbox_permissions:$e.enum(["use_default","require_escalated"]).optional(),justification:$e.string().optional(),prefix_rule:$e.array($e.string().min(1)).optional()}).strict(),kr=N({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:oa,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,login:n,timeout_ms:r})=>{try{let o=await st({cmd:e,workdir:t,login:n,yield_time_ms:r,source_tool:"shell_command"});return f(o)}catch(o){return f(`shell_command failed: ${o.message}`,!0)}}});import{z as _e}from"zod";var sa=_e.object({cmd:_e.string().min(1,"cmd cannot be empty"),workdir:_e.string().optional(),shell:_e.string().optional(),login:_e.boolean().optional(),tty:_e.boolean().optional(),yield_time_ms:_e.number().int().nonnegative().optional(),max_output_tokens:_e.number().int().positive().optional(),sandbox_permissions:_e.enum(["use_default","require_escalated"]).optional(),justification:_e.string().optional(),prefix_rule:_e.array(_e.string().min(1)).optional()}).strict(),An=N({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:sa,supportsParallelToolCalls:!0,isMutating:!0,execute:async e=>{try{let t=await st({...e,source_tool:"exec_command"});return f(t)}catch(t){return f(`exec_command failed: ${t.message}`,!0)}}});import{z as Tt}from"zod";var ia=Tt.object({session_id:Tt.number().int().positive(),chars:Tt.string().optional(),yield_time_ms:Tt.number().int().nonnegative().optional(),max_output_tokens:Tt.number().int().positive().optional()}).strict(),En=N({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:ia,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{try{let t=await Mr({...e,source_tool:"write_stdin"});return f(t)}catch(t){return f(`write_stdin failed: ${t.message}`,!0)}}});import{access as La,readFile as Na,writeFile as $a}from"fs/promises";import{z as me}from"zod";var Pa=di(Ur(),1);import{normalize as ba,resolve as Aa,dirname as sd,join as Ea,relative as Ma,isAbsolute as wa}from"path";import{homedir as ka}from"os";import{existsSync as ld,statSync as cd}from"fs";import{readFile as pd}from"fs/promises";function Ue(e){return ba(Aa(e))}function Ia(e,t){let n=Ma(t,e);return n===""||!n.startsWith("..")&&!wa(n)}function Ra(){let e=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>Ue(t)):[]}function Hr(){let e=new Set;e.add(Ue(process.cwd()));let t=process.env.MEMO_HOME?.trim()||Ea(ka(),".memo");e.add(Ue(t));for(let n of Ra())e.add(n);return Array.from(e)}function Oa(e){return Hr().some(n=>Ia(e,n))}function Fr(e){if(Oa(e))return null;let t=Hr();return`sandbox \u62D2\u7EDD\u5199\u5165: ${e} \u4E0D\u5728\u5141\u8BB8\u76EE\u5F55\u5185 (${t.join(", ")})`}var Da=me.object({old_string:me.string().min(1,"old_string cannot be empty"),new_string:me.string(),replace_all:me.boolean().optional()}).strict(),Ua=me.object({file_path:me.string().min(1),old_string:me.string().optional(),new_string:me.string().optional(),replace_all:me.boolean().optional(),edits:me.array(Da).min(1).optional()}).superRefine((e,t)=>{let n=!!(e.edits&&e.edits.length>0),r=e.old_string!==void 0||e.new_string!==void 0||e.replace_all!==void 0;if(n&&r){t.addIssue({code:me.ZodIssueCode.custom,message:"Use either edits or old_string/new_string fields, not both."});return}if(!n){if(typeof e.old_string!="string"||typeof e.new_string!="string"){t.addIssue({code:me.ZodIssueCode.custom,message:"Provide old_string/new_string, or use edits."});return}e.old_string.trim()||t.addIssue({code:me.ZodIssueCode.custom,message:"old_string cannot be empty",path:["old_string"]});return}for(let o=0;o<(e.edits?.length??0);o+=1){let s=e.edits?.[o];s&&(s.old_string.trim()||t.addIssue({code:me.ZodIssueCode.custom,message:"old_string cannot be empty",path:["edits",o,"old_string"]}))}}).strict();function Ha(e){let t=Fr(e);if(t)throw new Error(t)}function Fa(e){return e.edits&&e.edits.length>0?e.edits:[{old_string:e.old_string??"",new_string:e.new_string??"",replace_all:e.replace_all}]}var Br=N({name:"apply_patch",description:"Edit a local file by direct string replacement. Supports single replacement fields or batch edits.",inputSchema:Ua,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{let t=Ue(e.file_path);try{Ha(t),await La(t);let n=await Na(t,"utf8"),r=Fa(e),o=n,s=0;for(let i=0;i<r.length;i+=1){let a=r[i];if(!a)continue;let l=a.old_string,c=a.replace_all??!1;if(!o.includes(l))return r.length===1?f("apply_patch failed: target text not found.",!0):f(`apply_patch failed: target text not found at edit ${i+1}.`,!0);if(c){let u=o.split(l),d=u.length-1;o=u.join(a.new_string),s+=d}else o=o.replace(l,a.new_string),s+=1}return o===n?f("No changes made."):(await $a(t,o,"utf8"),f(`Success. Updated file: ${t}
15
- Edits: ${r.length}
16
- Replacements: ${s}`))}catch(n){return n.code==="ENOENT"?f(`apply_patch failed: file does not exist: ${t}`,!0):f(`apply_patch failed: ${n.message}`,!0)}}});import{readFile as Ba}from"fs/promises";import{z as be}from"zod";var Wr=500,jr=200,Wa=be.object({file_path:be.string().min(1),offset:be.number().int().positive().optional(),limit:be.number().int().positive().optional(),mode:be.enum(["slice","indentation"]).optional(),indentation:be.object({anchor_line:be.number().int().positive().optional(),max_levels:be.number().int().nonnegative().optional(),include_siblings:be.boolean().optional(),include_header:be.boolean().optional(),max_lines:be.number().int().positive().optional()}).strict().optional()}).strict();function ja(e){return e.length<=Wr?e:e.slice(0,Wr)}function za(e){let t=0;for(let n of e)if(n===" ")t+=1;else if(n===" ")t+=4;else break;return t}function qa(e){return e.split(/\r?\n/).map((n,r)=>({line:r+1,text:ja(n),indent:za(n)}))}function Ga(e){return e.map(t=>`L${t.line}: ${t.text}`).join(`
17
- `)}function Ka(e,t,n){let r=t-1;if(r>=e.length)throw new Error("offset exceeds file length");return e.slice(r,r+n)}function Va(e,t){let n=t.offset??1,r=t.limit??jr,o=t.indentation,s=o?.anchor_line??n;if(s<=0||s>e.length)throw new Error("anchor_line exceeds file length");let i=e[s-1];if(!i)throw new Error("anchor_line exceeds file length");let a=o?.max_levels??0,l=o?.include_siblings??!0,c=o?.include_header??!0,u=o?.max_lines??r,d=Math.max(1,Math.min(r,u)),y=a===0?0:Math.max(0,i.indent-a*4),p=s-1,h=s-1;for(;p-1>=0;){let m=e[p-1];if(!m)break;let k=/^\s*(#|\/\/|--)/.test(m.text),v=m.text.trim().length===0;if(m.indent<y||!l&&m.indent===y&&!k&&!v||!c&&(k||v)&&m.indent<i.indent||(p-=1,h-p+1>=d))break}for(;h+1<e.length&&h-p+1<d;){let m=e[h+1];if(!m||m.indent<y||!l&&m.indent===y)break;h+=1}return e.slice(p,h+1)}var zr=N({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Wa,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??1,n=e.limit??jr;if(t<=0)return f("offset must be a 1-indexed line number",!0);if(n<=0)return f("limit must be greater than zero",!0);let r=e.file_path.trim();if(!r.startsWith("/"))return f("file_path must be an absolute path",!0);let o=Ue(r);try{let s=await Ba(o,"utf8"),i=qa(s);if(i.length===0)return f("");let l=(e.mode??"slice")==="indentation"?Va(i,e):Ka(i,t,n);return f(Ga(l))}catch(s){return f(`read_file failed: ${s.message}`,!0)}}});import{readdir as Xa,lstat as Ja}from"fs/promises";import{join as Ya}from"path";import{z as _t}from"zod";var Za=1,Qa=25,el=2,tl=_t.object({dir_path:_t.string().min(1),offset:_t.number().int().positive().optional(),limit:_t.number().int().positive().optional(),depth:_t.number().int().positive().optional()}).strict();function nl(e){let t=" ".repeat(e.displayDepth*2),n="";e.kind==="dir"&&(n="/"),e.kind==="symlink"&&(n="@"),e.kind==="other"&&(n="?");let r=e.path.split("/"),o=r[r.length-1]??e.path;return`${t}${o}${n}`}var qr=N({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:tl,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??Za,n=e.limit??Qa,r=e.depth??el;if(t<=0)return f("offset must be a 1-indexed entry number",!0);if(n<=0)return f("limit must be greater than zero",!0);if(r<=0)return f("depth must be greater than zero",!0);let o=e.dir_path.trim();if(!o.startsWith("/"))return f("dir_path must be an absolute path",!0);let s=Ue(o);try{let i=[{absPath:s,depth:r,displayDepth:0}],a=[];for(;i.length>0;){let d=i.shift();if(!d)continue;let y=await Xa(d.absPath);y.sort((p,h)=>p.localeCompare(h));for(let p of y){let h=Ya(d.absPath,p),m=await Ja(h),k=m.isSymbolicLink()?"symlink":m.isDirectory()?"dir":m.isFile()?"file":"other";a.push({path:h,displayDepth:d.displayDepth,kind:k}),k==="dir"&&d.depth>1&&i.push({absPath:h,depth:d.depth-1,displayDepth:d.displayDepth+1})}}if(a.length===0)return f(`Absolute path: ${s}`);let l=t-1;if(l>=a.length)return f("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),u=[`Absolute path: ${s}`,...c.map(nl)];return l+n<a.length&&u.push(`More than ${n} entries found`),f(u.join(`
18
- `))}catch(i){return f(`list_dir failed: ${i.message}`,!0)}}});import{spawn as rl}from"child_process";import{resolve as ol}from"path";import{z as St}from"zod";var sl=100,il=2e3,al=3e4,ll=St.object({pattern:St.string().min(1),include:St.string().optional(),path:St.string().optional(),limit:St.number().int().positive().optional()}).strict();function cl(e){return new Promise((t,n)=>{let r=["--files-with-matches","--sortr=modified","--regexp",e.pattern,"--no-messages"];e.include?.trim()&&r.push("--glob",e.include.trim()),r.push("--",e.searchPath);let o=rl("rg",r,{cwd:e.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",l=>s.push(l)),o.stderr?.on("data",l=>i.push(l));let a=setTimeout(()=>{o.kill("SIGTERM"),n(new Error("rg timed out after 30 seconds"))},al);o.on("error",l=>{clearTimeout(a),n(l)}),o.on("close",l=>{clearTimeout(a),t({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var Gr=N({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:ll,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.pattern.trim();if(!t)return f("pattern must not be empty",!0);let n=Math.min(e.limit??sl,il),r=e.path?.trim()?ol(process.cwd(),e.path.trim()):process.cwd();try{let o=await cl({pattern:t,include:e.include,searchPath:r,cwd:process.cwd(),limit:n});if(o.exitCode===1)return f("No matches found.");if(o.exitCode!==0)return f(`rg failed: ${o.stderr||o.stdout}`,!0);let s=o.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,n);return s.length===0?f("No matches found."):f(s.join(`
19
- `))}catch(o){return f(`grep_files failed: ${o.message}`,!0)}}});import{z as He}from"zod";var Kr=null;function On(e){Kr=e}function Vr(){return Kr}var ul=He.object({server:He.string().optional(),cursor:He.string().optional()}).strict(),pl=He.object({server:He.string().optional(),cursor:He.string().optional()}).strict(),ml=He.object({server:He.string().min(1),uri:He.string().min(1)}).strict();function Ln(){let e=Vr();if(!e)throw new Error("MCP pool is not initialized");return e}var Xr=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:ul,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=Ln();if(e?.trim()){let s=n.get(e.trim());if(!s)return f(`MCP server not found: ${e}`,!0);let i=await s.client.listResources(t?{cursor:t}:void 0);return f(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(t)return f("cursor is only supported when server is specified",!0);let r=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),o=[];for(let s of r){let i=await s.client.listResources();for(let a of i.resources)o.push({server:s.name,...a})}return f(JSON.stringify({resources:o},null,2))}catch(n){return f(`list_mcp_resources failed: ${n.message}`,!0)}}}),Jr=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:pl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=Ln();if(e?.trim()){let s=n.get(e.trim());if(!s)return f(`MCP server not found: ${e}`,!0);let i=await s.client.listResourceTemplates(t?{cursor:t}:void 0);return f(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(t)return f("cursor is only supported when server is specified",!0);let r=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),o=[];for(let s of r){let i=await s.client.listResourceTemplates();for(let a of i.resourceTemplates)o.push({server:s.name,...a})}return f(JSON.stringify({resourceTemplates:o},null,2))}catch(n){return f(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Yr=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:ml,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,uri:t})=>{try{let r=Ln().get(e);if(!r)return f(`MCP server not found: ${e}`,!0);let o=await r.client.readResource({uri:t});return f(JSON.stringify({server:e,uri:t,...o},null,2))}catch(n){return f(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as it}from"zod";var dl=it.object({step:it.string().min(1),status:it.enum(["pending","in_progress","completed"])}).strict(),fl=it.object({explanation:it.string().optional(),plan:it.array(dl).min(1)}).strict(),Zr=[],Qr=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:fl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:e,plan:t})=>{if(t.filter(r=>r.status==="in_progress").length>1)return f("At most one step can be in_progress at a time",!0);if(t.length<4){let r=t[0]?.step??"";return f(`<system_hint tool="update_plan" reason="simple_task">Task "${r}" is simple (${t.length} step${t.length>1?"s":""}) - execute directly without update_plan.</system_hint>`)}return Zr=t,f(JSON.stringify({message:"Plan updated",explanation:e,plan:Zr},null,2))}});import{readFile as gl}from"fs/promises";import{homedir as hl}from"os";import{join as eo}from"path";import{z as to}from"zod";var yl=to.object({memory_id:to.string().min(1)}).strict();function Tl(){let e=process.env.MEMO_HOME?.trim()||eo(hl(),".memo");return eo(e,"Agents.md")}var no=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:yl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:e})=>{try{let t=Tl(),n=await gl(t,"utf8");return f(JSON.stringify({memory_id:e,memory_summary:n},null,2))}catch{return f(`memory not found for memory_id=${e}`,!0)}}});import{z as ro}from"zod";var _l=ro.object({url:ro.string().min(1)}).strict(),oo=1e4,vt=512e3,Nn=4e3,Sl=new Set(["http:","https:","data:"]),vl=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,xl=/<\s*(br|hr)\s*\/?>/gi,Cl=/<\s*li[^>]*>/gi,bl=/<[^>]+>/g,Al=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,El=e=>e.replace(/&nbsp;/gi," ").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&amp;/gi,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(r,o)=>{try{let s=o.startsWith("x")||o.startsWith("X")?parseInt(o.slice(1),16):parseInt(o,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),Ml=e=>{let r=e.replace(Al," ").replace(Cl,"- ").replace(xl,`
20
- `).replace(vl,`
21
- `).replace(bl," "),s=El(r).replace(/\r/g,"").split(`
12
+ `),r=n.pop()??"";return{completedLines:n,remainder:r}}function En(e){return e.length<=xr?e:e.slice(-xr)}var Qi=1e4,ea=250,ta=2e3,Bt=64;function na(e){return Math.ceil(e.length/4)}function ra(){return Math.random().toString(16).slice(2)||String(Date.now())}function oa(e){let t=e.login,n=e.shell?.trim();if(process.platform==="win32"){let o=n||"powershell.exe";return o.toLowerCase().includes("powershell")?{file:o,args:["-NoProfile","-Command",e.cmd]}:{file:o,args:[t?"-lc":"-c",e.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[t?"-lc":"-c",e.cmd]}}function sa(e,t){let r=(typeof t=="number"&&t>0?Math.floor(t):ta)*4,o=na(e);return e.length<=r?{output:e,originalTokenCount:o,deliveredChars:e.length}:{output:e.slice(0,r),originalTokenCount:o,deliveredChars:r}}function ia(e){let t=[];return t.push(`Chunk ID: ${e.chunkId}`),t.push(`Wall time: ${e.wallTimeSeconds.toFixed(4)} seconds`),e.exitCode!==null?t.push(`Process exited with code ${e.exitCode}`):t.push(`Process running with session ID ${e.sessionId}`),t.push(`Original token count: ${e.originalTokenCount}`),t.push("Output:"),t.push(e.output),t.join(`
13
+ `)}function Ar(e,t){return typeof e!="number"||Number.isNaN(e)?t:e<0?0:Math.floor(e)}async function wr(e,t){t<=0||e.exited||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},t),o=()=>{clearTimeout(r),s(),n()},s=()=>{e.eventBus.off("exit",o)};e.eventBus.on("exit",o)})])}async function Mr(e,t){e.exited||t<=0||await Promise.race([new Promise(n=>{let r=setTimeout(()=>{s(),n()},t),o=()=>{clearTimeout(r),s(),n()},s=()=>{e.eventBus.off("exit",o)};e.eventBus.on("exit",o)})])}var An=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Bt)return;let t=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,r)=>n.startedAtMs-r.startedAtMs);for(let n of t){if(this.sessions.size<=Bt)break;this.sessions.delete(n.id)}}activeSessionCount(){let t=0;for(let n of this.sessions.values())n.exited||(t+=1);return t}async terminateForTimeout(t){t.exited||(t.proc.kill("SIGTERM"),await Mr(t,200),t.exited||(t.proc.kill("SIGKILL"),await Mr(t,200)))}async start(t){let n=t.cmd.trim();if(!n)throw new Error("cmd must not be empty");if(this.cleanupSessions(),this.activeSessionCount()>=Bt)throw new Error(`too many active sessions (max ${Bt})`);let r=bn({toolName:t.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=oa({cmd:n,shell:t.shell,login:t.login!==!1}),a=t.workdir?.trim()?Zi(process.cwd(),t.workdir.trim()):process.cwd(),l=Ji(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),c={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new Yi,proc:l},u=(h,d)=>{let E=typeof d=="string"?d:d.toString("utf8");c.output+=h?`${h}${E}`:E,c.eventBus.emit("output")};l.stdout?.on("data",h=>u("",h)),l.stderr?.on("data",h=>u("",h)),l.on("error",h=>{c.output+=`
14
+ [exec error] ${h.message}`,c.eventBus.emit("output")}),l.on("close",h=>{c.exited=!0,c.exitCode=typeof h=="number"?h:-1,c.eventBus.emit("exit")}),this.sessions.set(o,c),this.cleanupSessions();let p=typeof t.execution_timeout_ms=="number"&&t.execution_timeout_ms>0?Math.floor(t.execution_timeout_ms):null,y=Ar(t.yield_time_ms,Qi),m=p!==null?Math.min(y,Math.max(0,p)):y;if(await wr(c,m),p!==null&&!c.exited&&Date.now()-s>=p)throw await this.terminateForTimeout(c),this.cleanupSessions(),new Error(`command timed out after ${p}ms`);return this.buildResponseText(c,t.max_output_tokens)}async write(t){let n=this.sessions.get(t.session_id);if(!n)throw new Error(`session_id ${t.session_id} not found`);if(!n.exited&&t.chars&&t.chars.length>0){let o=En(`${n.pendingStdinInput}${t.chars}`),{completedLines:s,remainder:i}=Er(o);for(let a of s){if(!a.trim())continue;let l=bn({toolName:t.source_tool??"write_stdin",command:a,sessionId:n.id});if(l.blocked)return n.pendingStdinInput="",l.xml}n.pendingStdinInput=En(i),n.proc.stdin?.write(t.chars)}let r=Ar(t.yield_time_ms,ea);return await wr(n,r),this.buildResponseText(n,t.max_output_tokens)}buildResponseText(t,n){let r=t.output.slice(t.readOffset),o=sa(r,n);t.readOffset+=o.deliveredChars;let s={sessionId:t.id,chunkId:ra(),wallTimeSeconds:(Date.now()-t.startedAtMs)/1e3,exitCode:t.exited?t.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return ia(s)}},kr=new An;async function st(e){return kr.start(e)}async function Pr(e){return kr.write(e)}var aa=Ne.object({command:Ne.array(Ne.string().min(1)).min(1,"command cannot be empty"),workdir:Ne.string().optional(),timeout_ms:Ne.number().int().positive().optional(),sandbox_permissions:Ne.enum(["use_default","require_escalated"]).optional(),justification:Ne.string().optional(),prefix_rule:Ne.array(Ne.string().min(1)).optional()}).strict(),la=/^[A-Za-z0-9_./:@%+-]+$/;function ca(e){return e.length===0?"''":la.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function ua(e){return e.map(t=>ca(t)).join(" ")}var Ir=N({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:aa,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,timeout_ms:n})=>{try{let r=await st({cmd:ua(e),workdir:t,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return f(r)}catch(r){return f(`shell failed: ${r.message}`,!0)}}});import{z as $e}from"zod";var pa=$e.object({command:$e.string().min(1,"command cannot be empty"),workdir:$e.string().optional(),login:$e.boolean().optional(),timeout_ms:$e.number().int().positive().optional(),sandbox_permissions:$e.enum(["use_default","require_escalated"]).optional(),justification:$e.string().optional(),prefix_rule:$e.array($e.string().min(1)).optional()}).strict(),Rr=N({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:pa,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,login:n,timeout_ms:r})=>{try{let o=await st({cmd:e,workdir:t,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return f(o)}catch(o){return f(`shell_command failed: ${o.message}`,!0)}}});import{z as _e}from"zod";var da=_e.object({cmd:_e.string().min(1,"cmd cannot be empty"),workdir:_e.string().optional(),shell:_e.string().optional(),login:_e.boolean().optional(),tty:_e.boolean().optional(),yield_time_ms:_e.number().int().nonnegative().optional(),max_output_tokens:_e.number().int().positive().optional(),sandbox_permissions:_e.enum(["use_default","require_escalated"]).optional(),justification:_e.string().optional(),prefix_rule:_e.array(_e.string().min(1)).optional()}).strict(),wn=N({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:da,supportsParallelToolCalls:!0,isMutating:!0,execute:async e=>{try{let t=await st({...e,source_tool:"exec_command"});return f(t)}catch(t){return f(`exec_command failed: ${t.message}`,!0)}}});import{z as yt}from"zod";var ma=yt.object({session_id:yt.number().int().positive(),chars:yt.string().optional(),yield_time_ms:yt.number().int().nonnegative().optional(),max_output_tokens:yt.number().int().positive().optional()}).strict(),Mn=N({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:ma,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{try{let t=await Pr({...e,source_tool:"write_stdin"});return f(t)}catch(t){return f(`write_stdin failed: ${t.message}`,!0)}}});import{access as Wa,readFile as ja,realpath as za,writeFile as qa}from"fs/promises";import{z as de}from"zod";var Ua=Ti(Br(),1);import{normalize as Ia,resolve as Ra,dirname as hm,join as Oa,relative as La,isAbsolute as Na}from"path";import{homedir as $a}from"os";import{existsSync as _m,statSync as Sm,realpathSync as Da}from"fs";import{readFile as xm}from"fs/promises";function Ue(e){return Ia(Ra(e))}function jt(e){let t=Ue(e);try{return Ue(Da(t))}catch{return t}}function Ha(e,t){let n=La(t,e);return n===""||!n.startsWith("..")&&!Na(n)}function Fa(){let e=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>jt(t)):[]}function Wr(){let e=new Set;e.add(jt(process.cwd()));let t=process.env.MEMO_HOME?.trim()||Oa($a(),".memo");e.add(jt(t));for(let n of Fa())e.add(n);return Array.from(e)}function Ba(e){let t=jt(e);return Wr().some(r=>Ha(t,r))}function jr(e){if(Ba(e))return null;let t=Wr();return`sandbox write denied: ${e} is not within allowed directories (${t.join(", ")})`}var Ga=de.object({old_string:de.string().min(1,"old_string cannot be empty"),new_string:de.string(),replace_all:de.boolean().optional()}).strict(),Ka=de.object({file_path:de.string().min(1),old_string:de.string().optional(),new_string:de.string().optional(),replace_all:de.boolean().optional(),edits:de.array(Ga).min(1).optional()}).superRefine((e,t)=>{let n=!!(e.edits&&e.edits.length>0),r=e.old_string!==void 0||e.new_string!==void 0||e.replace_all!==void 0;if(n&&r){t.addIssue({code:de.ZodIssueCode.custom,message:"Use either edits or old_string/new_string fields, not both."});return}if(!n){if(typeof e.old_string!="string"||typeof e.new_string!="string"){t.addIssue({code:de.ZodIssueCode.custom,message:"Provide old_string/new_string, or use edits."});return}e.old_string.trim()||t.addIssue({code:de.ZodIssueCode.custom,message:"old_string cannot be empty",path:["old_string"]});return}for(let o=0;o<(e.edits?.length??0);o+=1){let s=e.edits?.[o];s&&(s.old_string.trim()||t.addIssue({code:de.ZodIssueCode.custom,message:"old_string cannot be empty",path:["edits",o,"old_string"]}))}}).strict();function Va(e){let t=jr(e);if(t)throw new Error(t)}function Xa(e){return e.edits&&e.edits.length>0?e.edits:[{old_string:e.old_string??"",new_string:e.new_string??"",replace_all:e.replace_all}]}var zr=N({name:"apply_patch",description:"Edit a local file by direct string replacement. Supports single replacement fields or batch edits.",inputSchema:Ka,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{let t=Ue(e.file_path);try{await Wa(t);let n=Ue(await za(t));Va(n);let r=await ja(n,"utf8"),o=Xa(e),s=r,i=0;for(let a=0;a<o.length;a+=1){let l=o[a];if(!l)continue;let c=l.old_string,u=l.replace_all??!1;if(!s.includes(c))return o.length===1?f("apply_patch failed: target text not found.",!0):f(`apply_patch failed: target text not found at edit ${a+1}.`,!0);if(u){let p=s.split(c),y=p.length-1;s=p.join(l.new_string),i+=y}else s=s.replace(c,l.new_string),i+=1}return s===r?f("No changes made."):(await qa(n,s,"utf8"),f(`Success. Updated file: ${n}
15
+ Edits: ${o.length}
16
+ Replacements: ${i}`))}catch(n){return n.code==="ENOENT"?f(`apply_patch failed: file does not exist: ${t}`,!0):f(`apply_patch failed: ${n.message}`,!0)}}});import{readFile as Ja}from"fs/promises";import{z as be}from"zod";var qr=500,Gr=200,Ya=be.object({file_path:be.string().min(1),offset:be.number().int().positive().optional(),limit:be.number().int().positive().optional(),mode:be.enum(["slice","indentation"]).optional(),indentation:be.object({anchor_line:be.number().int().positive().optional(),max_levels:be.number().int().nonnegative().optional(),include_siblings:be.boolean().optional(),include_header:be.boolean().optional(),max_lines:be.number().int().positive().optional()}).strict().optional()}).strict();function Za(e){return e.length<=qr?e:e.slice(0,qr)}function Qa(e){let t=0;for(let n of e)if(n===" ")t+=1;else if(n===" ")t+=4;else break;return t}function el(e){return e.split(/\r?\n/).map((n,r)=>({line:r+1,text:Za(n),indent:Qa(n)}))}function tl(e){return e.map(t=>`L${t.line}: ${t.text}`).join(`
17
+ `)}function nl(e,t,n){let r=t-1;if(r>=e.length)throw new Error("offset exceeds file length");return e.slice(r,r+n)}function rl(e,t){let n=t.offset??1,r=t.limit??Gr,o=t.indentation,s=o?.anchor_line??n;if(s<=0||s>e.length)throw new Error("anchor_line exceeds file length");let i=e[s-1];if(!i)throw new Error("anchor_line exceeds file length");let a=o?.max_levels??0,l=o?.include_siblings??!0,c=o?.include_header??!0,u=o?.max_lines??r,p=Math.max(1,Math.min(r,u)),y=a===0?0:Math.max(0,i.indent-a*4),m=s-1,h=s-1;for(;m-1>=0;){let d=e[m-1];if(!d)break;let E=/^\s*(#|\/\/|--)/.test(d.text),v=d.text.trim().length===0;if(d.indent<y||!l&&d.indent===y&&!E&&!v||!c&&(E||v)&&d.indent<i.indent||(m-=1,h-m+1>=p))break}for(;h+1<e.length&&h-m+1<p;){let d=e[h+1];if(!d||d.indent<y||!l&&d.indent===y)break;h+=1}return e.slice(m,h+1)}var Kr=N({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Ya,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??1,n=e.limit??Gr;if(t<=0)return f("offset must be a 1-indexed line number",!0);if(n<=0)return f("limit must be greater than zero",!0);let r=e.file_path.trim();if(!r.startsWith("/"))return f("file_path must be an absolute path",!0);let o=Ue(r);try{let s=await Ja(o,"utf8"),i=el(s);if(i.length===0)return f("");let l=(e.mode??"slice")==="indentation"?rl(i,e):nl(i,t,n);return f(tl(l))}catch(s){return f(`read_file failed: ${s.message}`,!0)}}});import{readdir as ol,lstat as sl}from"fs/promises";import{join as il}from"path";import{z as Tt}from"zod";var al=1,ll=25,cl=2,ul=Tt.object({dir_path:Tt.string().min(1),offset:Tt.number().int().positive().optional(),limit:Tt.number().int().positive().optional(),depth:Tt.number().int().positive().optional()}).strict();function pl(e){let t=" ".repeat(e.displayDepth*2),n="";e.kind==="dir"&&(n="/"),e.kind==="symlink"&&(n="@"),e.kind==="other"&&(n="?");let r=e.path.split("/"),o=r[r.length-1]??e.path;return`${t}${o}${n}`}var Vr=N({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:ul,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??al,n=e.limit??ll,r=e.depth??cl;if(t<=0)return f("offset must be a 1-indexed entry number",!0);if(n<=0)return f("limit must be greater than zero",!0);if(r<=0)return f("depth must be greater than zero",!0);let o=e.dir_path.trim();if(!o.startsWith("/"))return f("dir_path must be an absolute path",!0);let s=Ue(o);try{let i=[{absPath:s,depth:r,displayDepth:0}],a=[];for(;i.length>0;){let p=i.shift();if(!p)continue;let y=await ol(p.absPath);y.sort((m,h)=>m.localeCompare(h));for(let m of y){let h=il(p.absPath,m),d=await sl(h),E=d.isSymbolicLink()?"symlink":d.isDirectory()?"dir":d.isFile()?"file":"other";a.push({path:h,displayDepth:p.displayDepth,kind:E}),E==="dir"&&p.depth>1&&i.push({absPath:h,depth:p.depth-1,displayDepth:p.displayDepth+1})}}if(a.length===0)return f(`Absolute path: ${s}`);let l=t-1;if(l>=a.length)return f("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),u=[`Absolute path: ${s}`,...c.map(pl)];return l+n<a.length&&u.push(`More than ${n} entries found`),f(u.join(`
18
+ `))}catch(i){return f(`list_dir failed: ${i.message}`,!0)}}});import{spawn as dl}from"child_process";import{resolve as ml}from"path";import{z as _t}from"zod";var fl=100,gl=2e3,hl=3e4,yl=_t.object({pattern:_t.string().min(1),include:_t.string().optional(),path:_t.string().optional(),limit:_t.number().int().positive().optional()}).strict();function Tl(e){return new Promise((t,n)=>{let r=["--files-with-matches","--sortr=modified","--regexp",e.pattern,"--no-messages"];e.include?.trim()&&r.push("--glob",e.include.trim()),r.push("--",e.searchPath);let o=dl("rg",r,{cwd:e.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",l=>s.push(l)),o.stderr?.on("data",l=>i.push(l));let a=setTimeout(()=>{o.kill("SIGTERM"),n(new Error("rg timed out after 30 seconds"))},hl);o.on("error",l=>{clearTimeout(a),n(l)}),o.on("close",l=>{clearTimeout(a),t({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var Xr=N({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:yl,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.pattern.trim();if(!t)return f("pattern must not be empty",!0);let n=Math.min(e.limit??fl,gl),r=e.path?.trim()?ml(process.cwd(),e.path.trim()):process.cwd();try{let o=await Tl({pattern:t,include:e.include,searchPath:r,cwd:process.cwd(),limit:n});if(o.exitCode===1)return f("No matches found.");if(o.exitCode!==0)return f(`rg failed: ${o.stderr||o.stdout}`,!0);let s=o.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,n);return s.length===0?f("No matches found."):f(s.join(`
19
+ `))}catch(o){return f(`grep_files failed: ${o.message}`,!0)}}});import{z as He}from"zod";var Jr=null;function Nn(e){Jr=e}function Yr(){return Jr}var _l=He.object({server:He.string().optional(),cursor:He.string().optional()}).strict(),Sl=He.object({server:He.string().optional(),cursor:He.string().optional()}).strict(),vl=He.object({server:He.string().min(1),uri:He.string().min(1)}).strict();function $n(){let e=Yr();if(!e)throw new Error("MCP pool is not initialized");return e}var Zr=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:_l,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=$n();if(e?.trim()){let s=n.get(e.trim());if(!s)return f(`MCP server not found: ${e}`,!0);let i=await s.client.listResources(t?{cursor:t}:void 0);return f(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(t)return f("cursor is only supported when server is specified",!0);let r=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),o=[];for(let s of r){let i=await s.client.listResources();for(let a of i.resources)o.push({server:s.name,...a})}return f(JSON.stringify({resources:o},null,2))}catch(n){return f(`list_mcp_resources failed: ${n.message}`,!0)}}}),Qr=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:Sl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=$n();if(e?.trim()){let s=n.get(e.trim());if(!s)return f(`MCP server not found: ${e}`,!0);let i=await s.client.listResourceTemplates(t?{cursor:t}:void 0);return f(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(t)return f("cursor is only supported when server is specified",!0);let r=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),o=[];for(let s of r){let i=await s.client.listResourceTemplates();for(let a of i.resourceTemplates)o.push({server:s.name,...a})}return f(JSON.stringify({resourceTemplates:o},null,2))}catch(n){return f(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),eo=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:vl,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,uri:t})=>{try{let r=$n().get(e);if(!r)return f(`MCP server not found: ${e}`,!0);let o=await r.client.readResource({uri:t});return f(JSON.stringify({server:e,uri:t,...o},null,2))}catch(n){return f(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as it}from"zod";var xl=it.object({step:it.string().min(1),status:it.enum(["pending","in_progress","completed"])}).strict(),Cl=it.object({explanation:it.string().optional(),plan:it.array(xl).min(1)}).strict(),to=[],no=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:Cl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:e,plan:t})=>{if(t.filter(r=>r.status==="in_progress").length>1)return f("At most one step can be in_progress at a time",!0);if(t.length<4){let r=t[0]?.step??"";return f(`<system_hint tool="update_plan" reason="simple_task">Task "${r}" is simple (${t.length} step${t.length>1?"s":""}) - execute directly without update_plan.</system_hint>`)}return to=t,f(JSON.stringify({message:"Plan updated",explanation:e,plan:to},null,2))}});import{readFile as bl}from"fs/promises";import{homedir as El}from"os";import{join as ro}from"path";import{z as oo}from"zod";var Al=oo.object({memory_id:oo.string().min(1)}).strict();function wl(){let e=process.env.MEMO_HOME?.trim()||ro(El(),".memo");return ro(e,"Agents.md")}var so=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:Al,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:e})=>{try{let t=wl(),n=await bl(t,"utf8");return f(JSON.stringify({memory_id:e,memory_summary:n},null,2))}catch{return f(`memory not found for memory_id=${e}`,!0)}}});import{z as io}from"zod";var Ml=io.object({url:io.string().min(1)}).strict(),ao=1e4,St=512e3,Dn=4e3,kl=new Set(["http:","https:"]),Pl=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Il=/<\s*(br|hr)\s*\/?>/gi,Rl=/<\s*li[^>]*>/gi,Ol=/<[^>]+>/g,Ll=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Nl=e=>e.replace(/&nbsp;/gi," ").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&amp;/gi,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(r,o)=>{try{let s=o.startsWith("x")||o.startsWith("X")?parseInt(o.slice(1),16):parseInt(o,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),$l=e=>{let r=e.replace(Ll," ").replace(Rl,"- ").replace(Il,`
20
+ `).replace(Pl,`
21
+ `).replace(Ol," "),s=Nl(r).replace(/\r/g,"").split(`
22
22
  `).map(a=>a.trim().replace(/[ \t]{2,}/g," "));return s.filter((a,l)=>a.length>0||l>0&&(s[l-1]?.length??0)>0).join(`
23
- `).trim()},wl=e=>e.replace(/\s+/g," ").trim(),so=N({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:_l,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t;try{t=new URL(e.url)}catch{return f(`Invalid URL: ${e.url}`,!0)}if(!Sl.has(t.protocol))return f(`Unsupported protocol: ${t.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),oo);try{let o=await globalThis.fetch(t,{signal:n.signal}),s=o.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>vt)return f(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(o.body&&o.body.getReader){let k=o.body.getReader(),v=[];for(;;){let{done:ee,value:q}=await k.read();if(ee)break;if(q){if(a+=q.byteLength,a>vt)return n.abort(),f(`Request aborted: response body exceeds ${vt} bytes`,!0);v.push(q)}}let S=new Uint8Array(a),W=0;for(let ee of v)S.set(ee,W),W+=ee.byteLength;l=new TextDecoder().decode(S)}else if(l=await o.text(),a=new TextEncoder().encode(l).byteLength,a>vt)return f(`Request rejected: response body exceeds ${vt} bytes`,!0);let c=o.headers.get("content-type")||"",u=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),d=u?Ml(l):l.trim(),y=wl(d),p=y.length>Nn?`${y.slice(0,Nn)}...`:y,h=y.length>Nn?" text_truncated=true":"",m=u?" source=html_stripped":"";return f(`status=${o.status} bytes=${a} text_chars=${y.length} text="${p}"${h}${m}`)}catch(o){return o.name==="AbortError"?f(`Request timeout or aborted (${oo}ms)`,!0):f(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as kl}from"child_process";import{existsSync as Pl}from"fs";import{resolve as Il}from"path";import{z as le}from"zod";var Rl=3e4,Ol=1e4,Ll=3e5,io=4,Nl=1500,ao=2e3,ze=new Map,$l=le.object({message:le.string().min(1),agent_type:le.string().optional()}).strict(),Dl=le.object({id:le.string().min(1),message:le.string().min(1),interrupt:le.boolean().optional()}).strict(),Ul=le.object({id:le.string().min(1)}).strict(),Hl=le.object({ids:le.array(le.string().min(1)).min(1),timeout_ms:le.number().int().positive().optional()}).strict(),Fl=le.object({id:le.string().min(1)}).strict();function at(){return new Date().toISOString()}function $n(e){return f(`agent not found: ${e}`,!0)}function Bl(){let e=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!e)return io;let t=Number(e);return!Number.isFinite(t)||t<=0?io:Math.floor(t)}function Wl(){let e=0;for(let t of ze.values())t.running&&(e+=1);return e}function jl(){let e=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(e)return e;let t=Il(process.cwd(),"dist/index.js");return Pl(t)?`node ${JSON.stringify(t)} --dangerous`:"memo --dangerous"}function zl(e){return e!=="running"}function ql(e){return new Promise(t=>{setTimeout(t,e)})}function Gl(e){return e===void 0?Rl:e<=0?null:Math.max(Ol,Math.min(Ll,e))}function Kl(e){return e.length<=ao?e:`${e.slice(0,ao)}
24
- ...[truncated]`}function Vl(e,t){let n=[],r=e.trim(),o=t.trim();return r&&n.push(r),o&&n.push(`stderr:
25
- ${o}`),Kl(n.join(`
23
+ `).trim()},Dl=e=>e.replace(/\s+/g," ").trim(),lo=N({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:Ml,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t;try{t=new URL(e.url)}catch{return f(`Invalid URL: ${e.url}`,!0)}if(!kl.has(t.protocol))return f(`Unsupported protocol: ${t.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),ao);try{let o=await globalThis.fetch(t,{signal:n.signal}),s=o.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>St)return f(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(o.body&&o.body.getReader){let E=o.body.getReader(),v=[];for(;;){let{done:ee,value:q}=await E.read();if(ee)break;if(q){if(a+=q.byteLength,a>St)return n.abort(),f(`Request aborted: response body exceeds ${St} bytes`,!0);v.push(q)}}let S=new Uint8Array(a),W=0;for(let ee of v)S.set(ee,W),W+=ee.byteLength;l=new TextDecoder().decode(S)}else if(l=await o.text(),a=new TextEncoder().encode(l).byteLength,a>St)return f(`Request rejected: response body exceeds ${St} bytes`,!0);let c=o.headers.get("content-type")||"",u=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),p=u?$l(l):l.trim(),y=Dl(p),m=y.length>Dn?`${y.slice(0,Dn)}...`:y,h=y.length>Dn?" text_truncated=true":"",d=u?" source=html_stripped":"";return f(`status=${o.status} bytes=${a} text_chars=${y.length} text="${m}"${h}${d}`)}catch(o){return o.name==="AbortError"?f(`Request timeout or aborted (${ao}ms)`,!0):f(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as Ul}from"child_process";import{existsSync as Hl}from"fs";import{resolve as Fl}from"path";import{z as le}from"zod";var Bl=3e4,Wl=1e4,jl=3e5,co=4,zl=1500,uo=2e3,ze=new Map,ql=le.object({message:le.string().min(1),agent_type:le.string().optional()}).strict(),Gl=le.object({id:le.string().min(1),message:le.string().min(1),interrupt:le.boolean().optional()}).strict(),Kl=le.object({id:le.string().min(1)}).strict(),Vl=le.object({ids:le.array(le.string().min(1)).min(1),timeout_ms:le.number().int().positive().optional()}).strict(),Xl=le.object({id:le.string().min(1)}).strict();function at(){return new Date().toISOString()}function Un(e){return f(`agent not found: ${e}`,!0)}function Jl(){let e=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!e)return co;let t=Number(e);return!Number.isFinite(t)||t<=0?co:Math.floor(t)}function Yl(){let e=0;for(let t of ze.values())t.running&&(e+=1);return e}function Zl(){let e=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(e)return e;let t=Fl(process.cwd(),"dist/index.js");return Hl(t)?`node ${JSON.stringify(t)} --dangerous`:"memo --dangerous"}function Ql(e){return e!=="running"}function ec(e){return new Promise(t=>{setTimeout(t,e)})}function tc(e){return e===void 0?Bl:e<=0?null:Math.max(Wl,Math.min(jl,e))}function nc(e){return e.length<=uo?e:`${e.slice(0,uo)}
24
+ ...[truncated]`}function rc(e,t){let n=[],r=e.trim(),o=t.trim();return r&&n.push(r),o&&n.push(`stderr:
25
+ ${o}`),nc(n.join(`
26
26
 
27
- `))}async function lo(e){let t=e.running;if(!t)return;t.interrupted=!0;let n=t.process;n.exitCode!==null||n.killed||await new Promise(r=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(i),n.off("close",s),r())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},Nl);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function Xl(e){let t=ze.get(e);return t?t.status:"not_found"}function Jl(e){let t=ze.get(e);return t?{status:t.status,last_message:t.lastMessage,last_output:t.lastOutput,last_error:t.lastError,last_submission_id:t.lastSubmissionId,updated_at:t.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function Yl(e){return{agent_id:e.id,status:e.status,created_at:e.createdAt,updated_at:e.updatedAt,last_message:e.lastMessage,last_submission_id:e.lastSubmissionId,has_last_output:!!e.lastOutput,has_last_error:!!e.lastError}}function Zl(e){let{record:t,submissionId:n,stdout:r,stderr:o,exitCode:s,interrupted:i}=e;if(!(!t.running||t.running.id!==n)&&(t.running=null,t.updatedAt=at(),t.lastOutput=Vl(r,o)||null,t.lastError=null,t.status!=="closed")){if(i){t.status="errored",t.lastError="interrupted",t.statusBeforeClose="errored";return}if(s===0){t.status="completed",t.statusBeforeClose="completed";return}t.status="errored",t.lastError=`submission failed with exit code ${s}`,t.statusBeforeClose="errored"}}async function co(e,t){let n=Bl();if(Wl()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=jl(),s=kl(o,{cwd:process.cwd(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],a=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",l=>i.push(l)),s.stderr?.on("data",l=>a.push(l)),s.on("error",l=>{a.push(`[spawn error] ${l.message}`)}),e.running={id:r,message:t,process:s,startedAt:at(),interrupted:!1},e.status="running",e.lastMessage=t,e.lastSubmissionId=r,e.updatedAt=at(),s.on("close",l=>{let c=typeof l=="number"?l:-1,u=!!(e.running?.id===r&&e.running.interrupted);Zl({record:e,submissionId:r,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:u})});try{s.stdin?.write(`${t.trim()}
28
- `)}catch{}try{s.stdin?.end()}catch{}return r}var uo=N({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:$l,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:e})=>{let t=e.trim();if(!t)return f("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=at(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:t,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};ze.set(n,o);try{let s=await co(o,t);return f(JSON.stringify({...Yl(o),submission_id:s},null,2))}catch(s){return ze.delete(n),f(`spawn_agent failed: ${s.message}`,!0)}}}),po=N({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Dl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e,message:t,interrupt:n})=>{let r=ze.get(e);if(!r)return $n(e);let o=t.trim();if(!o)return f("send_input failed: message must not be empty",!0);if(r.status==="closed")return f(`send_input failed: agent ${e} is closed; run resume_agent first`,!0);if(r.running){if(!n)return f(`send_input failed: agent ${e} is busy; set interrupt=true to cancel current submission`,!0);await lo(r)}try{let s=await co(r,o);return f(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return f(`send_input failed: ${s.message}`,!0)}}}),mo=N({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Ul,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=ze.get(e);return t?(t.status==="closed"&&(t.status=t.statusBeforeClose,t.updatedAt=at()),f(JSON.stringify({agent_id:e,status:t.status},null,2))):$n(e)}}),fo=N({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Hl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:e,timeout_ms:t})=>{let n=Gl(t);if(n===null)return f("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},a={};for(let l of e){let c=Xl(l);zl(c)&&(i[l]=c,a[l]=Jl(l))}return{status:i,details:a}},o=r();if(Object.keys(o.status).length>0)return f(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await ql(100),o=r(),Object.keys(o.status).length>0)return f(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return f(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),go=N({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Fl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=ze.get(e);return t?t.status==="closed"?f(JSON.stringify({agent_id:e,status:"closed"},null,2)):(t.statusBeforeClose=t.running?"completed":t.status,t.status="closed",t.updatedAt=at(),await lo(t),f(JSON.stringify({agent_id:e,status:"closed"},null,2))):$n(e)}});var Dn={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_file:"read",list_dir:"read",grep_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},ho=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),jt={read:0,write:1,execute:2},yo=["exec","run","shell","command","stdin"],To=["write","patch","create","delete","modify","update"],_o=["read","get","fetch","search","list","find"],So=new Set(["write","execute"]);function Hn(e){let t={...Dn,...e?.customLevels};return{getRiskLevel(n){if(n in t)return t[n];let r=n.toLowerCase();return Un(r,yo)?"execute":Un(r,To)?"write":Un(r,_o)?"read":"write"},compareRisk(n,r){return jt[n]-jt[r]},needsApproval(n,r){return r==="strict"?!0:So.has(n)}}}function Un(e,t){return t.some(n=>e.includes(n))}import{createHash as Ql}from"crypto";function zt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>zt(n)).join(",")+"]":`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${zt(r)}`).join(",")}}`}function Fn(e,t){let n=zt(t),r=`${e}:${n}`;return Ql("sha256").update(r).digest("hex").slice(0,16)}function ec(e){return`Tool "${e}" requires approval.`}function Bn(e){let{mode:t="auto",dangerous:n=!1,toolRiskLevels:r}=e||{},o=t==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=Hn({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(ho.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,o))return{needApproval:!1,decision:"auto-execute"};let u=Fn(a,l);return i.toolByFingerprint.set(u,a),i.sessionTools.has(a)||i.onceTools.has(a)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(a)?{needApproval:!0,fingerprint:u,riskLevel:c,reason:"This request was previously denied.",toolName:a,params:l}:{needApproval:!0,fingerprint:u,riskLevel:c,reason:ec(a),toolName:a,params:l}},recordDecision(a,l){let c=i.toolByFingerprint.get(a);if(c)switch(i.sessionTools.delete(c),i.onceTools.delete(c),i.deniedTools.delete(c),l){case"session":i.sessionTools.add(c);break;case"once":i.onceTools.add(c);break;case"deny":i.deniedTools.add(c);break}},isGranted(a){let l=i.toolByFingerprint.get(a);return l?i.sessionTools.has(l)||i.onceTools.has(l):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var vo=12e3;function tc(){let e=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!e)return vo;let t=Number(e);return!Number.isFinite(t)||t<=0?vo:Math.floor(t)}function nc(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function rc(e){let t=0;for(let n of e.content??[]){if(n.type==="text"){t+=n.text.length;continue}try{t+=JSON.stringify(n).length}catch{t+=100}}return t}function oc(e,t,n){return`<system_hint type="tool_output_omitted" tool="${nc(e)}" reason="too_long" actual_chars="${t}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function sc(e,t){let n=tc(),r=rc(t);return r<=n?t:{content:[{type:"text",text:oc(e,r,n)}],isError:!1}}function ic(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
29
- `)}function ac(e,t){let n=t;if(typeof t=="string"){let r=t.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}return typeof n!="object"||n===null?{ok:!1,error:`${e.name} invalid input: expected object`}:typeof e.validateInput=="function"?e.validateInput(n):{ok:!0,data:n}}function lc(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("sandbox")||t.includes("permission denied")||t.includes("operation not permitted")||t.includes("eacces")?"sandbox_denied":"execution_failed"}var Wn=class{constructor(t){this.config=t;this.approvalManager=Bn(t.approval)}approvalManager;async executeAction(t,n){let r=Date.now(),o=t.id??`${t.name}:${r}`,s=this.approvalManager.check(t.name,t.input);if(s.needApproval){let a={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(a);let l=n?.requestApproval?await n.requestApproval(a):"deny";if(this.approvalManager.recordDecision(s.fingerprint,l),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:l}),l==="deny")return{actionId:o,tool:t.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${t.name}`,durationMs:Date.now()-r,rejected:!0}}let i=this.config.tools[t.name];if(!i)return{actionId:o,tool:t.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${t.name}`,durationMs:Date.now()-r};try{let a=ac(i,t.input);if(!a.ok)return{actionId:o,tool:t.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-r};let l=await i.execute(a.data),c=sc(t.name,l);return{actionId:o,tool:t.name,status:"success",success:!0,observation:ic(c)||"(no tool output)",durationMs:Date.now()-r}}catch(a){let l=lc(a);return{actionId:o,tool:t.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-r}}}async executeActions(t,n={}){let r=n.executionMode??"sequential",o=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(r==="parallel"){let l=await Promise.all(t.map(c=>this.executeAction(c,n)));if(o==="fail_fast"){let c=l.findIndex(u=>u.rejected);s=c>=0?l.slice(0,c+1):l}else s=l}else for(let l of t){let c=await this.executeAction(l,n);if(s.push(c),c.rejected&&o==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
27
+ `))}async function po(e){let t=e.running;if(!t)return;t.interrupted=!0;let n=t.process;n.exitCode!==null||n.killed||await new Promise(r=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(i),n.off("close",s),r())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},zl);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function oc(e){let t=ze.get(e);return t?t.status:"not_found"}function sc(e){let t=ze.get(e);return t?{status:t.status,last_message:t.lastMessage,last_output:t.lastOutput,last_error:t.lastError,last_submission_id:t.lastSubmissionId,updated_at:t.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function ic(e){return{agent_id:e.id,status:e.status,created_at:e.createdAt,updated_at:e.updatedAt,last_message:e.lastMessage,last_submission_id:e.lastSubmissionId,has_last_output:!!e.lastOutput,has_last_error:!!e.lastError}}function ac(e){let{record:t,submissionId:n,stdout:r,stderr:o,exitCode:s,interrupted:i}=e;if(!(!t.running||t.running.id!==n)&&(t.running=null,t.updatedAt=at(),t.lastOutput=rc(r,o)||null,t.lastError=null,t.status!=="closed")){if(i){t.status="errored",t.lastError="interrupted",t.statusBeforeClose="errored";return}if(s===0){t.status="completed",t.statusBeforeClose="completed";return}t.status="errored",t.lastError=`submission failed with exit code ${s}`,t.statusBeforeClose="errored"}}async function mo(e,t){let n=Jl();if(Yl()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=Zl(),s=Ul(o,{cwd:process.cwd(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],a=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",l=>i.push(l)),s.stderr?.on("data",l=>a.push(l)),s.on("error",l=>{a.push(`[spawn error] ${l.message}`)}),e.running={id:r,message:t,process:s,startedAt:at(),interrupted:!1},e.status="running",e.lastMessage=t,e.lastSubmissionId=r,e.updatedAt=at(),s.on("close",l=>{let c=typeof l=="number"?l:-1,u=!!(e.running?.id===r&&e.running.interrupted);ac({record:e,submissionId:r,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:u})});try{s.stdin?.write(`${t.trim()}
28
+ `)}catch{}try{s.stdin?.end()}catch{}return r}var fo=N({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:ql,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:e})=>{let t=e.trim();if(!t)return f("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=at(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:t,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};ze.set(n,o);try{let s=await mo(o,t);return f(JSON.stringify({...ic(o),submission_id:s},null,2))}catch(s){return ze.delete(n),f(`spawn_agent failed: ${s.message}`,!0)}}}),go=N({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Gl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e,message:t,interrupt:n})=>{let r=ze.get(e);if(!r)return Un(e);let o=t.trim();if(!o)return f("send_input failed: message must not be empty",!0);if(r.status==="closed")return f(`send_input failed: agent ${e} is closed; run resume_agent first`,!0);if(r.running){if(!n)return f(`send_input failed: agent ${e} is busy; set interrupt=true to cancel current submission`,!0);await po(r)}try{let s=await mo(r,o);return f(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return f(`send_input failed: ${s.message}`,!0)}}}),ho=N({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Kl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=ze.get(e);return t?(t.status==="closed"&&(t.status=t.statusBeforeClose,t.updatedAt=at()),f(JSON.stringify({agent_id:e,status:t.status},null,2))):Un(e)}}),yo=N({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Vl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:e,timeout_ms:t})=>{let n=tc(t);if(n===null)return f("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},a={};for(let l of e){let c=oc(l);Ql(c)&&(i[l]=c,a[l]=sc(l))}return{status:i,details:a}},o=r();if(Object.keys(o.status).length>0)return f(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await ec(100),o=r(),Object.keys(o.status).length>0)return f(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return f(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),To=N({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Xl,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=ze.get(e);return t?t.status==="closed"?f(JSON.stringify({agent_id:e,status:"closed"},null,2)):(t.statusBeforeClose=t.running?"completed":t.status,t.status="closed",t.updatedAt=at(),await po(t),f(JSON.stringify({agent_id:e,status:"closed"},null,2))):Un(e)}});var Hn={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_file:"read",list_dir:"read",grep_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},_o=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),zt={read:0,write:1,execute:2},So=["exec","run","shell","command","stdin"],vo=["write","patch","create","delete","modify","update"],xo=["read","get","fetch","search","list","find"],Co=new Set(["write","execute"]);function Bn(e){let t={...Hn,...e?.customLevels};return{getRiskLevel(n){if(n in t)return t[n];let r=n.toLowerCase();return Fn(r,So)?"execute":Fn(r,vo)?"write":Fn(r,xo)?"read":"write"},compareRisk(n,r){return zt[n]-zt[r]},needsApproval(n,r){return r==="strict"?!0:Co.has(n)}}}function Fn(e,t){return t.some(n=>e.includes(n))}import{createHash as lc}from"crypto";function qt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>qt(n)).join(",")+"]":`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${qt(r)}`).join(",")}}`}function Wn(e,t){let n=qt(t),r=`${e}:${n}`;return lc("sha256").update(r).digest("hex").slice(0,16)}function cc(e){return`Tool "${e}" requires approval.`}function jn(e){let{mode:t="auto",dangerous:n=!1,toolRiskLevels:r}=e||{},o=t==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=Bn({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(_o.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,o))return{needApproval:!1,decision:"auto-execute"};let u=Wn(a,l);return i.toolByFingerprint.set(u,a),i.sessionTools.has(a)||i.onceTools.has(a)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(a)?{needApproval:!0,fingerprint:u,riskLevel:c,reason:"This request was previously denied.",toolName:a,params:l}:{needApproval:!0,fingerprint:u,riskLevel:c,reason:cc(a),toolName:a,params:l}},recordDecision(a,l){let c=i.toolByFingerprint.get(a);if(c)switch(i.sessionTools.delete(c),i.onceTools.delete(c),i.deniedTools.delete(c),l){case"session":i.sessionTools.add(c);break;case"once":i.onceTools.add(c);break;case"deny":i.deniedTools.add(c);break}},isGranted(a){let l=i.toolByFingerprint.get(a);return l?i.sessionTools.has(l)||i.onceTools.has(l):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var bo=12e3,Eo=1e5;function uc(){let e=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!e)return bo;let t=Number(e);return!Number.isFinite(t)||t<=0?bo:Math.floor(t)}function pc(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function dc(e){let t=0;for(let n of e.content??[]){if(n.type==="text"){t+=n.text.length;continue}try{t+=JSON.stringify(n).length}catch{t+=100}}return t}function mc(e,t,n){return`<system_hint type="tool_output_omitted" tool="${pc(e)}" reason="too_long" actual_chars="${t}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function fc(e,t){let n=uc(),r=dc(t);return r<=n?t:{content:[{type:"text",text:mc(e,r,n)}],isError:!1}}function gc(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
29
+ `)}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hc(e,t){let n=t;if(typeof t=="string"){if(t.length>Eo)return{ok:!1,error:`${e.name} invalid input: input string too large (max ${Eo} chars)`};let r=t.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!Ao(n))return{ok:!1,error:`${e.name} invalid input: expected object`};if(typeof e.validateInput=="function"){let r=e.validateInput(n);return r.ok?Ao(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${e.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function yc(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("sandbox")||t.includes("permission denied")||t.includes("operation not permitted")||t.includes("eacces")?"sandbox_denied":"execution_failed"}var zn=class{constructor(t){this.config=t;this.approvalManager=jn(t.approval)}approvalManager;async executeAction(t,n){let r=Date.now(),o=t.id??`${t.name}:${r}`,s=this.approvalManager.check(t.name,t.input);if(s.needApproval){let a={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(a);let l=n?.requestApproval?await n.requestApproval(a):"deny";if(this.approvalManager.recordDecision(s.fingerprint,l),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:l}),l==="deny")return{actionId:o,tool:t.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${t.name}`,durationMs:Date.now()-r,rejected:!0}}let i=this.config.tools[t.name];if(!i)return{actionId:o,tool:t.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${t.name}`,durationMs:Date.now()-r};try{let a=hc(i,t.input);if(!a.ok)return{actionId:o,tool:t.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-r};let l=await i.execute(a.data),c=fc(t.name,l);return{actionId:o,tool:t.name,status:"success",success:!0,observation:gc(c)||"(no tool output)",durationMs:Date.now()-r}}catch(a){let l=yc(a);return{actionId:o,tool:t.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-r}}}async executeActions(t,n={}){let r=n.executionMode??"sequential",o=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(r==="parallel"){let l=await Promise.all(t.map(c=>this.executeAction(c,n)));if(o==="fail_fast"){let c=l.findIndex(u=>u.rejected);s=c>=0?l.slice(0,c+1):l}else s=l}else for(let l of t){let c=await this.executeAction(l,n);if(s.push(c),c.rejected&&o==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
30
30
 
31
- `);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function xo(e){return new Wn(e)}var qt=class{tools=new Map;register(t){this.tools.set(t.name,t)}registerMany(t){for(let n of t)this.register(n)}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}};import{Client as cc}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as uc}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as pc}from"@modelcontextprotocol/sdk/client/stdio.js";function mc(e){if(!e)return;let t={...process.env,...e},n=Object.entries(t).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function Co(){return new cc({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function dc(e){if(!(!e||Object.keys(e).length===0))return{headers:e}}function fc(e){let t={...e.http_headers??e.headers??{}};if(e.bearer_token_env_var){let n=process.env[e.bearer_token_env_var];n&&!t.Authorization&&(t.Authorization=`Bearer ${n}`)}return t}async function gc(e){let t=new URL(e.url),n=dc(fc(e));try{let r=Co(),o=new uc(t,{requestInit:n});return await r.connect(o),{client:r,transport:o}}catch(r){let o=`Failed to connect via streamable_http (${r.message})`,s=new Error(o);throw s.cause=r,s}}async function hc(e){if("url"in e)return gc(e);let t={command:e.command,args:e.args,env:mc(e.env),stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new pc(t),r=Co();return await r.connect(n),{client:r,transport:n}}var Gt=class{connections=new Map;async connect(t,n){let r=this.connections.get(t);if(r)return r;let{client:o,transport:s}=await hc(n),i=await o.listTools(),a={name:t,client:o,transport:s,tools:(i.tools||[]).map(l=>({name:`${t}_${l.name}`,description:l.description||`Tool from ${t}: ${l.name}`,source:"mcp",serverName:t,originalName:l.name,inputSchema:l.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(t,a),a}get(t){return this.connections.get(t)}getAll(){return Array.from(this.connections.values())}getAllTools(){let t=[];for(let n of this.connections.values())for(let r of n.tools)t.push({name:r.name,description:r.description,serverName:r.serverName,originalName:r.originalName,inputSchema:r.inputSchema,client:n.client});return t}async closeAll(){let t=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(r){console.error(`[MCP] Error closing client ${n.name}:`,r)}});await Promise.all(t),this.connections.clear()}get size(){return this.connections.size}};var Kt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new Gt,On(this.pool),this.shouldLog=!(process.stdout.isTTY&&process.stdin.isTTY)}async loadServers(t){if(!t||Object.keys(t).length===0)return 0;let n=0;return await Promise.all(Object.entries(t).map(async([r,o])=>{try{let s=await this.pool.connect(r,o);for(let i of s.tools){let a={...i,execute:async l=>{let c=this.pool.get(i.serverName)?.client;if(!c)throw new Error(`MCP client for server '${i.serverName}' not found`);return c.callTool({name:i.originalName,arguments:l})}};this.tools.set(a.name,a)}n+=s.tools.length,this.shouldLog&&console.log(`[MCP] Connected to '${r}' with ${s.tools.length} tools`)}catch(s){this.shouldLog&&console.error(`[MCP] Failed to connect to server '${r}':`,s)}})),n}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),On(null)}getPool(){return this.pool}};var Vt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new qt,this.mcpRegistry=new Kt}registerNativeTool(t){this.nativeRegistry.register(t)}registerNativeTools(t){for(let n of t)this.registerNativeTool(n)}async loadMcpServers(t){return this.mcpRegistry.loadServers(t)}getTool(t){return this.nativeRegistry.get(t)??this.mcpRegistry.get(t)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(t){return this.nativeRegistry.has(t)||this.mcpRegistry.has(t)}getToolCount(){let t=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:t,mcp:n,total:t+n}}async execute(t,n){let r=this.getTool(t);if(!r)throw new Error(`Tool '${t}' not found`);return r.execute(n)}generateToolDefinitions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let t=this.getAllTools();if(t.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let r=t.filter(s=>s.source==="native"),o=t.filter(s=>s.source==="mcp");if(r.length>0){n.push("### Built-in Tools"),n.push("");for(let s of r)n.push(this.formatToolDescription(s));n.push("")}if(o.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(o);for(let[i,a]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let l of a)n.push(this.formatToolDescription(l));n.push("")}}return n.join(`
31
+ `);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function wo(e){return new zn(e)}var Gt=class{tools=new Map;register(t){this.tools.set(t.name,t)}registerMany(t){for(let n of t)this.register(n)}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}};import{Client as Tc}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as _c}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Sc}from"@modelcontextprotocol/sdk/client/stdio.js";function vc(e){if(!e)return;let t={...process.env,...e},n=Object.entries(t).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function Mo(){return new Tc({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function xc(e){if(!(!e||Object.keys(e).length===0))return{headers:e}}function Cc(e){let t={...e.http_headers??e.headers??{}};if(e.bearer_token_env_var){let n=process.env[e.bearer_token_env_var];n&&!t.Authorization&&(t.Authorization=`Bearer ${n}`)}return t}async function bc(e){let t=new URL(e.url),n=xc(Cc(e));try{let r=Mo(),o=new _c(t,{requestInit:n});return await r.connect(o),{client:r,transport:o}}catch(r){let o=`Failed to connect via streamable_http (${r.message})`,s=new Error(o);throw s.cause=r,s}}async function Ec(e){if("url"in e)return bc(e);let t={command:e.command,args:e.args,env:vc(e.env),stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new Sc(t),r=Mo();return await r.connect(n),{client:r,transport:n}}var Kt=class{connections=new Map;async connect(t,n){let r=this.connections.get(t);if(r)return r;let{client:o,transport:s}=await Ec(n),i=await o.listTools(),a={name:t,client:o,transport:s,tools:(i.tools||[]).map(l=>({name:`${t}_${l.name}`,description:l.description||`Tool from ${t}: ${l.name}`,source:"mcp",serverName:t,originalName:l.name,inputSchema:l.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(t,a),a}get(t){return this.connections.get(t)}getAll(){return Array.from(this.connections.values())}getAllTools(){let t=[];for(let n of this.connections.values())for(let r of n.tools)t.push({name:r.name,description:r.description,serverName:r.serverName,originalName:r.originalName,inputSchema:r.inputSchema,client:n.client});return t}async closeAll(){let t=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(r){console.error(`[MCP] Error closing client ${n.name}:`,r)}});await Promise.all(t),this.connections.clear()}get size(){return this.connections.size}};var Vt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new Kt,Nn(this.pool),this.shouldLog=!(process.stdout.isTTY&&process.stdin.isTTY)}async loadServers(t){if(!t||Object.keys(t).length===0)return 0;let n=0;return await Promise.all(Object.entries(t).map(async([r,o])=>{try{let s=await this.pool.connect(r,o);for(let i of s.tools){let a={...i,execute:async l=>{let c=this.pool.get(i.serverName)?.client;if(!c)throw new Error(`MCP client for server '${i.serverName}' not found`);return c.callTool({name:i.originalName,arguments:l})}};this.tools.set(a.name,a)}n+=s.tools.length,this.shouldLog&&console.log(`[MCP] Connected to '${r}' with ${s.tools.length} tools`)}catch(s){this.shouldLog&&console.error(`[MCP] Failed to connect to server '${r}':`,s)}})),n}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),Nn(null)}getPool(){return this.pool}};var Xt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new Gt,this.mcpRegistry=new Vt}registerNativeTool(t){this.nativeRegistry.register(t)}registerNativeTools(t){for(let n of t)this.registerNativeTool(n)}async loadMcpServers(t){return this.mcpRegistry.loadServers(t)}getTool(t){return this.nativeRegistry.get(t)??this.mcpRegistry.get(t)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(t){return this.nativeRegistry.has(t)||this.mcpRegistry.has(t)}getToolCount(){let t=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:t,mcp:n,total:t+n}}async execute(t,n){let r=this.getTool(t);if(!r)throw new Error(`Tool '${t}' not found`);return r.execute(n)}generateToolDefinitions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let t=this.getAllTools();if(t.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let r=t.filter(s=>s.source==="native"),o=t.filter(s=>s.source==="mcp");if(r.length>0){n.push("### Built-in Tools"),n.push("");for(let s of r)n.push(this.formatToolDescription(s));n.push("")}if(o.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(o);for(let[i,a]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let l of a)n.push(this.formatToolDescription(l));n.push("")}}return n.join(`
32
32
  `)}formatToolDescription(t){let n=[];return n.push(`#### ${t.name}`),n.push(`- **Description**: ${t.description}`),t.inputSchema&&Object.keys(t.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(t.inputSchema)}`),n.join(`
33
- `)}groupByServer(t){let n={};for(let r of t)if(r.source==="mcp"){let o=r.serverName;n[o]||(n[o]=[]),n[o].push(r)}return n}getToolDescriptions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,source:t.source,serverName:t.source==="mcp"?t.serverName:void 0,inputSchema:t.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};function yc(e){let t=process.env[e]?.trim();return t?new Set(t.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function Tc(){let e=[],t=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=yc("MEMO_EXPERIMENTAL_TOOLS"),r=n.size===0,o=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return t==="shell"?e.push(wr):t==="shell_command"?e.push(kr):t==="unified_exec"?e.push(An,En):t!=="disabled"&&e.push(An,En),e.push(Xr,Jr,Yr),e.push(Qr),e.push(Br),(r||n.has("grep_files"))&&e.push(Gr),(r||n.has("read_file"))&&e.push(zr),(r||n.has("list_dir"))&&e.push(qr),s&&e.push(no),e.push(so),o&&e.push(uo,po,mo,fo,go),e}function _c(e){let t={};for(let n of e)t[n.name]=n;return t}var Sc=_c(Tc()),vc=Object.values(Sc),bo=vc;import Dc from"openai";import{encoding_for_model as xc,get_encoding as Cc}from"@dqbd/tiktoken";var Ao="cl100k_base";function bc(e){let t=e?.trim()||Ao;try{let n=()=>xc(t);return n().free(),{model:t,factory:n}}catch{let n=Ao,r=()=>Cc(n);return r().free(),{model:n,factory:r}}}function Ac(e){if(e.role==="assistant"){let t=e.reasoning_content?`
33
+ `)}groupByServer(t){let n={};for(let r of t)if(r.source==="mcp"){let o=r.serverName;n[o]||(n[o]=[]),n[o].push(r)}return n}getToolDescriptions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,source:t.source,serverName:t.source==="mcp"?t.serverName:void 0,inputSchema:t.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};function Ac(e){let t=process.env[e]?.trim();return t?new Set(t.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function wc(){let e=[],t=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=Ac("MEMO_EXPERIMENTAL_TOOLS"),r=n.size===0,o=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return t==="shell"?e.push(Ir):t==="shell_command"?e.push(Rr):t==="unified_exec"?e.push(wn,Mn):t!=="disabled"&&e.push(wn,Mn),e.push(Zr,Qr,eo),e.push(no),e.push(zr),(r||n.has("grep_files"))&&e.push(Xr),(r||n.has("read_file"))&&e.push(Kr),(r||n.has("list_dir"))&&e.push(Vr),s&&e.push(so),e.push(lo),o&&e.push(fo,go,ho,yo,To),e}function Mc(e){let t={};for(let n of e)t[n.name]=n;return t}var kc=Mc(wc()),Pc=Object.values(kc),ko=Pc;import Gc from"openai";import{encoding_for_model as Ic,get_encoding as Rc}from"@dqbd/tiktoken";var Po="cl100k_base";function Oc(e){let t=e?.trim()||Po;try{let n=()=>Ic(t);return n().free(),{model:t,factory:n}}catch{let n=Po,r=()=>Rc(n);return r().free(),{model:n,factory:r}}}function Lc(e){if(e.role==="assistant"){let t=e.reasoning_content?`
34
34
  ${e.reasoning_content}`:"";return e.tool_calls?.length?`${e.content}${t}
35
35
  ${JSON.stringify(e.tool_calls)}`:`${e.content}${t}`}return e.role==="tool"?`${e.content}
36
36
  ${e.tool_call_id}
37
- ${e.name??""}`:e.content}function Eo(e){let{model:t,factory:n}=bc(e),r=n(),o=4,s=2,i=1,a=c=>c?r.encode(c).length:0;return{model:t,countText:a,countMessages:c=>{if(!c.length)return 0;let u=0;for(let d of c)u+=o,u+=a(Ac(d)),d.name&&(u+=i);return u+=s,u},dispose:()=>r.free()}}import{mkdir as Ec,writeFile as Mc,readFile as wc,access as kc}from"fs/promises";import{homedir as Mo}from"os";import{dirname as Pc,join as Ct}from"path";import{randomUUID as cg}from"crypto";import{parse as Ic}from"toml";var Rc=Ct(Mo(),".memo"),Oc="sessions",xt={current_provider:"deepseek",max_prompt_tokens:12e4,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function Lc(e){return/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e)}function Nc(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r)continue;let o=Array.isArray(r)?r:[r];for(let s of o){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),t.push(i)}}return t}function wo(e){return e.startsWith("~")?Ct(Mo(),e.slice(1)):e}function $c(e){let t=e.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${Lc(i)}]]`,`name = ${JSON.stringify(i)}`,`env_api_key = ${JSON.stringify(String(s.env_api_key??""))}`,`model = ${JSON.stringify(String(s.model??""))}`];return s.base_url&&l.push(`base_url = ${JSON.stringify(String(s.base_url))}`),l.join(`
37
+ ${e.name??""}`:e.content}function Io(e){let{model:t,factory:n}=Oc(e),r=n(),o=4,s=2,i=1,a=c=>c?r.encode(c).length:0;return{model:t,countText:a,countMessages:c=>{if(!c.length)return 0;let u=0;for(let p of c)u+=o,u+=a(Lc(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>r.free()}}import{mkdir as Nc,writeFile as $c,readFile as Dc,access as Uc}from"fs/promises";import{homedir as Ro}from"os";import{dirname as Hc,join as xt}from"path";import{randomUUID as Sg}from"crypto";import{parse as Fc}from"toml";var Bc=xt(Ro(),".memo"),Wc="sessions",vt={current_provider:"deepseek",max_prompt_tokens:12e4,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function jc(e){return/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e)}function zc(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r)continue;let o=Array.isArray(r)?r:[r];for(let s of o){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),t.push(i)}}return t}function Oo(e){return e.startsWith("~")?xt(Ro(),e.slice(1)):e}function qc(e){let t=e.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${jc(i)}]]`,`name = ${JSON.stringify(i)}`,`env_api_key = ${JSON.stringify(String(s.env_api_key??""))}`,`model = ${JSON.stringify(String(s.model??""))}`];return s.base_url&&l.push(`base_url = ${JSON.stringify(String(s.base_url))}`),l.join(`
38
38
  `)}).filter(Boolean).join(`
39
39
 
40
- `),n="";e.mcp_servers&&Object.keys(e.mcp_servers).length>0&&(n=Object.entries(e.mcp_servers).map(([s,i])=>{if("url"in i){let p=[`[mcp_servers.${s}]`];p.push(`type = "${i.type??"streamable_http"}"`),p.push(`url = "${i.url}"`),i.bearer_token_env_var&&p.push(`bearer_token_env_var = ${JSON.stringify(i.bearer_token_env_var)}`);let h=i.http_headers??i.headers;if(h&&Object.keys(h).length>0){let m=Object.entries(h).map(([v,S])=>`${JSON.stringify(v)} = ${JSON.stringify(S)}`).join(", "),k=i.http_headers?"http_headers":"headers";p.push(`${k} = { ${m} }`)}return p.join(`
40
+ `),n="";e.mcp_servers&&Object.keys(e.mcp_servers).length>0&&(n=Object.entries(e.mcp_servers).map(([s,i])=>{if("url"in i){let m=[`[mcp_servers.${s}]`];m.push(`type = "${i.type??"streamable_http"}"`),m.push(`url = "${i.url}"`),i.bearer_token_env_var&&m.push(`bearer_token_env_var = ${JSON.stringify(i.bearer_token_env_var)}`);let h=i.http_headers??i.headers;if(h&&Object.keys(h).length>0){let d=Object.entries(h).map(([v,S])=>`${JSON.stringify(v)} = ${JSON.stringify(S)}`).join(", "),E=i.http_headers?"http_headers":"headers";m.push(`${E} = { ${d} }`)}return m.join(`
41
41
  `)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",l=i.type?`type = "${i.type}"
42
42
  `:"",c=i.stderr?`stderr = "${i.stderr}"
43
43
  `:"",u=`[mcp_servers.${s}]
44
44
  ${l}command = "${i.command}"
45
- ${c}${a}`.trimEnd(),d=i.env?Object.entries(i.env):[];if(d.length===0)return u;let y=d.map(([p,h])=>`${JSON.stringify(p)} = ${JSON.stringify(h)}`).join(`
45
+ ${c}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let y=p.map(([m,h])=>`${JSON.stringify(m)} = ${JSON.stringify(h)}`).join(`
46
46
  `);return`${u}
47
47
 
48
48
  [mcp_servers.${s}.env]
@@ -51,51 +51,52 @@ ${y}`}).join(`
51
51
  `));let r=[`current_provider = "${e.current_provider}"`];return typeof e.max_prompt_tokens=="number"&&Number.isFinite(e.max_prompt_tokens)&&r.push(`max_prompt_tokens = ${Math.floor(e.max_prompt_tokens)}`),Array.isArray(e.active_mcp_servers)&&r.push(`active_mcp_servers = ${JSON.stringify(e.active_mcp_servers)}`),[r.join(`
52
52
  `),t,n].filter(Boolean).join(`
53
53
 
54
- `)}async function Se(e,t){await Ec(Pc(e),{recursive:!0}),await Mc(e,$c(t),"utf-8")}async function ce(){let e=process.env.MEMO_HOME?wo(process.env.MEMO_HOME):Rc,t=Ct(e,"config.toml");try{await kc(t);let n=await wc(t,"utf-8"),r=Ic(n),o=Nc(r.providers),s=typeof r.max_prompt_tokens=="number"&&Number.isFinite(r.max_prompt_tokens)&&r.max_prompt_tokens>0?Math.floor(r.max_prompt_tokens):void 0,i=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(c=>typeof c=="string"&&c.trim().length>0):void 0,a={current_provider:r.current_provider??xt.current_provider,max_prompt_tokens:s??xt.max_prompt_tokens,providers:o,mcp_servers:r.mcp_servers??{},active_mcp_servers:i},l=!a.providers.length;return{config:l?xt:a,home:e,configPath:t,needsSetup:l}}catch{return{config:xt,home:e,configPath:t,needsSetup:!0}}}function Ye(e,t){let n=t||e.current_provider,r=e.providers.find(o=>o.name===n);return r||(e.providers?.[0]??xt.providers[0])}function Xt(e,t){let n=t.historyDir??Ct(e.home,Oc);return wo(n)}function ko(e,t){let n=new Date,r=String(n.getFullYear()),o=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),a=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),c=`rollout-${r}-${o}-${s}T${i}-${a}-${l}-${t}.jsonl`;return Ct(e,r,o,s,c)}function Uc(e,t){if(!e||!t)return e;let n=new Set(t.map(o=>o.trim()).filter(Boolean));if(n.size===0)return{};let r={};for(let[o,s]of Object.entries(e))n.has(o)&&(r[o]=s);return r}function Hc(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}function Fc(e){if(e.role==="assistant"){let t={role:"assistant",content:e.content,tool_calls:e.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return e.reasoning_content&&(t.reasoning_content=e.reasoning_content),t}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:e.tool_call_id}:{role:e.role,content:e.content}}function Bc(e){let t=e?.reasoning_content;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}async function Po(e,t,n){let r=await ce(),o=r.config,s=new Vt;if(s.registerNativeTools(bo),await s.loadMcpServers(Uc(o.mcp_servers,t.activeMcpServers)),e.tools)for(let[y,p]of Object.entries(e.tools))s.registerNativeTool({name:y,description:p.description,source:"native",inputSchema:{type:"object"},execute:p.execute});let i=s.toRegistry(),a=async()=>{let y=await(e.loadPrompt??hr)(),p=s.generateToolDescriptions();return p&&(y+=`
54
+ `)}async function Se(e,t){await Nc(Hc(e),{recursive:!0}),await $c(e,qc(t),"utf-8")}async function ce(){let e=process.env.MEMO_HOME?Oo(process.env.MEMO_HOME):Bc,t=xt(e,"config.toml");try{await Uc(t);let n=await Dc(t,"utf-8"),r=Fc(n),o=zc(r.providers),s=typeof r.max_prompt_tokens=="number"&&Number.isFinite(r.max_prompt_tokens)&&r.max_prompt_tokens>0?Math.floor(r.max_prompt_tokens):void 0,i=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(c=>typeof c=="string"&&c.trim().length>0):void 0,a={current_provider:r.current_provider??vt.current_provider,max_prompt_tokens:s??vt.max_prompt_tokens,providers:o,mcp_servers:r.mcp_servers??{},active_mcp_servers:i},l=!a.providers.length;return{config:l?vt:a,home:e,configPath:t,needsSetup:l}}catch{return{config:vt,home:e,configPath:t,needsSetup:!0}}}function Ye(e,t){let n=t||e.current_provider,r=e.providers.find(o=>o.name===n);return r||(e.providers?.[0]??vt.providers[0])}function Jt(e,t){let n=t.historyDir??xt(e.home,Wc);return Oo(n)}function Lo(e,t){let n=new Date,r=String(n.getFullYear()),o=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),a=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),c=`rollout-${r}-${o}-${s}T${i}-${a}-${l}-${t}.jsonl`;return xt(e,r,o,s,c)}function Kc(e,t){if(!e||!t)return e;let n=new Set(t.map(o=>o.trim()).filter(Boolean));if(n.size===0)return{};let r={};for(let[o,s]of Object.entries(e))n.has(o)&&(r[o]=s);return r}function Vc(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}function Xc(e){if(e.role==="assistant"){let t={role:"assistant",content:e.content,tool_calls:e.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return e.reasoning_content&&(t.reasoning_content=e.reasoning_content),t}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:e.tool_call_id}:{role:e.role,content:e.content}}function Jc(e){let t=e?.reasoning_content;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}async function No(e,t,n){let r=await ce(),o=r.config,s=new Xt;if(s.registerNativeTools(ko),await s.loadMcpServers(Kc(o.mcp_servers,t.activeMcpServers)),e.tools)for(let[y,m]of Object.entries(e.tools))s.registerNativeTool({name:y,description:m.description,source:"native",inputSchema:{type:"object"},execute:m.execute});let i=s.toRegistry(),a=async()=>{let y=await(e.loadPrompt??_r)(),m=s.generateToolDescriptions();return m&&(y+=`
55
55
 
56
- ${p}`),y},l=s.generateToolDefinitions(),c=Xt(r,t),u=ko(c,n),d=new Bt(u);return{tools:i,dispose:async()=>{e.dispose&&await e.dispose(),await s.dispose()},callLLM:e.callLLM??(async(y,p,h)=>{let m=Ye(o,t.providerName),k=process.env[m.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!k)throw new Error(`Missing env var ${m.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let v=new Dc({apiKey:k,baseURL:m.base_url}),S=y.map(Fc),W=h?.tools??l,ee=W.length>0?W.map(F=>({type:"function",function:{name:F.name,description:F.description,parameters:F.input_schema}})):void 0,q=await v.chat.completions.create({model:m.model,messages:S,tools:ee,tool_choice:ee?"auto":void 0},{signal:h?.signal}),V=q.choices?.[0]?.message,he=Bc(V);if(V?.tool_calls&&V.tool_calls.length>0){let F=[];V.content&&F.push({type:"text",text:V.content});for(let P of V.tool_calls)if(P.type==="function"){let ue=Hc(P.function.arguments);ue.ok?F.push({type:"tool_use",id:P.id,name:P.function.name,input:ue.data}):F.push({type:"text",text:`[tool_use parse error] ${ue.error}; raw: ${ue.raw}`})}let E=F.some(P=>P.type==="tool_use");return{content:F,reasoning_content:he,stop_reason:E?"tool_use":"end_turn",usage:{prompt:q.usage?.prompt_tokens??void 0,completion:q.usage?.completion_tokens??void 0,total:q.usage?.total_tokens??void 0}}}let A=V?.content;if(typeof A!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:A}],reasoning_content:he,stop_reason:"end_turn",usage:{prompt:q.usage?.prompt_tokens??void 0,completion:q.usage?.completion_tokens??void 0,total:q.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:e.historySinks??[d],tokenCounter:e.tokenCounter??Eo(t.tokenizerModel),historyFilePath:u}}function Wc(e){let t=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=e.replace(n,(o,s,i)=>{let a=(i??"").trim();return a&&t.push(a),a});return{thinkingParts:t,cleaned:r.trim()}}function Io(e){if(e.length===0)return;let t=e.join(`
57
- `),{thinkingParts:n,cleaned:r}=Wc(t);return n.length>0?n.join(`
56
+ ${m}`),y},l=s.generateToolDefinitions(),c=Jt(r,t),u=Lo(c,n),p=new Ft(u);return{tools:i,dispose:async()=>{e.dispose&&await e.dispose(),await s.dispose()},callLLM:e.callLLM??(async(y,m,h)=>{let d=Ye(o,t.providerName),E=process.env[d.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!E)throw new Error(`Missing env var ${d.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let v=new Gc({apiKey:E,baseURL:d.base_url}),S=y.map(Xc),W=h?.tools??l,ee=W.length>0?W.map(F=>({type:"function",function:{name:F.name,description:F.description,parameters:F.input_schema}})):void 0,q=await v.chat.completions.create({model:d.model,messages:S,tools:ee,tool_choice:ee?"auto":void 0},{signal:h?.signal}),V=q.choices?.[0]?.message,he=Jc(V);if(V?.tool_calls&&V.tool_calls.length>0){let F=[];V.content&&F.push({type:"text",text:V.content});for(let P of V.tool_calls)if(P.type==="function"){let ue=Vc(P.function.arguments);ue.ok?F.push({type:"tool_use",id:P.id,name:P.function.name,input:ue.data}):F.push({type:"text",text:`[tool_use parse error] ${ue.error}; raw: ${ue.raw}`})}let w=F.some(P=>P.type==="tool_use");return{content:F,reasoning_content:he,stop_reason:w?"tool_use":"end_turn",usage:{prompt:q.usage?.prompt_tokens??void 0,completion:q.usage?.completion_tokens??void 0,total:q.usage?.total_tokens??void 0}}}let A=V?.content;if(typeof A!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:A}],reasoning_content:he,stop_reason:"end_turn",usage:{prompt:q.usage?.prompt_tokens??void 0,completion:q.usage?.completion_tokens??void 0,total:q.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:e.historySinks??[p],tokenCounter:e.tokenCounter??Io(t.tokenizerModel),historyFilePath:u}}function Yc(e){let t=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=e.replace(n,(o,s,i)=>{let a=(i??"").trim();return a&&t.push(a),a});return{thinkingParts:t,cleaned:r.trim()}}function $o(e){if(e.length===0)return;let t=e.join(`
57
+ `),{thinkingParts:n,cleaned:r}=Yc(t);return n.length>0?n.join(`
58
58
 
59
- `):r||void 0}import{randomUUID as Kc}from"crypto";var Jt="interactive";var jn="success",ct="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.",Ro=`Generate a concise session title based on the user's first prompt.
59
+ `):r||void 0}import{randomUUID as ou}from"crypto";var Yt="interactive";var Gn="success",lt="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.",Do=`Generate a concise session title based on the user's first prompt.
60
60
  Requirements:
61
61
  - 3 to 8 words when possible
62
62
  - Keep it specific and descriptive
63
63
  - Return title only, no quotes, no punctuation-only output
64
- `;var jc="Skipped tool execution after previous rejection.",Oo="Tool execution skipped: tools are disabled in current permission mode.";function Lo(e){if(e.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let t=e.dangerous??!1;return{mode:t?"full":"auto",toolsDisabled:!1,dangerous:t,approvalMode:"auto"}}function zn(){return{prompt:0,completion:0,total:0}}function qn(e,t){if(!t)return;let n=t.prompt??0,r=t.completion??0,o=t.total??n+r;e.prompt+=n,e.completion+=r,e.total+=o}function No(e){let t=e.content.filter(r=>r.type==="text"),n=e.content.filter(r=>r.type==="tool_use");return{textContent:t.map(r=>r.text).join(`
65
- `),toolUseBlocks:n.map(r=>({id:r.id,name:r.name,input:r.input})),reasoningContent:typeof e.reasoning_content=="string"&&e.reasoning_content.trim().length>0?e.reasoning_content:void 0,stopReason:e.stop_reason,usage:e.usage}}async function $o(e,t){for(let n of t)try{await n.append(e)}catch(r){console.error(`Failed to write history event: ${r.message}`)}}function Gn(e){return e instanceof Error&&e.name==="AbortError"}function lt(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(n=>lt(n)).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${lt(r)}`).join(",")}}`}function Do(e){return e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:lt(t.input)}}))}function Uo(e,t){let n=e.trim();if(!n)return null;let r=[n],o=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);o?.[1]&&r.push(o[1].trim());for(let s of r)if(!(!s.startsWith("{")||!s.endsWith("}")))try{let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,l=typeof a.tool=="string"?a.tool.trim():"";if(!l||!Object.prototype.hasOwnProperty.call(t,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}function Ho(e){return e.length<=60?e:`${e.slice(0,57).trimEnd()}...`}function Fo(e){let t=e.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!t)return"";let n=t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?Ho(n):""}function Bo(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"New Session";if(!t.includes(" "))return t.length<=20?t:`${t.slice(0,20).trimEnd()}...`;let r=t.split(" ").filter(Boolean).slice(0,8).join(" ");return Ho(r||t)}function Kn(e){return{role:"tool",content:e.observation,tool_call_id:e.actionId,name:e.tool}}function Wo(e,t,n){let r=new Map(t.map(o=>[o.actionId,o]));return e.map(o=>{let s=r.get(o.id);return s||{actionId:o.id,tool:o.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${jc} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as Gc}from"crypto";function zc(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function jo(e,t){t&&(t.onTurnStart&&e.onTurnStart.push(t.onTurnStart),t.onAction&&e.onAction.push(t.onAction),t.onObservation&&e.onObservation.push(t.onObservation),t.onFinal&&e.onFinal.push(t.onFinal),t.onApprovalRequest&&e.onApprovalRequest.push(t.onApprovalRequest),t.onApprovalResponse&&e.onApprovalResponse.push(t.onApprovalResponse),t.onTitleGenerated&&e.onTitleGenerated.push(t.onTitleGenerated))}function zo(e){let t=zc();if(jo(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)jo(t,n);return t}async function Q(e,t,n){let r=e[t];if(r.length)for(let o of r)try{await o(n)}catch(s){console.warn(`Hook ${t} failed: ${s.message}`)}}function ut(e){return e.map(t=>t.role==="assistant"&&t.tool_calls?.length?{...t,tool_calls:t.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...t})}var Yt=class{constructor(t,n,r,o,s){this.deps=t;this.options=n;this.id=n.sessionId||Gc(),this.mode=n.mode||Jt,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=t.historySinks??[],this.hooks=zo(t),this.historyFilePath=s;let i=Lo(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=xo({tools:t.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=zn();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(t,n){let r=`${t}:${lt(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=lt(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${t}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${o}${o.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}buildToolApprovalHooks(t,n){return{onApprovalRequest:async r=>{await Q(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:t,step:n,request:r})},requestApproval:async r=>this.deps.requestApproval?this.deps.requestApproval(r):"deny",onApprovalResponse:async({fingerprint:r,decision:o})=>{await Q(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:t,step:n,fingerprint:r,decision:o})}}}async executeToolAction(t,n,r,o,s){return this.toolOrchestrator.executeAction({id:t,name:n,input:r},this.buildToolApprovalHooks(o,s))}async maybeGenerateSessionTitle(t,n,r){if(t!==1||this.title)return;let o=Bo(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Ro},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=Fo(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(o=a,s="llm")}catch(i){if(Gn(i))return}this.title=o,await this.emitEvent("session_title",{turn:t,content:o,meta:{source:s,original_prompt:n}}),await Q(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:t,title:o,originalPrompt:n})}async runTurn(t){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=zn(),i=Date.now(),a=this.options.maxPromptTokens??12e4;if(!this.sessionStartEmitted){let l=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:l,role:l?"system":void 0,meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:t});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:t,meta:{tokens:{prompt:l}}}),await Q(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:t,promptTokens:l,history:ut(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,t,n.signal);let c="",u="ok",d,y=0,p=null,h=-1;for(let m=0;;m++){let k=this.tokenCounter.countMessages(this.history);if(k>a){let M=`Context tokens (${k}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:M}),u="prompt_limit",c=M,d=M,await this.emitEvent("final",{turn:r,step:m,content:M,role:"assistant",meta:{tokens:{prompt:k}}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:M,status:u,errorMessage:d,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&k>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${k}`);let v="",S=[],W,ee,q,V=!1;try{let M=await this.deps.callLLM(this.history,ne=>{ne&&(V=!0),this.deps.onAssistantStep?.(ne,m)},{signal:n.signal}),R=No(M);v=R.textContent,S=R.toolUseBlocks,ee=R.stopReason,W=R.usage,q=R.reasoningContent,v.trim().length>0&&(p=v,h=m)}catch(M){if(this.cancelling&&Gn(M)){u="cancelled",c="",d="Turn cancelled",await this.emitEvent("final",{turn:r,step:m,content:"",role:"assistant",meta:{cancelled:!0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:c,status:u,errorMessage:d,turnUsage:{...s},steps:o});break}let R=`LLM call failed: ${M.message}`;this.history.push({role:"assistant",content:R}),u="error",c=R,d=R,await this.emitEvent("final",{turn:r,content:R,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:c,status:u,errorMessage:d,turnUsage:{...s},steps:o});break}!V&&v&&this.deps.onAssistantStep?.(v,m);let he=S.length===0&&v?Uo(v,this.deps.tools):null,A,F=null;if(S.length>0){let M=S[0];if(M){let R=v?Io([v]):void 0;A={action:{tool:M.name,input:M.input},thinking:R},F={role:"assistant",content:v,reasoning_content:q,tool_calls:Do(S)}}else A={}}else v?(A={final:v},F={role:"assistant",content:v,reasoning_content:q}):A={};let E=this.tokenCounter.countText(v),P=W?.prompt??k,ue=W?.completion??E,Me=W?.total??P+ue,te={prompt:P,completion:ue,total:Me};if(qn(s,te),qn(this.sessionUsage,te),o.push({index:m,assistantText:v,parsed:A,tokenUsage:te}),await this.emitEvent("assistant",{turn:r,step:m,content:v,role:"assistant",meta:{tokens:te,protocol_violation:!!he,protocol_violation_count:he?y+1:y||void 0}}),he){y+=1;let M=`Model protocol error: returned plain-text tool JSON for "${he.tool}" ${y} times. Structured tool calls are required.`;u="error",c=M,d=M,this.history.push({role:"assistant",content:M}),await this.emitEvent("final",{turn:r,step:m,content:M,role:"assistant",meta:{error_type:"model_protocol_error",tool:he.tool,protocol_violation:!0,protocol_violation_count:y,tokens:te}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:c,status:u,errorMessage:d,tokenUsage:te,turnUsage:{...s},steps:o});break}if(F&&this.history.push(F),S.length>0&&this.toolsDisabled){for(let M of S)this.history.push({role:"tool",content:Oo,tool_call_id:M.id,name:M.name});u="error",c=ct,d=ct,this.history.push({role:"assistant",content:ct}),await this.emitEvent("final",{turn:r,step:m,content:ct,role:"assistant",meta:{error_type:"tool_disabled",tool_count:S.length,tools:S.map(M=>M.name).join(","),tokens:te}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:ct,status:u,errorMessage:d,tokenUsage:te,turnUsage:{...s},steps:o});break}if(S.length>1){for(let w of S)this.maybeWarnRepeatedAction(w.name,w.input);await this.emitEvent("action",{turn:r,step:m,meta:{tools:S.map(w=>w.name),action_ids:S.map(w=>w.id),action_id:S[0]?.id,parallel:!0,phase:"dispatch",thinking:A.thinking,toolBlocks:S.map(w=>({id:w.id,name:w.name,input:w.input}))}});let M=S[0];M&&await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:m,action:{tool:M.name,input:M.input},parallelActions:S.map(w=>({tool:w.name,input:w.input})),thinking:A.thinking,history:ut(this.history)});let R=S.every(w=>!!this.deps.tools[w.name]?.supportsParallelToolCalls),ne=S.some(w=>!!this.deps.tools[w.name]?.isMutating),se=R&&!ne?"parallel":"sequential",Be=await this.toolOrchestrator.executeActions(S.map(w=>({id:w.id,name:w.name,input:w.input})),{...this.buildToolApprovalHooks(r,m),executionMode:se,failurePolicy:"fail_fast"}),we=Wo(S,Be.results,Be.hasRejection);for(let[w,Y]of we.entries())this.history.push(Kn(Y)),await this.emitEvent("observation",{turn:r,step:m,content:Y.observation,meta:{tool:Y.tool,index:w,action_id:Y.actionId,phase:"result",status:Y.status,error_type:Y.errorType,duration_ms:Y.durationMs,execution_mode:se}});let pe=we.map(w=>`[${w.tool}]: ${w.observation}`).join(`
64
+ `;var Zc="Skipped tool execution after previous rejection.",Uo="Tool execution skipped: tools are disabled in current permission mode.";function Qc(e){process.stderr.write(`${JSON.stringify(e)}
65
+ `)}function Ho(e){if(e.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let t=e.dangerous??!1;return{mode:t?"full":"auto",toolsDisabled:!1,dangerous:t,approvalMode:"auto"}}function Kn(){return{prompt:0,completion:0,total:0}}function Vn(e,t){if(!t)return;let n=t.prompt??0,r=t.completion??0,o=t.total??n+r;e.prompt+=n,e.completion+=r,e.total+=o}function Fo(e){let t=e.content.filter(r=>r.type==="text"),n=e.content.filter(r=>r.type==="tool_use");return{textContent:t.map(r=>r.text).join(`
66
+ `),toolUseBlocks:n.map(r=>({id:r.id,name:r.name,input:r.input})),reasoningContent:typeof e.reasoning_content=="string"&&e.reasoning_content.trim().length>0?e.reasoning_content:void 0,stopReason:e.stop_reason,usage:e.usage}}async function Bo(e,t){for(let n of t)try{await n.append(e)}catch(r){Qc({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function Xn(e){return e instanceof Error&&e.name==="AbortError"}function Zt(e){return qn(e,new WeakSet,0)}var eu=100;function qn(e,t,n){if(n>eu)return JSON.stringify("[MaxDepthExceeded]");if(typeof e=="bigint")return JSON.stringify(e.toString());if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(t.has(e))return JSON.stringify("[Circular]");if(t.add(e),Array.isArray(e)){let s=`[${e.map(i=>qn(i,t,n+1)).join(",")}]`;return t.delete(e),s}let o=`{${Object.entries(e).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${JSON.stringify(s)}:${qn(i,t,n+1)}`).join(",")}}`;return t.delete(e),o}function Wo(e){return e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:Zt(t.input)}}))}function jo(e,t){let n=e.trim();if(!n)return null;let r=[n],o=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);o?.[1]&&r.push(o[1].trim());for(let s of r)if(!(!s.startsWith("{")||!s.endsWith("}")))try{let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,l=typeof a.tool=="string"?a.tool.trim():"";if(!l||!Object.prototype.hasOwnProperty.call(t,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}function zo(e){return e.length<=60?e:`${e.slice(0,57).trimEnd()}...`}function qo(e){let t=e.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!t)return"";let n=t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?zo(n):""}function Go(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"New Session";if(!t.includes(" "))return t.length<=20?t:`${t.slice(0,20).trimEnd()}...`;let r=t.split(" ").filter(Boolean).slice(0,8).join(" ");return zo(r||t)}function Jn(e){return{role:"tool",content:e.observation,tool_call_id:e.actionId,name:e.tool}}function Ko(e,t,n){let r=new Map(t.map(o=>[o.actionId,o]));return e.map(o=>{let s=r.get(o.id);return s||{actionId:o.id,tool:o.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${Zc} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as ru}from"crypto";function tu(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function Vo(e,t){t&&(t.onTurnStart&&e.onTurnStart.push(t.onTurnStart),t.onAction&&e.onAction.push(t.onAction),t.onObservation&&e.onObservation.push(t.onObservation),t.onFinal&&e.onFinal.push(t.onFinal),t.onApprovalRequest&&e.onApprovalRequest.push(t.onApprovalRequest),t.onApprovalResponse&&e.onApprovalResponse.push(t.onApprovalResponse),t.onTitleGenerated&&e.onTitleGenerated.push(t.onTitleGenerated))}function Xo(e){let t=tu();if(Vo(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)Vo(t,n);return t}async function Q(e,t,n){let r=e[t];if(r.length)for(let o of r)try{await o(n)}catch(s){console.warn(`Hook ${t} failed: ${s.message}`)}}function ct(e){return e.map(t=>t.role==="assistant"&&t.tool_calls?.length?{...t,tool_calls:t.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...t})}var Qt=class{constructor(t,n,r,o,s){this.deps=t;this.options=n;this.id=n.sessionId||ru(),this.mode=n.mode||Yt,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=t.historySinks??[],this.hooks=Xo(t),this.historyFilePath=s;let i=Ho(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=wo({tools:t.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=Kn();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(t,n){let r=`${t}:${Zt(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=Zt(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${t}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${o}${o.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}buildToolApprovalHooks(t,n){return{onApprovalRequest:async r=>{await Q(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:t,step:n,request:r})},requestApproval:async r=>this.deps.requestApproval?this.deps.requestApproval(r):"deny",onApprovalResponse:async({fingerprint:r,decision:o})=>{await Q(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:t,step:n,fingerprint:r,decision:o})}}}async executeToolAction(t,n,r,o,s){return this.toolOrchestrator.executeAction({id:t,name:n,input:r},this.buildToolApprovalHooks(o,s))}async maybeGenerateSessionTitle(t,n,r){if(t!==1||this.title)return;let o=Go(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Do},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=qo(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(o=a,s="llm")}catch(i){if(Xn(i))return}this.title=o,await this.emitEvent("session_title",{turn:t,content:o,meta:{source:s,original_prompt:n}}),await Q(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:t,title:o,originalPrompt:n})}async runTurn(t){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=Kn(),i=Date.now(),a=this.options.maxPromptTokens??12e4;if(!this.sessionStartEmitted){let l=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:l,role:l?"system":void 0,meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:t});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:t,meta:{tokens:{prompt:l}}}),await Q(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:t,promptTokens:l,history:ct(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,t,n.signal);let c="",u="ok",p,y=0,m=null,h=-1;for(let d=0;;d++){let E=this.tokenCounter.countMessages(this.history);if(E>a){let M=`Context tokens (${E}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:M}),u="prompt_limit",c=M,p=M,await this.emitEvent("final",{turn:r,step:d,content:M,role:"assistant",meta:{tokens:{prompt:E}}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:M,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&E>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${E}`);let v="",S=[],W,ee,q,V=!1;try{let M=await this.deps.callLLM(this.history,ne=>{ne&&(V=!0),this.deps.onAssistantStep?.(ne,d)},{signal:n.signal}),R=Fo(M);v=R.textContent,S=R.toolUseBlocks,ee=R.stopReason,W=R.usage,q=R.reasoningContent,v.trim().length>0&&(m=v,h=d)}catch(M){if(this.cancelling&&Xn(M)){u="cancelled",c="",p="Turn cancelled",await this.emitEvent("final",{turn:r,step:d,content:"",role:"assistant",meta:{cancelled:!0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}let R=`LLM call failed: ${M.message}`;this.history.push({role:"assistant",content:R}),u="error",c=R,p=R,await this.emitEvent("final",{turn:r,content:R,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o});break}!V&&v&&this.deps.onAssistantStep?.(v,d);let he=S.length===0&&v?jo(v,this.deps.tools):null,A,F=null;if(S.length>0){let M=S[0];if(M){let R=v?$o([v]):void 0;A={action:{tool:M.name,input:M.input},thinking:R},F={role:"assistant",content:v,reasoning_content:q,tool_calls:Wo(S)}}else A={}}else v?(A={final:v},F={role:"assistant",content:v,reasoning_content:q}):A={};let w=this.tokenCounter.countText(v),P=W?.prompt??E,ue=W?.completion??w,we=W?.total??P+ue,te={prompt:P,completion:ue,total:we};if(Vn(s,te),Vn(this.sessionUsage,te),o.push({index:d,assistantText:v,parsed:A,tokenUsage:te}),await this.emitEvent("assistant",{turn:r,step:d,content:v,role:"assistant",meta:{tokens:te,protocol_violation:!!he,protocol_violation_count:he?y+1:y||void 0}}),he){y+=1;let M=`Model protocol error: returned plain-text tool JSON for "${he.tool}" ${y} times. Structured tool calls are required.`;u="error",c=M,p=M,this.history.push({role:"assistant",content:M}),await this.emitEvent("final",{turn:r,step:d,content:M,role:"assistant",meta:{error_type:"model_protocol_error",tool:he.tool,protocol_violation:!0,protocol_violation_count:y,tokens:te}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,errorMessage:p,tokenUsage:te,turnUsage:{...s},steps:o});break}if(F&&this.history.push(F),S.length>0&&this.toolsDisabled){for(let M of S)this.history.push({role:"tool",content:Uo,tool_call_id:M.id,name:M.name});u="error",c=lt,p=lt,this.history.push({role:"assistant",content:lt}),await this.emitEvent("final",{turn:r,step:d,content:lt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:S.length,tools:S.map(M=>M.name).join(","),tokens:te}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:lt,status:u,errorMessage:p,tokenUsage:te,turnUsage:{...s},steps:o});break}if(S.length>1){for(let k of S)this.maybeWarnRepeatedAction(k.name,k.input);await this.emitEvent("action",{turn:r,step:d,meta:{tools:S.map(k=>k.name),action_ids:S.map(k=>k.id),action_id:S[0]?.id,parallel:!0,phase:"dispatch",thinking:A.thinking,toolBlocks:S.map(k=>({id:k.id,name:k.name,input:k.input}))}});let M=S[0];M&&await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:d,action:{tool:M.name,input:M.input},parallelActions:S.map(k=>({tool:k.name,input:k.input})),thinking:A.thinking,history:ct(this.history)});let R=S.every(k=>!!this.deps.tools[k.name]?.supportsParallelToolCalls),ne=S.some(k=>!!this.deps.tools[k.name]?.isMutating),se=R&&!ne?"parallel":"sequential",Be=await this.toolOrchestrator.executeActions(S.map(k=>({id:k.id,name:k.name,input:k.input})),{...this.buildToolApprovalHooks(r,d),executionMode:se,failurePolicy:"fail_fast"}),Me=Ko(S,Be.results,Be.hasRejection);for(let[k,Y]of Me.entries())this.history.push(Jn(Y)),await this.emitEvent("observation",{turn:r,step:d,content:Y.observation,meta:{tool:Y.tool,index:k,action_id:Y.actionId,phase:"result",status:Y.status,error_type:Y.errorType,duration_ms:Y.durationMs,execution_mode:se}});let pe=Me.map(k=>`[${k.tool}]: ${k.observation}`).join(`
66
67
 
67
- `),ke=we.map(w=>w.status),Xe=ke.find(w=>w!==jn)??jn,Le=o[o.length-1];if(Le&&(Le.observation=pe),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:m,tool:S.map(w=>w.name).join(", "),observation:pe,resultStatus:Xe,parallelResultStatuses:ke,history:ut(this.history)}),Be.hasRejection){let w=we.find(Y=>Y.rejected);u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:r,step:m,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:w?.actionId,error_type:w?.errorType??"approval_denied",duration_ms:w?.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}continue}else if(A.action){this.maybeWarnRepeatedAction(A.action.tool,A.action.input);let M=S[0]?.id??`${r}:${m}:single:${A.action.tool}`;await this.emitEvent("action",{turn:r,step:m,meta:{tool:A.action.tool,input:A.action.input,action_id:M,phase:"dispatch",thinking:A.thinking}}),await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:m,action:A.action,thinking:A.thinking,history:ut(this.history)});let R=await this.executeToolAction(M,A.action.tool,A.action.input,r,m);if(R.rejected){this.history.push(Kn({...R,observation:R.observation||`User denied tool execution: ${A.action.tool}`})),u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:r,step:m,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:R.actionId,error_type:R.errorType??"approval_denied",duration_ms:R.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}let ne=R.observation;this.history.push({role:"tool",content:ne,tool_call_id:R.actionId,name:A.action.tool});let se=o[o.length-1];se&&(se.observation=ne),await this.emitEvent("observation",{turn:r,step:m,content:ne,meta:{tool:A.action.tool,action_id:R.actionId,phase:"result",status:R.status,error_type:R.errorType,duration_ms:R.durationMs}}),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:m,tool:A.action.tool,observation:ne,resultStatus:R.status,history:ut(this.history)});continue}if(ee==="end_turn"||A.final){this.resetActionRepetition();let M=ee==="end_turn"&&!A.final&&v.trim().length===0&&!!p&&h===m-1;c=M?p??"":A.final||v,A.final&&(A.final=c),await this.emitEvent("final",{turn:r,step:m,content:c,role:"assistant",meta:{tokens:te,fallback_from_previous_text:M||void 0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:m,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}this.resetActionRepetition();break}return!c&&u!=="cancelled"&&(u==="ok"&&(u="error"),c="Unable to produce a final answer. Please retry or adjust the request.",d=c,this.history.push({role:"assistant",content:c}),await this.emitEvent("final",{turn:r,content:c,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:c,status:u,errorMessage:d,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:u,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:y||void 0}}),{finalText:c,steps:o,status:u,errorMessage:d,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async close(){if(this.closed)return;if(this.closed=!0,this.sessionStartEmitted||this.turnIndex>=0){await this.emitEvent("session_end",{meta:{durationMs:Date.now()-this.startedAt,tokens:this.sessionUsage}});for(let n of this.sinks)if(n.flush)try{await n.flush()}catch(r){console.error(`History flush failed: ${r.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(t,n){if(!this.sinks.length)return;let r=yr({sessionId:this.id,type:t,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await $o(r,this.sinks)}};async function Zt(e,t={}){let n=t.sessionId||Kc(),r=await Po(e,{...t,sessionId:n},n),o=await r.loadPrompt(),s=new Yt({...e,...r},{...t,sessionId:n,mode:t.mode??Jt},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as tt}from"crypto";import{readFile as Yp}from"fs/promises";import{useCallback as J,useEffect as $t,useMemo as Dt,useReducer as Zp,useRef as hn,useState as re}from"react";import{Box as Ys,Text as Qp,useApp as em}from"ink";import{memo as uu,useMemo as Qt}from"react";import{Box as rs,Static as pu,Text as en}from"ink";import{Box as qe,Text as oe}from"ink";var Fe={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import pt from"path";var Vc="success",bt=".";function Vn(e){return e?e===Vc?Fe.SUCCESS:Fe.ERROR:Fe.SUCCESS}function qo(e){if(e?.length)return e.map(t=>Vn(t))}function Go(e,t){return!t||t<=0||!e||e<=0?0:Math.min(100,e/t*100)}function Ko(e){return e?`tokens: ${e.total} (prompt ${e.prompt} / completion ${e.completion})`:""}function At(e,t=80){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function Vo(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Xn(e,t){let n=e.trim();if(!n)return e;if(n===bt)return bt;if(pt.isAbsolute(n)){let r=pt.relative(pt.resolve(t),n);return r?pt.normalize(r):bt}if(n.startsWith("./")||n.startsWith("../")){let r=pt.normalize(n);return!r||r==="."||r==="./"?bt:r}return n}function Xo(e){return e?e===bt||pt.isAbsolute(e)?!0:e.startsWith("./")||e.startsWith("../"):!1}import{Box as Ae,Text as fe}from"ink";import{marked as Xc}from"marked";var Jc=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Et(e){return e.map(t=>{let n=t;return typeof n.text=="string"?n.text:typeof n.raw=="string"?n.raw:Array.isArray(n.tokens)?Et(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Et(r.tokens):"").filter(Boolean).join(`
68
- `):""}).join("")}function Yc(e){let t=[],n=e.replace(/<think>([\s\S]*?)<\/think>/gi,(r,o)=>{let s=o.trim();return s&&t.push(s),""});return{think:t,cleaned:n}}function Zc(e){if(e.startsWith("`")&&e.endsWith("`"))return{type:"inlineCode",content:e.slice(1,-1)};if(e.startsWith("**")&&e.endsWith("**")||e.startsWith("__")&&e.endsWith("__"))return{type:"bold",content:e.slice(2,-2)};if(e.startsWith("*")&&e.endsWith("*")||e.startsWith("_")&&e.endsWith("_"))return{type:"italic",content:e.slice(1,-1)};let t=e.match(/^\[([^\]]+)\]\((.+)\)$/);return t?{type:"link",label:t[1]??"",href:t[2]??""}:{type:"text",content:e}}function Yo(e){if(!e)return[];let t=[],n=0;for(let r of e.matchAll(Jc)){let o=r[0];if(!o)continue;let s=r.index??0;s>n&&t.push({type:"text",content:e.slice(n,s)}),t.push(Zc(o)),n=s+o.length}return n<e.length&&t.push({type:"text",content:e.slice(n)}),t.filter(r=>r.type==="link"?r.label.length>0||r.href.length>0:r.content.length>0)}function Qc(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Et(e.tokens):""}function eu(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Et(e.tokens):typeof e.raw=="string"?e.raw.split(`
68
+ `),ke=Me.map(k=>k.status),Xe=ke.find(k=>k!==Gn)??Gn,Le=o[o.length-1];if(Le&&(Le.observation=pe),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:d,tool:S.map(k=>k.name).join(", "),observation:pe,resultStatus:Xe,parallelResultStatuses:ke,history:ct(this.history)}),Be.hasRejection){let k=Me.find(Y=>Y.rejected);u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:r,step:d,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:k?.actionId,error_type:k?.errorType??"approval_denied",duration_ms:k?.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}continue}else if(A.action){this.maybeWarnRepeatedAction(A.action.tool,A.action.input);let M=S[0]?.id??`${r}:${d}:single:${A.action.tool}`;await this.emitEvent("action",{turn:r,step:d,meta:{tool:A.action.tool,input:A.action.input,action_id:M,phase:"dispatch",thinking:A.thinking}}),await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:d,action:A.action,thinking:A.thinking,history:ct(this.history)});let R=await this.executeToolAction(M,A.action.tool,A.action.input,r,d);if(R.rejected){this.history.push(Jn({...R,observation:R.observation||`User denied tool execution: ${A.action.tool}`})),u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:r,step:d,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:R.actionId,error_type:R.errorType??"approval_denied",duration_ms:R.durationMs}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}let ne=R.observation;this.history.push({role:"tool",content:ne,tool_call_id:R.actionId,name:A.action.tool});let se=o[o.length-1];se&&(se.observation=ne),await this.emitEvent("observation",{turn:r,step:d,content:ne,meta:{tool:A.action.tool,action_id:R.actionId,phase:"result",status:R.status,error_type:R.errorType,duration_ms:R.durationMs}}),await Q(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:d,tool:A.action.tool,observation:ne,resultStatus:R.status,history:ct(this.history)});continue}if(ee==="end_turn"||A.final){this.resetActionRepetition();let M=ee==="end_turn"&&!A.final&&v.trim().length===0&&!!m&&h===d-1;c=M?m??"":A.final||v,A.final&&(A.final=c),await this.emitEvent("final",{turn:r,step:d,content:c,role:"assistant",meta:{tokens:te,fallback_from_previous_text:M||void 0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:d,finalText:c,status:u,tokenUsage:te,turnUsage:{...s},steps:o});break}this.resetActionRepetition();break}return!c&&u!=="cancelled"&&(u==="ok"&&(u="error"),c="Unable to produce a final answer. Please retry or adjust the request.",p=c,this.history.push({role:"assistant",content:c}),await this.emitEvent("final",{turn:r,content:c,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:u,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:y||void 0}}),{finalText:c,steps:o,status:u,errorMessage:p,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async close(){if(this.closed)return;if(this.closed=!0,this.sessionStartEmitted||this.turnIndex>=0){await this.emitEvent("session_end",{meta:{durationMs:Date.now()-this.startedAt,tokens:this.sessionUsage}});for(let n of this.sinks)try{n.close?await n.close():n.flush&&await n.flush()}catch(r){console.error(`History flush failed: ${r.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(t,n){if(!this.sinks.length)return;let r=Sr({sessionId:this.id,type:t,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Bo(r,this.sinks)}};async function en(e,t={}){let n=t.sessionId||ou(),r=await No(e,{...t,sessionId:n},n),o=await r.loadPrompt(),s=new Qt({...e,...r},{...t,sessionId:n,mode:t.mode??Yt},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as tt}from"crypto";import{readFile as ld}from"fs/promises";import{useCallback as J,useEffect as Nt,useMemo as $t,useReducer as cd,useRef as Tn,useState as re}from"react";import{Box as ni,Text as ud,useApp as pd}from"ink";import{memo as vu,useMemo as tn}from"react";import{Box as ls,Static as xu,Text as nn}from"ink";import{Box as qe,Text as oe}from"ink";var Fe={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import ut from"path";var su="success",Ct=".";function Yn(e){return e?e===su?Fe.SUCCESS:Fe.ERROR:Fe.SUCCESS}function Jo(e){if(e?.length)return e.map(t=>Yn(t))}function Yo(e,t){return!t||t<=0||!e||e<=0?0:Math.min(100,e/t*100)}function Zo(e){return e?`tokens: ${e.total} (prompt ${e.prompt} / completion ${e.completion})`:""}function bt(e,t=80){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function Qo(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Zn(e,t){let n=e.trim();if(!n)return e;if(n===Ct)return Ct;if(ut.isAbsolute(n)){let r=ut.relative(ut.resolve(t),n);return r?ut.normalize(r):Ct}if(n.startsWith("./")||n.startsWith("../")){let r=ut.normalize(n);return!r||r==="."||r==="./"?Ct:r}return n}function es(e){return e?e===Ct||ut.isAbsolute(e)?!0:e.startsWith("./")||e.startsWith("../"):!1}import{Box as Ee,Text as fe}from"ink";import{marked as iu}from"marked";var au=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Et(e){return e.map(t=>{let n=t;return typeof n.text=="string"?n.text:typeof n.raw=="string"?n.raw:Array.isArray(n.tokens)?Et(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Et(r.tokens):"").filter(Boolean).join(`
69
+ `):""}).join("")}function lu(e){let t=[],n=e.replace(/<think>([\s\S]*?)<\/think>/gi,(r,o)=>{let s=o.trim();return s&&t.push(s),""});return{think:t,cleaned:n}}function cu(e){if(e.startsWith("`")&&e.endsWith("`"))return{type:"inlineCode",content:e.slice(1,-1)};if(e.startsWith("**")&&e.endsWith("**")||e.startsWith("__")&&e.endsWith("__"))return{type:"bold",content:e.slice(2,-2)};if(e.startsWith("*")&&e.endsWith("*")||e.startsWith("_")&&e.endsWith("_"))return{type:"italic",content:e.slice(1,-1)};let t=e.match(/^\[([^\]]+)\]\((.+)\)$/);return t?{type:"link",label:t[1]??"",href:t[2]??""}:{type:"text",content:e}}function ns(e){if(!e)return[];let t=[],n=0;for(let r of e.matchAll(au)){let o=r[0];if(!o)continue;let s=r.index??0;s>n&&t.push({type:"text",content:e.slice(n,s)}),t.push(cu(o)),n=s+o.length}return n<e.length&&t.push({type:"text",content:e.slice(n)}),t.filter(r=>r.type==="link"?r.label.length>0||r.href.length>0:r.content.length>0)}function uu(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Et(e.tokens):""}function pu(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Et(e.tokens):typeof e.raw=="string"?e.raw.split(`
69
70
  `).map(t=>t.replace(/^>\s?/,"")).join(`
70
- `).trim():""}function Jo(e){return typeof e.text=="string"?e.text:Array.isArray(e.tokens)?Et(e.tokens):typeof e.raw=="string"?e.raw:""}function Zo(e){let{think:t,cleaned:n}=Yc(e),r=[];t.length>0&&r.push({type:"think",content:t.join(`
71
+ `).trim():""}function ts(e){return typeof e.text=="string"?e.text:Array.isArray(e.tokens)?Et(e.tokens):typeof e.raw=="string"?e.raw:""}function rs(e){let{think:t,cleaned:n}=lu(e),r=[];t.length>0&&r.push({type:"think",content:t.join(`
71
72
 
72
- `)});let o=Xc.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??Jo(s)});break}case"paragraph":case"text":{let i=Jo(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=eu(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(a=>Qc(a)).filter(a=>a.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as lu,jsx as B,jsxs as mt}from"react/jsx-runtime";var tu="\u2014\u2014\u2014";function nu(e,t){return e.repeat(Math.max(0,t))}function ru(e){let t=e.split(`
73
- `);if(t.length===0)return["Think:"];let n=t.findIndex(r=>r.trim().length>0);return n<0&&(n=0),t.map((r,o)=>o===n?`Think: ${r}`:r)}function ou(e){return e.split(`
74
- `)}function su({content:e}){let t=ou(e);return B(Ae,{flexDirection:"column",marginY:1,children:t.map((n,r)=>B(fe,{children:n},r))})}function iu({node:e}){switch(e.type){case"bold":return B(fe,{bold:!0,children:e.content});case"italic":return B(fe,{italic:!0,children:e.content});case"inlineCode":return B(fe,{color:"cyan",children:e.content});case"link":return mt(lu,{children:[B(fe,{color:"blue",underline:!0,children:e.label}),mt(fe,{color:"gray",children:[" (",e.href,")"]})]});case"text":return B(fe,{children:e.content});default:return null}}function Jn({content:e}){let t=Yo(e);return B(Ae,{flexWrap:"wrap",children:t.map((n,r)=>B(iu,{node:n},r))})}function au(e,t){switch(e.type){case"html":return B(Ae,{children:B(fe,{color:"gray",dimColor:!0,children:e.content})},t);case"hr":return B(Ae,{marginY:1,children:B(fe,{color:"gray",dimColor:!0,children:tu})},t);case"think":return B(Ae,{flexDirection:"column",marginY:1,children:ru(e.content).map((n,r)=>B(fe,{color:"gray",dimColor:!0,children:n},r))},t);case"heading":return B(Ae,{children:mt(fe,{bold:!0,color:"cyan",children:[nu("#",e.level)," ",e.content]})},t);case"paragraph":return B(Jn,{content:e.content},t);case"code":return B(su,{content:e.content},t);case"blockquote":return B(Ae,{flexDirection:"column",children:e.content.split(`
75
- `).map((n,r)=>mt(Ae,{children:[B(fe,{color:"gray",dimColor:!0,children:"> "}),B(Jn,{content:n})]},r))},t);case"list":return B(Ae,{flexDirection:"column",children:e.items.map((n,r)=>mt(Ae,{children:[mt(fe,{color:"gray",children:[e.ordered?`${r+1}.`:"\u2022"," "]}),B(Jn,{content:n})]},r))},t);default:return null}}function Qo({content:e}){let t=Zo(e);return B(Ae,{flexDirection:"column",children:t.map((n,r)=>au(n,`${n.type}-${r}`))})}import{jsx as de,jsxs as ve}from"react/jsx-runtime";function es(e){return e===Fe.ERROR?"red":e===Fe.EXECUTING?"yellow":"green"}function ts(e,t){if(e==null)return null;if(typeof e=="string"){let s=Xo(e)?Xn(e,t):e;return At(s,70)}if(typeof e!="object"||Array.isArray(e))return At(String(e),70);let n=e,r=["cmd","path","file_path","dir_path","query","pattern","url","content"],o=new Set(["path","file_path","dir_path"]);for(let s of r){let i=n[s];if(i==null||i==="")continue;let a=String(i),l=o.has(s)?Xn(a,t):a;return At(l,70)}return At(Vo(n),70)}function ns({message:e}){let t=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return ve(qe,{flexDirection:"column",children:[ve(oe,{color:t,children:["\u25CF ",e.title]}),de(oe,{color:"gray",children:e.content})]})}function cu({step:e,cwd:t}){let n=!!(e.parallelActions&&e.parallelActions.length>1),r=!n&&e.action?ts(e.action.input,t):null;return ve(qe,{flexDirection:"column",children:[e.thinking?ve(qe,{children:[de(oe,{color:"gray",children:"\u25CF "}),de(oe,{color:"gray",children:e.thinking})]}):null,n?e.parallelActions?.map((o,s)=>{let i=ts(o.input,t);return ve(qe,{children:[ve(oe,{color:es(e.parallelToolStatuses?.[s]??e.toolStatus),children:["\u25CF"," "]}),de(oe,{color:"gray",children:"Used "}),de(oe,{color:"cyan",children:o.tool}),i?ve(oe,{color:"gray",children:[" (",i,")"]}):null]},`${o.tool}-${s}`)}):null,!n&&e.action?ve(qe,{children:[de(oe,{color:es(e.toolStatus),children:"\u25CF "}),de(oe,{color:"gray",children:"Used "}),de(oe,{color:"cyan",children:e.action.tool}),r?ve(oe,{color:"gray",children:[" (",r,")"]}):null]}):null]})}function Yn({turn:e,cwd:t}){return ve(qe,{flexDirection:"column",children:[ve(qe,{marginY:.5,children:[de(oe,{color:"gray",children:"\u203A "}),de(oe,{children:e.userInput})]}),e.steps.map(n=>de(cu,{step:n,cwd:t},`${e.index}-${n.index}`)),e.finalText?de(qe,{marginTop:0,children:de(Qo,{content:e.finalText})}):null,e.status&&e.status!=="ok"?ve(oe,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?de(oe,{color:"red",children:e.errorMessage}):null]})}import{jsx as Mt,jsxs as wt}from"react/jsx-runtime";function os(e){return e.sequence??0}function mu(e){return e.type==="header"}function du(e){return e.id!==void 0}var ss=uu(function({header:t,systemMessages:n,turns:r,historicalTurns:o}){let s=Qt(()=>[...o,...r],[o,r]),i=s.length>0?s[s.length-1]:void 0,a=i&&!!(i.finalText||i.status&&i.status!=="ok"),l=a?s:s.slice(0,-1),c=a?void 0:i,u=Qt(()=>({type:"header",data:t}),[t]),d=Qt(()=>{let p=[...n,...l];return p.sort((h,m)=>os(h)-os(m)),p},[l,n]),y=Qt(()=>[u,...d],[u,d]);return wt(rs,{flexDirection:"column",children:[Mt(pu,{items:y,children:p=>mu(p)?wt(rs,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[Mt(en,{bold:!0,children:"Memo CLI"}),wt(en,{color:"gray",children:[p.data.providerName," / ",p.data.model," \u2022 v",p.data.version]}),wt(en,{color:"gray",children:["cwd: ",p.data.cwd]}),wt(en,{color:"gray",children:["mcp: ",p.data.mcpNames.join(", ")||"none"]})]},`header-${p.data.sessionId}`):du(p)?Mt(ns,{message:p},p.id):Mt(Yn,{turn:p,cwd:t.cwd},`turn-${p.sequence??p.index}`)}),c?Mt(Yn,{turn:c,cwd:t.cwd}):null]})});import{useCallback as et,useEffect as un,useMemo as Ps,useRef as It,useState as Ge}from"react";import{Box as er,Text as pn,useInput as ep,useStdout as tp}from"ink";var dt=[8e4,12e4,15e4,2e5],is=dt[1],$={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",MODELS:"models",CONTEXT:"context",TOOLS:"tools",MCP:"mcp",INIT:"init"},H={NONE:"none",ONCE:"once",FULL:"full"};function ge(e){return`/${e}`}var as="exit";var tn=[{name:$.HELP,description:"Show command and shortcut help"},{name:$.EXIT,description:"Exit current session"},{name:$.NEW,description:"Start a fresh session"},{name:$.RESUME,description:"List and load session history"},{name:$.MODELS,description:"List or switch configured models"},{name:$.CONTEXT,description:"Set context window (80k/120k/150k/200k)"},{name:$.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:$.MCP,description:"Show configured MCP servers"},{name:$.INIT,description:"Generate AGENTS.md with agent instructions"}],fu={none:H.NONE,off:H.NONE,disabled:H.NONE,"no-tools":H.NONE,once:H.ONCE,ask:H.ONCE,single:H.ONCE,strict:H.ONCE,full:H.FULL,all:H.FULL,dangerous:H.FULL,"full-access":H.FULL};function gu(e){if(!e)return null;let t=e.trim().toLowerCase();return t?fu[t]??null:null}function ls(e){return e===H.NONE?"none (no tools)":e===H.ONCE?"once (approval required)":"full (no approval)"}function hu(){let e=tn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...tn.map(n=>` ${ge(n.name).padEnd(e+3)} ${n.description}`)," exit Exit session (without slash)","","Shortcuts:"," Enter Send message"," Shift+Enter New line"," Up/Down Browse local input history"," Tab Accept active suggestion"," Ctrl+L Clear screen and start new session"," Esc Esc Interrupt running turn / clear input"].join(`
76
- `)}function yu(e){if(!e)return null;let n=e.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!n)return null;let r=Number(n[1]);return Number.isFinite(r)?r*(n[2]?1e3:1):null}function cs(e,t){let[n,...r]=e.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case $.HELP:return{kind:"message",title:"Help",content:hu()};case $.EXIT:return{kind:"exit"};case $.NEW:return{kind:"new"};case $.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case $.MODELS:{if(!t.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${t.configPath}`};let s=r.join(" ").trim(),i=t.providers.find(c=>c.name===s)??t.providers.find(c=>c.model===s);if(i)return{kind:"switch_model",provider:i};let a=t.providers.map(c=>{let u=c.name===t.providerName&&c.model===t.model?" (current)":"",d=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${d}${u}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
73
+ `)});let o=iu.lexer(n);for(let s of o)switch(s.type){case"html":{r.push({type:"html",content:s.text??s.raw??""});break}case"hr":{r.push({type:"hr"});break}case"heading":{r.push({type:"heading",level:typeof s.depth=="number"?s.depth:1,content:s.text??ts(s)});break}case"paragraph":case"text":{let i=ts(s);i.trim().length>0&&r.push({type:"paragraph",content:i});break}case"code":{r.push({type:"code",language:s.lang,content:s.text??""});break}case"blockquote":{let i=pu(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(a=>uu(a)).filter(a=>a.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as _u,jsx as B,jsxs as pt}from"react/jsx-runtime";var du="\u2014\u2014\u2014";function mu(e,t){return e.repeat(Math.max(0,t))}function fu(e){let t=e.split(`
74
+ `);if(t.length===0)return["Think:"];let n=t.findIndex(r=>r.trim().length>0);return n<0&&(n=0),t.map((r,o)=>o===n?`Think: ${r}`:r)}function gu(e){return e.split(`
75
+ `)}function hu({content:e}){let t=gu(e);return B(Ee,{flexDirection:"column",marginY:1,children:t.map((n,r)=>B(fe,{children:n},r))})}function yu({node:e}){switch(e.type){case"bold":return B(fe,{bold:!0,children:e.content});case"italic":return B(fe,{italic:!0,children:e.content});case"inlineCode":return B(fe,{color:"cyan",children:e.content});case"link":return pt(_u,{children:[B(fe,{color:"blue",underline:!0,children:e.label}),pt(fe,{color:"gray",children:[" (",e.href,")"]})]});case"text":return B(fe,{children:e.content});default:return null}}function Qn({content:e}){let t=ns(e);return B(Ee,{flexWrap:"wrap",children:t.map((n,r)=>B(yu,{node:n},r))})}function Tu(e,t){switch(e.type){case"html":return B(Ee,{children:B(fe,{color:"gray",dimColor:!0,children:e.content})},t);case"hr":return B(Ee,{marginY:1,children:B(fe,{color:"gray",dimColor:!0,children:du})},t);case"think":return B(Ee,{flexDirection:"column",marginY:1,children:fu(e.content).map((n,r)=>B(fe,{color:"gray",dimColor:!0,children:n},r))},t);case"heading":return B(Ee,{children:pt(fe,{bold:!0,color:"cyan",children:[mu("#",e.level)," ",e.content]})},t);case"paragraph":return B(Qn,{content:e.content},t);case"code":return B(hu,{content:e.content},t);case"blockquote":return B(Ee,{flexDirection:"column",children:e.content.split(`
76
+ `).map((n,r)=>pt(Ee,{children:[B(fe,{color:"gray",dimColor:!0,children:"> "}),B(Qn,{content:n})]},r))},t);case"list":return B(Ee,{flexDirection:"column",children:e.items.map((n,r)=>pt(Ee,{children:[pt(fe,{color:"gray",children:[e.ordered?`${r+1}.`:"\u2022"," "]}),B(Qn,{content:n})]},r))},t);default:return null}}function os({content:e}){let t=rs(e);return B(Ee,{flexDirection:"column",children:t.map((n,r)=>Tu(n,`${n.type}-${r}`))})}import{jsx as me,jsxs as ve}from"react/jsx-runtime";function ss(e){return e===Fe.ERROR?"red":e===Fe.EXECUTING?"yellow":"green"}function is(e,t){if(e==null)return null;if(typeof e=="string"){let s=es(e)?Zn(e,t):e;return bt(s,70)}if(typeof e!="object"||Array.isArray(e))return bt(String(e),70);let n=e,r=["cmd","path","file_path","dir_path","query","pattern","url","content"],o=new Set(["path","file_path","dir_path"]);for(let s of r){let i=n[s];if(i==null||i==="")continue;let a=String(i),l=o.has(s)?Zn(a,t):a;return bt(l,70)}return bt(Qo(n),70)}function as({message:e}){let t=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return ve(qe,{flexDirection:"column",children:[ve(oe,{color:t,children:["\u25CF ",e.title]}),me(oe,{color:"gray",children:e.content})]})}function Su({step:e,cwd:t}){let n=!!(e.parallelActions&&e.parallelActions.length>1),r=!n&&e.action?is(e.action.input,t):null;return ve(qe,{flexDirection:"column",children:[e.thinking?ve(qe,{children:[me(oe,{color:"gray",children:"\u25CF "}),me(oe,{color:"gray",children:e.thinking})]}):null,n?e.parallelActions?.map((o,s)=>{let i=is(o.input,t);return ve(qe,{children:[ve(oe,{color:ss(e.parallelToolStatuses?.[s]??e.toolStatus),children:["\u25CF"," "]}),me(oe,{color:"gray",children:"Used "}),me(oe,{color:"cyan",children:o.tool}),i?ve(oe,{color:"gray",children:[" (",i,")"]}):null]},`${o.tool}-${s}`)}):null,!n&&e.action?ve(qe,{children:[me(oe,{color:ss(e.toolStatus),children:"\u25CF "}),me(oe,{color:"gray",children:"Used "}),me(oe,{color:"cyan",children:e.action.tool}),r?ve(oe,{color:"gray",children:[" (",r,")"]}):null]}):null]})}function er({turn:e,cwd:t}){return ve(qe,{flexDirection:"column",children:[ve(qe,{marginY:.5,children:[me(oe,{color:"gray",children:"\u203A "}),me(oe,{children:e.userInput})]}),e.steps.map(n=>me(Su,{step:n,cwd:t},`${e.index}-${n.index}`)),e.finalText?me(qe,{marginTop:0,children:me(os,{content:e.finalText})}):null,e.status&&e.status!=="ok"?ve(oe,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?me(oe,{color:"red",children:e.errorMessage}):null]})}import{jsx as At,jsxs as wt}from"react/jsx-runtime";function cs(e){return e.sequence??0}function Cu(e){return e.type==="header"}function bu(e){return e.id!==void 0}var us=vu(function({header:t,systemMessages:n,turns:r,historicalTurns:o}){let s=tn(()=>[...o,...r],[o,r]),i=s.length>0?s[s.length-1]:void 0,a=i&&!!(i.finalText||i.status&&i.status!=="ok"),l=a?s:s.slice(0,-1),c=a?void 0:i,u=tn(()=>({type:"header",data:t}),[t]),p=tn(()=>{let m=[...n,...l];return m.sort((h,d)=>cs(h)-cs(d)),m},[l,n]),y=tn(()=>[u,...p],[u,p]);return wt(ls,{flexDirection:"column",children:[At(xu,{items:y,children:m=>Cu(m)?wt(ls,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[At(nn,{bold:!0,children:"Memo CLI"}),wt(nn,{color:"gray",children:[m.data.providerName," / ",m.data.model," \u2022 v",m.data.version]}),wt(nn,{color:"gray",children:["cwd: ",m.data.cwd]}),wt(nn,{color:"gray",children:["mcp: ",m.data.mcpNames.join(", ")||"none"]})]},`header-${m.data.sessionId}`):bu(m)?At(as,{message:m},m.id):At(er,{turn:m,cwd:t.cwd},`turn-${m.sequence??m.index}`)}),c?At(er,{turn:c,cwd:t.cwd}):null]})});import{useCallback as et,useEffect as dn,useMemo as Ns,useRef as Pt,useState as Ge}from"react";import{Box as rr,Text as mn,useInput as pp,useStdout as dp}from"ink";var dt=[8e4,12e4,15e4,2e5],ps=dt[1],$={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",MODELS:"models",CONTEXT:"context",TOOLS:"tools",MCP:"mcp",INIT:"init"},H={NONE:"none",ONCE:"once",FULL:"full"};function ge(e){return`/${e}`}var ds="exit";var rn=[{name:$.HELP,description:"Show command and shortcut help"},{name:$.EXIT,description:"Exit current session"},{name:$.NEW,description:"Start a fresh session"},{name:$.RESUME,description:"List and load session history"},{name:$.MODELS,description:"List or switch configured models"},{name:$.CONTEXT,description:"Set context window (80k/120k/150k/200k)"},{name:$.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:$.MCP,description:"Show configured MCP servers"},{name:$.INIT,description:"Generate AGENTS.md with agent instructions"}],Eu={none:H.NONE,off:H.NONE,disabled:H.NONE,"no-tools":H.NONE,once:H.ONCE,ask:H.ONCE,single:H.ONCE,strict:H.ONCE,full:H.FULL,all:H.FULL,dangerous:H.FULL,"full-access":H.FULL};function Au(e){if(!e)return null;let t=e.trim().toLowerCase();return t?Eu[t]??null:null}function ms(e){return e===H.NONE?"none (no tools)":e===H.ONCE?"once (approval required)":"full (no approval)"}function wu(){let e=rn.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...rn.map(n=>` ${ge(n.name).padEnd(e+3)} ${n.description}`)," exit Exit session (without slash)","","Shortcuts:"," Enter Send message"," Shift+Enter New line"," Up/Down Browse local input history"," Tab Accept active suggestion"," Ctrl+L Clear screen and start new session"," Esc Esc Interrupt running turn / clear input"].join(`
77
+ `)}function Mu(e){if(!e)return null;let n=e.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!n)return null;let r=Number(n[1]);return Number.isFinite(r)?r*(n[2]?1e3:1):null}function fs(e,t){let[n,...r]=e.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case $.HELP:return{kind:"message",title:"Help",content:wu()};case $.EXIT:return{kind:"exit"};case $.NEW:return{kind:"new"};case $.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case $.MODELS:{if(!t.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${t.configPath}`};let s=r.join(" ").trim(),i=t.providers.find(c=>c.name===s)??t.providers.find(c=>c.model===s);if(i)return{kind:"switch_model",provider:i};let a=t.providers.map(c=>{let u=c.name===t.providerName&&c.model===t.model?" (current)":"",p=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${p}${u}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
77
78
 
78
79
  `:""}${a.join(`
79
- `)}`}}case $.CONTEXT:{let s=yu(r[0]),i=dt.map(a=>`${Math.floor(a/1e3)}k`).join(", ");return s===null?{kind:"message",title:"Context",content:`Current: ${(t.contextLimit/1e3).toFixed(0)}k
80
+ `)}`}}case $.CONTEXT:{let s=Mu(r[0]),i=dt.map(a=>`${Math.floor(a/1e3)}k`).join(", ");return s===null?{kind:"message",title:"Context",content:`Current: ${(t.contextLimit/1e3).toFixed(0)}k
80
81
  Usage: ${ge($.CONTEXT)} <length>
81
- Choices: ${i}`}:dt.includes(s)?{kind:"set_context_limit",limit:s}:{kind:"message",title:"Context",content:`Unsupported value: ${s}. Choose one of ${i}`}}case $.TOOLS:{let s=r.join(" ").trim(),i=gu(s),a=["none","once","full"].join(", ");return s?i?i===t.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${ls(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
82
- Choose one of: ${a}`}:{kind:"message",title:"Tools",content:`Current: ${ls(t.toolPermissionMode)}
82
+ Choices: ${i}`}:dt.includes(s)?{kind:"set_context_limit",limit:s}:{kind:"message",title:"Context",content:`Unsupported value: ${s}. Choose one of ${i}`}}case $.TOOLS:{let s=r.join(" ").trim(),i=Au(s),a=["none","once","full"].join(", ");return s?i?i===t.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${ms(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
83
+ Choose one of: ${a}`}:{kind:"message",title:"Tools",content:`Current: ${ms(t.toolPermissionMode)}
83
84
  Usage: ${ge($.TOOLS)} <mode>
84
85
  Modes: ${a}`}}case $.MCP:{let s=Object.keys(t.mcpServers);if(!s.length)return{kind:"message",title:"MCP Servers",content:"No MCP servers configured in current config."};let i=[];i.push(`Total: ${s.length}`),i.push("");for(let[a,l]of Object.entries(t.mcpServers))i.push(`- ${a}`),"url"in l?(i.push(` type: ${l.type??"streamable_http"}`),i.push(` url: ${l.url}`),l.bearer_token_env_var&&i.push(` bearer: ${l.bearer_token_env_var}`)):(i.push(` type: ${l.type??"stdio"}`),i.push(` command: ${l.command}`),l.args?.length&&i.push(` args: ${l.args.join(" ")}`)),i.push("");return{kind:"message",title:"MCP Servers",content:i.join(`
85
86
  `)}}case $.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${e}
86
- Type ${ge($.HELP)} for available commands.`}}}import{readdir as Tu}from"fs/promises";import{join as _u,relative as Su,sep as vu}from"path";var xu=6,Cu=2500,us=25,bu=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),nn=new Map;function Au(e){return e.split(vu).join("/")}function Eu(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):xu,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):Cu,limit:typeof e.limit=="number"?Math.max(1,e.limit):us,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}function Mu(e,t){let n=e.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>bu.has(o))||r.endsWith(".log")?!0:t.ignoreGlobs.length?t.ignoreGlobs.some(o=>{let s=o.replace(/\\/g,"/").trim();if(!s)return!1;if(s.endsWith("/**")){let i=s.slice(0,-3);return e.startsWith(i)}if(s.startsWith("*")){let i=s.slice(1);return e.endsWith(i)}return e.includes(s)}):!1}function wu(e){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,ignoreGlobs:e.ignoreGlobs})}async function ku(e,t){let n=[],r=async(o,s)=>{if(n.length>=t.maxEntries)return;let i;try{i=await Tu(o,{withFileTypes:!0})}catch{return}for(let a of i){if(n.length>=t.maxEntries)break;if(a.isSymbolicLink())continue;let l=_u(o,a.name),c=Su(e,l);if(!c)continue;let u=Au(c);if(Mu(u,t))continue;let d=u.split("/").filter(Boolean),y=a.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:d,segmentsLower:d.map(p=>p.toLowerCase()),depth:s,isDir:y}),y&&s<t.maxDepth&&await r(l,s+1)}};return await r(e,0),n.sort((o,s)=>o.path.localeCompare(s.path)),n}async function Pu(e,t){let n=Eu(t),r=wu(n),o=nn.get(e);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=ku(e,n).then(i=>(nn.set(e,{entries:i,signature:r}),i)).catch(i=>{throw nn.delete(e),i});return nn.set(e,{entries:[],signature:r,pending:s}),s}function Iu(e,t){if(!t.length)return e.depth+(e.isDir?-.2:.2);let n=e.depth,r=0;for(let o of t){let s=-1;for(let i=r;i<e.segmentsLower.length;i++){let a=e.segmentsLower[i];if(a.startsWith(o)){s=i,n+=(i-r)*1.2,n+=a.length-o.length;break}let l=a.indexOf(o);if(l!==-1){s=i,n+=(i-r)*2+l+2;break}}if(s===-1)return null;r=s+1}return e.isDir&&(n-=.5),n}function Ru(e,t,n){let o=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of e){let a=Iu(i,o);a!==null&&s.push({entry:i,score:a})}return s.sort((i,a)=>{let l=i.score-a.score;return l!==0?l:i.entry.path.localeCompare(a.entry.path)}),s.slice(0,n).map(({entry:i})=>({id:i.path,path:i.path,name:i.segments[i.segments.length-1]??i.path,parent:i.segments.length>1?i.segments.slice(0,-1).join("/"):void 0,isDir:i.isDir}))}async function ps(e){let t=await Pu(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):us;return Ru(t,e.query,n)}import{readdir as Ou,readFile as Lu,stat as Nu}from"fs/promises";import{basename as $u,join as rn,resolve as kt}from"path";function ms(e){let t=kt(e);return process.platform==="win32"?t.toLowerCase():t}function Du(e,t){return t?ms(e)===ms(t):!1}function Uu(e){return $u(e).replace(/\.jsonl$/i,"")}function Hu(e){let t=null,n=null,r=null;for(let o of e.split(`
87
- `)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!(!i||typeof i!="object")){if(i.type==="session_start"&&!r){let a=i.meta?.cwd;typeof a=="string"&&a.trim()&&(r=a);continue}if(i.type==="turn_start"&&!t){let a=typeof i.content=="string"?i.content.trim():"";a&&(t=a)}if(i.type==="session_title"&&!n){let a=typeof i.content=="string"?i.content.trim():"";a&&(n=a)}}}return{firstPrompt:t,sessionTitle:n,sessionCwd:r}}async function Fu(e,t,n){try{let r=await Lu(e,"utf8"),{firstPrompt:o,sessionTitle:s,sessionCwd:i}=Hu(r);if(!Du(t,i))return null;let a=s?.trim()||o?.trim()||Uu(e);return{id:e,cwd:t,input:a,ts:n,sessionFile:e}}catch{return null}}async function Bu(e){let t=async s=>{try{return await Ou(s,{withFileTypes:!0})}catch{return[]}},n=(await t(e)).filter(s=>s.isDirectory()&&/^\d{4}$/.test(s.name)),r=[];for(let s of n){let i=rn(e,s.name),a=(await t(i)).filter(l=>l.isDirectory()&&/^\d{2}$/.test(l.name));for(let l of a){let c=rn(i,l.name),u=(await t(c)).filter(d=>d.isDirectory()&&/^\d{2}$/.test(d.name));for(let d of u){let y=rn(c,d.name),p=(await t(y)).filter(h=>h.isFile()&&h.name.endsWith(".jsonl"));for(let h of p)r.push(rn(y,h.name))}}}return(await Promise.all(r.map(async s=>{try{let i=await Nu(s);return{path:s,mtimeMs:i.mtimeMs}}catch{return null}}))).filter(s=>!!s)}async function ds(e){let t=e.activeSessionFile?kt(e.activeSessionFile):null,r=(await Bu(e.sessionsDir)).filter(a=>!t||kt(a.path)!==t).filter((a,l,c)=>c.findIndex(u=>kt(u.path)===kt(a.path))===l).sort((a,l)=>l.mtimeMs-a.mtimeMs),o=e.keyword?.trim().toLowerCase(),s=e.limit??10,i=[];for(let a of r){if(i.length>=s)break;let l=await Fu(a.path,e.cwd,a.mtimeMs);l&&(o&&!l.input.toLowerCase().includes(o)||i.push(l))}return i}import{Box as on,Text as sn}from"ink";import{jsx as Ze,jsxs as ju}from"react/jsx-runtime";var Wu="#3a3a3a",an="#262626";function fs({items:e,activeIndex:t,loading:n}){return n?Ze(on,{paddingX:1,backgroundColor:an,children:Ze(sn,{color:"gray",children:"Loading..."})}):e.length?Ze(on,{flexDirection:"column",backgroundColor:an,children:e.map((r,o)=>{let s=o===t;return ju(on,{paddingX:1,gap:2,backgroundColor:s?Wu:an,children:[Ze(sn,{color:s?"cyan":"white",bold:s,children:r.title}),r.subtitle?Ze(sn,{color:"gray",children:r.subtitle}):null]},r.id)})}):Ze(on,{paddingX:1,backgroundColor:an,children:Ze(sn,{color:"gray",children:"No matches"})})}import zu from"string-width";var qu=55296,Gu=56319,Ku=56320,Vu=57343;function gs(e){return e>=qu&&e<=Gu}function hs(e){return e>=Ku&&e<=Vu}function xe(e,t){if(!Number.isFinite(t)||t<=0)return 0;if(t>=e.length)return e.length;if(e.length===0)return 0;let n=Math.floor(t);if(n<=0)return 0;if(n>=e.length)return e.length;let r=e.charCodeAt(n),o=e.charCodeAt(n-1);return hs(r)&&gs(o)?n-1:n}function ys(e,t){let n=xe(e,t);if(n>=e.length)return e.length;let r=e.codePointAt(n);return r===void 0?Math.min(e.length,n+1):Math.min(e.length,n+(r>65535?2:1))}function Qe(e,t){let n=xe(e,t);if(n<=0)return 0;let r=n-1;if(r<=0)return r;let o=e.charCodeAt(r),s=e.charCodeAt(r-1);return hs(o)&&gs(s)?r-1:r}function ln(e,t){let n=xe(e,t),r=e.lastIndexOf(`
88
- `,Math.max(0,n-1));return r===-1?0:r+1}function cn(e,t){let n=xe(e,t),r=e.indexOf(`
89
- `,n);return r===-1?e.length:r}function Xu(e){return/[\p{L}\p{N}_]/u.test(e)}function Ts(e,t,n){let r=xe(e,t);return n?{value:`${e.slice(0,r)}${n}${e.slice(r)}`,cursor:r+n.length}:{value:e,cursor:r}}function _s(e,t){let n=xe(e,t);if(n<=0)return{value:e,cursor:n};let r=Qe(e,n);return{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function Zn(e,t){let n=xe(e,t);if(n>=e.length)return{value:e,cursor:n};let r=ys(e,n);return{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function Ss(e,t){let n=xe(e,t);if(n<=0)return{value:e,cursor:n};let r=n;for(;r>0;){let s=Qe(e,r);if(e.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=Qe(e,r),i=e.slice(s,r);if(!Xu(i))break;r=s}return r===n&&(r=Qe(e,n)),{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function vs(e,t){let n=xe(e,t),r=ln(e,n);return r>=n?{value:e,cursor:n}:{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function xs(e,t){let n=xe(e,t),r=cn(e,n);return r<=n?{value:e,cursor:n}:{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function Cs(e,t){return Qe(e,t)}function bs(e,t){return ys(e,t)}function As(e,t){return ln(e,t)}function Es(e,t){return cn(e,t)}function Qn(e,t,n,r){let o=xe(e,t),s=ln(e,o),i=cn(e,o),a=o-s,l=r??a;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:l,changed:!1};let y=s-1,p=ln(e,y),h=Math.min(p+l,y);return{cursor:h,preferredColumn:l,changed:h!==o}}if(i>=e.length)return{cursor:o,preferredColumn:l,changed:!1};let c=i+1,u=cn(e,c),d=Math.min(c+l,u);return{cursor:d,preferredColumn:l,changed:d!==o}}function Ms(e,t,n){let r=xe(e,t),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,a=0,l="",c=0,u=()=>{s.push({text:l,start:i,end:a})},d=0;for(let h of e){let m=d;if(d+=h.length,h===`
90
- `){a=m,u(),i=d,a=d,l="",c=0;continue}let k=Math.max(0,zu(h));l.length>0&&c+k>o&&(u(),i=m,a=m,l="",c=0),l+=h,a=d,c+=k}if(u(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let y=Math.max(0,s.length-1),p=(s[y]?.text??"").length;for(let h=0;h<s.length;h+=1){let m=s[h];if(m&&!(r<m.start)&&r<=m.end){y=h,p=r-m.start;break}}return{lines:s,row:y,cursorInRow:p}}function ws(e,t){let n=e==="\b"||e==="\x7F",r=!!t.ctrl&&e.toLowerCase()==="h";return t.backspace||n||r||t.delete&&!(t.ctrl||t.meta)?"backspace":t.delete?"delete":"none"}var Ju=3,ks=8,Yu=120,Zu=process.platform==="win32"?60:8,Pt=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(t={}){this.minChars=t.minChars??Ju,this.charIntervalMs=t.charIntervalMs??ks,this.enterSuppressWindowMs=t.enterSuppressWindowMs??Yu,this.activeIdleTimeoutMs=t.activeIdleTimeoutMs??Zu}static recommendedFlushDelayMs(){return ks+1}recommendedActiveFlushDelayMs(){return this.activeIdleTimeoutMs+1}onPlainChar(t,n){let r=Array.from(t)[0]??"";return this.notePlainChar(n),this.active?(this.extendWindow(n),{type:"buffer_append"}):this.pendingFirstChar&&n-this.pendingFirstChar.atMs<=this.charIntervalMs?(this.active=!0,this.buffer+=this.pendingFirstChar.ch,this.pendingFirstChar=null,this.extendWindow(n),{type:"begin_buffer_from_pending"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:r?(this.pendingFirstChar={ch:r,atMs:n},{type:"retain_first_char"}):{type:"retain_first_char"}}onPlainCharNoHold(t){return this.notePlainChar(t),this.active?(this.extendWindow(t),{type:"buffer_append"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:null}flushIfDue(t){let n=this.isActiveInternal()?this.activeIdleTimeoutMs:this.charIntervalMs;if(!(this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs>n))return{type:"none"};if(this.isActiveInternal()){this.active=!1;let o=this.buffer;return this.buffer="",{type:"paste",text:o}}if(this.pendingFirstChar){let o=this.pendingFirstChar.ch;return this.pendingFirstChar=null,{type:"typed",text:o}}return{type:"none"}}appendNewlineIfActive(t){return this.isActiveInternal()?(this.buffer+=`
91
- `,this.extendWindow(t),!0):!1}newlineShouldInsertInsteadOfSubmit(t){let n=this.burstWindowUntilMs!==null&&t<=this.burstWindowUntilMs;return this.isActiveInternal()||n}extendWindow(t){this.burstWindowUntilMs=t+this.enterSuppressWindowMs}beginWithRetroGrabbed(t,n){t&&(this.buffer+=t),this.active=!0,this.extendWindow(n)}appendCharToBuffer(t,n){t&&(this.buffer+=t,this.extendWindow(n))}decideBeginBuffer(t,n,r){let o=Qu(n,r),s=n.slice(o);return/\s/u.test(s)||Array.from(s).length>=16?(this.beginWithRetroGrabbed(s,t),{start:o,grabbed:s}):null}flushBeforeModifiedInput(){if(!this.isActive())return null;this.active=!1;let t=this.buffer;return this.buffer="",this.pendingFirstChar&&(t+=this.pendingFirstChar.ch,this.pendingFirstChar=null),t}clearWindowAfterNonChar(){this.consecutivePlainChars=0,this.lastPlainCharAtMs=null,this.burstWindowUntilMs=null,this.active=!1,this.pendingFirstChar=null}isActive(){return this.isActiveInternal()||this.pendingFirstChar!==null}isBuffering(){return this.isActiveInternal()}hasPendingFirstChar(){return this.pendingFirstChar!==null}clearAfterExplicitPaste(){this.lastPlainCharAtMs=null,this.consecutivePlainChars=0,this.burstWindowUntilMs=null,this.active=!1,this.buffer="",this.pendingFirstChar=null}notePlainChar(t){this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs<=this.charIntervalMs?this.consecutivePlainChars+=1:this.consecutivePlainChars=1,this.lastPlainCharAtMs=t}isActiveInternal(){return this.active||this.buffer.length>0}};function Qu(e,t){if(t<=0)return e.length;let n=e.length,r=t;for(;r>0&&n>0;)n=Qe(e,n),r-=1;return n}import{jsx as ft,jsxs as Is}from"react/jsx-runtime";var np=400,tr=ge($.MODELS),nr=ge($.CONTEXT),rr=ge($.TOOLS),rp=ge($.INIT),op=[{mode:H.NONE,description:"Disable all tool calls"},{mode:H.ONCE,description:"Require approval when needed"},{mode:H.FULL,description:"Run tools without approval"}];function sp(e){let t=e.lastIndexOf("@");if(t===-1)return null;if(t>0){let r=e[t-1];if(r&&!/\s/.test(r))return null}let n=e.slice(t+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:t+1}}function ip(e){let t=e.trimStart(),n=e.length-t.length;if(!t.length)return null;let r=t;if(r.startsWith("/")&&(r=r.slice(1)),!r.toLowerCase().startsWith($.RESUME)||e.slice(0,n).trim().length>0)return null;let s=r.slice($.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function ap(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1);return n.includes(" ")?null:n.length?/^[a-zA-Z-]+$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:null:{type:"slash",keyword:""}}function lp(e){let t=e.trimStart();if(!t.startsWith(tr))return null;let n=t.slice(tr.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function cp(e){let t=e.trimStart();if(!t.startsWith(nr))return null;let n=t.slice(nr.length);return n&&!n.startsWith(" ")?null:{type:"context"}}function up(e){let t=e.trimStart();if(!t.startsWith(rr))return null;let n=t.slice(rr.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function pp(e){return up(e)??cp(e)??lp(e)??ap(e)??sp(e)??ip(e)}function mp(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getFullYear()),r=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${s}:${i}`}function dp(e,t){return{mode:"model",items:e.filter(r=>{if(!t)return!0;let o=r.name.toLowerCase(),s=r.model.toLowerCase();return o.includes(t)||s.includes(t)}).map(r=>({id:r.name,title:`${r.name}: ${r.model}`,subtitle:r.base_url,kind:"model",value:`${tr} ${r.name}`,meta:{type:"model",provider:r}}))}}function fp(e){return{mode:"context",items:dt.map(n=>({id:`${n}`,title:`${Math.floor(n/1e3)}k tokens`,subtitle:n===e?"Current":void 0,kind:"context",value:`${nr} ${Math.floor(n/1e3)}k`,meta:{type:"context",value:n}}))}}function gp(e){return{mode:"tools",items:op.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===e?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${rr} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function hp(e){return{mode:"slash",items:tn.filter(n=>n.name.startsWith(e)).map(n=>({id:n.name,title:`/${n.name}`,subtitle:n.description,kind:"slash",value:`/${n.name}`,meta:{type:"slash"}}))}}async function yp({trigger:e,cwd:t,sessionsDir:n,currentSessionFile:r,providers:o,contextLimit:s,toolPermissionMode:i}){switch(e.type){case"file":return{mode:"file",items:(await ps({cwd:t,query:e.query,limit:8})).map(c=>({id:c.id,title:c.isDir?`${c.path}/`:c.path,kind:"file",value:c.isDir?`${c.path}/`:c.path,meta:{type:"file",isDir:c.isDir}}))};case"history":return{mode:"history",items:(await ds({sessionsDir:n,cwd:t,keyword:e.keyword,activeSessionFile:r})).map(c=>({id:c.id,title:c.input,subtitle:mp(c.ts),kind:"history",value:c.input,meta:{type:"history",entry:c}}))};case"models":return dp(o,e.keyword);case"context":return fp(s);case"tools":return gp(i);case"slash":return hp(e.keyword)}}function Rs({disabled:e,busy:t,history:n,cwd:r,sessionsDir:o,currentSessionFile:s,providers:i,configPath:a,providerName:l,model:c,contextLimit:u,toolPermissionMode:d,mcpServers:y,onSubmit:p,onExit:h,onClear:m,onNewSession:k,onCancelRun:v,onHistorySelect:S,onModelSelect:W,onSetContextLimit:ee,onSetToolPermission:q,onSystemMessage:V}){let{stdout:he}=tp(),[A,F]=Ge({value:"",cursor:0}),E=It(A),P=It(null),[ue,Me]=Ge(null),[te,M]=Ge(""),[R,ne]=Ge("none"),[se,Be]=Ge([]),[we,pe]=Ge(0),[ke,Xe]=Ge(!1),[Le,w]=Ge(!1),Y=It(0),nt=It(0),G=It(new Pt);un(()=>{E.current=A,w(!1)},[A]);let yn=Ps(()=>({configPath:a,providerName:l,model:c,mcpServers:y,providers:i,contextLimit:u,toolPermissionMode:d}),[a,l,c,y,i,u,d]),j=Ps(()=>e||Le?null:pp(A.value),[e,A.value,Le]),z=et((T=!0)=>{T&&w(!0),ne("none"),Be([]),pe(0),Xe(!1)},[]),O=et((T,x=!1)=>{E.current=T,F(T),x&&(Me(null),M(""))},[]),Pe=et(()=>{O({value:"",cursor:0},!0)},[O]),ie=et((T,x=!0)=>{if(!T)return;let U=E.current;P.current=null;let Z=Ts(U.value,U.cursor,T);O(Z,x),T.includes(`
92
- `)&&z(!1)},[O,z]),K=et(T=>T.type==="none"?!1:T.type==="paste"?(T.text&&ie(T.text,!0),!0):(ie(T.text,!0),!0),[ie]),Ce=et((T=!0)=>{let x=G.current.flushBeforeModifiedInput();return x&&ie(x,!0),T&&G.current.clearWindowAfterNonChar(),!!x},[ie]);un(()=>{let T=setInterval(()=>{let x=G.current.flushIfDue(Date.now());K(x)},Pt.recommendedFlushDelayMs());return()=>{clearInterval(T)}},[K]),un(()=>{e&&z(!1)},[e,z]),un(()=>{if(!j){z(!1);return}let T=!1,x=++Y.current;return Xe(!0),(async()=>{try{let{mode:U,items:Z}=await yp({trigger:j,cwd:r,sessionsDir:o,currentSessionFile:s,providers:i,contextLimit:u,toolPermissionMode:d});if(T||x!==Y.current)return;ne(U),Be(Z),pe(ye=>Z.length?Math.min(ye,Z.length-1):0)}finally{!T&&x===Y.current&&Xe(!1)}})(),()=>{T=!0}},[j,r,o,s,i,u,d,z]);let We=et(T=>{if(T){if(R==="file"&&j?.type==="file"){let x=E.current.value,U=x.slice(0,j.tokenStart),Z=x.slice(j.tokenStart+j.query.length),ye=`${U}${T.value}${Z}`,Ie=U.length+T.value.length;O({value:ye,cursor:Ie},!0),T.meta?.type==="file"&&T.meta.isDir||z();return}switch(T.meta?.type){case"history":S(T.meta.entry),O({value:T.value,cursor:T.value.length},!1),z();return;case"model":W(T.meta.provider),Pe(),z();return;case"context":ee(T.meta.value),Pe(),z();return;case"tools":q(T.meta.mode),Pe(),z();return;case"slash":O({value:`${T.value} `,cursor:`${T.value} `.length},!0),z(!1);return;default:O({value:T.value,cursor:T.value.length},!0),z()}}},[O,R,j,z,Pe,S,W,ee,q]);ep((T,x)=>{if(x.ctrl&&T==="c"){h();return}if(e)return;let U=Date.now();K(G.current.flushIfDue(U));let Z=R!=="none",ye=Z&&se.length>0,Ie=ws(T,x),Tn=!!(x.ctrl||x.meta),rt=!!T&&!Tn&&!x.return&&!x.tab&&Ie==="none"&&!x.escape&&!x.upArrow&&!x.downArrow&&!x.leftArrow&&!x.rightArrow;if(!rt&&!x.return&&Ce(!0),x.ctrl&&T==="a"){let C=E.current,L=As(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.ctrl&&T==="e"){let C=E.current,L=Es(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.ctrl&&T==="u"){let C=E.current,L=vs(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="k"){let C=E.current,L=xs(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="w"){let C=E.current,L=Ss(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="d"){let C=E.current;if(!C.value){h();return}let L=Zn(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="l"){O({value:"",cursor:0},!0),z(),m(),k();return}if(x.escape){if(U-nt.current<=np){nt.current=0,t?v():(P.current=null,O({value:"",cursor:0},!0),z());return}nt.current=U,Z&&z();return}if(x.upArrow){if(ye){pe(D=>D<=0?se.length-1:D-1);return}let C=E.current;if(C.value.includes(`
93
- `)){let D=Qn(C.value,C.cursor,"up",P.current??void 0);if(D.changed){P.current=D.preferredColumn,O({value:C.value,cursor:D.cursor},!1);return}}if(!n.length)return;if(ue===null){M(C.value);let D=n.length-1;Me(D);let Re=n[D]??"";P.current=null,O({value:Re,cursor:Re.length},!1);return}let L=Math.max(0,ue-1);Me(L);let ae=n[L]??"";P.current=null,O({value:ae,cursor:ae.length},!1);return}if(x.downArrow){if(ye){pe(D=>(D+1)%se.length);return}let C=E.current;if(C.value.includes(`
94
- `)){let D=Qn(C.value,C.cursor,"down",P.current??void 0);if(D.changed){P.current=D.preferredColumn,O({value:C.value,cursor:D.cursor},!1);return}}if(ue===null)return;let L=ue+1;if(L>=n.length){Me(null),P.current=null,O({value:te,cursor:te.length},!1),M("");return}Me(L);let ae=n[L]??"";P.current=null,O({value:ae,cursor:ae.length},!1);return}if(x.leftArrow){let C=E.current,L=Cs(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.rightArrow){let C=E.current,L=bs(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.tab&&ye){We(se[we]);return}if(x.return){if(ye){We(se[we]);return}G.current.hasPendingFirstChar()&&!G.current.isBuffering()&&Ce(!1);let C=E.current.value.trimStart().startsWith("/");if(!x.shift&&!C){if(G.current.appendNewlineIfActive(U))return;if(G.current.newlineShouldInsertInsteadOfSubmit(U)){Ce(!1),ie(`
87
+ Type ${ge($.HELP)} for available commands.`}}}import{readdir as ku}from"fs/promises";import{join as Pu,relative as Iu,sep as Ru}from"path";var Ou=6,Lu=2500,gs=25,Nu=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),on=new Map;function $u(e){return e.split(Ru).join("/")}function Du(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):Ou,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):Lu,limit:typeof e.limit=="number"?Math.max(1,e.limit):gs,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}function Uu(e,t){let n=e.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>Nu.has(o))||r.endsWith(".log")?!0:t.ignoreGlobs.length?t.ignoreGlobs.some(o=>{let s=o.replace(/\\/g,"/").trim();if(!s)return!1;if(s.endsWith("/**")){let i=s.slice(0,-3);return e.startsWith(i)}if(s.startsWith("*")){let i=s.slice(1);return e.endsWith(i)}return e.includes(s)}):!1}function Hu(e){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,ignoreGlobs:e.ignoreGlobs})}async function Fu(e,t){let n=[],r=async(o,s)=>{if(n.length>=t.maxEntries)return;let i;try{i=await ku(o,{withFileTypes:!0})}catch{return}for(let a of i){if(n.length>=t.maxEntries)break;if(a.isSymbolicLink())continue;let l=Pu(o,a.name),c=Iu(e,l);if(!c)continue;let u=$u(c);if(Uu(u,t))continue;let p=u.split("/").filter(Boolean),y=a.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:p,segmentsLower:p.map(m=>m.toLowerCase()),depth:s,isDir:y}),y&&s<t.maxDepth&&await r(l,s+1)}};return await r(e,0),n.sort((o,s)=>o.path.localeCompare(s.path)),n}async function Bu(e,t){let n=Du(t),r=Hu(n),o=on.get(e);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=Fu(e,n).then(i=>(on.set(e,{entries:i,signature:r}),i)).catch(i=>{throw on.delete(e),i});return on.set(e,{entries:[],signature:r,pending:s}),s}function Wu(e,t){if(!t.length)return e.depth+(e.isDir?-.2:.2);let n=e.depth,r=0;for(let o of t){let s=-1;for(let i=r;i<e.segmentsLower.length;i++){let a=e.segmentsLower[i];if(a.startsWith(o)){s=i,n+=(i-r)*1.2,n+=a.length-o.length;break}let l=a.indexOf(o);if(l!==-1){s=i,n+=(i-r)*2+l+2;break}}if(s===-1)return null;r=s+1}return e.isDir&&(n-=.5),n}function ju(e,t,n){let o=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of e){let a=Wu(i,o);a!==null&&s.push({entry:i,score:a})}return s.sort((i,a)=>{let l=i.score-a.score;return l!==0?l:i.entry.path.localeCompare(a.entry.path)}),s.slice(0,n).map(({entry:i})=>({id:i.path,path:i.path,name:i.segments[i.segments.length-1]??i.path,parent:i.segments.length>1?i.segments.slice(0,-1).join("/"):void 0,isDir:i.isDir}))}async function hs(e){let t=await Bu(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):gs;return ju(t,e.query,n)}import{readdir as zu,readFile as qu,stat as Gu}from"fs/promises";import{basename as Ku,join as sn,resolve as Mt}from"path";function ys(e){let t=Mt(e);return process.platform==="win32"?t.toLowerCase():t}function Vu(e,t){return t?ys(e)===ys(t):!1}function Xu(e){return Ku(e).replace(/\.jsonl$/i,"")}function Ju(e){let t=null,n=null,r=null;for(let o of e.split(`
88
+ `)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!(!i||typeof i!="object")){if(i.type==="session_start"&&!r){let a=i.meta?.cwd;typeof a=="string"&&a.trim()&&(r=a);continue}if(i.type==="turn_start"&&!t){let a=typeof i.content=="string"?i.content.trim():"";a&&(t=a)}if(i.type==="session_title"&&!n){let a=typeof i.content=="string"?i.content.trim():"";a&&(n=a)}}}return{firstPrompt:t,sessionTitle:n,sessionCwd:r}}async function Yu(e,t,n){try{let r=await qu(e,"utf8"),{firstPrompt:o,sessionTitle:s,sessionCwd:i}=Ju(r);if(!Vu(t,i))return null;let a=s?.trim()||o?.trim()||Xu(e);return{id:e,cwd:t,input:a,ts:n,sessionFile:e}}catch{return null}}async function Zu(e){let t=async s=>{try{return await zu(s,{withFileTypes:!0})}catch{return[]}},n=(await t(e)).filter(s=>s.isDirectory()&&/^\d{4}$/.test(s.name)),r=[];for(let s of n){let i=sn(e,s.name),a=(await t(i)).filter(l=>l.isDirectory()&&/^\d{2}$/.test(l.name));for(let l of a){let c=sn(i,l.name),u=(await t(c)).filter(p=>p.isDirectory()&&/^\d{2}$/.test(p.name));for(let p of u){let y=sn(c,p.name),m=(await t(y)).filter(h=>h.isFile()&&h.name.endsWith(".jsonl"));for(let h of m)r.push(sn(y,h.name))}}}return(await Promise.all(r.map(async s=>{try{let i=await Gu(s);return{path:s,mtimeMs:i.mtimeMs}}catch{return null}}))).filter(s=>!!s)}async function Ts(e){let t=e.activeSessionFile?Mt(e.activeSessionFile):null,r=(await Zu(e.sessionsDir)).filter(a=>!t||Mt(a.path)!==t).filter((a,l,c)=>c.findIndex(u=>Mt(u.path)===Mt(a.path))===l).sort((a,l)=>l.mtimeMs-a.mtimeMs),o=e.keyword?.trim().toLowerCase(),s=e.limit??10,i=[];for(let a of r){if(i.length>=s)break;let l=await Yu(a.path,e.cwd,a.mtimeMs);l&&(o&&!l.input.toLowerCase().includes(o)||i.push(l))}return i}import{Box as an,Text as ln}from"ink";import{jsx as Ze,jsxs as ep}from"react/jsx-runtime";var Qu="#3a3a3a",cn="#262626";function _s({items:e,activeIndex:t,loading:n}){return n?Ze(an,{paddingX:1,backgroundColor:cn,children:Ze(ln,{color:"gray",children:"Loading..."})}):e.length?Ze(an,{flexDirection:"column",backgroundColor:cn,children:e.map((r,o)=>{let s=o===t;return ep(an,{paddingX:1,gap:2,backgroundColor:s?Qu:cn,children:[Ze(ln,{color:s?"cyan":"white",bold:s,children:r.title}),r.subtitle?Ze(ln,{color:"gray",children:r.subtitle}):null]},r.id)})}):Ze(an,{paddingX:1,backgroundColor:cn,children:Ze(ln,{color:"gray",children:"No matches"})})}import tp from"string-width";var np=55296,rp=56319,op=56320,sp=57343;function Ss(e){return e>=np&&e<=rp}function vs(e){return e>=op&&e<=sp}function xe(e,t){if(!Number.isFinite(t)||t<=0)return 0;if(t>=e.length)return e.length;if(e.length===0)return 0;let n=Math.floor(t);if(n<=0)return 0;if(n>=e.length)return e.length;let r=e.charCodeAt(n),o=e.charCodeAt(n-1);return vs(r)&&Ss(o)?n-1:n}function xs(e,t){let n=xe(e,t);if(n>=e.length)return e.length;let r=e.codePointAt(n);return r===void 0?Math.min(e.length,n+1):Math.min(e.length,n+(r>65535?2:1))}function Qe(e,t){let n=xe(e,t);if(n<=0)return 0;let r=n-1;if(r<=0)return r;let o=e.charCodeAt(r),s=e.charCodeAt(r-1);return vs(o)&&Ss(s)?r-1:r}function un(e,t){let n=xe(e,t),r=e.lastIndexOf(`
89
+ `,Math.max(0,n-1));return r===-1?0:r+1}function pn(e,t){let n=xe(e,t),r=e.indexOf(`
90
+ `,n);return r===-1?e.length:r}function ip(e){return/[\p{L}\p{N}_]/u.test(e)}function Cs(e,t,n){let r=xe(e,t);return n?{value:`${e.slice(0,r)}${n}${e.slice(r)}`,cursor:r+n.length}:{value:e,cursor:r}}function bs(e,t){let n=xe(e,t);if(n<=0)return{value:e,cursor:n};let r=Qe(e,n);return{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function tr(e,t){let n=xe(e,t);if(n>=e.length)return{value:e,cursor:n};let r=xs(e,n);return{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function Es(e,t){let n=xe(e,t);if(n<=0)return{value:e,cursor:n};let r=n;for(;r>0;){let s=Qe(e,r);if(e.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=Qe(e,r),i=e.slice(s,r);if(!ip(i))break;r=s}return r===n&&(r=Qe(e,n)),{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function As(e,t){let n=xe(e,t),r=un(e,n);return r>=n?{value:e,cursor:n}:{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function ws(e,t){let n=xe(e,t),r=pn(e,n);return r<=n?{value:e,cursor:n}:{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function Ms(e,t){return Qe(e,t)}function ks(e,t){return xs(e,t)}function Ps(e,t){return un(e,t)}function Is(e,t){return pn(e,t)}function nr(e,t,n,r){let o=xe(e,t),s=un(e,o),i=pn(e,o),a=o-s,l=r??a;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:l,changed:!1};let y=s-1,m=un(e,y),h=Math.min(m+l,y);return{cursor:h,preferredColumn:l,changed:h!==o}}if(i>=e.length)return{cursor:o,preferredColumn:l,changed:!1};let c=i+1,u=pn(e,c),p=Math.min(c+l,u);return{cursor:p,preferredColumn:l,changed:p!==o}}function Rs(e,t,n){let r=xe(e,t),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,a=0,l="",c=0,u=()=>{s.push({text:l,start:i,end:a})},p=0;for(let h of e){let d=p;if(p+=h.length,h===`
91
+ `){a=d,u(),i=p,a=p,l="",c=0;continue}let E=Math.max(0,tp(h));l.length>0&&c+E>o&&(u(),i=d,a=d,l="",c=0),l+=h,a=p,c+=E}if(u(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let y=Math.max(0,s.length-1),m=(s[y]?.text??"").length;for(let h=0;h<s.length;h+=1){let d=s[h];if(d&&!(r<d.start)&&r<=d.end){y=h,m=r-d.start;break}}return{lines:s,row:y,cursorInRow:m}}function Os(e,t){let n=e==="\b"||e==="\x7F",r=!!t.ctrl&&e.toLowerCase()==="h";return t.backspace||n||r||t.delete&&!(t.ctrl||t.meta)?"backspace":t.delete?"delete":"none"}var ap=3,Ls=8,lp=120,cp=process.platform==="win32"?60:8,kt=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(t={}){this.minChars=t.minChars??ap,this.charIntervalMs=t.charIntervalMs??Ls,this.enterSuppressWindowMs=t.enterSuppressWindowMs??lp,this.activeIdleTimeoutMs=t.activeIdleTimeoutMs??cp}static recommendedFlushDelayMs(){return Ls+1}recommendedActiveFlushDelayMs(){return this.activeIdleTimeoutMs+1}onPlainChar(t,n){let r=Array.from(t)[0]??"";return this.notePlainChar(n),this.active?(this.extendWindow(n),{type:"buffer_append"}):this.pendingFirstChar&&n-this.pendingFirstChar.atMs<=this.charIntervalMs?(this.active=!0,this.buffer+=this.pendingFirstChar.ch,this.pendingFirstChar=null,this.extendWindow(n),{type:"begin_buffer_from_pending"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:r?(this.pendingFirstChar={ch:r,atMs:n},{type:"retain_first_char"}):{type:"retain_first_char"}}onPlainCharNoHold(t){return this.notePlainChar(t),this.active?(this.extendWindow(t),{type:"buffer_append"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:null}flushIfDue(t){let n=this.isActiveInternal()?this.activeIdleTimeoutMs:this.charIntervalMs;if(!(this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs>n))return{type:"none"};if(this.isActiveInternal()){this.active=!1;let o=this.buffer;return this.buffer="",{type:"paste",text:o}}if(this.pendingFirstChar){let o=this.pendingFirstChar.ch;return this.pendingFirstChar=null,{type:"typed",text:o}}return{type:"none"}}appendNewlineIfActive(t){return this.isActiveInternal()?(this.buffer+=`
92
+ `,this.extendWindow(t),!0):!1}newlineShouldInsertInsteadOfSubmit(t){let n=this.burstWindowUntilMs!==null&&t<=this.burstWindowUntilMs;return this.isActiveInternal()||n}extendWindow(t){this.burstWindowUntilMs=t+this.enterSuppressWindowMs}beginWithRetroGrabbed(t,n){t&&(this.buffer+=t),this.active=!0,this.extendWindow(n)}appendCharToBuffer(t,n){t&&(this.buffer+=t,this.extendWindow(n))}decideBeginBuffer(t,n,r){let o=up(n,r),s=n.slice(o);return/\s/u.test(s)||Array.from(s).length>=16?(this.beginWithRetroGrabbed(s,t),{start:o,grabbed:s}):null}flushBeforeModifiedInput(){if(!this.isActive())return null;this.active=!1;let t=this.buffer;return this.buffer="",this.pendingFirstChar&&(t+=this.pendingFirstChar.ch,this.pendingFirstChar=null),t}clearWindowAfterNonChar(){this.consecutivePlainChars=0,this.lastPlainCharAtMs=null,this.burstWindowUntilMs=null,this.active=!1,this.pendingFirstChar=null}isActive(){return this.isActiveInternal()||this.pendingFirstChar!==null}isBuffering(){return this.isActiveInternal()}hasPendingFirstChar(){return this.pendingFirstChar!==null}clearAfterExplicitPaste(){this.lastPlainCharAtMs=null,this.consecutivePlainChars=0,this.burstWindowUntilMs=null,this.active=!1,this.buffer="",this.pendingFirstChar=null}notePlainChar(t){this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs<=this.charIntervalMs?this.consecutivePlainChars+=1:this.consecutivePlainChars=1,this.lastPlainCharAtMs=t}isActiveInternal(){return this.active||this.buffer.length>0}};function up(e,t){if(t<=0)return e.length;let n=e.length,r=t;for(;r>0&&n>0;)n=Qe(e,n),r-=1;return n}import{jsx as mt,jsxs as $s}from"react/jsx-runtime";var mp=400,or=ge($.MODELS),sr=ge($.CONTEXT),ir=ge($.TOOLS),fp=ge($.INIT),gp=[{mode:H.NONE,description:"Disable all tool calls"},{mode:H.ONCE,description:"Require approval when needed"},{mode:H.FULL,description:"Run tools without approval"}];function hp(e){let t=e.lastIndexOf("@");if(t===-1)return null;if(t>0){let r=e[t-1];if(r&&!/\s/.test(r))return null}let n=e.slice(t+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:t+1}}function yp(e){let t=e.trimStart(),n=e.length-t.length;if(!t.length)return null;let r=t;if(r.startsWith("/")&&(r=r.slice(1)),!r.toLowerCase().startsWith($.RESUME)||e.slice(0,n).trim().length>0)return null;let s=r.slice($.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function Tp(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1);return n.includes(" ")?null:n.length?/^[a-zA-Z-]+$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:null:{type:"slash",keyword:""}}function _p(e){let t=e.trimStart();if(!t.startsWith(or))return null;let n=t.slice(or.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function Sp(e){let t=e.trimStart();if(!t.startsWith(sr))return null;let n=t.slice(sr.length);return n&&!n.startsWith(" ")?null:{type:"context"}}function vp(e){let t=e.trimStart();if(!t.startsWith(ir))return null;let n=t.slice(ir.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function xp(e){return vp(e)??Sp(e)??_p(e)??Tp(e)??hp(e)??yp(e)}function Cp(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getFullYear()),r=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${s}:${i}`}function bp(e,t){return{mode:"model",items:e.filter(r=>{if(!t)return!0;let o=r.name.toLowerCase(),s=r.model.toLowerCase();return o.includes(t)||s.includes(t)}).map(r=>({id:r.name,title:`${r.name}: ${r.model}`,subtitle:r.base_url,kind:"model",value:`${or} ${r.name}`,meta:{type:"model",provider:r}}))}}function Ep(e){return{mode:"context",items:dt.map(n=>({id:`${n}`,title:`${Math.floor(n/1e3)}k tokens`,subtitle:n===e?"Current":void 0,kind:"context",value:`${sr} ${Math.floor(n/1e3)}k`,meta:{type:"context",value:n}}))}}function Ap(e){return{mode:"tools",items:gp.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===e?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${ir} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function wp(e){return{mode:"slash",items:rn.filter(n=>n.name.startsWith(e)).map(n=>({id:n.name,title:`/${n.name}`,subtitle:n.description,kind:"slash",value:`/${n.name}`,meta:{type:"slash"}}))}}async function Mp({trigger:e,cwd:t,sessionsDir:n,currentSessionFile:r,providers:o,contextLimit:s,toolPermissionMode:i}){switch(e.type){case"file":return{mode:"file",items:(await hs({cwd:t,query:e.query,limit:8})).map(c=>({id:c.id,title:c.isDir?`${c.path}/`:c.path,kind:"file",value:c.isDir?`${c.path}/`:c.path,meta:{type:"file",isDir:c.isDir}}))};case"history":return{mode:"history",items:(await Ts({sessionsDir:n,cwd:t,keyword:e.keyword,activeSessionFile:r})).map(c=>({id:c.id,title:c.input,subtitle:Cp(c.ts),kind:"history",value:c.input,meta:{type:"history",entry:c}}))};case"models":return bp(o,e.keyword);case"context":return Ep(s);case"tools":return Ap(i);case"slash":return wp(e.keyword)}}function Ds({disabled:e,busy:t,history:n,cwd:r,sessionsDir:o,currentSessionFile:s,providers:i,configPath:a,providerName:l,model:c,contextLimit:u,toolPermissionMode:p,mcpServers:y,onSubmit:m,onExit:h,onClear:d,onNewSession:E,onCancelRun:v,onHistorySelect:S,onModelSelect:W,onSetContextLimit:ee,onSetToolPermission:q,onSystemMessage:V}){let{stdout:he}=dp(),[A,F]=Ge({value:"",cursor:0}),w=Pt(A),P=Pt(null),[ue,we]=Ge(null),[te,M]=Ge(""),[R,ne]=Ge("none"),[se,Be]=Ge([]),[Me,pe]=Ge(0),[ke,Xe]=Ge(!1),[Le,k]=Ge(!1),Y=Pt(0),nt=Pt(0),G=Pt(new kt);dn(()=>{w.current=A,k(!1)},[A]);let _n=Ns(()=>({configPath:a,providerName:l,model:c,mcpServers:y,providers:i,contextLimit:u,toolPermissionMode:p}),[a,l,c,y,i,u,p]),j=Ns(()=>e||Le?null:xp(A.value),[e,A.value,Le]),z=et((T=!0)=>{T&&k(!0),ne("none"),Be([]),pe(0),Xe(!1)},[]),O=et((T,x=!1)=>{w.current=T,F(T),x&&(we(null),M(""))},[]),Pe=et(()=>{O({value:"",cursor:0},!0)},[O]),ie=et((T,x=!0)=>{if(!T)return;let U=w.current;P.current=null;let Z=Cs(U.value,U.cursor,T);O(Z,x),T.includes(`
93
+ `)&&z(!1)},[O,z]),K=et(T=>T.type==="none"?!1:T.type==="paste"?(T.text&&ie(T.text,!0),!0):(ie(T.text,!0),!0),[ie]),Ce=et((T=!0)=>{let x=G.current.flushBeforeModifiedInput();return x&&ie(x,!0),T&&G.current.clearWindowAfterNonChar(),!!x},[ie]);dn(()=>{let T=setInterval(()=>{let x=G.current.flushIfDue(Date.now());K(x)},kt.recommendedFlushDelayMs());return()=>{clearInterval(T)}},[K]),dn(()=>{e&&z(!1)},[e,z]),dn(()=>{if(!j){z(!1);return}let T=!1,x=++Y.current;return Xe(!0),(async()=>{try{let{mode:U,items:Z}=await Mp({trigger:j,cwd:r,sessionsDir:o,currentSessionFile:s,providers:i,contextLimit:u,toolPermissionMode:p});if(T||x!==Y.current)return;ne(U),Be(Z),pe(ye=>Z.length?Math.min(ye,Z.length-1):0)}finally{!T&&x===Y.current&&Xe(!1)}})(),()=>{T=!0}},[j,r,o,s,i,u,p,z]);let We=et(T=>{if(T){if(R==="file"&&j?.type==="file"){let x=w.current.value,U=x.slice(0,j.tokenStart),Z=x.slice(j.tokenStart+j.query.length),ye=`${U}${T.value}${Z}`,Ie=U.length+T.value.length;O({value:ye,cursor:Ie},!0),T.meta?.type==="file"&&T.meta.isDir||z();return}switch(T.meta?.type){case"history":S(T.meta.entry),O({value:T.value,cursor:T.value.length},!1),z();return;case"model":W(T.meta.provider),Pe(),z();return;case"context":ee(T.meta.value),Pe(),z();return;case"tools":q(T.meta.mode),Pe(),z();return;case"slash":O({value:`${T.value} `,cursor:`${T.value} `.length},!0),z(!1);return;default:O({value:T.value,cursor:T.value.length},!0),z()}}},[O,R,j,z,Pe,S,W,ee,q]);pp((T,x)=>{if(x.ctrl&&T==="c"){h();return}if(e)return;let U=Date.now();K(G.current.flushIfDue(U));let Z=R!=="none",ye=Z&&se.length>0,Ie=Os(T,x),Sn=!!(x.ctrl||x.meta),rt=!!T&&!Sn&&!x.return&&!x.tab&&Ie==="none"&&!x.escape&&!x.upArrow&&!x.downArrow&&!x.leftArrow&&!x.rightArrow;if(!rt&&!x.return&&Ce(!0),x.ctrl&&T==="a"){let C=w.current,L=Ps(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.ctrl&&T==="e"){let C=w.current,L=Is(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.ctrl&&T==="u"){let C=w.current,L=As(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="k"){let C=w.current,L=ws(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="w"){let C=w.current,L=Es(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="d"){let C=w.current;if(!C.value){h();return}let L=tr(C.value,C.cursor);P.current=null,O(L,!0);return}if(x.ctrl&&T==="l"){O({value:"",cursor:0},!0),z(),d(),E();return}if(x.escape){if(U-nt.current<=mp){nt.current=0,t?v():(P.current=null,O({value:"",cursor:0},!0),z());return}nt.current=U,Z&&z();return}if(x.upArrow){if(ye){pe(D=>D<=0?se.length-1:D-1);return}let C=w.current;if(C.value.includes(`
94
+ `)){let D=nr(C.value,C.cursor,"up",P.current??void 0);if(D.changed){P.current=D.preferredColumn,O({value:C.value,cursor:D.cursor},!1);return}}if(!n.length)return;if(ue===null){M(C.value);let D=n.length-1;we(D);let Re=n[D]??"";P.current=null,O({value:Re,cursor:Re.length},!1);return}let L=Math.max(0,ue-1);we(L);let ae=n[L]??"";P.current=null,O({value:ae,cursor:ae.length},!1);return}if(x.downArrow){if(ye){pe(D=>(D+1)%se.length);return}let C=w.current;if(C.value.includes(`
95
+ `)){let D=nr(C.value,C.cursor,"down",P.current??void 0);if(D.changed){P.current=D.preferredColumn,O({value:C.value,cursor:D.cursor},!1);return}}if(ue===null)return;let L=ue+1;if(L>=n.length){we(null),P.current=null,O({value:te,cursor:te.length},!1),M("");return}we(L);let ae=n[L]??"";P.current=null,O({value:ae,cursor:ae.length},!1);return}if(x.leftArrow){let C=w.current,L=Ms(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.rightArrow){let C=w.current,L=ks(C.value,C.cursor);P.current=null,O({value:C.value,cursor:L},!1);return}if(x.tab&&ye){We(se[Me]);return}if(x.return){if(ye){We(se[Me]);return}G.current.hasPendingFirstChar()&&!G.current.isBuffering()&&Ce(!1);let C=w.current.value.trimStart().startsWith("/");if(!x.shift&&!C){if(G.current.appendNewlineIfActive(U))return;if(G.current.newlineShouldInsertInsteadOfSubmit(U)){Ce(!1),ie(`
95
96
  `,!0),G.current.extendWindow(U);return}}if(Ce(!0),x.shift){ie(`
96
- `,!0);return}let ae=E.current.value.trim();if(!ae)return;if(ae.startsWith("/")){let D=cs(ae,yn);D.kind==="message"?V(D.title,D.content):D.kind==="new"?k():D.kind==="exit"?h():D.kind==="switch_model"?W(D.provider):D.kind==="set_context_limit"?ee(D.limit):D.kind==="set_tool_permission"?q(D.mode):D.kind==="init_agents_md"&&p(rp),P.current=null,O({value:"",cursor:0},!0),z(!1);return}p(ae),P.current=null,O({value:"",cursor:0},!0),z(!1);return}if(Ie!=="none"){let C=E.current,L=Ie==="backspace"?_s(C.value,C.cursor):Zn(C.value,C.cursor);P.current=null,O(L,!0);return}if(T&&rt){let C=Array.from(T);if(C.length!==1){Ce(!1),ie(T,!0),G.current.clearAfterExplicitPaste();return}let L=C[0]??"";if(!L)return;let ae=je=>{let ot=E.current,Ft=ot.value.slice(0,ot.cursor),_n=ot.value.slice(ot.cursor),yt=G.current.decideBeginBuffer(U,Ft,je);return yt?(P.current=null,O({value:`${Ft.slice(0,yt.start)}${_n}`,cursor:yt.start},!0),G.current.appendCharToBuffer(L,U),!0):!1};if(!((L.codePointAt(0)??0)<=127)){let je=G.current.onPlainCharNoHold(U);if(je?.type==="buffer_append"){G.current.appendCharToBuffer(L,U);return}if(je?.type==="begin_buffer"&&ae(je.retroChars))return;Ce(!1),ie(L,!0);return}let Re=G.current.onPlainChar(L,U);if(Re.type==="retain_first_char")return;if(Re.type==="buffer_append"||Re.type==="begin_buffer_from_pending"){G.current.appendCharToBuffer(L,U);return}if(Re.type==="begin_buffer"&&ae(Re.retroChars))return;Ce(!1),ie(L,!0);return}T&&(ie(T,!0),G.current.clearWindowAfterNonChar())});let Ut=he?.columns??process.stdout?.columns??80,X=Math.max(1,Ut-3),b=Ms(A.value,A.cursor,X),Ht=b.lines;return Is(er,{flexDirection:"column",gap:1,children:[ft(er,{flexDirection:"column",paddingY:1,children:Ht.map((T,x)=>{let U=T.text,Z=!e&&x===b.row,ye=Z?U.slice(0,b.cursorInRow):U,Ie=Z?U.slice(b.cursorInRow):"";return Is(er,{children:[ft(pn,{color:"gray",children:x===0?"\u203A ":" "}),ft(pn,{children:ye}),Z?ft(pn,{color:"cyan",children:"\u258A"}):null,Z?ft(pn,{children:Ie}):null]},`line-${x}`)})}),R!=="none"?ft(fs,{items:se.map(({value:T,meta:x,...U})=>U),activeIndex:we,loading:ke}):null]})}import{Box as Tp,Text as Os}from"ink";import{jsx as _p,jsxs as Ls}from"react/jsx-runtime";function Ns({busy:e,pendingApproval:t=!1,contextPercent:n,tokenLine:r}){let o=`${n.toFixed(1)}%`;return Ls(Tp,{justifyContent:"space-between",children:[_p(Os,{color:"gray",children:t?"Approval pending \u2022 \u2191/\u2193 select \u2022 Enter confirm \u2022 Esc deny":e?"Working... Esc Esc to interrupt":"Enter send \u2022 Shift+Enter newline \u2022 /help"}),Ls(Os,{color:"gray",children:[r?`${r} \u2022 `:"","context: ",o]})]})}import{useState as Sp}from"react";import{Box as $s,Text as mn,useInput as vp}from"ink";import{jsx as or,jsxs as sr}from"react/jsx-runtime";var xp=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function Cp(e){if(!e)return"";if(typeof e!="object")return String(e);let t=Object.entries(e);if(!t.length)return"";let[n,r]=t[0]??[];if(!n)return"";let o=typeof r=="string"?r:JSON.stringify(r);return`${n}=${o?.slice(0,60)??""}${o&&o.length>60?"...":""}`}function Ds({request:e,onDecision:t}){let[n,r]=Sp(0),o=xp;vp((i,a)=>{if(a.upArrow){r(l=>l<=0?o.length-1:l-1);return}if(a.downArrow){r(l=>(l+1)%o.length);return}if(a.return){let l=o[n];l&&t(l.decision);return}(a.escape||a.ctrl&&i==="c")&&t("deny")});let s=Cp(e.params);return sr($s,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[or(mn,{bold:!0,color:"yellow",children:"Tool Approval Required"}),sr(mn,{children:[e.toolName,s?` (${s})`:""]}),or(mn,{color:"gray",children:e.reason}),or($s,{marginTop:1,flexDirection:"column",children:o.map((i,a)=>sr(mn,{color:n===a?"green":"gray",children:[n===a?"> ":" ",i.label]},i.decision))})]})}import{useMemo as Us,useState as ir}from"react";import{Box as ar,Text as gt,useInput as bp}from"ink";import{jsx as dn,jsxs as Rt}from"react/jsx-runtime";function Ap(e,t){let n=new Set(e);return t.filter(r=>n.has(r))}function Hs({serverNames:e,defaultSelected:t,onConfirm:n,onExit:r}){let o=Us(()=>{let p=Ap(e,t);return t.length===0?[]:p.length>0?p:[...e]},[t,e]),[s,i]=ir(o),[a,l]=ir(0),[c,u]=ir(!0),d=Us(()=>new Set(s),[s]),y=s.length===e.length;return bp((p,h)=>{if(h.ctrl&&p==="c"){r();return}if(h.upArrow){l(m=>m<=0?e.length-1:m-1);return}if(h.downArrow){l(m=>(m+1)%e.length);return}if(h.return){n(s,c);return}if(p===" "){let m=e[a];if(!m)return;i(k=>{let v=new Set(k);return v.has(m)?v.delete(m):v.add(m),e.filter(S=>v.has(S))});return}if(p.toLowerCase()==="a"){i([...e]);return}if(p.toLowerCase()==="n"){i([]);return}if(p.toLowerCase()==="p"){u(m=>!m);return}h.escape&&n(s,c)}),Rt(ar,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[dn(gt,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),dn(gt,{color:"gray",children:"Select servers to load for this run."}),dn(ar,{marginTop:1,flexDirection:"column",children:e.map((p,h)=>{let m=d.has(p);return Rt(gt,{color:h===a?"green":"gray",children:[h===a?"> ":" ","[",m?"x":" ","] ",p]},p)})}),Rt(ar,{marginTop:1,flexDirection:"column",children:[Rt(gt,{color:"gray",children:["Selected: ",s.length,"/",e.length,y?" (all)":""]}),Rt(gt,{color:"gray",children:["Persist as default: ",c?"yes":"no"]}),dn(gt,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, A all, N none, P persist, Enter confirm"})]})]})}import{spawn as Ep}from"child_process";var lr="\x07",Mp="Memo: Approval required",wp="Memo CLI",kp=2e3;function Pp(e){return e.replace(/\s+/g," ").trim()}function Ip(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function Rp(e){let t=Pp(e.reason),n=`Tool ${e.toolName} is waiting for your approval.`;return t?Ip(`${n} ${t}`,220):n}function Fs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Op(e,t=process.platform){let n=Mp,r=Rp(e);return t==="darwin"?{command:"osascript",args:["-e",`display notification "${Fs(r)}" with title "${Fs(n)}"`]}:t==="linux"?{command:"notify-send",args:["--app-name",wp,n,r]}:null}async function Lp(e,t){await new Promise((n,r)=>{let o=Ep(e,t,{stdio:"ignore"}),s=!1,i=l=>{if(!s){if(s=!0,l){r(l);return}n()}},a=setTimeout(()=>{try{o.kill()}catch{}i()},kp);o.once("error",l=>{clearTimeout(a),i(l)}),o.once("exit",l=>{if(clearTimeout(a),l===0||l===null){i();return}i(new Error(`${e} exited with code ${l}`))})})}function Np(e){if(e){e(lr);return}try{if(process.stdout?.isTTY){process.stdout.write(lr);return}process.stderr?.isTTY&&process.stderr.write(lr)}catch{}}async function Bs(e,t={}){Np(t.writeBell);let n=Op(e,t.platform??process.platform);if(!n)return;let r=t.runCommand??Lp;try{await r(n.command,n.args)}catch{}}import{Box as Ot,Text as Ee,useInput as $p}from"ink";import{useCallback as Ws,useMemo as Dp,useState as Lt}from"react";import{jsx as Oe,jsxs as ht}from"react/jsx-runtime";var Ke=[{key:"name",label:"Provider name",hint:"Used for /models switching",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Read at runtime from environment variables",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",defaultValue:"https://api.deepseek.com"}];function js({configPath:e,onComplete:t,onExit:n}){let[r,o]=Lt(0),[s,i]=Lt(""),[a,l]=Lt({}),[c,u]=Lt(!1),[d,y]=Lt(null),p=Ke[r]??Ke[0],h=Ws(async v=>{u(!0),y(null);try{let S={current_provider:v.name,providers:[{name:v.name,env_api_key:v.envKey,model:v.model,base_url:v.baseUrl||void 0}]};await Se(e,S),t()}catch(S){y(S.message),u(!1)}},[e,t]),m=Ws(async()=>{if(!p)return;let v=s.trim()||p.defaultValue,S={...a,[p.key]:v};if(l(S),i(""),r<Ke.length-1){o(r+1);return}let W={name:S.name||Ke[0].defaultValue,envKey:S.envKey||Ke[1].defaultValue,model:S.model||Ke[2].defaultValue,baseUrl:S.baseUrl||Ke[3].defaultValue};await h(W)},[s,h,p,r,a]);$p((v,S)=>{if(!c){if(S.ctrl&&v==="c"){n();return}if(S.return){m();return}if(S.backspace||S.delete){i(W=>W.slice(0,-1));return}v&&i(W=>W+v)}});let k=Dp(()=>`Step ${r+1}/${Ke.length}`,[r]);return p?ht(Ot,{flexDirection:"column",children:[Oe(Ee,{bold:!0,children:"Memo setup"}),Oe(Ee,{color:"gray",children:"No provider config found. Complete setup to continue."}),ht(Ee,{color:"gray",children:["Config path: ",e]}),ht(Ot,{marginTop:1,flexDirection:"column",children:[Oe(Ee,{color:"cyan",children:k}),Oe(Ee,{children:p.label}),ht(Ee,{color:"gray",children:["Default: ",p.defaultValue]}),p.hint?Oe(Ee,{color:"gray",children:p.hint}):null]}),ht(Ot,{marginTop:1,children:[Oe(Ee,{children:"> "}),Oe(Ee,{children:s})]}),Oe(Ot,{marginTop:1,children:Oe(Ee,{color:"gray",children:"Enter to continue, Ctrl+C to exit."})}),d?Oe(Ot,{marginTop:1,children:ht(Ee,{color:"red",children:["Failed to save config: ",d]})}):null]}):null}function zs(e){let t=[],n=[],r=[],o=e.split(`
97
- `).map(l=>l.trim()).filter(Boolean),s=null,i=0,a=0;for(let l of o){let c;try{c=JSON.parse(l)}catch{continue}if(!(!c||typeof c!="object")){if(c.type==="turn_start"){let u=typeof c.content=="string"?c.content:"";s={index:-(i+1),userInput:u,steps:[],status:"ok",sequence:a+=1},n.push(s),u&&(t.push({role:"user",content:u}),r.push(`User: ${u}`)),i+=1;continue}if(c.type==="assistant"){let u=typeof c.content=="string"?c.content:"";if(u&&(t.push({role:"assistant",content:u}),r.push(`Assistant: ${u}`),s)){let d={index:s.steps.length,assistantText:u};s.steps=[...s.steps,d],s.finalText=u}continue}if(c.type==="action"&&s){let u=c.meta;if(u&&typeof u=="object"){let d=typeof u.tool=="string"?u.tool:"",y=u.input,p=typeof u.thinking=="string"?u.thinking:"",m=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(v=>{let S=typeof v?.name=="string"?v.name:"";return S?{tool:S,input:v?.input}:null}).filter(Boolean),k=s.steps[s.steps.length-1];k&&(m.length>1?(k.action=m[0],k.parallelActions=m):d&&(k.action={tool:d,input:y}),p&&(k.thinking=p))}continue}if(c.type==="observation"&&s){let u=typeof c.content=="string"?c.content:"",d=s.steps[s.steps.length-1];d&&(d.observation=u);continue}}}return{summary:r.join(`
98
- `),messages:t,turns:n,maxSequence:a}}function ur(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function Up(e,t){return{index:e,userInput:"",steps:[],sequence:t}}function cr(e,t){let n=e.slice();for(;n.length<=t;)n.push({index:n.length,assistantText:""});return n}function Nt(e,t,n){let r=e.turns.slice(),o=r.findIndex(i=>i.index===t);if(o===-1){let i=e.sequence+1;return r.push(n(Up(t,i))),{turns:r,sequence:i}}let s=r[o];return s?(r[o]=n(s),{turns:r,sequence:e.sequence}):{turns:r,sequence:e.sequence}}function Hp(e){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:e.title,content:e.content,tone:e.tone??"info",sequence:e.sequence}}function qs(e,t){switch(t.type){case"append_system_message":{let n=e.sequence+1;return{...e,sequence:n,systemMessages:[...e.systemMessages,Hp({title:t.title,content:t.content,tone:t.tone,sequence:n})]}}case"turn_start":{let n=Nt(e,t.turn,r=>({...r,index:t.turn,userInput:t.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:t.promptTokens??r.contextPromptTokens}));return{...e,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Nt(e,t.turn,r=>{let o=cr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,assistantText:`${s.assistantText}${t.chunk}`},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Nt(e,t.turn,r=>{let o=cr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,action:t.action,thinking:t.thinking,parallelActions:t.parallelActions&&t.parallelActions.length>1?t.parallelActions:void 0,toolStatus:Fe.EXECUTING},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Nt(e,t.turn,r=>{let o=cr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,observation:t.observation,toolStatus:t.toolStatus,parallelToolStatuses:t.parallelToolStatuses},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=Nt(e,t.turn,r=>{let o=r.startedAt??Date.now(),s=Math.max(0,Date.now()-o),i=t.tokenUsage?.prompt??r.contextPromptTokens;return{...r,finalText:t.finalText,status:t.status,errorMessage:t.errorMessage,tokenUsage:t.turnUsage,contextPromptTokens:i,startedAt:o,durationMs:s}});return{...e,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...e,historicalTurns:t.turns,sequence:Math.max(e.sequence,t.maxSequence)};case"clear_current_timeline":return{...e,turns:[],systemMessages:[]};case"reset_all":return ur();default:return e}}import{dirname as fn,join as Ks,resolve as Fp}from"path";import{statSync as Bp,existsSync as Vs,readFileSync as Wp}from"fs";import{readFile as jp}from"fs/promises";import{get as zp}from"https";import{fileURLToPath as qp}from"url";function Gs(e){let t=e.trim().replace(/^v/i,""),[n="",r]=t.split("-",2),o=n.split(".").map(s=>Number(s));return o.length<3||o.some(s=>!Number.isFinite(s))?null:{major:o[0]??0,minor:o[1]??0,patch:o[2]??0,prerelease:r??null}}function Gp(e,t){let n=Gs(e),r=Gs(t);return!n||!r?!1:n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch!==r.patch?n.patch>r.patch:n.prerelease&&!r.prerelease?!1:!n.prerelease&&r.prerelease?!0:n.prerelease&&r.prerelease?n.prerelease>r.prerelease:!1}function Xs(){try{let t=qp(import.meta.url);return fn(t)}catch{}let e=Fp(process.argv[1]??process.cwd());try{return Bp(e).isFile()?fn(e):e}catch{return process.cwd()}}async function Kp(e){let t=Ks(e,"package.json");if(!Vs(t))return null;let n=await jp(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function Vp(e){let t=Ks(e,"package.json");if(!Vs(t))return null;try{let n=Wp(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function Xp(){let e=Xs();for(;;){let t=await Kp(e);if(t&&t.name==="@memo-code/memo")return t;let n=fn(e);if(n===e)break;e=n}return null}function gn(){let e=Xs();for(;;){let t=Vp(e);if(t&&t.name==="@memo-code/memo")return t;let n=fn(e);if(n===e)break;e=n}return null}async function Jp(e,t=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(o=>{let s=zp(r,{timeout:t},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));o(l.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function Js(){let e=await Xp();if(!e)return null;let t=await Jp(e.name);return!t||!Gp(t,e.version)?null:{current:e.version,latest:t}}import{jsx as Ve,jsxs as om}from"react/jsx-runtime";function tm(e,t){if(e.length===0)return[];if(t===void 0)return[...e];if(t.length===0)return[];let n=new Set(e),r=t.filter(o=>n.has(o));return r.length>0?r:[...e]}function nm(e,t){if(e.length===0)return[];if(t.length===0)return[];let n=new Set(e);return t.filter(r=>n.has(r))}function rm(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function Zs({sessionOptions:e,providerName:t,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:u}=em(),d=Dt(()=>Object.keys(o??{}).sort(),[o]),y=Dt(()=>tm(d,e.activeMcpServers),[d,e.activeMcpServers]),p=e.toolPermissionMode??(l?H.FULL:H.ONCE),[h,m]=Zp(qs,void 0,ur),[k,v]=re(t),[S,W]=re(n),[ee,q]=re(a),[V,he]=re(p),[A,F]=re({...e,providerName:t,dangerous:p===H.FULL,toolPermissionMode:p}),[E,P]=re(!1),[ue,Me]=re([]),[te,M]=re(null),[R,ne]=re(null),[se,Be]=re(e.maxPromptTokens??is),[we,pe]=re(0),[ke,Xe]=re(c),[Le,w]=re(!c&&d.length>0),[Y,nt]=re(y),[G,yn]=re(null),[j,z]=re(null),O=hn(null),Pe=hn(null),ie=hn(null),[K,Ce]=re(null),We=hn(null),Ut=Dt(()=>gn(),[]),X=J(g=>{m(g)},[]);$t(()=>{ke||(nt(y),w(d.length>0))},[ke,y,d.length]);let b=J((g,_,I="info")=>{X({type:"append_system_message",title:g,content:_,tone:I})},[X]),Ht=Dt(()=>({onAssistantStep:(g,_)=>{let I=Pe.current;I&&X({type:"assistant_chunk",turn:I,step:_,chunk:g})},requestApproval:V===H.FULL||V===H.NONE?void 0:g=>new Promise(_=>{Bs(g),Ce(g),We.current=_}),hooks:{onTurnStart:({turn:g,input:_,promptTokens:I})=>{Pe.current=g;let Te=ie.current;Te&&(ie.current=null);let Je=Te??_;I&&I>0&&pe(I),X({type:"turn_start",turn:g,input:Je,promptTokens:I})},onAction:({turn:g,step:_,action:I,thinking:Te,parallelActions:Je})=>{X({type:"tool_action",turn:g,step:_,action:I,thinking:Te,parallelActions:Je})},onObservation:({turn:g,step:_,observation:I,resultStatus:Te,parallelResultStatuses:Je})=>{X({type:"tool_observation",turn:g,step:_,observation:I,toolStatus:Vn(Te),parallelToolStatuses:qo(Je)})},onFinal:({turn:g,finalText:_,status:I,errorMessage:Te,turnUsage:Je,tokenUsage:si})=>{X({type:"turn_final",turn:g,finalText:_,status:I,errorMessage:Te,turnUsage:Je,tokenUsage:si}),P(!1)}}}),[X,V]);$t(()=>{let g=!1;return(async()=>{if(!(ke||Le))try{let _=O.current;_&&await _.close();let I=await Zt(Ht,A);if(g){await I.close();return}O.current=I,z(I),M(I.historyFilePath??null)}catch(_){if(g)return;O.current=null,z(null),M(null),P(!1),b("Session",`Failed to create session: ${_.message}`,"error")}})(),()=>{g=!0}},[b,Ht,Le,A,ke]),$t(()=>{let g=!1;return(async()=>{let _=await Js();g||!_||b("Update",`Update available: v${_.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{g=!0}},[b]),$t(()=>()=>{O.current&&O.current.close()},[]);let T=J(async()=>{let g=We.current;g&&(g("deny"),We.current=null),K&&Ce(null),O.current&&await O.current.close(),yn("Bye!"),setTimeout(()=>u(),250)},[u,K]),x=J(()=>{if(E){b("Clear","Cancel current run before clearing timeline.","warning");return}if(K){b("Clear","Resolve current approval request before clearing timeline.","warning");return}X({type:"clear_current_timeline"}),ne(null),pe(0),rm()},[b,E,X,K]),U=J(()=>{if(E){b("New Session","Cancel current run before starting a new session.","warning");return}if(K){b("New Session","Resolve current approval request before starting a new session.","warning");return}X({type:"reset_all"}),ne(null),pe(0),Pe.current=null,F(g=>({...g,sessionId:tt()})),b("New Session","Started a fresh session.")},[b,E,X,K]),Z=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,current_provider:g})}catch(_){b("Config",`Failed to persist provider: ${_.message}`,"warning")}},[b]),ye=J(async g=>{if(E){b("Model switch","Cancel current run before switching models.","warning");return}if(g.name===k&&g.model===S){b("Model switch",`Already using ${g.name} (${g.model}).`);return}X({type:"reset_all"}),pe(0),Pe.current=null,v(g.name),W(g.model),F(_=>({..._,sessionId:tt(),providerName:g.name})),await Z(g.name),b("Model switch",`Switched to ${g.name} (${g.model}).`)},[b,E,S,k,X,Z]),Ie=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,max_prompt_tokens:g})}catch(_){b("Context",`Failed to persist context limit: ${_.message}`,"warning")}},[b]),Tn=J(g=>{if(E){b("Context","Cancel current run before changing context window.","warning");return}if(K){b("Context","Resolve current approval request before changing context window.","warning");return}Be(g),pe(0),F(_=>({..._,maxPromptTokens:g,sessionId:tt()})),b("Context",`Context window set to ${Math.floor(g/1e3)}k.`),Ie(g)},[b,E,K,Ie]),rt=J(g=>g===H.NONE?"none (no tools)":g===H.ONCE?"once (approval required)":"full (no approval)",[]),C=J(g=>{if(E){b("Tools","Cancel current run before changing tool permission mode.","warning");return}if(K){b("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(g===V){b("Tools",`Already using ${rt(g)}.`);return}he(g),F(_=>({..._,sessionId:tt(),dangerous:g===H.FULL,toolPermissionMode:g})),b("Tools",`Tool permission set to ${rt(g)}.`)},[b,E,K,rt,V]),L=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,active_mcp_servers:g})}catch(_){b("MCP",`Failed to persist active MCP servers: ${_.message}`,"warning")}},[b]),ae=J((g,_)=>{let I=nm(d,g);nt(I),w(!1),F(Te=>({...Te,sessionId:tt(),activeMcpServers:I})),_&&L(I)},[d,L]),D=J(async g=>{if(E){b("History","Cancel current run before loading session history.","warning");return}if(K){b("History","Resolve current approval request before loading session history.","warning");return}try{let _=await Yp(g.sessionFile,"utf8"),I=zs(_);X({type:"clear_current_timeline"}),X({type:"replace_history",turns:I.turns,maxSequence:I.maxSequence}),ne(I.messages),P(!1),z(null),M(null),pe(0),Pe.current=null,F(Te=>({...Te,sessionId:tt()})),b("History",I.summary||g.input)}catch(_){b("History",`Failed to load ${g.sessionFile}: ${_.message}`,"error")}},[b,E,X,K]),Re=J(()=>{E&&j?.cancelCurrentTurn?.()},[E,j]),je=J(async()=>{if(!j||E)return;let g=`Please analyze the current project and create an AGENTS.md file at the project root.
97
+ `,!0);return}let ae=w.current.value.trim();if(!ae)return;if(ae.startsWith("/")){let D=fs(ae,_n);D.kind==="message"?V(D.title,D.content):D.kind==="new"?E():D.kind==="exit"?h():D.kind==="switch_model"?W(D.provider):D.kind==="set_context_limit"?ee(D.limit):D.kind==="set_tool_permission"?q(D.mode):D.kind==="init_agents_md"&&m(fp),P.current=null,O({value:"",cursor:0},!0),z(!1);return}m(ae),P.current=null,O({value:"",cursor:0},!0),z(!1);return}if(Ie!=="none"){let C=w.current,L=Ie==="backspace"?bs(C.value,C.cursor):tr(C.value,C.cursor);P.current=null,O(L,!0);return}if(T&&rt){let C=Array.from(T);if(C.length!==1){Ce(!1),ie(T,!0),G.current.clearAfterExplicitPaste();return}let L=C[0]??"";if(!L)return;let ae=je=>{let ot=w.current,Ht=ot.value.slice(0,ot.cursor),vn=ot.value.slice(ot.cursor),ht=G.current.decideBeginBuffer(U,Ht,je);return ht?(P.current=null,O({value:`${Ht.slice(0,ht.start)}${vn}`,cursor:ht.start},!0),G.current.appendCharToBuffer(L,U),!0):!1};if(!((L.codePointAt(0)??0)<=127)){let je=G.current.onPlainCharNoHold(U);if(je?.type==="buffer_append"){G.current.appendCharToBuffer(L,U);return}if(je?.type==="begin_buffer"&&ae(je.retroChars))return;Ce(!1),ie(L,!0);return}let Re=G.current.onPlainChar(L,U);if(Re.type==="retain_first_char")return;if(Re.type==="buffer_append"||Re.type==="begin_buffer_from_pending"){G.current.appendCharToBuffer(L,U);return}if(Re.type==="begin_buffer"&&ae(Re.retroChars))return;Ce(!1),ie(L,!0);return}T&&(ie(T,!0),G.current.clearWindowAfterNonChar())});let Dt=he?.columns??process.stdout?.columns??80,X=Math.max(1,Dt-3),b=Rs(A.value,A.cursor,X),Ut=b.lines;return $s(rr,{flexDirection:"column",gap:1,children:[mt(rr,{flexDirection:"column",paddingY:1,children:Ut.map((T,x)=>{let U=T.text,Z=!e&&x===b.row,ye=Z?U.slice(0,b.cursorInRow):U,Ie=Z?U.slice(b.cursorInRow):"";return $s(rr,{children:[mt(mn,{color:"gray",children:x===0?"\u203A ":" "}),mt(mn,{children:ye}),Z?mt(mn,{color:"cyan",children:"\u258A"}):null,Z?mt(mn,{children:Ie}):null]},`line-${x}`)})}),R!=="none"?mt(_s,{items:se.map(({value:T,meta:x,...U})=>U),activeIndex:Me,loading:ke}):null]})}import{Box as kp,Text as Us}from"ink";import{jsx as Pp,jsxs as Hs}from"react/jsx-runtime";function Fs({busy:e,pendingApproval:t=!1,contextPercent:n,tokenLine:r}){let o=`${n.toFixed(1)}%`;return Hs(kp,{justifyContent:"space-between",children:[Pp(Us,{color:"gray",children:t?"Approval pending \u2022 \u2191/\u2193 select \u2022 Enter confirm \u2022 Esc deny":e?"Working... Esc Esc to interrupt":"Enter send \u2022 Shift+Enter newline \u2022 /help"}),Hs(Us,{color:"gray",children:[r?`${r} \u2022 `:"","context: ",o]})]})}import{useState as Ip}from"react";import{Box as Bs,Text as fn,useInput as Rp}from"ink";import{jsx as ar,jsxs as lr}from"react/jsx-runtime";var Op=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function Lp(e){if(!e)return"";if(typeof e!="object")return String(e);let t=Object.entries(e);if(!t.length)return"";let[n,r]=t[0]??[];if(!n)return"";let o=typeof r=="string"?r:JSON.stringify(r);return`${n}=${o?.slice(0,60)??""}${o&&o.length>60?"...":""}`}function Ws({request:e,onDecision:t}){let[n,r]=Ip(0),o=Op;Rp((i,a)=>{if(a.upArrow){r(l=>l<=0?o.length-1:l-1);return}if(a.downArrow){r(l=>(l+1)%o.length);return}if(a.return){let l=o[n];l&&t(l.decision);return}(a.escape||a.ctrl&&i==="c")&&t("deny")});let s=Lp(e.params);return lr(Bs,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[ar(fn,{bold:!0,color:"yellow",children:"Tool Approval Required"}),lr(fn,{children:[e.toolName,s?` (${s})`:""]}),ar(fn,{color:"gray",children:e.reason}),ar(Bs,{marginTop:1,flexDirection:"column",children:o.map((i,a)=>lr(fn,{color:n===a?"green":"gray",children:[n===a?"> ":" ",i.label]},i.decision))})]})}import{useMemo as js,useState as cr}from"react";import{Box as ur,Text as ft,useInput as Np}from"ink";import{jsx as gn,jsxs as It}from"react/jsx-runtime";function $p(e,t){let n=new Set(e);return t.filter(r=>n.has(r))}function zs({serverNames:e,defaultSelected:t,onConfirm:n,onExit:r}){let o=js(()=>{let m=$p(e,t);return t.length===0?[]:m.length>0?m:[...e]},[t,e]),[s,i]=cr(o),[a,l]=cr(0),[c,u]=cr(!0),p=js(()=>new Set(s),[s]),y=s.length===e.length;return Np((m,h)=>{if(h.ctrl&&m==="c"){r();return}if(h.upArrow){l(d=>d<=0?e.length-1:d-1);return}if(h.downArrow){l(d=>(d+1)%e.length);return}if(h.return){n(s,c);return}if(m===" "){let d=e[a];if(!d)return;i(E=>{let v=new Set(E);return v.has(d)?v.delete(d):v.add(d),e.filter(S=>v.has(S))});return}if(m.toLowerCase()==="a"){i([...e]);return}if(m.toLowerCase()==="n"){i([]);return}if(m.toLowerCase()==="p"){u(d=>!d);return}h.escape&&n(s,c)}),It(ur,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[gn(ft,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),gn(ft,{color:"gray",children:"Select servers to load for this run."}),gn(ur,{marginTop:1,flexDirection:"column",children:e.map((m,h)=>{let d=p.has(m);return It(ft,{color:h===a?"green":"gray",children:[h===a?"> ":" ","[",d?"x":" ","] ",m]},m)})}),It(ur,{marginTop:1,flexDirection:"column",children:[It(ft,{color:"gray",children:["Selected: ",s.length,"/",e.length,y?" (all)":""]}),It(ft,{color:"gray",children:["Persist as default: ",c?"yes":"no"]}),gn(ft,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, A all, N none, P persist, Enter confirm"})]})]})}import{spawn as Dp}from"child_process";var pr="\x07",Up="Memo: Approval required",Hp="Memo CLI",Fp=2e3;function Bp(e){return e.replace(/\s+/g," ").trim()}function Wp(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function jp(e){let t=Bp(e.reason),n=`Tool ${e.toolName} is waiting for your approval.`;return t?Wp(`${n} ${t}`,220):n}function qs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function zp(e,t=process.platform){let n=Up,r=jp(e);return t==="darwin"?{command:"osascript",args:["-e",`display notification "${qs(r)}" with title "${qs(n)}"`]}:t==="linux"?{command:"notify-send",args:["--app-name",Hp,n,r]}:null}async function qp(e,t){await new Promise((n,r)=>{let o=Dp(e,t,{stdio:"ignore"}),s=!1,i=l=>{if(!s){if(s=!0,l){r(l);return}n()}},a=setTimeout(()=>{try{o.kill()}catch{}i()},Fp);o.once("error",l=>{clearTimeout(a),i(l)}),o.once("exit",l=>{if(clearTimeout(a),l===0||l===null){i();return}i(new Error(`${e} exited with code ${l}`))})})}function Gp(e){if(e){e(pr);return}try{if(process.stdout?.isTTY){process.stdout.write(pr);return}process.stderr?.isTTY&&process.stderr.write(pr)}catch{}}async function Gs(e,t={}){Gp(t.writeBell);let n=zp(e,t.platform??process.platform);if(!n)return;let r=t.runCommand??qp;try{await r(n.command,n.args)}catch{}}import{Box as Rt,Text as Ae,useInput as Kp}from"ink";import{useCallback as Ks,useMemo as Vp,useState as Ot}from"react";import{jsx as Oe,jsxs as gt}from"react/jsx-runtime";var Ke=[{key:"name",label:"Provider name",hint:"Used for /models switching",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Read at runtime from environment variables",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",defaultValue:"https://api.deepseek.com"}];function Vs({configPath:e,onComplete:t,onExit:n}){let[r,o]=Ot(0),[s,i]=Ot(""),[a,l]=Ot({}),[c,u]=Ot(!1),[p,y]=Ot(null),m=Ke[r]??Ke[0],h=Ks(async v=>{u(!0),y(null);try{let S={current_provider:v.name,providers:[{name:v.name,env_api_key:v.envKey,model:v.model,base_url:v.baseUrl||void 0}]};await Se(e,S),t()}catch(S){y(S.message),u(!1)}},[e,t]),d=Ks(async()=>{if(!m)return;let v=s.trim()||m.defaultValue,S={...a,[m.key]:v};if(l(S),i(""),r<Ke.length-1){o(r+1);return}let W={name:S.name||Ke[0].defaultValue,envKey:S.envKey||Ke[1].defaultValue,model:S.model||Ke[2].defaultValue,baseUrl:S.baseUrl||Ke[3].defaultValue};await h(W)},[s,h,m,r,a]);Kp((v,S)=>{if(!c){if(S.ctrl&&v==="c"){n();return}if(S.return){d();return}if(S.backspace||S.delete){i(W=>W.slice(0,-1));return}v&&i(W=>W+v)}});let E=Vp(()=>`Step ${r+1}/${Ke.length}`,[r]);return m?gt(Rt,{flexDirection:"column",children:[Oe(Ae,{bold:!0,children:"Memo setup"}),Oe(Ae,{color:"gray",children:"No provider config found. Complete setup to continue."}),gt(Ae,{color:"gray",children:["Config path: ",e]}),gt(Rt,{marginTop:1,flexDirection:"column",children:[Oe(Ae,{color:"cyan",children:E}),Oe(Ae,{children:m.label}),gt(Ae,{color:"gray",children:["Default: ",m.defaultValue]}),m.hint?Oe(Ae,{color:"gray",children:m.hint}):null]}),gt(Rt,{marginTop:1,children:[Oe(Ae,{children:"> "}),Oe(Ae,{children:s})]}),Oe(Rt,{marginTop:1,children:Oe(Ae,{color:"gray",children:"Enter to continue, Ctrl+C to exit."})}),p?Oe(Rt,{marginTop:1,children:gt(Ae,{color:"red",children:["Failed to save config: ",p]})}):null]}):null}function Xs(e){let t=[],n=[],r=[],o=e.split(`
98
+ `).map(l=>l.trim()).filter(Boolean),s=null,i=0,a=0;for(let l of o){let c;try{c=JSON.parse(l)}catch{continue}if(!(!c||typeof c!="object")){if(c.type==="turn_start"){let u=typeof c.content=="string"?c.content:"";s={index:-(i+1),userInput:u,steps:[],status:"ok",sequence:a+=1},n.push(s),u&&(t.push({role:"user",content:u}),r.push(`User: ${u}`)),i+=1;continue}if(c.type==="assistant"){let u=typeof c.content=="string"?c.content:"";if(u&&(t.push({role:"assistant",content:u}),r.push(`Assistant: ${u}`),s)){let p={index:s.steps.length,assistantText:u};s.steps=[...s.steps,p],s.finalText=u}continue}if(c.type==="action"&&s){let u=c.meta;if(u&&typeof u=="object"){let p=typeof u.tool=="string"?u.tool:"",y=u.input,m=typeof u.thinking=="string"?u.thinking:"",d=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(v=>{let S=typeof v?.name=="string"?v.name:"";return S?{tool:S,input:v?.input}:null}).filter(Boolean),E=s.steps[s.steps.length-1];E&&(d.length>1?(E.action=d[0],E.parallelActions=d):p&&(E.action={tool:p,input:y}),m&&(E.thinking=m))}continue}if(c.type==="observation"&&s){let u=typeof c.content=="string"?c.content:"",p=s.steps[s.steps.length-1];p&&(p.observation=u);continue}}}return{summary:r.join(`
99
+ `),messages:t,turns:n,maxSequence:a}}function mr(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function Xp(e,t){return{index:e,userInput:"",steps:[],sequence:t}}function dr(e,t){let n=e.slice();for(;n.length<=t;)n.push({index:n.length,assistantText:""});return n}function Lt(e,t,n){let r=e.turns.slice(),o=r.findIndex(i=>i.index===t);if(o===-1){let i=e.sequence+1;return r.push(n(Xp(t,i))),{turns:r,sequence:i}}let s=r[o];return s?(r[o]=n(s),{turns:r,sequence:e.sequence}):{turns:r,sequence:e.sequence}}function Jp(e){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:e.title,content:e.content,tone:e.tone??"info",sequence:e.sequence}}function Js(e,t){switch(t.type){case"append_system_message":{let n=e.sequence+1;return{...e,sequence:n,systemMessages:[...e.systemMessages,Jp({title:t.title,content:t.content,tone:t.tone,sequence:n})]}}case"turn_start":{let n=Lt(e,t.turn,r=>({...r,index:t.turn,userInput:t.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:t.promptTokens??r.contextPromptTokens}));return{...e,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Lt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,assistantText:`${s.assistantText}${t.chunk}`},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Lt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,action:t.action,thinking:t.thinking,parallelActions:t.parallelActions&&t.parallelActions.length>1?t.parallelActions:void 0,toolStatus:Fe.EXECUTING},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Lt(e,t.turn,r=>{let o=dr(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,observation:t.observation,toolStatus:t.toolStatus,parallelToolStatuses:t.parallelToolStatuses},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=Lt(e,t.turn,r=>{let o=r.startedAt??Date.now(),s=Math.max(0,Date.now()-o),i=t.tokenUsage?.prompt??r.contextPromptTokens;return{...r,finalText:t.finalText,status:t.status,errorMessage:t.errorMessage,tokenUsage:t.turnUsage,contextPromptTokens:i,startedAt:o,durationMs:s}});return{...e,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...e,historicalTurns:t.turns,sequence:Math.max(e.sequence,t.maxSequence)};case"clear_current_timeline":return{...e,turns:[],systemMessages:[]};case"reset_all":return mr();default:return e}}import{dirname as hn,join as Zs,resolve as Yp}from"path";import{statSync as Zp,existsSync as Qs,readFileSync as Qp}from"fs";import{readFile as ed}from"fs/promises";import{get as td}from"https";import{fileURLToPath as nd}from"url";function Ys(e){let t=e.trim().replace(/^v/i,""),[n="",r]=t.split("-",2),o=n.split(".").map(s=>Number(s));return o.length<3||o.some(s=>!Number.isFinite(s))?null:{major:o[0]??0,minor:o[1]??0,patch:o[2]??0,prerelease:r??null}}function rd(e,t){let n=Ys(e),r=Ys(t);return!n||!r?!1:n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch!==r.patch?n.patch>r.patch:n.prerelease&&!r.prerelease?!1:!n.prerelease&&r.prerelease?!0:n.prerelease&&r.prerelease?n.prerelease>r.prerelease:!1}function ei(){try{let t=nd(import.meta.url);return hn(t)}catch{}let e=Yp(process.argv[1]??process.cwd());try{return Zp(e).isFile()?hn(e):e}catch{return process.cwd()}}async function od(e){let t=Zs(e,"package.json");if(!Qs(t))return null;let n=await ed(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function sd(e){let t=Zs(e,"package.json");if(!Qs(t))return null;try{let n=Qp(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function id(){let e=ei();for(;;){let t=await od(e);if(t&&t.name==="@memo-code/memo")return t;let n=hn(e);if(n===e)break;e=n}return null}function yn(){let e=ei();for(;;){let t=sd(e);if(t&&t.name==="@memo-code/memo")return t;let n=hn(e);if(n===e)break;e=n}return null}async function ad(e,t=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(o=>{let s=td(r,{timeout:t},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));o(l.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function ti(){let e=await id();if(!e)return null;let t=await ad(e.name);return!t||!rd(t,e.version)?null:{current:e.version,latest:t}}import{jsx as Ve,jsxs as gd}from"react/jsx-runtime";function dd(e,t){if(e.length===0)return[];if(t===void 0)return[...e];if(t.length===0)return[];let n=new Set(e),r=t.filter(o=>n.has(o));return r.length>0?r:[...e]}function md(e,t){if(e.length===0)return[];if(t.length===0)return[];let n=new Set(e);return t.filter(r=>n.has(r))}function fd(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function ri({sessionOptions:e,providerName:t,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:u}=pd(),p=$t(()=>Object.keys(o??{}).sort(),[o]),y=$t(()=>dd(p,e.activeMcpServers),[p,e.activeMcpServers]),m=e.toolPermissionMode??(l?H.FULL:H.ONCE),[h,d]=cd(Js,void 0,mr),[E,v]=re(t),[S,W]=re(n),[ee,q]=re(a),[V,he]=re(m),[A,F]=re({...e,providerName:t,dangerous:m===H.FULL,toolPermissionMode:m}),[w,P]=re(!1),[ue,we]=re([]),[te,M]=re(null),[R,ne]=re(null),[se,Be]=re(e.maxPromptTokens??ps),[Me,pe]=re(0),[ke,Xe]=re(c),[Le,k]=re(!c&&p.length>0),[Y,nt]=re(y),[G,_n]=re(null),[j,z]=re(null),O=Tn(null),Pe=Tn(null),ie=Tn(null),[K,Ce]=re(null),We=Tn(null),Dt=$t(()=>yn(),[]),X=J(g=>{d(g)},[]);Nt(()=>{ke||(nt(y),k(p.length>0))},[ke,y,p.length]);let b=J((g,_,I="info")=>{X({type:"append_system_message",title:g,content:_,tone:I})},[X]),Ut=$t(()=>({onAssistantStep:(g,_)=>{let I=Pe.current;I&&X({type:"assistant_chunk",turn:I,step:_,chunk:g})},requestApproval:V===H.FULL||V===H.NONE?void 0:g=>new Promise(_=>{Gs(g),Ce(g),We.current=_}),hooks:{onTurnStart:({turn:g,input:_,promptTokens:I})=>{Pe.current=g;let Te=ie.current;Te&&(ie.current=null);let Je=Te??_;I&&I>0&&pe(I),X({type:"turn_start",turn:g,input:Je,promptTokens:I})},onAction:({turn:g,step:_,action:I,thinking:Te,parallelActions:Je})=>{X({type:"tool_action",turn:g,step:_,action:I,thinking:Te,parallelActions:Je})},onObservation:({turn:g,step:_,observation:I,resultStatus:Te,parallelResultStatuses:Je})=>{X({type:"tool_observation",turn:g,step:_,observation:I,toolStatus:Yn(Te),parallelToolStatuses:Jo(Je)})},onFinal:({turn:g,finalText:_,status:I,errorMessage:Te,turnUsage:Je,tokenUsage:ui})=>{X({type:"turn_final",turn:g,finalText:_,status:I,errorMessage:Te,turnUsage:Je,tokenUsage:ui}),P(!1)}}}),[X,V]);Nt(()=>{let g=!1;return(async()=>{if(!(ke||Le))try{let _=O.current;_&&await _.close();let I=await en(Ut,A);if(g){await I.close();return}O.current=I,z(I),M(I.historyFilePath??null)}catch(_){if(g)return;O.current=null,z(null),M(null),P(!1),b("Session",`Failed to create session: ${_.message}`,"error")}})(),()=>{g=!0}},[b,Ut,Le,A,ke]),Nt(()=>{let g=!1;return(async()=>{let _=await ti();g||!_||b("Update",`Update available: v${_.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{g=!0}},[b]),Nt(()=>()=>{O.current&&O.current.close()},[]);let T=J(async()=>{let g=We.current;g&&(g("deny"),We.current=null),K&&Ce(null),O.current&&await O.current.close(),_n("Bye!"),setTimeout(()=>u(),250)},[u,K]),x=J(()=>{if(w){b("Clear","Cancel current run before clearing timeline.","warning");return}if(K){b("Clear","Resolve current approval request before clearing timeline.","warning");return}X({type:"clear_current_timeline"}),ne(null),pe(0),fd()},[b,w,X,K]),U=J(()=>{if(w){b("New Session","Cancel current run before starting a new session.","warning");return}if(K){b("New Session","Resolve current approval request before starting a new session.","warning");return}X({type:"reset_all"}),ne(null),pe(0),Pe.current=null,F(g=>({...g,sessionId:tt()})),b("New Session","Started a fresh session.")},[b,w,X,K]),Z=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,current_provider:g})}catch(_){b("Config",`Failed to persist provider: ${_.message}`,"warning")}},[b]),ye=J(async g=>{if(w){b("Model switch","Cancel current run before switching models.","warning");return}if(g.name===E&&g.model===S){b("Model switch",`Already using ${g.name} (${g.model}).`);return}X({type:"reset_all"}),pe(0),Pe.current=null,v(g.name),W(g.model),F(_=>({..._,sessionId:tt(),providerName:g.name})),await Z(g.name),b("Model switch",`Switched to ${g.name} (${g.model}).`)},[b,w,S,E,X,Z]),Ie=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,max_prompt_tokens:g})}catch(_){b("Context",`Failed to persist context limit: ${_.message}`,"warning")}},[b]),Sn=J(g=>{if(w){b("Context","Cancel current run before changing context window.","warning");return}if(K){b("Context","Resolve current approval request before changing context window.","warning");return}Be(g),pe(0),F(_=>({..._,maxPromptTokens:g,sessionId:tt()})),b("Context",`Context window set to ${Math.floor(g/1e3)}k.`),Ie(g)},[b,w,K,Ie]),rt=J(g=>g===H.NONE?"none (no tools)":g===H.ONCE?"once (approval required)":"full (no approval)",[]),C=J(g=>{if(w){b("Tools","Cancel current run before changing tool permission mode.","warning");return}if(K){b("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(g===V){b("Tools",`Already using ${rt(g)}.`);return}he(g),F(_=>({..._,sessionId:tt(),dangerous:g===H.FULL,toolPermissionMode:g})),b("Tools",`Tool permission set to ${rt(g)}.`)},[b,w,K,rt,V]),L=J(async g=>{try{let _=await ce();await Se(_.configPath,{..._.config,active_mcp_servers:g})}catch(_){b("MCP",`Failed to persist active MCP servers: ${_.message}`,"warning")}},[b]),ae=J((g,_)=>{let I=md(p,g);nt(I),k(!1),F(Te=>({...Te,sessionId:tt(),activeMcpServers:I})),_&&L(I)},[p,L]),D=J(async g=>{if(w){b("History","Cancel current run before loading session history.","warning");return}if(K){b("History","Resolve current approval request before loading session history.","warning");return}try{let _=await ld(g.sessionFile,"utf8"),I=Xs(_);X({type:"clear_current_timeline"}),X({type:"replace_history",turns:I.turns,maxSequence:I.maxSequence}),ne(I.messages),P(!1),z(null),M(null),pe(0),Pe.current=null,F(Te=>({...Te,sessionId:tt()})),b("History",I.summary||g.input)}catch(_){b("History",`Failed to load ${g.sessionFile}: ${_.message}`,"error")}},[b,w,X,K]),Re=J(()=>{w&&j?.cancelCurrentTurn?.()},[w,j]),je=J(async()=>{if(!j||w)return;let g=`Please analyze the current project and create an AGENTS.md file at the project root.
99
100
 
100
101
  The AGENTS.md should include:
101
102
  1. Project name and brief description
@@ -111,7 +112,7 @@ Steps:
111
112
  3. Understand stack and conventions
112
113
  4. Create AGENTS.md using apply_patch
113
114
 
114
- Keep the result concise and actionable.`,_=ge($.INIT);Me(I=>[...I,_]),P(!0);try{ie.current=_,await j.runTurn(g)}catch(I){P(!1),b("Init",`Failed to run init task: ${I.message}`,"error")}},[b,E,j]),ot=J(async g=>{let _=g.trim();if(_){if(_.toLowerCase()===as){await T();return}if(_===ge($.INIT)){await je();return}if(!(!j||E)){Me(I=>[...I,_]),P(!0);try{await j.runTurn(_)}catch(I){P(!1),b("Run",`Turn failed: ${I.message}`,"error")}}}},[b,E,T,je,j]),Ft=J(async()=>{try{let g=await ce(),_=Ye(g.config);q(g.config.providers),v(_.name),W(_.model),F(I=>({...I,sessionId:tt(),providerName:_.name})),Xe(!1),b("Setup",`Config saved to ${g.configPath}`)}catch(g){b("Setup",`Failed to reload config: ${g.message}`,"error")}},[b]);$t(()=>{if(!j||!R?.length)return;let g=j.history[0];g&&(j.history.splice(0,j.history.length,g,...R),ne(null))},[R,j]);let _n=J(g=>{let _=We.current;_&&(_(g),We.current=null),Ce(null)},[]),yt=Ko(h.turns[h.turns.length-1]?.tokenUsage),ri=Go(we,se),oi=Dt(()=>({providerName:k,model:S,cwd:s,sessionId:A.sessionId??"unknown",mcpNames:Y,version:Ut?.version??"unknown"}),[Y,S,k,s,Ut?.version,A.sessionId]);return G?Ve(Ys,{children:Ve(Qp,{color:"green",children:G})}):ke?Ve(js,{configPath:r,onComplete:Ft,onExit:T}):Le?Ve(Hs,{serverNames:d,defaultSelected:y,onConfirm:ae,onExit:()=>{T()}}):om(Ys,{flexDirection:"column",children:[Ve(ss,{header:oi,systemMessages:h.systemMessages,turns:h.turns,historicalTurns:h.historicalTurns}),Ve(Rs,{disabled:!j||!!K,busy:E,history:ue,cwd:s,sessionsDir:i,currentSessionFile:te??void 0,providers:ee,configPath:r,providerName:k,model:S,contextLimit:se,toolPermissionMode:V,mcpServers:o,onSubmit:g=>{ot(g)},onExit:()=>{T()},onClear:x,onNewSession:U,onCancelRun:Re,onHistorySelect:g=>{D(g)},onModelSelect:g=>{ye(g)},onSetContextLimit:Tn,onSetToolPermission:C,onSystemMessage:b}),K?Ve(Ds,{request:K,onDecision:_n}):null,Ve(Ns,{busy:E,pendingApproval:!!K,contextPercent:ri,tokenLine:yt})]})}var sm=`
115
+ Keep the result concise and actionable.`,_=ge($.INIT);we(I=>[...I,_]),P(!0);try{ie.current=_,await j.runTurn(g)}catch(I){P(!1),b("Init",`Failed to run init task: ${I.message}`,"error")}},[b,w,j]),ot=J(async g=>{let _=g.trim();if(_){if(_.toLowerCase()===ds){await T();return}if(_===ge($.INIT)){await je();return}if(!(!j||w)){we(I=>[...I,_]),P(!0);try{await j.runTurn(_)}catch(I){P(!1),b("Run",`Turn failed: ${I.message}`,"error")}}}},[b,w,T,je,j]),Ht=J(async()=>{try{let g=await ce(),_=Ye(g.config);q(g.config.providers),v(_.name),W(_.model),F(I=>({...I,sessionId:tt(),providerName:_.name})),Xe(!1),b("Setup",`Config saved to ${g.configPath}`)}catch(g){b("Setup",`Failed to reload config: ${g.message}`,"error")}},[b]);Nt(()=>{if(!j||!R?.length)return;let g=j.history[0];g&&(j.history.splice(0,j.history.length,g,...R),ne(null))},[R,j]);let vn=J(g=>{let _=We.current;_&&(_(g),We.current=null),Ce(null)},[]),ht=Zo(h.turns[h.turns.length-1]?.tokenUsage),li=Yo(Me,se),ci=$t(()=>({providerName:E,model:S,cwd:s,sessionId:A.sessionId??"unknown",mcpNames:Y,version:Dt?.version??"unknown"}),[Y,S,E,s,Dt?.version,A.sessionId]);return G?Ve(ni,{children:Ve(ud,{color:"green",children:G})}):ke?Ve(Vs,{configPath:r,onComplete:Ht,onExit:T}):Le?Ve(zs,{serverNames:p,defaultSelected:y,onConfirm:ae,onExit:()=>{T()}}):gd(ni,{flexDirection:"column",children:[Ve(us,{header:ci,systemMessages:h.systemMessages,turns:h.turns,historicalTurns:h.historicalTurns}),Ve(Ds,{disabled:!j||!!K,busy:w,history:ue,cwd:s,sessionsDir:i,currentSessionFile:te??void 0,providers:ee,configPath:r,providerName:E,model:S,contextLimit:se,toolPermissionMode:V,mcpServers:o,onSubmit:g=>{ot(g)},onExit:()=>{T()},onClear:x,onNewSession:U,onCancelRun:Re,onHistorySelect:g=>{D(g)},onModelSelect:g=>{ye(g)},onSetContextLimit:Sn,onSetToolPermission:C,onSystemMessage:b}),K?Ve(Ws,{request:K,onDecision:vn}):null,Ve(Fs,{busy:w,pendingApproval:!!K,contextPercent:li,tokenLine:ht})]})}var hd=`
115
116
  Usage:
116
117
  memo mcp list [--json]
117
118
  memo mcp get <name> [--json]
@@ -120,14 +121,14 @@ Usage:
120
121
  memo mcp remove <name>
121
122
  memo mcp login <name> [--scopes scope1,scope2]
122
123
  memo mcp logout <name>
123
- `;function pr(){console.log(sm.trim())}function im(e){let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1);return n?{key:n,value:r}:null}function Qs(e,t){let n=[];if(n.push(`${e}`),"url"in t){n.push(` type: ${t.type??"streamable_http"}`),n.push(` url: ${t.url}`),t.bearer_token_env_var&&n.push(` bearer_token_env_var: ${t.bearer_token_env_var}`);let r=t.http_headers??t.headers;r&&Object.keys(r).length>0&&n.push(` headers: ${Object.entries(r).map(([o,s])=>`${o}=${s}`).join(", ")}`)}else n.push(` type: ${t.type??"stdio"}`),n.push(` command: ${t.command}`),t.args&&t.args.length>0&&n.push(` args: ${t.args.join(" ")}`),t.env&&Object.keys(t.env).length>0&&n.push(` env: ${Object.entries(t.env).map(([r,o])=>`${r}=${o}`).join(", ")}`);return n.join(`
124
- `)}function am(e){let t=e.shift();if(!t)return{error:"Missing server name."};let n,r,o={},s=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(a){if(a==="--"){s=e.slice(i+1);break}if(a==="--url"){let l=e[i+1];if(!l)return{error:"Missing value for --url."};n=l,i+=1;continue}if(a==="--bearer-token-env-var"){let l=e[i+1];if(!l)return{error:"Missing value for --bearer-token-env-var."};r=l,i+=1;continue}if(a==="--env"){let l=e[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=im(l);if(!c)return{error:"Invalid --env format. Use KEY=VALUE."};o[c.key]=c.value,i+=1;continue}return a==="--help"||a==="-h"?{error:""}:{error:`Unknown option: ${a}`}}}return n?s.length>0?{error:"Use either --url or a stdio command, not both."}:Object.keys(o).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:t,url:n,bearerTokenEnvVar:r}}:r?{error:"--bearer-token-env-var is only supported with HTTP servers."}:s.length===0?{error:"Missing stdio command. Use `-- <command...>`."}:{options:{name:t,command:s[0],args:s.slice(1),env:Object.keys(o).length>0?o:void 0}}}function lm(e){let[t,...n]=e;return!t||t==="--help"||t==="-h"||t==="help"?{command:"help",rest:[]}:{command:t,rest:n}}function mr(e,t=[]){let n=new Set(t);for(let r=0;r<e.length;r+=1){let o=e[r];if(o){if(o.startsWith("--")){n.has(o)&&(r+=1);continue}return o}}return null}async function ei(e){let{command:t,rest:n}=lm(e);if(t==="help"){pr();return}if(t==="list"){let r=n.includes("--json"),s=(await ce()).config.mcp_servers??{};if(r){console.log(JSON.stringify(s,null,2));return}let i=Object.keys(s);if(i.length===0){console.log('No MCP servers configured. Add one with "memo mcp add".');return}console.log(`MCP servers (${i.length}):`);for(let a of i){let l=s[a];l&&console.log(Qs(a,l))}return}if(t==="get"){let r=n.includes("--json"),o=mr(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await ce()).config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(r){console.log(JSON.stringify(i,null,2));return}console.log(Qs(o,i));return}if(t==="add"){let r=am(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),pr();return}let o=r.options;if(!o)return;if(o.url)try{new URL(o.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await ce(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let a;o.url?a={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:a={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=a,await Se(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(t==="remove"){let r=mr(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await ce(),s={...o.config.mcp_servers??{}};if(!s[r]){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}delete s[r],await Se(o.configPath,{...o.config,mcp_servers:s}),console.log(`Removed MCP server "${r}".`);return}if(t==="login"||t==="logout"){let r=mr(n,["--scopes"]);if(!r){console.error("Missing server name."),process.exitCode=1;return}let s=(await ce()).config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth login/logout only applies to streamable HTTP servers."),process.exitCode=1;return}console.error("OAuth login/logout is not supported in memo yet. Configure a bearer token env var instead."),process.exitCode=1;return}console.error(`Unknown subcommand: ${t}`),pr(),process.exitCode=1}import{jsx as Tm}from"react/jsx-runtime";function dm(e){let t={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o!==void 0){if(o==="--version"||o==="-v"){t.showVersion=!0;continue}if(o==="--once"){t.removedOnceFlag=!0;continue}if(o==="--dangerous"||o==="-d"){t.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:t}}async function ni(e){let t=await ce();if(!t.needsSetup)return t;let n=t.config.providers[0],o=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&o)return await Se(t.configPath,t.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${t.configPath}`),{...t,needsSetup:!1};if(e==="tui")return t;let s=cm({input:um,output:pm}),i=async(a,l)=>(await s.question(a)).trim()||l;try{console.log("No provider config found. Please answer the prompts:");let a=await i("Provider name [deepseek]: ","deepseek"),l=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),c=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),d={current_provider:a,providers:[{name:a,env_api_key:l,model:c,base_url:u||void 0}]};return await Se(t.configPath,d),console.log(`Config written to ${t.configPath}
125
- `),{...t,config:d,needsSetup:!1}}finally{s.close()}}async function fm(e){let t=await ni("plain"),n=Ye(t.config),o={sessionId:ti(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous};e.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={requestApproval:e.options.dangerous?void 0:l=>(console.log(`
124
+ `;function fr(){console.log(hd.trim())}function yd(e){let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1);return n?{key:n,value:r}:null}function oi(e,t){let n=[];if(n.push(`${e}`),"url"in t){n.push(` type: ${t.type??"streamable_http"}`),n.push(` url: ${t.url}`),t.bearer_token_env_var&&n.push(` bearer_token_env_var: ${t.bearer_token_env_var}`);let r=t.http_headers??t.headers;r&&Object.keys(r).length>0&&n.push(` headers: ${Object.entries(r).map(([o,s])=>`${o}=${s}`).join(", ")}`)}else n.push(` type: ${t.type??"stdio"}`),n.push(` command: ${t.command}`),t.args&&t.args.length>0&&n.push(` args: ${t.args.join(" ")}`),t.env&&Object.keys(t.env).length>0&&n.push(` env: ${Object.entries(t.env).map(([r,o])=>`${r}=${o}`).join(", ")}`);return n.join(`
125
+ `)}function Td(e){let t=e.shift();if(!t)return{error:"Missing server name."};let n,r,o={},s=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(a){if(a==="--"){s=e.slice(i+1);break}if(a==="--url"){let l=e[i+1];if(!l)return{error:"Missing value for --url."};n=l,i+=1;continue}if(a==="--bearer-token-env-var"){let l=e[i+1];if(!l)return{error:"Missing value for --bearer-token-env-var."};r=l,i+=1;continue}if(a==="--env"){let l=e[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=yd(l);if(!c)return{error:"Invalid --env format. Use KEY=VALUE."};o[c.key]=c.value,i+=1;continue}return a==="--help"||a==="-h"?{error:""}:{error:`Unknown option: ${a}`}}}return n?s.length>0?{error:"Use either --url or a stdio command, not both."}:Object.keys(o).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:t,url:n,bearerTokenEnvVar:r}}:r?{error:"--bearer-token-env-var is only supported with HTTP servers."}:s.length===0?{error:"Missing stdio command. Use `-- <command...>`."}:{options:{name:t,command:s[0],args:s.slice(1),env:Object.keys(o).length>0?o:void 0}}}function _d(e){let[t,...n]=e;return!t||t==="--help"||t==="-h"||t==="help"?{command:"help",rest:[]}:{command:t,rest:n}}function gr(e,t=[]){let n=new Set(t);for(let r=0;r<e.length;r+=1){let o=e[r];if(o){if(o.startsWith("--")){n.has(o)&&(r+=1);continue}return o}}return null}async function si(e){let{command:t,rest:n}=_d(e);if(t==="help"){fr();return}if(t==="list"){let r=n.includes("--json"),s=(await ce()).config.mcp_servers??{};if(r){console.log(JSON.stringify(s,null,2));return}let i=Object.keys(s);if(i.length===0){console.log('No MCP servers configured. Add one with "memo mcp add".');return}console.log(`MCP servers (${i.length}):`);for(let a of i){let l=s[a];l&&console.log(oi(a,l))}return}if(t==="get"){let r=n.includes("--json"),o=gr(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await ce()).config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(r){console.log(JSON.stringify(i,null,2));return}console.log(oi(o,i));return}if(t==="add"){let r=Td(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),fr();return}let o=r.options;if(!o)return;if(o.url)try{new URL(o.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await ce(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let a;o.url?a={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:a={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=a,await Se(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(t==="remove"){let r=gr(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await ce(),s={...o.config.mcp_servers??{}};if(!s[r]){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}delete s[r],await Se(o.configPath,{...o.config,mcp_servers:s}),console.log(`Removed MCP server "${r}".`);return}if(t==="login"||t==="logout"){let r=gr(n,["--scopes"]);if(!r){console.error("Missing server name."),process.exitCode=1;return}let s=(await ce()).config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth login/logout only applies to streamable HTTP servers."),process.exitCode=1;return}console.error("OAuth login/logout is not supported in memo yet. Configure a bearer token env var instead."),process.exitCode=1;return}console.error(`Unknown subcommand: ${t}`),fr(),process.exitCode=1}import{jsx as kd}from"react/jsx-runtime";function bd(e){let t={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o!==void 0){if(o==="--version"||o==="-v"){t.showVersion=!0;continue}if(o==="--once"){t.removedOnceFlag=!0;continue}if(o==="--dangerous"||o==="-d"){t.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:t}}async function ai(e){let t=await ce();if(!t.needsSetup)return t;let n=t.config.providers[0],o=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&o)return await Se(t.configPath,t.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${t.configPath}`),{...t,needsSetup:!1};if(e==="tui")return t;let s=Sd({input:vd,output:xd}),i=async(a,l)=>(await s.question(a)).trim()||l;try{console.log("No provider config found. Please answer the prompts:");let a=await i("Provider name [deepseek]: ","deepseek"),l=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),c=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),p={current_provider:a,providers:[{name:a,env_api_key:l,model:c,base_url:u||void 0}]};return await Se(t.configPath,p),console.log(`Config written to ${t.configPath}
126
+ `),{...t,config:p,needsSetup:!1}}finally{s.close()}}async function Ed(e){let t=await ai("plain"),n=Ye(t.config),o={sessionId:ii(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous};e.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={requestApproval:e.options.dangerous?void 0:l=>(console.log(`
126
127
  [approval required] ${l.toolName}: ${l.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:l})=>{console.log(`
127
- [tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await Zt(s,o),a=e.question;if(!a&&!process.stdin.isTTY&&(a=await ym()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
128
+ [tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await en(s,o),a=e.question;if(!a&&!process.stdin.isTTY&&(a=await Md()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
128
129
  `);let l=await i.runTurn(a);console.log(`
129
130
  ${l.finalText}`),console.log(`
130
131
  [tokens] prompt=${l.tokenUsage.prompt} completion=${l.tokenUsage.completion} total=${l.tokenUsage.total}`),console.log(`
131
- provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function gm(e){let t=await ni("tui"),n=Ye(t.config),o={sessionId:ti(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous},s=Xt(t,o);e.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
132
- `)),await mm(Tm(Zs,{sessionOptions:o,providerName:n.name,model:n.model,configPath:t.configPath,mcpServers:t.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:s,providers:t.config.providers,dangerous:e.options.dangerous,needsSetup:t.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function hm(){let e=process.argv.slice(2);if(e[0]==="mcp"||e[0]==="--"&&e[1]==="mcp"){let r=e[0]==="--"?2:1;await ei(e.slice(r));return}let t=dm(e);if(t.options.removedOnceFlag){console.error("`--once` has been removed. Use `memo` (interactive) or pipe input to `memo`."),process.exitCode=1;return}if(t.options.showVersion){let o=gn()?.version??"unknown";console.log(o);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await fm(t);return}await gm(t)}hm();async function ym(){return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim())}),process.stdin.resume()})}
132
+ provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function Ad(e){let t=await ai("tui"),n=Ye(t.config),o={sessionId:ii(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous},s=Jt(t,o);e.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
133
+ `)),await Cd(kd(ri,{sessionOptions:o,providerName:n.name,model:n.model,configPath:t.configPath,mcpServers:t.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:s,providers:t.config.providers,dangerous:e.options.dangerous,needsSetup:t.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function wd(){let e=process.argv.slice(2);if(e[0]==="mcp"||e[0]==="--"&&e[1]==="mcp"){let r=e[0]==="--"?2:1;await si(e.slice(r));return}let t=bd(e);if(t.options.removedOnceFlag){console.error("`--once` has been removed. Use `memo` (interactive) or pipe input to `memo`."),process.exitCode=1;return}if(t.options.showVersion){let o=yn()?.version??"unknown";console.log(o);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await Ed(t);return}await Ad(t)}wd();async function Md(){return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim())}),process.stdin.resume()})}
133
134
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memo-code/memo",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "A lightweight coding agent that runs in your terminal",