@memo-code/memo 0.6.0 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -21
- package/README.zh.md +8 -11
- package/dist/index.js +84 -80
- package/dist/prompt.md +46 -40
- package/package.json +1 -2
package/dist/index.js
CHANGED
|
@@ -1,65 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"utf8")}async flush(){return Promise.resolve()}};function
|
|
4
|
-
`)
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
`).
|
|
9
|
-
`)
|
|
10
|
-
`
|
|
11
|
-
`)
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
`)
|
|
17
|
-
`
|
|
18
|
-
`),w=y
|
|
19
|
-
...
|
|
2
|
+
var As=Object.create;var zn=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var Ps=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,Is=Object.prototype.hasOwnProperty;var Gn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $s=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ps(e))!Is.call(t,r)&&r!==n&&zn(t,r,{get:()=>e[r],enumerable:!(o=Ms(e,r))||o.enumerable});return t};var Kn=(t,e,n)=>(n=t!=null?As(Rs(t)):{},$s(e||!t||!t.__esModule?zn(n,"default",{value:t,enumerable:!0}):n,t));var po=Gn((om,uo)=>{"use strict";function oo(t){return Array.isArray(t)?t:[t]}var nn="",ro=" ",en="\\",ai=/^\s+$/,li=/(?:[^\\]|^)\\$/,ci=/^\\!/,ui=/^\\#/,pi=/\r?\n/g,mi=/^\.*\/|^\.+$/,tn="/",ao="node-ignore";typeof Symbol<"u"&&(ao=Symbol.for("node-ignore"));var so=ao,di=(t,e,n)=>Object.defineProperty(t,e,{value:n}),fi=/([0-z])-([0-z])/g,lo=()=>!1,gi=t=>t.replace(fi,(e,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?e:nn),hi=t=>{let{length:e}=t;return t.slice(0,e-e%2)},yi=[[/^\uFEFF/,()=>nn],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?ro:nn)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+ro}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return e+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>en],[/\\\\/g,()=>en],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,o,r)=>e===en?`\\[${n}${hi(o)}${r}`:r==="]"&&o.length%2===0?`[${gi(n)}${o}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],io=Object.create(null),Ti=(t,e)=>{let n=io[t];return n||(n=yi.reduce((o,[r,s])=>o.replace(r,s.bind(t)),t),io[t]=n),e?new RegExp(n,"i"):new RegExp(n)},sn=t=>typeof t=="string",_i=t=>t&&sn(t)&&!ai.test(t)&&!li.test(t)&&t.indexOf("#")!==0,xi=t=>t.split(pi),on=class{constructor(e,n,o,r){this.origin=e,this.pattern=n,this.negative=o,this.regex=r}},Si=(t,e)=>{let n=t,o=!1;t.indexOf("!")===0&&(o=!0,t=t.substr(1)),t=t.replace(ci,"!").replace(ui,"#");let r=Ti(t,e);return new on(n,t,o,r)},vi=(t,e)=>{throw new e(t)},ke=(t,e,n)=>sn(t)?t?ke.isNotRelative(t)?n(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${e}\``,TypeError),co=t=>mi.test(t);ke.isNotRelative=co;ke.convert=t=>t;var rn=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:o=!1}={}){di(this,so,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[so]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(_i(e)){let n=Si(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,oo(sn(e)?xi(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,n){let o=!1,r=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(r===i&&o!==r||i&&!o&&!r&&!n)return;s.regex.test(e)&&(o=!i,r=i)}),{ignored:o,unignored:r}}_test(e,n,o,r){let s=e&&ke.convert(e);return ke(s,e,this._allowRelativePaths?lo:vi),this._t(s,n,o,r)}_t(e,n,o,r){if(e in n)return n[e];if(r||(r=e.split(tn)),r.pop(),!r.length)return n[e]=this._testOne(e,o);let s=this._t(r.join(tn)+tn,n,o,r);return n[e]=s.ignored?s:this._testOne(e,o)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return oo(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},wt=t=>new rn(t),Ci=t=>ke(t&&ke.convert(t),t,lo);wt.isPathValid=Ci;wt.default=wt;uo.exports=wt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");ke.convert=t;let e=/^[a-z]:\//i;ke.isNotRelative=n=>e.test(n)||co(n)}});var Lr=Gn((Mg,Dt)=>{"use strict";function Ar(t){return Array.isArray(t)?t:[t]}var wc=void 0,En="",kr=" ",wn="\\",Ec=/^\s+$/,kc=/(?:[^\\]|^)\\$/,bc=/^\\!/,Ac=/^\\#/,Mc=/\r?\n/g,Pc=/^\.{0,2}\/|^\.{1,2}$/,Rc=/\/$/,Je="/",Mr="node-ignore";typeof Symbol<"u"&&(Mr=Symbol.for("node-ignore"));var Pr=Mr,Ye=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),Ic=/([0-z])-([0-z])/g,Rr=()=>!1,$c=t=>t.replace(Ic,(e,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?e:En),Lc=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Oc=[[/^\uFEFF/,()=>En],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?kr:En)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+kr}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return e+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>wn],[/\\\\/g,()=>wn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,o,r)=>e===wn?`\\[${n}${Lc(o)}${r}`:r==="]"&&o.length%2===0?`[${$c(n)}${o}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],Nc=/(^|\\\/)?\\\*$/,pt="regex",Ot="checkRegex",br="_",Dc={[pt](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Ot](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Uc=t=>Oc.reduce((e,[n,o])=>e.replace(n,o.bind(t)),t),Nt=t=>typeof t=="string",Hc=t=>t&&Nt(t)&&!Ec.test(t)&&!kc.test(t)&&t.indexOf("#")!==0,Fc=t=>t.split(Mc).filter(Boolean),kn=class{constructor(e,n,o,r,s,i){this.pattern=e,this.mark=n,this.negative=s,Ye(this,"body",o),Ye(this,"ignoreCase",r),Ye(this,"regexPrefix",i)}get regex(){let e=br+pt;return this[e]?this[e]:this._make(pt,e)}get checkRegex(){let e=br+Ot;return this[e]?this[e]:this._make(Ot,e)}_make(e,n){let o=this.regexPrefix.replace(Nc,Dc[e]),r=this.ignoreCase?new RegExp(o,"i"):new RegExp(o);return Ye(this,n,r)}},jc=({pattern:t,mark:e},n)=>{let o=!1,r=t;r.indexOf("!")===0&&(o=!0,r=r.substr(1)),r=r.replace(bc,"!").replace(Ac,"#");let s=Uc(r);return new kn(t,e,r,n,o,s)},bn=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Pr]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Nt(e)&&(e={pattern:e}),Hc(e.pattern)){let n=jc(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,Ar(Nt(e)?Fc(e):e).forEach(this._add,this),this._added}test(e,n,o){let r=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&r!==s||c&&!r&&!s&&!n||!l[o].test(e)||(r=!c,s=c,i=c?wc:l)});let a={ignored:r,unignored:s};return i&&(a.rule=i),a}},Bc=(t,e)=>{throw new e(t)},Me=(t,e,n)=>Nt(t)?t?Me.isNotRelative(t)?n(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${e}\``,TypeError),Ir=t=>Pc.test(t);Me.isNotRelative=Ir;Me.convert=t=>t;var An=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:o=!1}={}){Ye(this,Pr,!0),this._rules=new bn(n),this._strictPathCheck=!o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,n,o,r){let s=e&&Me.convert(e);return Me(s,e,this._strictPathCheck?Bc:Rr),this._t(s,n,o,r)}checkIgnore(e){if(!Rc.test(e))return this.test(e);let n=e.split(Je).filter(Boolean);if(n.pop(),n.length){let o=this._t(n.join(Je)+Je,this._testCache,!0,n);if(o.ignored)return o}return this._rules.test(e,!1,Ot)}_t(e,n,o,r){if(e in n)return n[e];if(r||(r=e.split(Je).filter(Boolean)),r.pop(),!r.length)return n[e]=this._rules.test(e,o,pt);let s=this._t(r.join(Je)+Je,n,o,r);return n[e]=s.ignored?s:this._rules.test(e,o,pt)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Ar(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Mn=t=>new An(t),Wc=t=>Me(t&&Me.convert(t),t,Rr),$r=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Me.convert=t;let e=/^[a-z]:\//i;Me.isNotRelative=n=>e.test(n)||Ir(n)};typeof process<"u"&&process.platform==="win32"&&$r();Dt.exports=Mn;Mn.default=Mn;Dt.exports.isPathValid=Wc;Ye(Dt.exports,Symbol.for("setupWindows"),$r)});import{randomUUID as hs}from"crypto";import{createInterface as pp}from"readline/promises";import{stdin as mp,stdout as dp}from"process";import{render as fp}from"ink";import Ls from"os";import{readFile as Os}from"fs/promises";import{join as Ns,dirname as Ds}from"path";import{fileURLToPath as Us}from"url";var Hs=/{{\s*([\w.-]+)\s*}}/g;function Fs(t,e){return t.replace(Hs,(n,o)=>e[o]??"")}function js(){try{return Ls.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function qn(){let t=Ds(Us(import.meta.url)),e=Ns(t,"prompt.md"),n=await Os(e,"utf-8"),o={date:new Date().toISOString(),user:js(),pwd:process.cwd()};return Fs(n,o)}import{appendFile as Bs,mkdir as Ws}from"fs/promises";import{dirname as Vs}from"path";var Ct=class{constructor(e){this.filePath=e}ready=!1;async append(e){this.ready||(await Ws(Vs(this.filePath),{recursive:!0}),this.ready=!0),await Bs(this.filePath,`${JSON.stringify(e)}
|
|
3
|
+
`,"utf8")}async flush(){return Promise.resolve()}};function Xn(t){return{ts:new Date().toISOString(),sessionId:t.sessionId,turn:t.turn,step:t.step,type:t.type,content:t.content,role:t.role,meta:t.meta}}import{z as we}from"zod";function L(t){let{inputSchema:e,execute:n,...o}=t,r=e.toJSONSchema?.(),{$schema:s,...i}=r??{};return{...o,source:"native",inputSchema:i,validateInput:a=>{let l=e.safeParse(a);if(!l.success){let c=l.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${t.name} invalid input: ${c}`}}return{ok:!0,data:l.data}},execute:n}}function d(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}import{spawn as zs}from"child_process";import{EventEmitter as Gs}from"events";import{resolve as Ks}from"path";var qs=1e4,Xs=250,Js=2e3,Jn=64;function Ys(t){return Math.ceil(t.length/4)}function Zs(){return Math.random().toString(16).slice(2)||String(Date.now())}function Qs(t){let e=t.login,n=t.shell?.trim();if(process.platform==="win32"){let r=n||"powershell.exe";return r.toLowerCase().includes("powershell")?{file:r,args:["-NoProfile","-Command",t.cmd]}:{file:r,args:[e?"-lc":"-c",t.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[e?"-lc":"-c",t.cmd]}}function ei(t,e){let o=(typeof e=="number"&&e>0?Math.floor(e):Js)*4,r=Ys(t);return t.length<=o?{output:t,originalTokenCount:r}:{output:t.slice(0,o),originalTokenCount:r}}function ti(t){let e=[];return e.push(`Chunk ID: ${t.chunkId}`),e.push(`Wall time: ${t.wallTimeSeconds.toFixed(4)} seconds`),t.exitCode!==null?e.push(`Process exited with code ${t.exitCode}`):e.push(`Process running with session ID ${t.sessionId}`),e.push(`Original token count: ${t.originalTokenCount}`),e.push("Output:"),e.push(t.output),e.join(`
|
|
4
|
+
`)}function Yn(t,e){return typeof t!="number"||Number.isNaN(t)?e:t<0?0:Math.floor(t)}async function Zn(t,e){e<=0||t.exited||await Promise.race([new Promise(n=>{let o=setTimeout(()=>{s(),n()},e),r=()=>{clearTimeout(o),s(),n()},s=()=>{t.eventBus.off("exit",r)};t.eventBus.on("exit",r)})])}var Yt=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Jn)return;let e=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,o)=>n.startedAtMs-o.startedAtMs);for(let n of e){if(this.sessions.size<=Jn)break;this.sessions.delete(n.id)}}async start(e){let n=e.cmd.trim();if(!n)throw new Error("cmd must not be empty");let o=this.nextId++,r=Date.now(),s=Qs({cmd:n,shell:e.shell,login:e.login!==!1}),i=e.workdir?.trim()?Ks(process.cwd(),e.workdir.trim()):process.cwd(),a=zs(s.file,s.args,{cwd:i,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),l={id:o,output:"",readOffset:0,startedAtMs:r,exited:!1,exitCode:null,eventBus:new Gs,proc:a},c=(p,T)=>{let m=typeof T=="string"?T:T.toString("utf8");l.output+=p?`${p}${m}`:m,l.eventBus.emit("output")};a.stdout?.on("data",p=>c("",p)),a.stderr?.on("data",p=>c("",p)),a.on("error",p=>{l.output+=`
|
|
5
|
+
[exec error] ${p.message}`,l.eventBus.emit("output")}),a.on("close",p=>{l.exited=!0,l.exitCode=typeof p=="number"?p:-1,l.eventBus.emit("exit")}),this.sessions.set(o,l),this.cleanupSessions();let u=Yn(e.yield_time_ms,qs);return await Zn(l,u),this.buildResponseText(l,e.max_output_tokens)}async write(e){let n=this.sessions.get(e.session_id);if(!n)throw new Error(`session_id ${e.session_id} not found`);!n.exited&&e.chars&&e.chars.length>0&&n.proc.stdin?.write(e.chars);let o=Yn(e.yield_time_ms,Xs);return await Zn(n,o),this.buildResponseText(n,e.max_output_tokens)}buildResponseText(e,n){let o=e.output.slice(e.readOffset);e.readOffset=e.output.length;let r=ei(o,n),s={sessionId:e.id,chunkId:Zs(),wallTimeSeconds:(Date.now()-e.startedAtMs)/1e3,exitCode:e.exited?e.exitCode:null,output:r.output,originalTokenCount:r.originalTokenCount};return ti(s)}},Qn=new Yt;async function We(t){return Qn.start(t)}async function eo(t){return Qn.write(t)}var ni=we.object({command:we.array(we.string().min(1)).min(1,"command \u4E0D\u80FD\u4E3A\u7A7A"),workdir:we.string().optional(),timeout_ms:we.number().int().positive().optional(),sandbox_permissions:we.enum(["use_default","require_escalated"]).optional(),justification:we.string().optional(),prefix_rule:we.array(we.string().min(1)).optional()}).strict();function oi(t){return t.map(e=>/^[A-Za-z0-9_./:@%+-]+$/.test(e)?e:JSON.stringify(e)).join(" ")}var to=L({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:ni,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,timeout_ms:n})=>{try{let o=await We({cmd:oi(t),workdir:e,login:!1,yield_time_ms:n});return d(o)}catch(o){return d(`shell failed: ${o.message}`,!0)}}});import{z as Ee}from"zod";var ri=Ee.object({command:Ee.string().min(1,"command \u4E0D\u80FD\u4E3A\u7A7A"),workdir:Ee.string().optional(),login:Ee.boolean().optional(),timeout_ms:Ee.number().int().positive().optional(),sandbox_permissions:Ee.enum(["use_default","require_escalated"]).optional(),justification:Ee.string().optional(),prefix_rule:Ee.array(Ee.string().min(1)).optional()}).strict(),no=L({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:ri,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:t,workdir:e,login:n,timeout_ms:o})=>{try{let r=await We({cmd:t,workdir:e,login:n,yield_time_ms:o});return d(r)}catch(r){return d(`shell_command failed: ${r.message}`,!0)}}});import{z as pe}from"zod";var si=pe.object({cmd:pe.string().min(1,"cmd \u4E0D\u80FD\u4E3A\u7A7A"),workdir:pe.string().optional(),shell:pe.string().optional(),login:pe.boolean().optional(),tty:pe.boolean().optional(),yield_time_ms:pe.number().int().nonnegative().optional(),max_output_tokens:pe.number().int().positive().optional(),sandbox_permissions:pe.enum(["use_default","require_escalated"]).optional(),justification:pe.string().optional(),prefix_rule:pe.array(pe.string().min(1)).optional()}).strict(),Zt=L({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:si,supportsParallelToolCalls:!0,isMutating:!0,execute:async t=>{try{let e=await We(t);return d(e)}catch(e){return d(`exec_command failed: ${e.message}`,!0)}}});import{z as tt}from"zod";var ii=tt.object({session_id:tt.number().int().positive(),chars:tt.string().optional(),yield_time_ms:tt.number().int().nonnegative().optional(),max_output_tokens:tt.number().int().positive().optional()}).strict(),Qt=L({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:ii,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=await eo(t);return d(e)}catch(e){return d(`write_stdin failed: ${e.message}`,!0)}}});import{mkdir as go,readFile as Li,rm as ho,writeFile as an}from"fs/promises";import{dirname as yo}from"path";import{z as To}from"zod";var Pi=Kn(po(),1);import{normalize as wi,resolve as Ei,dirname as sm,join as ki,relative as bi,isAbsolute as Ai}from"path";import{homedir as Mi}from"os";import{existsSync as lm,statSync as cm}from"fs";import{readFile as pm}from"fs/promises";function me(t){return wi(Ei(t))}function Ri(t,e){let n=bi(e,t);return n===""||!n.startsWith("..")&&!Ai(n)}function Ii(){let t=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>me(e)):[]}function mo(){let t=new Set;t.add(me(process.cwd()));let e=process.env.MEMO_HOME?.trim()||ki(Mi(),".memo");t.add(me(e));for(let n of Ii())t.add(n);return Array.from(t)}function $i(t){return mo().some(n=>Ri(t,n))}function fo(t){if($i(t))return null;let e=mo();return`sandbox \u62D2\u7EDD\u5199\u5165: ${t} \u4E0D\u5728\u5141\u8BB8\u76EE\u5F55\u5185 (${e.join(", ")})`}var Oi=To.object({input:To.string().min(1,"patch input \u4E0D\u80FD\u4E3A\u7A7A")}).strict();function Ni(t){let e=t.replace(/\r/g,"").split(`
|
|
6
|
+
`);if(e[0]!=="*** Begin Patch")throw new Error("patch must start with *** Begin Patch");let n=[],o=1;for(;o<e.length;){let r=e[o]??"";if(r==="*** End Patch")break;if(!r){o+=1;continue}if(r.startsWith("*** Add File: ")){let s=r.slice(14).trim();if(!s)throw new Error("Add File requires a path");o+=1;let i=[];for(;o<e.length;){let a=e[o];if(a===void 0||a.startsWith("*** "))break;if(!a.startsWith("+"))throw new Error("Add File lines must start with +");i.push(a.slice(1)),o+=1}n.push({type:"add",file:s,lines:i});continue}if(r.startsWith("*** Delete File: ")){let s=r.slice(17).trim();if(!s)throw new Error("Delete File requires a path");n.push({type:"delete",file:s}),o+=1;continue}if(r.startsWith("*** Update File: ")){let s=r.slice(17).trim();if(!s)throw new Error("Update File requires a path");o+=1;let i,a=e[o];a&&a.startsWith("*** Move to: ")&&(i=a.slice(13).trim(),o+=1);let l=[],c=[];for(;o<e.length;){let u=e[o];if(u===void 0||u.startsWith("*** "))break;if(u.startsWith("@@")){c.length>0&&(l.push(c),c=[]),o+=1;continue}if(u==="*** End of File"){o+=1;continue}if(u.startsWith("+")||u.startsWith("-")||u.startsWith(" ")){c.push(u),o+=1;continue}throw new Error(`Unexpected patch line: ${u}`)}if(c.length>0&&l.push(c),l.length===0)throw new Error(`Update File ${s} has no hunks`);n.push({type:"update",file:s,moveTo:i,hunks:l});continue}throw new Error(`Unexpected patch marker: ${r}`)}if(n.length===0)throw new Error("patch contains no operations");return n}function Di(t,e){let n=e.filter(s=>s.startsWith(" ")||s.startsWith("-")).map(s=>s.slice(1)).join(`
|
|
7
|
+
`),o=e.filter(s=>s.startsWith(" ")||s.startsWith("+")).map(s=>s.slice(1)).join(`
|
|
8
|
+
`);if(!n){if(!o)return t;if(!t)return o;let s=t.endsWith(`
|
|
9
|
+
`)?"":`
|
|
10
|
+
`;return`${t}${s}${o}`}let r=t.indexOf(n);if(r<0)throw new Error("patch hunk context not found in target file");return`${t.slice(0,r)}${o}${t.slice(r+n.length)}`}function Et(t){let e=fo(t);if(e)throw new Error(e)}var _o=L({name:"apply_patch",description:"Apply a structured patch with Add/Update/Delete operations and hunk-based replacements.",inputSchema:Oi,supportsParallelToolCalls:!1,isMutating:!0,execute:async t=>{try{let e=Ni(t.input);for(let n of e){if(n.type==="add"){let s=me(n.file);Et(s),await go(yo(s),{recursive:!0}),await an(s,n.lines.join(`
|
|
11
|
+
`),"utf8");continue}if(n.type==="delete"){let s=me(n.file);Et(s),await ho(s);continue}let o=me(n.file);Et(o);let r=await Li(o,"utf8");for(let s of n.hunks)r=Di(r,s);if(n.moveTo){let s=me(n.moveTo);Et(s),await go(yo(s),{recursive:!0}),await an(s,r,"utf8"),s!==o&&await ho(o)}else await an(o,r,"utf8")}return d(`apply_patch succeeded (${e.length} operations)`)}catch(e){return d(`apply_patch failed: ${e.message}`,!0)}}});import{readFile as Ui}from"fs/promises";import{z as ye}from"zod";var xo=500,So=200,Hi=ye.object({file_path:ye.string().min(1),offset:ye.number().int().positive().optional(),limit:ye.number().int().positive().optional(),mode:ye.enum(["slice","indentation"]).optional(),indentation:ye.object({anchor_line:ye.number().int().positive().optional(),max_levels:ye.number().int().nonnegative().optional(),include_siblings:ye.boolean().optional(),include_header:ye.boolean().optional(),max_lines:ye.number().int().positive().optional()}).strict().optional()}).strict();function Fi(t){return t.length<=xo?t:t.slice(0,xo)}function ji(t){let e=0;for(let n of t)if(n===" ")e+=1;else if(n===" ")e+=4;else break;return e}function Bi(t){return t.split(/\r?\n/).map((n,o)=>({line:o+1,text:Fi(n),indent:ji(n)}))}function Wi(t){return t.map(e=>`L${e.line}: ${e.text}`).join(`
|
|
12
|
+
`)}function Vi(t,e,n){let o=e-1;if(o>=t.length)throw new Error("offset exceeds file length");return t.slice(o,o+n)}function zi(t,e){let n=e.offset??1,o=e.limit??So,r=e.indentation,s=r?.anchor_line??n;if(s<=0||s>t.length)throw new Error("anchor_line exceeds file length");let i=t[s-1];if(!i)throw new Error("anchor_line exceeds file length");let a=r?.max_levels??0,l=r?.include_siblings??!0,c=r?.include_header??!0,u=r?.max_lines??o,p=Math.max(1,Math.min(o,u)),T=a===0?0:Math.max(0,i.indent-a*4),m=s-1,S=s-1;for(;m-1>=0;){let _=t[m-1];if(!_)break;let v=/^\s*(#|\/\/|--)/.test(_.text),N=_.text.trim().length===0;if(_.indent<T||!l&&_.indent===T&&!v&&!N||!c&&(v||N)&&_.indent<i.indent||(m-=1,S-m+1>=p))break}for(;S+1<t.length&&S-m+1<p;){let _=t[S+1];if(!_||_.indent<T||!l&&_.indent===T)break;S+=1}return t.slice(m,S+1)}var vo=L({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Hi,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??1,n=t.limit??So;if(e<=0)return d("offset must be a 1-indexed line number",!0);if(n<=0)return d("limit must be greater than zero",!0);let o=t.file_path.trim();if(!o.startsWith("/"))return d("file_path must be an absolute path",!0);let r=me(o);try{let s=await Ui(r,"utf8"),i=Bi(s);if(i.length===0)return d("");let l=(t.mode??"slice")==="indentation"?zi(i,t):Vi(i,e,n);return d(Wi(l))}catch(s){return d(`read_file failed: ${s.message}`,!0)}}});import{readdir as Gi,lstat as Ki}from"fs/promises";import{join as qi}from"path";import{z as nt}from"zod";var Xi=1,Ji=25,Yi=2,Zi=nt.object({dir_path:nt.string().min(1),offset:nt.number().int().positive().optional(),limit:nt.number().int().positive().optional(),depth:nt.number().int().positive().optional()}).strict();function Qi(t){let e=" ".repeat(t.displayDepth*2),n="";t.kind==="dir"&&(n="/"),t.kind==="symlink"&&(n="@"),t.kind==="other"&&(n="?");let o=t.path.split("/"),r=o[o.length-1]??t.path;return`${e}${r}${n}`}var Co=L({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:Zi,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.offset??Xi,n=t.limit??Ji,o=t.depth??Yi;if(e<=0)return d("offset must be a 1-indexed entry number",!0);if(n<=0)return d("limit must be greater than zero",!0);if(o<=0)return d("depth must be greater than zero",!0);let r=t.dir_path.trim();if(!r.startsWith("/"))return d("dir_path must be an absolute path",!0);let s=me(r);try{let i=[{absPath:s,depth:o,displayDepth:0}],a=[];for(;i.length>0;){let p=i.shift();if(!p)continue;let T=await Gi(p.absPath);T.sort((m,S)=>m.localeCompare(S));for(let m of T){let S=qi(p.absPath,m),_=await Ki(S),v=_.isSymbolicLink()?"symlink":_.isDirectory()?"dir":_.isFile()?"file":"other";a.push({path:S,displayDepth:p.displayDepth,kind:v}),v==="dir"&&p.depth>1&&i.push({absPath:S,depth:p.depth-1,displayDepth:p.displayDepth+1})}}if(a.length===0)return d(`Absolute path: ${s}`);let l=e-1;if(l>=a.length)return d("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),u=[`Absolute path: ${s}`,...c.map(Qi)];return l+n<a.length&&u.push(`More than ${n} entries found`),d(u.join(`
|
|
13
|
+
`))}catch(i){return d(`list_dir failed: ${i.message}`,!0)}}});import{spawn as ea}from"child_process";import{resolve as ta}from"path";import{z as ot}from"zod";var na=100,oa=2e3,ra=3e4,sa=ot.object({pattern:ot.string().min(1),include:ot.string().optional(),path:ot.string().optional(),limit:ot.number().int().positive().optional()}).strict();function ia(t){return new Promise((e,n)=>{let o=["--files-with-matches","--sortr=modified","--regexp",t.pattern,"--no-messages"];t.include?.trim()&&o.push("--glob",t.include.trim()),o.push("--",t.searchPath);let r=ea("rg",o,{cwd:t.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>s.push(l)),r.stderr?.on("data",l=>i.push(l));let a=setTimeout(()=>{r.kill("SIGTERM"),n(new Error("rg timed out after 30 seconds"))},ra);r.on("error",l=>{clearTimeout(a),n(l)}),r.on("close",l=>{clearTimeout(a),e({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var wo=L({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:sa,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e=t.pattern.trim();if(!e)return d("pattern must not be empty",!0);let n=Math.min(t.limit??na,oa),o=t.path?.trim()?ta(process.cwd(),t.path.trim()):process.cwd();try{let r=await ia({pattern:e,include:t.include,searchPath:o,cwd:process.cwd(),limit:n});if(r.exitCode===1)return d("No matches found.");if(r.exitCode!==0)return d(`rg failed: ${r.stderr||r.stdout}`,!0);let s=r.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,n);return s.length===0?d("No matches found."):d(s.join(`
|
|
14
|
+
`))}catch(r){return d(`grep_files failed: ${r.message}`,!0)}}});import{z as be}from"zod";var Eo=null;function ln(t){Eo=t}function ko(){return Eo}var aa=be.object({server:be.string().optional(),cursor:be.string().optional()}).strict(),la=be.object({server:be.string().optional(),cursor:be.string().optional()}).strict(),ca=be.object({server:be.string().min(1),uri:be.string().min(1)}).strict();function cn(){let t=ko();if(!t)throw new Error("MCP pool is not initialized");return t}var bo=L({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:aa,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=cn();if(t?.trim()){let s=n.get(t.trim());if(!s)return d(`MCP server not found: ${t}`,!0);let i=await s.client.listResources(e?{cursor:e}:void 0);return d(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(e)return d("cursor is only supported when server is specified",!0);let o=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),r=[];for(let s of o){let i=await s.client.listResources();for(let a of i.resources)r.push({server:s.name,...a})}return d(JSON.stringify({resources:r},null,2))}catch(n){return d(`list_mcp_resources failed: ${n.message}`,!0)}}}),Ao=L({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:la,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=cn();if(t?.trim()){let s=n.get(t.trim());if(!s)return d(`MCP server not found: ${t}`,!0);let i=await s.client.listResourceTemplates(e?{cursor:e}:void 0);return d(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(e)return d("cursor is only supported when server is specified",!0);let o=n.getAll().sort((s,i)=>s.name.localeCompare(i.name)),r=[];for(let s of o){let i=await s.client.listResourceTemplates();for(let a of i.resourceTemplates)r.push({server:s.name,...a})}return d(JSON.stringify({resourceTemplates:r},null,2))}catch(n){return d(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Mo=L({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:ca,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let o=cn().get(t);if(!o)return d(`MCP server not found: ${t}`,!0);let r=await o.client.readResource({uri:e});return d(JSON.stringify({server:t,uri:e,...r},null,2))}catch(n){return d(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as Ve}from"zod";var ua=Ve.object({step:Ve.string().min(1),status:Ve.enum(["pending","in_progress","completed"])}).strict(),pa=Ve.object({explanation:Ve.string().optional(),plan:Ve.array(ua).min(1)}).strict(),Po=[],Ro=L({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:pa,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>e.filter(o=>o.status==="in_progress").length>1?d("At most one step can be in_progress at a time",!0):(Po=e,d(JSON.stringify({message:"Plan updated",explanation:t,plan:Po},null,2)))});import{readFile as ma}from"fs/promises";import{homedir as da}from"os";import{join as Io}from"path";import{z as $o}from"zod";var fa=$o.object({memory_id:$o.string().min(1)}).strict();function ga(){let t=process.env.MEMO_HOME?.trim()||Io(da(),".memo");return Io(t,"Agents.md")}var Lo=L({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:fa,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=ga(),n=await ma(e,"utf8");return d(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return d(`memory not found for memory_id=${t}`,!0)}}});import{z as Oo}from"zod";var ha=Oo.object({url:Oo.string().min(1)}).strict(),No=1e4,rt=512e3,un=4e3,ya=new Set(["http:","https:","data:"]),Ta=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,_a=/<\s*(br|hr)\s*\/?>/gi,xa=/<\s*li[^>]*>/gi,Sa=/<[^>]+>/g,va=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Ca=t=>t.replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(o,r)=>{try{let s=r.startsWith("x")||r.startsWith("X")?parseInt(r.slice(1),16):parseInt(r,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),wa=t=>{let o=t.replace(va," ").replace(xa,"- ").replace(_a,`
|
|
15
|
+
`).replace(Ta,`
|
|
16
|
+
`).replace(Sa," "),s=Ca(o).replace(/\r/g,"").split(`
|
|
17
|
+
`).map(a=>a.trim().replace(/[ \t]{2,}/g," "));return s.filter((a,l)=>a.length>0||l>0&&(s[l-1]?.length??0)>0).join(`
|
|
18
|
+
`).trim()},Ea=t=>t.replace(/\s+/g," ").trim(),Do=L({name:"webfetch",description:"HTTP GET \u8BF7\u6C42\uFF0C\u8FD4\u56DE\u5904\u7406\u540E\u7684\u7EAF\u6587\u672C\u6B63\u6587\uFF08\u81EA\u52A8\u5265\u79BB HTML \u6807\u7B7E\uFF09",inputSchema:ha,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return d(`\u65E0\u6548 URL: ${t.url}`,!0)}if(!ya.has(e.protocol))return d(`\u4E0D\u652F\u6301\u7684\u534F\u8BAE: ${e.protocol}`,!0);let n=new AbortController,o=setTimeout(()=>n.abort(),No);try{let r=await globalThis.fetch(e,{signal:n.signal}),s=r.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>rt)return d(`\u8BF7\u6C42\u88AB\u62D2\u7EDD: \u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${i} bytes\uFF09`,!0);let a=0,l="";if(r.body&&r.body.getReader){let v=r.body.getReader(),N=[];for(;;){let{done:y,value:k}=await v.read();if(y)break;if(k){if(a+=k.byteLength,a>rt)return n.abort(),d(`\u8BF7\u6C42\u88AB\u4E2D\u6B62: \u54CD\u5E94\u4F53\u8D85\u8FC7 ${rt} bytes`,!0);N.push(k)}}let R=new Uint8Array(a),w=0;for(let y of N)R.set(y,w),w+=y.byteLength;l=new TextDecoder().decode(R)}else if(l=await r.text(),a=new TextEncoder().encode(l).byteLength,a>rt)return d(`\u8BF7\u6C42\u88AB\u62D2\u7EDD: \u54CD\u5E94\u4F53\u8D85\u8FC7 ${rt} bytes`,!0);let c=r.headers.get("content-type")||"",u=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),p=u?wa(l):l.trim(),T=Ea(p),m=T.length>un?`${T.slice(0,un)}...`:T,S=T.length>un?" text_truncated=true":"",_=u?" source=html_stripped":"";return d(`status=${r.status} bytes=${a} text_chars=${T.length} text="${m}"${S}${_}`)}catch(r){return r.name==="AbortError"?d(`\u8BF7\u6C42\u8D85\u65F6\u6216\u88AB\u4E2D\u6B62\uFF08${No}ms\uFF09`,!0):d(`\u8BF7\u6C42\u5931\u8D25: ${r.message}`,!0)}finally{clearTimeout(o)}}});import{spawn as ka}from"child_process";import{existsSync as ba}from"fs";import{resolve as Aa}from"path";import{z as ne}from"zod";var Ma=3e4,Pa=1e4,Ra=3e5,Uo=4,Ia=1500,Ho=2e3,$e=new Map,$a=ne.object({message:ne.string().min(1),agent_type:ne.string().optional()}).strict(),La=ne.object({id:ne.string().min(1),message:ne.string().min(1),interrupt:ne.boolean().optional()}).strict(),Oa=ne.object({id:ne.string().min(1)}).strict(),Na=ne.object({ids:ne.array(ne.string().min(1)).min(1),timeout_ms:ne.number().int().positive().optional()}).strict(),Da=ne.object({id:ne.string().min(1)}).strict();function ze(){return new Date().toISOString()}function pn(t){return d(`agent not found: ${t}`,!0)}function Ua(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return Uo;let e=Number(t);return!Number.isFinite(e)||e<=0?Uo:Math.floor(e)}function Ha(){let t=0;for(let e of $e.values())e.running&&(t+=1);return t}function Fa(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=Aa(process.cwd(),"dist/index.js");return ba(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function ja(t){return t!=="running"}function Ba(t){return new Promise(e=>{setTimeout(e,t)})}function Wa(t){return t===void 0?Ma:t<=0?null:Math.max(Pa,Math.min(Ra,t))}function Va(t){return t.length<=Ho?t:`${t.slice(0,Ho)}
|
|
19
|
+
...[truncated]`}function za(t,e){let n=[],o=t.trim(),r=e.trim();return o&&n.push(o),r&&n.push(`stderr:
|
|
20
|
+
${r}`),Va(n.join(`
|
|
21
|
+
|
|
22
|
+
`))}async function Fo(t){let e=t.running;if(!e)return;e.interrupted=!0;let n=e.process;n.exitCode!==null||n.killed||await new Promise(o=>{let r=!1,s=()=>{r||(r=!0,clearTimeout(i),n.off("close",s),o())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},Ia);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function Ga(t){let e=$e.get(t);return e?e.status:"not_found"}function Ka(t){let e=$e.get(t);return e?{status:e.status,last_message:e.lastMessage,last_output:e.lastOutput,last_error:e.lastError,last_submission_id:e.lastSubmissionId,updated_at:e.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function qa(t){return{agent_id:t.id,status:t.status,created_at:t.createdAt,updated_at:t.updatedAt,last_message:t.lastMessage,last_submission_id:t.lastSubmissionId,has_last_output:!!t.lastOutput,has_last_error:!!t.lastError}}function Xa(t){let{record:e,submissionId:n,stdout:o,stderr:r,exitCode:s,interrupted:i}=t;if(!(!e.running||e.running.id!==n)&&(e.running=null,e.updatedAt=ze(),e.lastOutput=za(o,r)||null,e.lastError=null,e.status!=="closed")){if(i){e.status="errored",e.lastError="interrupted",e.statusBeforeClose="errored";return}if(s===0){e.status="completed",e.statusBeforeClose="completed";return}e.status="errored",e.lastError=`submission failed with exit code ${s}`,e.statusBeforeClose="errored"}}async function jo(t,e){let n=Ua();if(Ha()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let o=crypto.randomUUID(),r=Fa(),s=ka(r,{cwd:process.cwd(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],a=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",l=>i.push(l)),s.stderr?.on("data",l=>a.push(l)),s.on("error",l=>{a.push(`[spawn error] ${l.message}`)}),t.running={id:o,message:e,process:s,startedAt:ze(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=o,t.updatedAt=ze(),s.on("close",l=>{let c=typeof l=="number"?l:-1,u=!!(t.running?.id===o&&t.running.interrupted);Xa({record:t,submissionId:o,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:u})});try{s.stdin?.write(`${e.trim()}
|
|
23
|
+
`)}catch{}try{s.stdin?.end()}catch{}return o}var Bo=L({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:$a,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return d("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),o=ze(),r={id:n,createdAt:o,updatedAt:o,status:"running",statusBeforeClose:"completed",lastMessage:e,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};$e.set(n,r);try{let s=await jo(r,e);return d(JSON.stringify({...qa(r),submission_id:s},null,2))}catch(s){return $e.delete(n),d(`spawn_agent failed: ${s.message}`,!0)}}}),Wo=L({name:"send_input",description:"Send a message to an existing agent.",inputSchema:La,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let o=$e.get(t);if(!o)return pn(t);let r=e.trim();if(!r)return d("send_input failed: message must not be empty",!0);if(o.status==="closed")return d(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(o.running){if(!n)return d(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await Fo(o)}try{let s=await jo(o,r);return d(JSON.stringify({agent_id:o.id,status:o.status,submission_id:s},null,2))}catch(s){return d(`send_input failed: ${s.message}`,!0)}}}),Vo=L({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Oa,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=$e.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=ze()),d(JSON.stringify({agent_id:t,status:e.status},null,2))):pn(t)}}),zo=L({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Na,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=Wa(e);if(n===null)return d("wait failed: timeout_ms must be greater than zero",!0);let o=()=>{let i={},a={};for(let l of t){let c=Ga(l);ja(c)&&(i[l]=c,a[l]=Ka(l))}return{status:i,details:a}},r=o();if(Object.keys(r.status).length>0)return d(JSON.stringify({status:r.status,details:r.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await Ba(100),r=o(),Object.keys(r.status).length>0)return d(JSON.stringify({status:r.status,details:r.details,timed_out:!1},null,2));return d(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),Go=L({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Da,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=$e.get(t);return e?e.status==="closed"?d(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=ze(),await Fo(e),d(JSON.stringify({agent_id:t,status:"closed"},null,2))):pn(t)}});var mn={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_file:"read",list_dir:"read",grep_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},Ko=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]);var kt={read:0,write:1,execute:2},dn={read:t=>`${t} \u5C06\u8BFB\u53D6\u6587\u4EF6\u6216\u6570\u636E`,write:t=>`${t} \u5C06\u4FEE\u6539\u6216\u521B\u5EFA\u6587\u4EF6`,execute:t=>`${t} \u5C06\u6267\u884C\u7CFB\u7EDF\u547D\u4EE4`};function fn(t){let e={...mn,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let o=n.toLowerCase();return o.includes("exec")||o.includes("run")||o.includes("shell")||o.includes("command")||o.includes("stdin")?"execute":o.includes("write")||o.includes("patch")||o.includes("create")||o.includes("delete")||o.includes("modify")||o.includes("update")?"write":o.includes("read")||o.includes("get")||o.includes("fetch")||o.includes("search")||o.includes("list")||o.includes("find")?"read":"write"},compareRisk(n,o){return kt[n]-kt[o]},needsApproval(n,o){return o==="strict"?!0:n==="write"||n==="execute"}}}import{createHash as Ja}from"crypto";function bt(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>bt(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${bt(o)}`).join(",")}}`}function gn(t,e){let n=bt(e),o=`${t}:${n}`;return Ja("sha256").update(o).digest("hex").slice(0,16)}function hn(t){let{mode:e="auto",dangerous:n=!1,toolRiskLevels:o}=t||{},r=e==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=fn({customLevels:o}),i={session:new Set,once:new Set,denied:new Set};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(Ko.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,r))return{needApproval:!1,decision:"auto-execute"};let u=gn(a,l);return i.session.has(u)||i.once.has(u)?{needApproval:!1,decision:"auto-execute"}:i.denied.has(u)?{needApproval:!0,fingerprint:u,riskLevel:c,reason:"\u8BE5\u8BF7\u6C42\u5DF2\u88AB\u62D2\u7EDD",toolName:a,params:l}:{needApproval:!0,fingerprint:u,riskLevel:c,reason:dn[c](a),toolName:a,params:l}},recordDecision(a,l){switch(i.session.delete(a),i.once.delete(a),i.denied.delete(a),l){case"session":i.session.add(a);break;case"once":i.once.add(a);break;case"deny":i.denied.add(a);break}},isGranted(a){return i.session.has(a)||i.once.has(a)},clearOnceApprovals(){i.once.clear()},dispose(){i.session.clear(),i.once.clear(),i.denied.clear()}}}var qo=12e3;function Ya(){let t=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!t)return qo;let e=Number(t);return!Number.isFinite(e)||e<=0?qo:Math.floor(e)}function Za(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Qa(t){let e=0;for(let n of t.content??[]){if(n.type==="text"){e+=n.text.length;continue}try{e+=JSON.stringify(n).length}catch{e+=100}}return e}function el(t,e,n){return`<system_hint type="tool_output_omitted" tool="${Za(t)}" reason="too_long" actual_chars="${e}" max_chars="${n}">\u5DE5\u5177\u8FD4\u56DE\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u81EA\u52A8\u7701\u7565\u3002\u8BF7\u7F29\u5C0F\u8303\u56F4\u6216\u589E\u52A0\u9650\u5236\u53C2\u6570\u540E\u91CD\u8BD5\u3002</system_hint>`}function tl(t,e){let n=Ya(),o=Qa(e);return o<=n?e:{content:[{type:"text",text:el(t,o,n)}],isError:!1}}function nl(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
|
|
24
|
+
`)}function ol(t,e){let n=e;if(typeof e=="string"){let o=e.trim();if(o)try{n=JSON.parse(o)}catch{n=o}else n={}}return typeof n!="object"||n===null?{ok:!1,error:`${t.name} invalid input: expected object`}:typeof t.validateInput=="function"?t.validateInput(n):{ok:!0,data:n}}function rl(t){let e=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return e.includes("sandbox")||e.includes("permission denied")||e.includes("operation not permitted")||e.includes("eacces")?"sandbox_denied":"execution_failed"}var yn=class{constructor(e){this.config=e;this.approvalManager=hn(e.approval)}approvalManager;async executeAction(e,n){let o=Date.now(),r=e.id??`${e.name}:${o}`,s=this.approvalManager.check(e.name,e.input);if(s.needApproval){let a={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(a);let l=n?.requestApproval?await n.requestApproval(a):"deny";if(this.approvalManager.recordDecision(s.fingerprint,l),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:l}),l==="deny")return{actionId:r,tool:e.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C: ${e.name}`,durationMs:Date.now()-o,rejected:!0}}let i=this.config.tools[e.name];if(!i)return{actionId:r,tool:e.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${e.name}`,durationMs:Date.now()-o};try{let a=ol(i,e.input);if(!a.ok)return{actionId:r,tool:e.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-o};let l=await i.execute(a.data),c=tl(e.name,l);return{actionId:r,tool:e.name,status:"success",success:!0,observation:nl(c)||"(no tool output)",durationMs:Date.now()-o}}catch(a){let l=rl(a);return{actionId:r,tool:e.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-o}}}async executeActions(e,n={}){let o=n.executionMode??"sequential",r=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(o==="parallel"){let l=await Promise.all(e.map(c=>this.executeAction(c,n)));if(r==="fail_fast"){let c=l.findIndex(u=>u.rejected);s=c>=0?l.slice(0,c+1):l}else s=l}else for(let l of e){let c=await this.executeAction(l,n);if(s.push(c),c.rejected&&r==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
|
|
25
|
+
|
|
26
|
+
`);return{results:s,combinedObservation:a,hasRejection:i,executionMode:o,failurePolicy:r}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function Xo(t){return new yn(t)}var At=class{tools=new Map;register(e){this.tools.set(e.name,e)}registerMany(e){for(let n of e)this.register(n)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,o]of this.tools)e[n]=o;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}};import{Client as sl}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as il}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as al}from"@modelcontextprotocol/sdk/client/stdio.js";function ll(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(o=>typeof o[1]=="string");return Object.fromEntries(n)}function Jo(){return new sl({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function cl(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function ul(t){let e={...t.http_headers??t.headers??{}};if(t.bearer_token_env_var){let n=process.env[t.bearer_token_env_var];n&&!e.Authorization&&(e.Authorization=`Bearer ${n}`)}return e}async function pl(t){let e=new URL(t.url),n=cl(ul(t));try{let o=Jo(),r=new il(e,{requestInit:n});return await o.connect(r),{client:o,transport:r}}catch(o){let r=`Failed to connect via streamable_http (${o.message})`,s=new Error(r);throw s.cause=o,s}}async function ml(t){if("url"in t)return pl(t);let e={command:t.command,args:t.args,env:ll(t.env),stderr:t.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new al(e),o=Jo();return await o.connect(n),{client:o,transport:n}}var Mt=class{connections=new Map;async connect(e,n){let o=this.connections.get(e);if(o)return o;let{client:r,transport:s}=await ml(n),i=await r.listTools(),a={name:e,client:r,transport:s,tools:(i.tools||[]).map(l=>({name:`${e}_${l.name}`,description:l.description||`Tool from ${e}: ${l.name}`,source:"mcp",serverName:e,originalName:l.name,inputSchema:l.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(e,a),a}get(e){return this.connections.get(e)}getAll(){return Array.from(this.connections.values())}getAllTools(){let e=[];for(let n of this.connections.values())for(let o of n.tools)e.push({name:o.name,description:o.description,serverName:o.serverName,originalName:o.originalName,inputSchema:o.inputSchema,client:n.client});return e}async closeAll(){let e=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(o){console.error(`[MCP] Error closing client ${n.name}:`,o)}});await Promise.all(e),this.connections.clear()}get size(){return this.connections.size}};var Pt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new Mt,ln(this.pool),this.shouldLog=process.env.MEMO_MCP_LOG==="1"||!(process.stdout.isTTY&&process.stdin.isTTY)}async loadServers(e){if(!e||Object.keys(e).length===0)return 0;let n=0;return await Promise.all(Object.entries(e).map(async([o,r])=>{try{let s=await this.pool.connect(o,r);for(let i of s.tools){let a={...i,execute:async l=>{let c=this.pool.get(i.serverName)?.client;if(!c)throw new Error(`MCP client for server '${i.serverName}' not found`);return c.callTool({name:i.originalName,arguments:l})}};this.tools.set(a.name,a)}n+=s.tools.length,this.shouldLog&&console.log(`[MCP] Connected to '${o}' with ${s.tools.length} tools`)}catch(s){this.shouldLog&&console.error(`[MCP] Failed to connect to server '${o}':`,s)}})),n}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,o]of this.tools)e[n]=o;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),ln(null)}getPool(){return this.pool}};var Rt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new At,this.mcpRegistry=new Pt}registerNativeTool(e){this.nativeRegistry.register(e)}registerNativeTools(e){for(let n of e)this.registerNativeTool(n)}async loadMcpServers(e){return this.mcpRegistry.loadServers(e)}getTool(e){return this.nativeRegistry.get(e)??this.mcpRegistry.get(e)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(e){return this.nativeRegistry.has(e)||this.mcpRegistry.has(e)}getToolCount(){let e=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:e,mcp:n,total:e+n}}async execute(e,n){let o=this.getTool(e);if(!o)throw new Error(`Tool '${e}' not found`);return o.execute(n)}generateToolDefinitions(){return this.getAllTools().map(e=>({name:e.name,description:e.description,input_schema:e.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let e=this.getAllTools();if(e.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let o=e.filter(s=>s.source==="native"),r=e.filter(s=>s.source==="mcp");if(o.length>0){n.push("### Built-in Tools"),n.push("");for(let s of o)n.push(this.formatToolDescription(s));n.push("")}if(r.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(r);for(let[i,a]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let l of a)n.push(this.formatToolDescription(l));n.push("")}}return n.join(`
|
|
27
|
+
`)}formatToolDescription(e){let n=[];return n.push(`#### ${e.name}`),n.push(`- **Description**: ${e.description}`),e.inputSchema&&Object.keys(e.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(e.inputSchema)}`),n.join(`
|
|
28
|
+
`)}groupByServer(e){let n={};for(let o of e)if(o.source==="mcp"){let r=o.serverName;n[r]||(n[r]=[]),n[r].push(o)}return n}getToolDescriptions(){return this.getAllTools().map(e=>({name:e.name,description:e.description,source:e.source,serverName:e.source==="mcp"?e.serverName:void 0,inputSchema:e.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};function dl(t){let e=process.env[t]?.trim();return e?new Set(e.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function fl(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=dl("MEMO_EXPERIMENTAL_TOOLS"),o=n.size===0,r=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return e==="shell"?t.push(to):e==="shell_command"?t.push(no):e==="unified_exec"?t.push(Zt,Qt):e!=="disabled"&&t.push(Zt,Qt),t.push(bo,Ao,Mo),t.push(Ro),t.push(_o),(o||n.has("grep_files"))&&t.push(wo),(o||n.has("read_file"))&&t.push(vo),(o||n.has("list_dir"))&&t.push(Co),s&&t.push(Lo),t.push(Do),r&&t.push(Bo,Wo,Vo,zo,Go),t}function gl(t){let e={};for(let n of t)e[n.name]=n;return e}var hl=gl(fl()),yl=Object.values(hl),Yo=yl;import $l from"openai";import{encoding_for_model as Tl,get_encoding as _l}from"@dqbd/tiktoken";var Zo="cl100k_base";function xl(t){let e=t?.trim()||Zo;try{let n=()=>Tl(e);return n().free(),{model:e,factory:n}}catch{let n=Zo,o=()=>_l(n);return o().free(),{model:n,factory:o}}}function Sl(t){return t.role==="assistant"&&t.tool_calls?.length?`${t.content}
|
|
29
|
+
${JSON.stringify(t.tool_calls)}`:t.role==="tool"?`${t.content}
|
|
30
|
+
${t.tool_call_id}
|
|
31
|
+
${t.name??""}`:t.content}function Qo(t){let{model:e,factory:n}=xl(t),o=n(),r=4,s=2,i=1,a=c=>c?o.encode(c).length:0;return{model:e,countText:a,countMessages:c=>{if(!c.length)return 0;let u=0;for(let p of c)u+=r,u+=a(Sl(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>o.free()}}import{mkdir as vl,writeFile as Cl,readFile as wl,access as El}from"fs/promises";import{homedir as er}from"os";import{dirname as kl,join as it}from"path";import{randomUUID as pf}from"crypto";import{parse as bl}from"toml";var Al=it(er(),".memo"),Ml="sessions",st={current_provider:"deepseek",max_prompt_tokens:12e4,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function Pl(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function Rl(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=[];for(let[n,o]of Object.entries(t)){if(!o)continue;let r=Array.isArray(o)?o:[o];for(let s of r){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),e.push(i)}}return e}function tr(t){return t.startsWith("~")?it(er(),t.slice(1)):t}function Il(t){let e=t.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${Pl(i)}]]`,`name = ${JSON.stringify(i)}`,`env_api_key = ${JSON.stringify(String(s.env_api_key??""))}`,`model = ${JSON.stringify(String(s.model??""))}`];return s.base_url&&l.push(`base_url = ${JSON.stringify(String(s.base_url))}`),l.join(`
|
|
20
32
|
`)}).filter(Boolean).join(`
|
|
21
33
|
|
|
22
|
-
`),n="";
|
|
23
|
-
`)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",
|
|
24
|
-
`:"",
|
|
34
|
+
`),n="";t.mcp_servers&&Object.keys(t.mcp_servers).length>0&&(n=Object.entries(t.mcp_servers).map(([s,i])=>{if("url"in i){let 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 S=i.http_headers??i.headers;if(S&&Object.keys(S).length>0){let _=Object.entries(S).map(([N,R])=>`${JSON.stringify(N)} = ${JSON.stringify(R)}`).join(", "),v=i.http_headers?"http_headers":"headers";m.push(`${v} = { ${_} }`)}return m.join(`
|
|
35
|
+
`)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",l=i.type?`type = "${i.type}"
|
|
36
|
+
`:"",c=i.stderr?`stderr = "${i.stderr}"
|
|
25
37
|
`:"",u=`[mcp_servers.${s}]
|
|
26
|
-
${
|
|
27
|
-
${
|
|
38
|
+
${l}command = "${i.command}"
|
|
39
|
+
${c}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let T=p.map(([m,S])=>`${JSON.stringify(m)} = ${JSON.stringify(S)}`).join(`
|
|
28
40
|
`);return`${u}
|
|
29
41
|
|
|
30
42
|
[mcp_servers.${s}.env]
|
|
31
|
-
${
|
|
32
|
-
|
|
33
|
-
`));let o=[`current_provider = "${e.current_provider}"`,`stream_output = ${e.stream_output??!1}`];return typeof e.max_prompt_tokens=="number"&&Number.isFinite(e.max_prompt_tokens)&&o.push(`max_prompt_tokens = ${Math.floor(e.max_prompt_tokens)}`),[o.join(`
|
|
34
|
-
`),t,n].filter(Boolean).join(`
|
|
43
|
+
${T}`}).join(`
|
|
35
44
|
|
|
36
|
-
`)
|
|
37
|
-
`)
|
|
38
|
-
`)}groupByServer(t){let n={};for(let o of t)if(o.source==="mcp"){let r=o.serverName;n[r]||(n[r]=[]),n[r].push(o)}return n}getToolDescriptions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,source:t.source,serverName:t.source==="mcp"?t.serverName:void 0,inputSchema:t.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};import{readFile as Da,access as Ua}from"fs/promises";function Ha(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}async function Bo(e,t,n){let o=await oe(),r=o.config,s=new wt;if(s.registerNativeTools(Ro),await s.loadMcpServers(r.mcp_servers),e.tools)for(let[y,b]of Object.entries(e.tools))s.registerNativeTool({name:y,description:b.description,source:"native",inputSchema:{type:"object"},execute:b.execute});let i=s.toRegistry(),a=async()=>{let y=await(e.loadPrompt??Gn)(),b=s.generateToolDescriptions();b&&(y+=`
|
|
45
|
+
`));let o=[`current_provider = "${t.current_provider}"`];return typeof t.max_prompt_tokens=="number"&&Number.isFinite(t.max_prompt_tokens)&&o.push(`max_prompt_tokens = ${Math.floor(t.max_prompt_tokens)}`),[o.join(`
|
|
46
|
+
`),e,n].filter(Boolean).join(`
|
|
39
47
|
|
|
40
|
-
|
|
48
|
+
`)}async function Te(t,e){await vl(kl(t),{recursive:!0}),await Cl(t,Il(e),"utf-8")}async function se(){let t=process.env.MEMO_HOME?tr(process.env.MEMO_HOME):Al,e=it(t,"config.toml");try{await El(e);let n=await wl(e,"utf-8"),o=bl(n),r=Rl(o.providers),s=typeof o.max_prompt_tokens=="number"&&Number.isFinite(o.max_prompt_tokens)&&o.max_prompt_tokens>0?Math.floor(o.max_prompt_tokens):void 0,i={current_provider:o.current_provider??st.current_provider,max_prompt_tokens:s??st.max_prompt_tokens,providers:r,mcp_servers:o.mcp_servers??{}},a=!i.providers.length;return{config:a?st:i,home:t,configPath:e,needsSetup:a}}catch{return{config:st,home:t,configPath:e,needsSetup:!0}}}function Ue(t,e){let n=e||t.current_provider,o=t.providers.find(r=>r.name===n);return o||(t.providers?.[0]??st.providers[0])}function It(t,e){let n=e.historyDir??it(t.home,Ml);return tr(n)}function nr(t,e){let n=new Date,o=String(n.getFullYear()),r=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),a=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),c=`rollout-${o}-${r}-${s}T${i}-${a}-${l}-${e}.jsonl`;return it(t,o,r,s,c)}function Ll(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function Ol(t){return t.role==="assistant"?{role:"assistant",content:t.content,tool_calls:t.tool_calls?.map(e=>({id:e.id,type:e.type,function:{name:e.function.name,arguments:e.function.arguments}}))}:t.role==="tool"?{role:"tool",content:t.content,tool_call_id:t.tool_call_id}:{role:t.role,content:t.content}}async function or(t,e,n){let o=await se(),r=o.config,s=new Rt;if(s.registerNativeTools(Yo),await s.loadMcpServers(r.mcp_servers),t.tools)for(let[T,m]of Object.entries(t.tools))s.registerNativeTool({name:T,description:m.description,source:"native",inputSchema:{type:"object"},execute:m.execute});let i=s.toRegistry(),a=async()=>{let T=await(t.loadPrompt??qn)(),m=s.generateToolDescriptions();return m&&(T+=`
|
|
41
49
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
`),{thinkingParts:n,cleaned:o}=Va(t);return n.length>0?n.join(`
|
|
50
|
+
${m}`),T},l=s.generateToolDefinitions(),c=It(o,e),u=nr(c,n),p=new Ct(u);return{tools:i,dispose:async()=>{t.dispose&&await t.dispose(),await s.dispose()},callLLM:t.callLLM??(async(T,m,S)=>{let _=Ue(r,e.providerName),v=process.env[_.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!v)throw new Error(`Missing env var ${_.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let N=new $l({apiKey:v,baseURL:_.base_url}),R=T.map(Ol),w=l.length>0?l.map(D=>({type:"function",function:{name:D.name,description:D.description,parameters:D.input_schema}})):void 0,y=await N.chat.completions.create({model:_.model,messages:R,tools:w,tool_choice:w?"auto":void 0},{signal:S?.signal}),k=y.choices?.[0]?.message;if(k?.tool_calls&&k.tool_calls.length>0){let D=[];k.content&&D.push({type:"text",text:k.content});for(let H of k.tool_calls)if(H.type==="function"){let I=Ll(H.function.arguments);I.ok?D.push({type:"tool_use",id:H.id,name:H.function.name,input:I.data}):D.push({type:"text",text:`[tool_use parse error] ${I.error}; raw: ${I.raw}`})}let fe=D.some(H=>H.type==="tool_use");return{content:D,stop_reason:fe?"tool_use":"end_turn",usage:{prompt:y.usage?.prompt_tokens??void 0,completion:y.usage?.completion_tokens??void 0,total:y.usage?.total_tokens??void 0}}}let K=k?.content;if(typeof K!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:K}],stop_reason:"end_turn",usage:{prompt:y.usage?.prompt_tokens??void 0,completion:y.usage?.completion_tokens??void 0,total:y.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:t.historySinks??[p],tokenCounter:t.tokenCounter??Qo(e.tokenizerModel),historyFilePath:u}}function Nl(t){let e=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,o=t.replace(n,(r,s,i)=>{let a=(i??"").trim();return a&&e.push(a),a});return{thinkingParts:e,cleaned:o.trim()}}function rr(t){if(t.length===0)return;let e=t.join(`
|
|
51
|
+
`),{thinkingParts:n,cleaned:o}=Nl(e);return n.length>0?n.join(`
|
|
45
52
|
|
|
46
|
-
`):o||void 0}
|
|
47
|
-
`),toolUseBlocks:n.map(o=>({id:o.id,name:o.name,input:o.input})),stopReason:"stop_reason"in e?e.stop_reason:void 0,usage:"usage"in e?e.usage:void 0}}return{textContent:"",toolUseBlocks:[]}}async function Ja(e,t){for(let n of t)try{await n.append(e)}catch(o){console.error(`Failed to write history event: ${o.message}`)}}function qa(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
`)
|
|
51
|
-
|
|
52
|
-
`).map(t=>t.length>0?` ${t}`:"").join(`
|
|
53
|
-
`).trimEnd()}function uc(e){let t=e.header.map(r=>r.text).join(" | "),n=e.header.map(()=>"---").join(" | "),o=e.rows.map(r=>r.map(s=>s.text).join(" | "));return[t,n,...o].join(`
|
|
54
|
-
`)}function pc(e){return e.type==="table"&&"header"in e&&"rows"in e&&"align"in e}function mc(e,t,n){switch(e.type){case"space":case"def":return null;case"heading":return Q(G,{bold:!0,color:t.textColor,children:ke(e.tokens,t,`${n}-heading`)},n);case"paragraph":{let o=e.tokens??Mt(e.text);return Q(G,{color:t.textColor,children:ke(o,t,`${n}-para`)},n)}case"text":{let o=e.tokens??Mt(e.text);return Q(G,{color:t.textColor,children:ke(o,t,`${n}-text`)},n)}case"code":{let o=lc(e.text);return Q(G,{color:t.codeColor,children:o},n)}case"list":{let o=typeof e.start=="number"?e.start:1;return Q(gn,{flexDirection:"column",children:e.items.map((r,s)=>{let i=e.ordered?`${o+s}.`:"-",a=r.task?r.checked?"[x] ":"[ ] ":"",c=cc(r);return Fe(gn,{children:[Fe(G,{color:t.textColor,children:[i," "]}),Fe(G,{color:t.textColor,children:[a,ke(c,t,`${n}-item-${s}`)]})]},`${n}-item-${s}`)})},n)}case"blockquote":return Fe(G,{color:"gray",dimColor:!0,children:["> ",e.text.trim()]},n);case"hr":return Q(G,{color:"gray",children:"---"},n);case"table":return pc(e)?Q(G,{color:t.textColor,children:uc(e)},n):Q(G,{color:t.textColor,children:"text"in e?e.text:e.raw},n);case"html":return Q(G,{color:t.textColor,children:e.text},n);default:return Q(G,{color:t.textColor,children:"text"in e?e.text:e.raw},n)}}function dc(e,t,n){return e.flatMap((o,r)=>{let s=mc(o,t,`${n}-${r}`);return s?[s]:[]})}var Ve=sc(function({text:t,tone:n="normal"}){let o=rr(()=>({textColor:n==="muted"?"gray":void 0,codeColor:n==="muted"?"gray":"cyan",linkColor:n==="muted"?"gray":"blue",muted:n==="muted"}),[n]),r=rr(()=>{let s=rc.lexer(t,{gfm:!0,breaks:!0});return dc(s,o,"markdown")},[t,o]);return Q(gn,{flexDirection:"column",gap:1,children:r})});import{Fragment as hn,jsx as J,jsxs as Ge}from"react/jsx-runtime";function sr(e){if(!e)return;if(typeof e=="string")return e.length>50?e.slice(0,47)+"...":e;if(typeof e!="object"||Array.isArray(e))return;let t=e,n=["file_path","path","file","filename","url","command","pattern","glob","query","content","cwd","dir"];for(let o of n)if(t[o]){let r=String(t[o]);return r.length>50?r.slice(0,47)+"...":r}for(let[o,r]of Object.entries(t))if(typeof r=="string"&&o!=="description")return r.length>50?r.slice(0,47)+"...":r}function gc(e,t){let n=e.step,o=t.step;return!(n.index!==o.index||n.assistantText!==o.assistantText||n.thinking!==o.thinking||n.action?.tool!==o.action?.tool||JSON.stringify(n.action?.input)!==JSON.stringify(o.action?.input)||JSON.stringify(n.parallelActions)!==JSON.stringify(o.parallelActions)||n.toolStatus!==o.toolStatus)}var ir=fc(function({step:t}){let n=t.action?.tool,o=t.action?.input,r=sr(o),s=t.parallelActions??[],i=s.length>1;return Ge(Ze,{flexDirection:"column",gap:0,children:[t.thinking&&Ge(Ze,{children:[J(ce,{color:"gray",children:"\u25CF "}),J(Ze,{flexDirection:"column",flexGrow:1,children:J(Ve,{text:t.thinking,tone:"muted"})})]}),i&&J(hn,{children:s.map((a,c)=>{let l=sr(a.input);return Ge(Ze,{children:[J(ce,{color:"green",children:"\u25CF "}),J(ce,{color:"gray",children:"Used "}),J(ce,{color:"cyan",children:a.tool}),l&&Ge(hn,{children:[J(ce,{color:"gray",children:" ("}),J(ce,{color:"cyan",children:l}),J(ce,{color:"gray",children:")"})]})]},c)})}),!i&&n&&Ge(Ze,{children:[J(ce,{color:"green",children:"\u25CF "}),J(ce,{color:"gray",children:"Used "}),J(ce,{color:"cyan",children:n}),r&&Ge(hn,{children:[J(ce,{color:"gray",children:" ("}),J(ce,{color:"cyan",children:r}),J(ce,{color:"gray",children:")"})]})]})]})},gc);import{Box as hc,Text as ar}from"ink";import{memo as yc}from"react";import{jsx as cr,jsxs as xc}from"react/jsx-runtime";var lr=yc(function({text:t}){return xc(hc,{paddingY:1,children:[cr(ar,{color:"gray",children:"\u203A "}),cr(ar,{color:"white",children:t})]})});import{Box as Qe,Text as Oe}from"ink";import{memo as yn,useMemo as vc}from"react";import{Fragment as Sc,jsx as me,jsxs as Pt}from"react/jsx-runtime";function Tc(e){let t=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,n=[],o,r=0,s=[];for(;(o=t.exec(e))!==null;){s.push({start:o.index,end:t.lastIndex});let a=o[2]?.trim();a&&n.push(a)}if(s.length===0)return{content:e,thinking:null};let i="";r=0;for(let{start:a,end:c}of s)i+=e.slice(r,a),r=c;return i+=e.slice(r),i=i.replace(/\n{3,}/g,`
|
|
53
|
+
`):o||void 0}import{randomUUID as cr}from"crypto";function Dl(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[]}}function sr(t,e){e&&(e.onTurnStart&&t.onTurnStart.push(e.onTurnStart),e.onAction&&t.onAction.push(e.onAction),e.onObservation&&t.onObservation.push(e.onObservation),e.onFinal&&t.onFinal.push(e.onFinal),e.onApprovalRequest&&t.onApprovalRequest.push(e.onApprovalRequest),e.onApprovalResponse&&t.onApprovalResponse.push(e.onApprovalResponse))}function ir(t){let e=Dl();if(sr(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)sr(e,n);return e}async function Z(t,e,n){let o=t[e];if(o.length)for(let r of o)try{await r(n)}catch(s){console.warn(`Hook ${e} failed: ${s.message}`)}}function Ge(t){return t.map(e=>e.role==="assistant"&&e.tool_calls?.length?{...e,tool_calls:e.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...e})}var ur="interactive",Ul=12e4;function ar(){return{prompt:0,completion:0,total:0}}function lr(t,e){if(!e)return;let n=e.prompt??0,o=e.completion??0,r=e.total??n+o;t.prompt+=n,t.completion+=o,t.total+=r}function Hl(t){let e=t.content.filter(o=>o.type==="text"),n=t.content.filter(o=>o.type==="tool_use");return{textContent:e.map(o=>o.text).join(`
|
|
54
|
+
`),toolUseBlocks:n.map(o=>({id:o.id,name:o.name,input:o.input})),stopReason:t.stop_reason,usage:t.usage}}async function Fl(t,e){for(let n of e)try{await n.append(t)}catch(o){console.error(`Failed to write history event: ${o.message}`)}}function jl(t){return t instanceof Error&&t.name==="AbortError"}function at(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(n=>at(n)).join(",")}]`:`{${Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${at(o)}`).join(",")}}`}function Bl(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:at(e.input)}}))}function Wl(t,e){let n=t.trim();if(!n)return null;let o=[n],r=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);r?.[1]&&o.push(r[1].trim());for(let s of o)if(!(!s.startsWith("{")||!s.endsWith("}")))try{let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,l=typeof a.tool=="string"?a.tool.trim():"";if(!l||!Object.prototype.hasOwnProperty.call(e,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}var Tn=class{constructor(e,n,o,r,s){this.deps=e;this.options=n;this.id=n.sessionId||cr(),this.mode=n.mode||ur,this.history=[{role:"system",content:o}],this.tokenCounter=r,this.sinks=e.historySinks??[],this.hooks=ir(e),this.historyFilePath=s,this.toolOrchestrator=Xo({tools:e.tools,approval:{dangerous:n.dangerous??!1,mode:"auto"}})}id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=ar();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(e,n){let o=`${e}:${at(n)}`;if(this.lastActionSignature===o?this.repeatedActionCount+=1:(this.lastActionSignature=o,this.repeatedActionCount=1),this.repeatedActionCount===3){let r=at(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${e}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${r}${r.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}buildToolApprovalHooks(e,n){return{onApprovalRequest:async o=>{await Z(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:e,step:n,request:o})},requestApproval:async o=>this.deps.requestApproval?this.deps.requestApproval(o):"deny",onApprovalResponse:async({fingerprint:o,decision:r})=>{await Z(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:e,step:n,fingerprint:o,decision:r})}}}async executeToolAction(e,n,o,r,s){return this.toolOrchestrator.executeAction({id:e,name:n,input:o},this.buildToolApprovalHooks(r,s))}async runTurn(e){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let o=this.turnIndex,r=[],s=ar(),i=Date.now(),a=this.options.maxPromptTokens??Ul;this.sessionStartEmitted||(await this.emitEvent("session_start",{meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a}}),this.sessionStartEmitted=!0),this.history.push({role:"user",content:e});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:o,content:e,meta:{tokens:{prompt:l}}}),await Z(this.hooks,"onTurnStart",{sessionId:this.id,turn:o,input:e,promptTokens:l,history:Ge(this.history)});let c="",u="ok",p,T=0;for(let m=0;;m++){let S=this.tokenCounter.countMessages(this.history);if(S>a){let E=`Context tokens (${S}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:E}),u="prompt_limit",c=E,p=E,await this.emitEvent("final",{turn:o,step:m,content:E,role:"assistant",meta:{tokens:{prompt:S}}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:E,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.options.warnPromptTokens&&S>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${S}`);let _="",v=[],N,R;try{let E=await this.deps.callLLM(this.history,z=>this.deps.onAssistantStep?.(z,m),{signal:n.signal}),A=Hl(E);_=A.textContent,v=A.toolUseBlocks,R=A.stopReason,N=A.usage}catch(E){if(this.cancelling&&jl(E)){u="cancelled",c="",p="Turn cancelled",await this.emitEvent("final",{turn:o,step:m,content:"",role:"assistant",meta:{cancelled:!0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}let A=`LLM call failed: ${E.message}`;this.history.push({role:"assistant",content:A}),u="error",c=A,p=A,await this.emitEvent("final",{turn:o,content:A,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.deps.onAssistantStep?.(_,m);let w=v.length===0&&_?Wl(_,this.deps.tools):null,y,k=null;if(v.length>0){let E=v[0];if(E){let A=_?rr([_]):void 0;y={action:{tool:E.name,input:E.input},thinking:A},k={role:"assistant",content:_,tool_calls:Bl(v)}}else y={}}else _?(y={final:_},k={role:"assistant",content:_}):y={};let K=this.tokenCounter.countText(_),D=N?.prompt??S,fe=N?.completion??K,H=N?.total??D+fe,I={prompt:D,completion:fe,total:H};if(lr(s,I),lr(this.sessionUsage,I),r.push({index:m,assistantText:_,parsed:y,tokenUsage:I}),await this.emitEvent("assistant",{turn:o,step:m,content:_,role:"assistant",meta:{tokens:I,protocol_violation:!!w,protocol_violation_count:w?T+1:T||void 0}}),w){T+=1;let E=`Model protocol error: returned plain-text tool JSON for "${w.tool}" ${T} times. Structured tool calls are required.`;u="error",c=E,p=E,this.history.push({role:"assistant",content:E}),await this.emitEvent("final",{turn:o,step:m,content:E,role:"assistant",meta:{error_type:"model_protocol_error",tool:w.tool,protocol_violation:!0,protocol_violation_count:T,tokens:I}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:c,status:u,errorMessage:p,tokenUsage:I,turnUsage:{...s},steps:r});break}if(k&&this.history.push(k),v.length>1){for(let b of v)this.maybeWarnRepeatedAction(b.name,b.input);await this.emitEvent("action",{turn:o,step:m,meta:{tools:v.map(b=>b.name),action_ids:v.map(b=>b.id),action_id:v[0]?.id,parallel:!0,phase:"dispatch",thinking:y.thinking,toolBlocks:v.map(b=>({id:b.id,name:b.name,input:b.input}))}});let E=v[0];E&&await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:m,action:{tool:E.name,input:E.input},parallelActions:v.map(b=>({tool:b.name,input:b.input})),thinking:y.thinking,history:Ge(this.history)});let A=v.every(b=>!!this.deps.tools[b.name]?.supportsParallelToolCalls),z=v.some(b=>!!this.deps.tools[b.name]?.isMutating),ie=A&&!z?"parallel":"sequential",Y=await this.toolOrchestrator.executeActions(v.map(b=>({id:b.id,name:b.name,input:b.input})),{...this.buildToolApprovalHooks(o,m),executionMode:ie,failurePolicy:"fail_fast"});for(let[b,V]of Y.results.entries())this.history.push({role:"tool",content:V.observation,tool_call_id:V.actionId,name:V.tool}),await this.emitEvent("observation",{turn:o,step:m,content:V.observation,meta:{tool:V.tool,index:b,action_id:V.actionId,phase:"result",status:V.status,error_type:V.errorType,duration_ms:V.durationMs,execution_mode:ie}});let Ce=Y.combinedObservation,xe=r[r.length-1];if(xe&&(xe.observation=Ce),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:m,tool:v.map(b=>b.name).join(", "),observation:Ce,history:Ge(this.history)}),Y.hasRejection){let b=Y.results.find(V=>V.rejected);u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:m,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:b?.actionId,error_type:b?.errorType??"approval_denied",duration_ms:b?.durationMs}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:c,status:u,tokenUsage:I,turnUsage:{...s},steps:r});break}continue}else if(y.action){this.maybeWarnRepeatedAction(y.action.tool,y.action.input);let E=v[0]?.id??`${o}:${m}:single:${y.action.tool}`;await this.emitEvent("action",{turn:o,step:m,meta:{tool:y.action.tool,input:y.action.input,action_id:E,phase:"dispatch",thinking:y.thinking}}),await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:m,action:y.action,thinking:y.thinking,history:Ge(this.history)});let A=await this.executeToolAction(E,y.action.tool,y.action.input,o,m);if(A.rejected){u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:m,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:A.actionId,error_type:A.errorType??"approval_denied",duration_ms:A.durationMs}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:c,status:u,tokenUsage:I,turnUsage:{...s},steps:r});break}let z=A.observation;this.history.push({role:"tool",content:z,tool_call_id:A.actionId,name:y.action.tool});let ie=r[r.length-1];ie&&(ie.observation=z),await this.emitEvent("observation",{turn:o,step:m,content:z,meta:{tool:y.action.tool,action_id:A.actionId,phase:"result",status:A.status,error_type:A.errorType,duration_ms:A.durationMs}}),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:m,tool:y.action.tool,observation:z,history:Ge(this.history)});continue}if(R==="end_turn"||y.final){this.resetActionRepetition(),c=y.final||_,y.final&&(y.final=c),await this.emitEvent("final",{turn:o,step:m,content:c,role:"assistant",meta:{tokens:I}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:m,finalText:c,status:u,tokenUsage:I,turnUsage:{...s},steps:r});break}this.resetActionRepetition();break}return!c&&u!=="cancelled"&&(u==="ok"&&(u="error"),c="Unable to produce a final answer. Please retry or adjust the request.",p=c,this.history.push({role:"assistant",content:c}),await this.emitEvent("final",{turn:o,content:c,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r})),await this.emitEvent("turn_end",{turn:o,meta:{status:u,stepCount:r.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:T||void 0}}),{finalText:c,steps:r,status:u,errorMessage:p,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async close(){if(this.closed)return;if(this.closed=!0,this.sessionStartEmitted||this.turnIndex>=0){await this.emitEvent("session_end",{meta:{durationMs:Date.now()-this.startedAt,tokens:this.sessionUsage}});for(let n of this.sinks)if(n.flush)try{await n.flush()}catch(o){console.error(`History flush failed: ${o.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(e,n){if(!this.sinks.length)return;let o=Xn({sessionId:this.id,type:e,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Fl(o,this.sinks)}};async function lt(t,e={}){let n=e.sessionId||cr(),o=await or(t,{...e,sessionId:n},n),r=await o.loadPrompt(),s=new Tn({...t,...o},{...e,sessionId:n,mode:e.mode??ur},r,o.tokenCounter,o.historyFilePath);return await s.init(),s}import{useCallback as X,useEffect as zt,useMemo as Dn,useRef as Tt,useState as J}from"react";import{readFile as Zu}from"fs/promises";import"path";import{randomUUID as _t}from"crypto";import{exec as Qu}from"child_process";import{promisify as ep}from"util";import{Box as ms,useApp as tp,Text as np}from"ink";import{Box as pr,Text as Vl}from"ink";import{memo as zl}from"react";import{jsx as mr,jsxs as Gl}from"react/jsx-runtime";var dr=zl(function({contextPercent:e=0}){let n=e>0?` ${e.toFixed(1)}%`:" 0.0%";return mr(pr,{justifyContent:"flex-end",children:mr(pr,{marginTop:8,children:Gl(Vl,{color:"gray",children:["context:",n]})})})});import{Box as Se,Static as Tc,Text as ue}from"ink";import{memo as _c}from"react";import xc from"os";import{Box as Kl,Text as fr}from"ink";import{memo as ql}from"react";import{jsx as Xl,jsxs as gr}from"react/jsx-runtime";var hr=ql(function({message:e}){return gr(Kl,{flexDirection:"column",gap:0,children:[gr(fr,{color:"cyan",children:["\u25CF ",e.title]}),Xl(fr,{color:"gray",children:e.content})]})});import{Box as fc,Text as gc}from"ink";import{memo as hc}from"react";import{Box as ct,Text as ce}from"ink";import{memo as ic}from"react";import{Box as _n,Text as G}from"ink";import{marked as Jl}from"marked";import{useMemo as yr,memo as Yl}from"react";import{jsx as oe,jsxs as Ke}from"react/jsx-runtime";var Zl="#2b2b2b";function $t(t){return t?[{type:"text",raw:t,text:t}]:[]}function Ql(t,e,n){switch(t.type){case"text":return t.tokens&&t.tokens.length>0?Ae(t.tokens,e,`${n}-text`):t.text;case"escape":return t.text;case"strong":return oe(G,{bold:!0,children:Ae(t.tokens,e,`${n}-strong`)},n);case"em":return oe(G,{italic:!0,children:Ae(t.tokens,e,`${n}-em`)},n);case"codespan":return oe(G,{color:e.codeColor,backgroundColor:Zl,children:t.text},n);case"del":return oe(G,{strikethrough:!0,children:Ae(t.tokens,e,`${n}-del`)},n);case"link":{let o=t.tokens&&t.tokens.length>0?Ae(t.tokens,e,`${n}-link`):t.text,r=t.href&&t.text&&t.text!==t.href?` (${t.href})`:"";return Ke(G,{underline:!0,color:e.linkColor,children:[o,r]},n)}case"image":{let o=t.text||"image";return Ke(G,{color:e.linkColor,children:["[",o,"](",t.href,")"]},n)}case"br":return`
|
|
55
|
+
`;case"checkbox":return t.checked?"[x]":"[ ]";case"html":return t.text;default:return"text"in t?t.text:t.raw}}function Ae(t,e,n){return!t||t.length===0?[]:t.flatMap((o,r)=>{let s=`${n}-${r}`,i=Ql(o,e,s);return Array.isArray(i)?i:[i]})}function ec(t){let e=t.tokens[0];return e?.type==="paragraph"||e?.type==="text"?e.tokens??$t(e.text):t.tokens.length>0?t.tokens:$t(t.text)}function tc(t){return t.split(`
|
|
56
|
+
`).map(e=>e.length>0?` ${e}`:"").join(`
|
|
57
|
+
`).trimEnd()}function nc(t){let e=t.header.map(r=>r.text).join(" | "),n=t.header.map(()=>"---").join(" | "),o=t.rows.map(r=>r.map(s=>s.text).join(" | "));return[e,n,...o].join(`
|
|
58
|
+
`)}function oc(t){return t.type==="table"&&"header"in t&&"rows"in t&&"align"in t}function rc(t,e,n){switch(t.type){case"space":case"def":return null;case"heading":return oe(G,{bold:!0,color:e.textColor,children:Ae(t.tokens,e,`${n}-heading`)},n);case"paragraph":{let o=t.tokens??$t(t.text);return oe(G,{color:e.textColor,children:Ae(o,e,`${n}-para`)},n)}case"text":{let o=t.tokens??$t(t.text);return oe(G,{color:e.textColor,children:Ae(o,e,`${n}-text`)},n)}case"code":{let o=tc(t.text);return oe(G,{color:e.codeColor,children:o},n)}case"list":{let o=typeof t.start=="number"?t.start:1;return oe(_n,{flexDirection:"column",children:t.items.map((r,s)=>{let i=t.ordered?`${o+s}.`:"-",a=r.task?r.checked?"[x] ":"[ ] ":"",l=ec(r);return Ke(_n,{children:[Ke(G,{color:e.textColor,children:[i," "]}),Ke(G,{color:e.textColor,children:[a,Ae(l,e,`${n}-item-${s}`)]})]},`${n}-item-${s}`)})},n)}case"blockquote":return Ke(G,{color:"gray",dimColor:!0,children:["> ",t.text.trim()]},n);case"hr":return oe(G,{color:"gray",children:"---"},n);case"table":return oc(t)?oe(G,{color:e.textColor,children:nc(t)},n):oe(G,{color:e.textColor,children:"text"in t?t.text:t.raw},n);case"html":return oe(G,{color:e.textColor,children:t.text},n);default:return oe(G,{color:e.textColor,children:"text"in t?t.text:t.raw},n)}}function sc(t,e,n){return t.flatMap((o,r)=>{let s=rc(o,e,`${n}-${r}`);return s?[s]:[]})}var qe=Yl(function({text:e,tone:n="normal"}){let o=yr(()=>({textColor:n==="muted"?"gray":void 0,codeColor:n==="muted"?"gray":"cyan",linkColor:n==="muted"?"gray":"blue",muted:n==="muted"}),[n]),r=yr(()=>{let s=Jl.lexer(e,{gfm:!0,breaks:!0});return sc(s,o,"markdown")},[e,o]);return oe(_n,{flexDirection:"column",gap:1,children:r})});import{Fragment as xn,jsx as Q,jsxs as Xe}from"react/jsx-runtime";function Tr(t){if(!t)return;if(typeof t=="string")return t.length>50?t.slice(0,47)+"...":t;if(typeof t!="object"||Array.isArray(t))return;let e=t,n=["cmd","dir_path","file_path","path","file","filename","url","command","pattern","include","query","content","cwd","dir"];for(let o of n)if(e[o]){let r=String(e[o]);return r.length>50?r.slice(0,47)+"...":r}for(let[o,r]of Object.entries(e))if(typeof r=="string"&&o!=="description")return r.length>50?r.slice(0,47)+"...":r}function ac(t,e){let n=t.step,o=e.step;return!(n.index!==o.index||n.assistantText!==o.assistantText||n.thinking!==o.thinking||n.action?.tool!==o.action?.tool||JSON.stringify(n.action?.input)!==JSON.stringify(o.action?.input)||JSON.stringify(n.parallelActions)!==JSON.stringify(o.parallelActions)||n.toolStatus!==o.toolStatus)}var _r=ic(function({step:e}){let n=e.action?.tool,o=e.action?.input,r=Tr(o),s=e.parallelActions??[],i=s.length>1;return Xe(ct,{flexDirection:"column",gap:0,children:[e.thinking&&Xe(ct,{children:[Q(ce,{color:"gray",children:"\u25CF "}),Q(ct,{flexDirection:"column",flexGrow:1,children:Q(qe,{text:e.thinking,tone:"muted"})})]}),i&&Q(xn,{children:s.map((a,l)=>{let c=Tr(a.input);return Xe(ct,{children:[Q(ce,{color:"green",children:"\u25CF "}),Q(ce,{color:"gray",children:"Used "}),Q(ce,{color:"cyan",children:a.tool}),c&&Xe(xn,{children:[Q(ce,{color:"gray",children:" ("}),Q(ce,{color:"cyan",children:c}),Q(ce,{color:"gray",children:")"})]})]},l)})}),!i&&n&&Xe(ct,{children:[Q(ce,{color:"green",children:"\u25CF "}),Q(ce,{color:"gray",children:"Used "}),Q(ce,{color:"cyan",children:n}),r&&Xe(xn,{children:[Q(ce,{color:"gray",children:" ("}),Q(ce,{color:"cyan",children:r}),Q(ce,{color:"gray",children:")"})]})]})]})},ac);import{Box as lc,Text as xr}from"ink";import{memo as cc}from"react";import{jsx as Sr,jsxs as uc}from"react/jsx-runtime";var vr=cc(function({text:e}){return uc(lc,{paddingY:1,children:[Sr(xr,{color:"gray",children:"\u203A "}),Sr(xr,{color:"white",children:e})]})});import{Box as ut,Text as He}from"ink";import{memo as Sn,useMemo as pc}from"react";import{Fragment as dc,jsx as de,jsxs as Lt}from"react/jsx-runtime";function mc(t){let e=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,n=[],o,r=0,s=[];for(;(o=e.exec(t))!==null;){s.push({start:o.index,end:e.lastIndex});let a=o[2]?.trim();a&&n.push(a)}if(s.length===0)return{content:t,thinking:null};let i="";r=0;for(let{start:a,end:l}of s)i+=t.slice(r,a),r=l;return i+=t.slice(r),i=i.replace(/\n{3,}/g,`
|
|
55
59
|
|
|
56
60
|
`).trim(),{content:i,thinking:n.length>0?n.join(`
|
|
57
61
|
|
|
58
|
-
`):null}}var ur=yn(function({text:t,isThinking:n=!1}){let{content:o,thinking:r}=vc(()=>Tc(t),[t]);return n?me(Qe,{flexDirection:"column",flexGrow:1,children:me(Ve,{text:t,tone:"muted"})}):Pt(Qe,{flexDirection:"column",flexGrow:1,gap:1,children:[r&&me(Qe,{flexDirection:"column",paddingLeft:2,children:me(Ve,{text:r,tone:"muted"})}),me(Ve,{text:o,tone:"normal"})]})}),Pd=yn(function({text:t}){return me(Qe,{children:Pt(Oe,{color:"gray",children:["\u2022 ",t]})})}),Rd=yn(function({toolName:t,fileName:n}){return Pt(Qe,{children:[me(Oe,{color:"green",children:"\u25CF "}),me(Oe,{color:"gray",children:"Used "}),me(Oe,{color:"cyan",children:t}),n&&Pt(Sc,{children:[me(Oe,{color:"gray",children:" ("}),me(Oe,{color:"cyan",children:n}),me(Oe,{color:"gray",children:")"})]})]})});import{jsx as xn,jsxs as pr}from"react/jsx-runtime";function wc(e,t){let n=e.turn,o=t.turn;if(n.index!==o.index||n.userInput!==o.userInput||n.finalText!==o.finalText||n.status!==o.status||n.steps.length!==o.steps.length||n.tokenUsage?.total!==o.tokenUsage?.total)return!1;for(let r=0;r<n.steps.length;r++){let s=n.steps[r],i=o.steps[r];if(!s||!i||s.assistantText!==i.assistantText||s.thinking!==i.thinking||s.action?.tool!==i.action?.tool)return!1}return!0}var vn=bc(function({turn:t}){let n=t.finalText?.trim()??"",o=n.length>0;return pr(_c,{flexDirection:"column",children:[xn(lr,{text:t.userInput}),t.steps.map(r=>xn(ir,{step:r},`step-${t.index}-${r.index}`)),o?xn(ur,{text:n,isThinking:!1}):null,t.status&&t.status!=="ok"?pr(kc,{color:"red",children:["Status: ",t.status]}):null]})},wc);import{jsx as q,jsxs as he}from"react/jsx-runtime";function Mc(e){let t=Ac.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Pc(e){return e.length>16?`${e.slice(0,8)}...${e.slice(-4)}`:e}function Rc(e,t){if(e.headerInfo?.sessionId!==t.headerInfo?.sessionId||e.headerInfo?.model!==t.headerInfo?.model||e.headerInfo?.providerName!==t.headerInfo?.providerName||e.headerInfo?.cwd!==t.headerInfo?.cwd||e.headerInfo?.version!==t.headerInfo?.version||e.headerInfo?.mcpNames?.length!==t.headerInfo?.mcpNames?.length)return!1;if(e.headerInfo?.mcpNames&&t.headerInfo?.mcpNames){let n=e.headerInfo.mcpNames,o=t.headerInfo.mcpNames;for(let r=0;r<n.length;r++)if(n[r]!==o[r])return!1}if(e.systemMessages.length!==t.systemMessages.length)return!1;for(let n=0;n<e.systemMessages.length;n++)if(e.systemMessages[n]?.id!==t.systemMessages[n]?.id)return!1;if(e.turns.length!==t.turns.length)return!1;for(let n=0;n<e.turns.length;n++)if(e.turns[n]!==t.turns[n])return!1;return!0}var mr=Ec(function({systemMessages:t,turns:n,headerInfo:o}){let r=n.length>0?n[n.length-1]:void 0,s=r&&(r.finalText||r.status&&r.status!=="ok"),i=s?n:n.slice(0,-1),a=s?void 0:r,c=[];o&&c.push({type:"header",data:o});let l=[];for(let u of t)l.push({sequence:u.sequence,item:{type:"system",data:u}});for(let u of i){let p=u.sequence??0;l.push({sequence:p,item:{type:"turn",data:u}})}l.sort((u,p)=>u.sequence-p.sequence);for(let u of l)c.push(u.item);return he(xe,{flexDirection:"column",gap:0,children:[q(Cc,{items:c,children:u=>{if(u.type==="header"&&u.data){let p=u.data;return he(xe,{borderStyle:"round",borderColor:"blueBright",paddingX:2,paddingY:1,flexDirection:"column",gap:1,children:[q(xe,{gap:1,alignItems:"center",children:he(xe,{flexDirection:"column",children:[q(le,{bold:!0,children:"Welcome to Memo Code CLI!"}),q(le,{color:"gray",children:"Send /help for help information."})]})}),he(xe,{flexDirection:"column",gap:0,children:[he(xe,{children:[q(le,{color:"gray",children:"Directory: "}),q(le,{color:"cyan",children:Mc(p.cwd)})]}),he(xe,{children:[q(le,{color:"gray",children:"Session: "}),q(le,{color:"cyan",children:Pc(p.sessionId)})]}),he(xe,{children:[q(le,{color:"gray",children:"Model: "}),q(le,{color:"cyan",children:p.model}),he(le,{color:"gray",children:[" ","(powered by ",p.providerName,")"]})]}),he(xe,{children:[q(le,{color:"gray",children:"Version: "}),he(le,{color:"cyan",children:["v",p.version]})]}),he(xe,{children:[q(le,{color:"gray",children:"MCP: "}),q(le,{color:"cyan",children:p.mcpNames.length>0?p.mcpNames.join(", "):"none"})]})]})]},"header")}return u.type==="system"?q(or,{message:u.data},u.data.id):u.type==="turn"?q(vn,{turn:u.data},`turn-${u.data.index}`):null}}),a&&q(vn,{turn:a},`turn-live-${a.index}`)]})},Rc);import{useCallback as Ur,useEffect as An,useMemo as Tl,useRef as Mn,useState as Ae}from"react";import{readFile as Sl,readdir as _l,stat as kl}from"fs/promises";import{basename as bl,join as wl,resolve as Hr}from"path";import{Box as Dt,Text as Ne,useInput as Cl}from"ink";var kr=Vn(Sr(),1);import{readFile as Zc,readdir as Qc}from"fs/promises";import{join as _r,relative as el,sep as tl}from"path";var nl=6,ol=2500,br=25,rl=[".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs","*.log"],Lt=new Map;function sl(e){return e.split(tl).join("/")}function il(e,t){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,respectGitIgnore:e.respectGitIgnore,ignoreGlobs:e.ignoreGlobs,gitignore:t})}function al(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):nl,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):ol,limit:typeof e.limit=="number"?Math.max(1,e.limit):br,respectGitIgnore:e.respectGitIgnore!==!1,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}async function cl(e,t){if(!t)return"";try{return await Zc(_r(e,".gitignore"),"utf8")}catch{}return""}async function ll(e,t){let n=await cl(t,e.respectGitIgnore),o=(0,kr.default)();o.add(rl),e.ignoreGlobs.length&&o.add(e.ignoreGlobs),n.trim()&&o.add(n);let r=il(e,n);return Object.assign(o,{__memoSignature:r})}async function ul(e,t,n){let o=[],r=t.maxEntries,s=async(i,a)=>{if(o.length>=r)return;let c;try{c=await Qc(i,{withFileTypes:!0})}catch{return}for(let l of c){if(o.length>=r)break;if(l.isSymbolicLink())continue;let u=_r(i,l.name),p=el(e,u);if(!p)continue;let h=sl(p);if(n.ignores(h))continue;let y=h.split("/").filter(Boolean),b=y.map(w=>w.toLowerCase()),x=l.isDirectory();if(o.push({path:h,pathLower:h.toLowerCase(),segments:y,segmentsLower:b,depth:a,isDir:x}),o.length>=r)break;x&&a<t.maxDepth&&await s(u,a+1)}};return await s(e,0),o.sort((i,a)=>i.path.localeCompare(a.path)),{entries:o,signature:n.__memoSignature}}async function pl(e,t){let n=al(t),o=await ll(n,e),r=o.__memoSignature,s=Lt.get(e);if(s&&s.signature===r)return s.pending?s.pending:s.entries;let i=ul(e,n,o).then(a=>(Lt.set(e,{entries:a.entries,signature:a.signature}),a.entries)).catch(a=>{throw Lt.delete(e),a});return Lt.set(e,{entries:[],signature:r,pending:i}),i}function ml(e){return e.depth+(e.isDir?-.2:.2)}function dl(e,t){if(!t.length)return ml(e);let n=e.depth,o=0;for(let r of t){let s=-1;for(let i=o;i<e.segmentsLower.length;i++){let a=e.segmentsLower[i];if(a.startsWith(r)){s=i,n+=(i-o)*1.5,n+=a.length-r.length;break}let c=a.indexOf(r);if(c!==-1){s=i,n+=(i-o)*2+c+2;break}}if(s===-1)return null;o=s+1}return e.isDir&&(n-=.5),n}function fl(e,t,n){let s=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(a=>a.toLowerCase()),i=[];for(let a of e){let c=dl(a,s);c!==null&&i.push({entry:a,score:c})}return i.sort((a,c)=>{let l=a.score-c.score;return l!==0?l:a.entry.path.localeCompare(c.entry.path)}),i.slice(0,n).map(({entry:a})=>({id:a.path,path:a.path,name:a.segments[a.segments.length-1]??a.path,parent:a.segments.length>1?a.segments.slice(0,-1).join("/"):void 0,isDir:a.isDir}))}async function wr(e){let t=await pl(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):br;return fl(t,e.query,n)}import{mkdir as Qd,readFile as ef,writeFile as tf}from"fs/promises";import{dirname as of}from"path";import{randomUUID as sf}from"crypto";import{Box as tt,Text as Ke}from"ink";import{jsx as we,jsxs as Er}from"react/jsx-runtime";var gl="#3a3a3a",Ot="#2b2b2b",Cr="#888888",hl="#666666";function Ar({items:e,activeIndex:t,loading:n}){return n?we(tt,{flexDirection:"column",paddingX:1,backgroundColor:Ot,children:we(Ke,{color:"gray",children:"Loading..."})}):e.length?we(tt,{flexDirection:"column",backgroundColor:Ot,children:e.map((o,r)=>{let s=r===t,i=s?gl:Ot;return o.kind==="slash"?Er(tt,{flexDirection:"row",gap:2,paddingX:1,backgroundColor:i,children:[we(Ke,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?we(Ke,{color:Cr,children:o.subtitle}):null]},o.id):Er(tt,{flexDirection:"row",gap:1,paddingX:1,backgroundColor:i,children:[we(Ke,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?we(Ke,{color:Cr,children:o.subtitle}):null]},o.id)})}):we(tt,{flexDirection:"column",paddingX:1,backgroundColor:Ot,children:we(Ke,{color:hl,children:"No matches"})})}var Cn=[{name:"help",description:"Show help and shortcuts"},{name:"exit",description:"Exit the session"},{name:"new",description:"Start a new session"},{name:"resume",description:"Resume session history"},{name:"models",description:"Select a model (from configured providers)"},{name:"context",description:"Set context length limit (80k/120k/150k/200k) (starts new session)"},{name:"mcp",description:"Show configured MCP servers"},{name:"init",description:"Generate AGENTS.md for current project"}],yl=Object.fromEntries(Cn.map(e=>[e.name,e.description]));function X(e){return yl[e]}function Mr(){let e=Cn.reduce((t,n)=>Math.max(t,n.name.length),0);return Cn.map(t=>` /${t.name.padEnd(e)} ${t.description}`)}var Pr={name:"new",description:X("new"),run:({closeSuggestions:e,setInputValue:t,clearScreen:n,showSystemMessage:o,newSession:r})=>{e(),t(""),n(),o("New Session","Starting a new session..."),r?.()}};var Rr={name:"exit",description:X("exit"),run:({closeSuggestions:e,exitApp:t})=>{e(),t()}};var $r={name:"resume",description:X("resume"),run:({closeSuggestions:e,setInputValue:t,showSystemMessage:n})=>{e(!1),t("resume "),n("Resume",'Type "resume" followed by keywords to filter and select from session history.')}};var Ir={name:"models",description:X("models"),run:({closeSuggestions:e,setInputValue:t,showSystemMessage:n,data:o})=>{e(!1);let{providers:r,providerName:s,model:i}=o;if(!r.length){n("Models",`No providers configured. Check ${o.configPath}`),t("");return}let a=r.map(c=>{let l=c.name===s&&c.model===i?" (current)":"",u=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${u}${l}`});t("/models "),n("Models",`Available models:
|
|
62
|
+
`):null}}var Cr=Sn(function({text:e,isThinking:n=!1}){let{content:o,thinking:r}=pc(()=>mc(e),[e]);return n?de(ut,{flexDirection:"column",flexGrow:1,children:de(qe,{text:e,tone:"muted"})}):Lt(ut,{flexDirection:"column",flexGrow:1,gap:1,children:[r&&de(ut,{flexDirection:"column",paddingLeft:2,children:de(qe,{text:r,tone:"muted"})}),de(qe,{text:o,tone:"normal"})]})}),pg=Sn(function({text:e}){return de(ut,{children:Lt(He,{color:"gray",children:["\u2022 ",e]})})}),mg=Sn(function({toolName:e,fileName:n}){return Lt(ut,{children:[de(He,{color:"green",children:"\u25CF "}),de(He,{color:"gray",children:"Used "}),de(He,{color:"cyan",children:e}),n&&Lt(dc,{children:[de(He,{color:"gray",children:" ("}),de(He,{color:"cyan",children:n}),de(He,{color:"gray",children:")"})]})]})});import{jsx as vn,jsxs as wr}from"react/jsx-runtime";function yc(t,e){let n=t.turn,o=e.turn;if(n.index!==o.index||n.userInput!==o.userInput||n.finalText!==o.finalText||n.status!==o.status||n.steps.length!==o.steps.length||n.tokenUsage?.total!==o.tokenUsage?.total)return!1;for(let r=0;r<n.steps.length;r++){let s=n.steps[r],i=o.steps[r];if(!s||!i||s.assistantText!==i.assistantText||s.thinking!==i.thinking||s.action?.tool!==i.action?.tool)return!1}return!0}var Cn=hc(function({turn:e}){let n=e.finalText?.trim()??"",o=n.length>0;return wr(fc,{flexDirection:"column",children:[vn(vr,{text:e.userInput}),e.steps.map(r=>vn(_r,{step:r},`step-${e.index}-${r.index}`)),o?vn(Cr,{text:n,isThinking:!1}):null,e.status&&e.status!=="ok"?wr(gc,{color:"red",children:["Status: ",e.status]}):null]})},yc);import{jsx as ee,jsxs as _e}from"react/jsx-runtime";function Sc(t){let e=xc.homedir();return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}function vc(t){return t.length>16?`${t.slice(0,8)}...${t.slice(-4)}`:t}function Cc(t,e){if(t.headerInfo?.sessionId!==e.headerInfo?.sessionId||t.headerInfo?.model!==e.headerInfo?.model||t.headerInfo?.providerName!==e.headerInfo?.providerName||t.headerInfo?.cwd!==e.headerInfo?.cwd||t.headerInfo?.version!==e.headerInfo?.version||t.headerInfo?.mcpNames?.length!==e.headerInfo?.mcpNames?.length)return!1;if(t.headerInfo?.mcpNames&&e.headerInfo?.mcpNames){let n=t.headerInfo.mcpNames,o=e.headerInfo.mcpNames;for(let r=0;r<n.length;r++)if(n[r]!==o[r])return!1}if(t.systemMessages.length!==e.systemMessages.length)return!1;for(let n=0;n<t.systemMessages.length;n++)if(t.systemMessages[n]?.id!==e.systemMessages[n]?.id)return!1;if(t.turns.length!==e.turns.length)return!1;for(let n=0;n<t.turns.length;n++)if(t.turns[n]!==e.turns[n])return!1;return!0}var Er=_c(function({systemMessages:e,turns:n,headerInfo:o}){let r=n.length>0?n[n.length-1]:void 0,s=r&&(r.finalText||r.status&&r.status!=="ok"),i=s?n:n.slice(0,-1),a=s?void 0:r,l=[];o&&l.push({type:"header",data:o});let c=[];for(let u of e)c.push({sequence:u.sequence,item:{type:"system",data:u}});for(let u of i){let p=u.sequence??0;c.push({sequence:p,item:{type:"turn",data:u}})}c.sort((u,p)=>u.sequence-p.sequence);for(let u of c)l.push(u.item);return _e(Se,{flexDirection:"column",gap:0,children:[ee(Tc,{items:l,children:u=>{if(u.type==="header"&&u.data){let p=u.data;return _e(Se,{borderStyle:"round",borderColor:"blueBright",paddingX:2,paddingY:1,flexDirection:"column",gap:1,children:[ee(Se,{gap:1,alignItems:"center",children:_e(Se,{flexDirection:"column",children:[ee(ue,{bold:!0,children:"Welcome to Memo Code CLI!"}),ee(ue,{color:"gray",children:"Send /help for help information."})]})}),_e(Se,{flexDirection:"column",gap:0,children:[_e(Se,{children:[ee(ue,{color:"gray",children:"Directory: "}),ee(ue,{color:"cyan",children:Sc(p.cwd)})]}),_e(Se,{children:[ee(ue,{color:"gray",children:"Session: "}),ee(ue,{color:"cyan",children:vc(p.sessionId)})]}),_e(Se,{children:[ee(ue,{color:"gray",children:"Model: "}),ee(ue,{color:"cyan",children:p.model}),_e(ue,{color:"gray",children:[" ","(powered by ",p.providerName,")"]})]}),_e(Se,{children:[ee(ue,{color:"gray",children:"Version: "}),_e(ue,{color:"cyan",children:["v",p.version]})]}),_e(Se,{children:[ee(ue,{color:"gray",children:"MCP: "}),ee(ue,{color:"cyan",children:p.mcpNames.length>0?p.mcpNames.join(", "):"none"})]})]})]},"header")}return u.type==="system"?ee(hr,{message:u.data},u.data.id):u.type==="turn"?ee(Cn,{turn:u.data},`turn-${u.data.index}`):null}}),a&&ee(Cn,{turn:a},`turn-live-${a.index}`)]})},Cc);import{useCallback as Yr,useEffect as In,useMemo as mu,useRef as $n,useState as Le}from"react";import{readFile as du,readdir as fu,stat as gu}from"fs/promises";import{basename as hu,join as jt,resolve as ft}from"path";import{Box as Bt,Text as Fe,useInput as yu}from"ink";var Nr=Kn(Lr(),1);import{readFile as Vc,readdir as zc}from"fs/promises";import{join as Or,relative as Gc,sep as Kc}from"path";var qc=6,Xc=2500,Dr=25,Jc=[".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs","*.log"],Ut=new Map;function Yc(t){return t.split(Kc).join("/")}function Zc(t,e){return JSON.stringify({maxDepth:t.maxDepth,maxEntries:t.maxEntries,respectGitIgnore:t.respectGitIgnore,ignoreGlobs:t.ignoreGlobs,gitignore:e})}function Qc(t){return{maxDepth:typeof t.maxDepth=="number"?Math.max(1,t.maxDepth):qc,maxEntries:typeof t.maxEntries=="number"?Math.max(100,t.maxEntries):Xc,limit:typeof t.limit=="number"?Math.max(1,t.limit):Dr,respectGitIgnore:t.respectGitIgnore!==!1,ignoreGlobs:t.ignoreGlobs?.length?t.ignoreGlobs:[]}}async function eu(t,e){if(!e)return"";try{return await Vc(Or(t,".gitignore"),"utf8")}catch{}return""}async function tu(t,e){let n=await eu(e,t.respectGitIgnore),o=(0,Nr.default)();o.add(Jc),t.ignoreGlobs.length&&o.add(t.ignoreGlobs),n.trim()&&o.add(n);let r=Zc(t,n);return Object.assign(o,{__memoSignature:r})}async function nu(t,e,n){let o=[],r=e.maxEntries,s=async(i,a)=>{if(o.length>=r)return;let l;try{l=await zc(i,{withFileTypes:!0})}catch{return}for(let c of l){if(o.length>=r)break;if(c.isSymbolicLink())continue;let u=Or(i,c.name),p=Gc(t,u);if(!p)continue;let T=Yc(p);if(n.ignores(T))continue;let m=T.split("/").filter(Boolean),S=m.map(v=>v.toLowerCase()),_=c.isDirectory();if(o.push({path:T,pathLower:T.toLowerCase(),segments:m,segmentsLower:S,depth:a,isDir:_}),o.length>=r)break;_&&a<e.maxDepth&&await s(u,a+1)}};return await s(t,0),o.sort((i,a)=>i.path.localeCompare(a.path)),{entries:o,signature:n.__memoSignature}}async function ou(t,e){let n=Qc(e),o=await tu(n,t),r=o.__memoSignature,s=Ut.get(t);if(s&&s.signature===r)return s.pending?s.pending:s.entries;let i=nu(t,n,o).then(a=>(Ut.set(t,{entries:a.entries,signature:a.signature}),a.entries)).catch(a=>{throw Ut.delete(t),a});return Ut.set(t,{entries:[],signature:r,pending:i}),i}function ru(t){return t.depth+(t.isDir?-.2:.2)}function su(t,e){if(!e.length)return ru(t);let n=t.depth,o=0;for(let r of e){let s=-1;for(let i=o;i<t.segmentsLower.length;i++){let a=t.segmentsLower[i];if(a.startsWith(r)){s=i,n+=(i-o)*1.5,n+=a.length-r.length;break}let l=a.indexOf(r);if(l!==-1){s=i,n+=(i-o)*2+l+2;break}}if(s===-1)return null;o=s+1}return t.isDir&&(n-=.5),n}function iu(t,e,n){let s=e.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(a=>a.toLowerCase()),i=[];for(let a of t){let l=su(a,s);l!==null&&i.push({entry:a,score:l})}return i.sort((a,l)=>{let c=a.score-l.score;return c!==0?c:a.entry.path.localeCompare(l.entry.path)}),i.slice(0,n).map(({entry:a})=>({id:a.path,path:a.path,name:a.segments[a.segments.length-1]??a.path,parent:a.segments.length>1?a.segments.slice(0,-1).join("/"):void 0,isDir:a.isDir}))}async function Ur(t){let e=await ou(t.cwd,t),n=typeof t.limit=="number"?Math.max(1,t.limit):Dr;return iu(e,t.query,n)}import{mkdir as Lg,readFile as Og,writeFile as Ng}from"fs/promises";import{dirname as Ug}from"path";import{randomUUID as Fg}from"crypto";import{Box as mt,Text as Ze}from"ink";import{jsx as Pe,jsxs as Fr}from"react/jsx-runtime";var au="#3a3a3a",Ht="#2b2b2b",Hr="#888888",lu="#666666";function jr({items:t,activeIndex:e,loading:n}){return n?Pe(mt,{flexDirection:"column",paddingX:1,backgroundColor:Ht,children:Pe(Ze,{color:"gray",children:"Loading..."})}):t.length?Pe(mt,{flexDirection:"column",backgroundColor:Ht,children:t.map((o,r)=>{let s=r===e,i=s?au:Ht;return o.kind==="slash"?Fr(mt,{flexDirection:"row",gap:2,paddingX:1,backgroundColor:i,children:[Pe(Ze,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?Pe(Ze,{color:Hr,children:o.subtitle}):null]},o.id):Fr(mt,{flexDirection:"row",gap:1,paddingX:1,backgroundColor:i,children:[Pe(Ze,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?Pe(Ze,{color:Hr,children:o.subtitle}):null]},o.id)})}):Pe(mt,{flexDirection:"column",paddingX:1,backgroundColor:Ht,children:Pe(Ze,{color:lu,children:"No matches"})})}var Pn=[{name:"help",description:"Show help and shortcuts"},{name:"exit",description:"Exit the session"},{name:"new",description:"Start a new session"},{name:"resume",description:"Resume session history"},{name:"models",description:"Select a model (from configured providers)"},{name:"context",description:"Set context length limit (80k/120k/150k/200k) (starts new session)"},{name:"mcp",description:"Show configured MCP servers"},{name:"init",description:"Generate AGENTS.md for current project"}],cu=Object.fromEntries(Pn.map(t=>[t.name,t.description]));function te(t){return cu[t]}function Br(){let t=Pn.reduce((e,n)=>Math.max(e,n.name.length),0);return Pn.map(e=>` /${e.name.padEnd(t)} ${e.description}`)}var Wr={name:"new",description:te("new"),run:({closeSuggestions:t,setInputValue:e,clearScreen:n,showSystemMessage:o,newSession:r})=>{t(),e(""),n(),o("New Session","Starting a new session..."),r?.()}};var Vr={name:"exit",description:te("exit"),run:({closeSuggestions:t,exitApp:e})=>{t(),e()}};var zr={name:"resume",description:te("resume"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n})=>{t(!1),e("resume "),n("Resume",'Type "resume" followed by keywords to filter and select from session history.')}};var Gr={name:"models",description:te("models"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n,data:o})=>{t(!1);let{providers:r,providerName:s,model:i}=o;if(!r.length){n("Models",`No providers configured. Check ${o.configPath}`),e("");return}let a=r.map(l=>{let c=l.name===s&&l.model===i?" (current)":"",u=l.base_url?` @ ${l.base_url}`:"";return`- ${l.name}: ${l.model}${u}${c}`});e("/models "),n("Models",`Available models:
|
|
59
63
|
${a.join(`
|
|
60
|
-
`)}`)}};var
|
|
61
|
-
`),
|
|
62
|
-
${
|
|
64
|
+
`)}`)}};var uu=Br().join(`
|
|
65
|
+
`),Ft=`Available commands:
|
|
66
|
+
${uu}
|
|
63
67
|
exit Exit the session (no slash)
|
|
64
68
|
$ Execute shell command (e.g. $ git status)
|
|
65
69
|
|
|
@@ -71,24 +75,24 @@ Shortcuts:
|
|
|
71
75
|
Ctrl+L Start a new session
|
|
72
76
|
Ctrl+C Exit
|
|
73
77
|
exit Type in input to exit
|
|
74
|
-
Esc Esc Cancel / Clear input`;var
|
|
75
|
-
`)}var
|
|
76
|
-
|
|
77
|
-
Add servers to ${s}`),
|
|
78
|
-
`);for(let[c
|
|
79
|
-
`))}};var
|
|
80
|
-
`;
|
|
81
|
-
`),
|
|
82
|
-
`)){let
|
|
83
|
-
Current provider: ${
|
|
84
|
-
Current model: ${
|
|
78
|
+
Esc Esc Cancel / Clear input`;var Kr={name:"help",description:te("help"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n})=>{t(),e(""),n("Help",Ft)}};var qr={name:"context",description:te("context"),run:({closeSuggestions:t,setInputValue:e})=>{t(!1),e("/context ")}};function pu(t,e){let n=[];if(n.push(`- **${t}**`),"url"in e){n.push(` - Type: ${e.type??"streamable_http"}`),n.push(` - URL: ${e.url}`),e.bearer_token_env_var&&n.push(` - Bearer token env: ${e.bearer_token_env_var}`);let o=e.http_headers??e.headers;if(o&&Object.keys(o).length>0){let r=Object.entries(o).map(([s,i])=>`${s}=${i}`).join(", ");n.push(` - Headers: ${r}`)}}else if(n.push(` - Type: ${e.type??"stdio"}`),n.push(` - Command: ${e.command}`),e.args&&e.args.length>0&&n.push(` - Args: ${e.args.join(" ")}`),e.env&&Object.keys(e.env).length>0){let o=Object.entries(e.env).map(([r,s])=>`${r}=${s}`).join(", ");n.push(` - Env: ${o}`)}return n.join(`
|
|
79
|
+
`)}var Xr={name:"mcp",description:te("mcp"),run:({closeSuggestions:t,setInputValue:e,showSystemMessage:n,data:o})=>{t();let{mcpServers:r,configPath:s}=o,i=Object.keys(r);if(i.length===0){n("MCP Servers",`No MCP servers configured.
|
|
80
|
+
|
|
81
|
+
Add servers to ${s}`),e("");return}let a=[];a.push(`Total: ${i.length} server(s)
|
|
82
|
+
`);for(let[l,c]of Object.entries(r))a.push(pu(l,c)),a.push("");e(""),n("MCP Servers",a.join(`
|
|
83
|
+
`))}};var Jr={name:"init",description:te("init"),run:({closeSuggestions:t,setInputValue:e})=>{t(!1),e("/init")}};var Rn=[Kr,Vr,Wr,zr,Gr,qr,Xr,Jr];import{Fragment as $u,jsx as Oe,jsxs as dt}from"react/jsx-runtime";var Tu=400;function Qr({disabled:t,onSubmit:e,onExit:n,onClear:o,onNewSession:r,onCancelRun:s,onModelSelect:i,onSystemMessage:a,onSetContextLimit:l,history:c,cwd:u,sessionsDir:p,currentSessionFile:T,onHistorySelect:m,providers:S,configPath:_,providerName:v,model:N,contextLimit:R,mcpServers:w}){let[y,k]=Le(""),[K,D]=Le(null),[fe,H]=Le(""),[I,E]=Le("none"),[A,z]=Le([]),[ie,Y]=Le(0),[Ce,xe]=Le(!1),[b,V]=Le(!1),ge=$n(0),ae=$n(0),j=$n(""),Gt="\u203A ";In(()=>{j.current=y,V(!1)},[y]);let B=mu(()=>b||t?null:Eu(y),[t,b,y]),q=Yr(($=!0)=>{$&&V(!0),E("none"),z([]),Y(0),xe(!1)},[]);In(()=>{t&&q(!1)},[t,q]),In(()=>{if(!B){E("none"),z([]),Y(0),xe(!1);return}let $=!1,F=++ge.current;return xe(!0),(async()=>{try{if(B.type==="file"){let M=await Ur({cwd:u,query:B.query,limit:8});if($||F!==ge.current)return;let U=M.map(h=>{let C=h.isDir?`${h.path}/`:h.path;return{id:h.id,title:C,kind:"file",value:C,meta:{isDir:h.isDir}}});E("file"),z(U),Y(h=>U.length?Math.min(h,U.length-1):0);return}if(B.type==="history"){let M=await _u({sessionsDir:p,cwd:u,keyword:B.keyword,activeSessionFile:T});if($||F!==ge.current)return;let U=M.map(Ru);E("history"),z(U),Y(h=>U.length?Math.min(h,U.length-1):0);return}if(B.type==="models"){let M=B.keyword.toLowerCase(),h=(S??[]).filter(C=>{let re=C.name?.toLowerCase()??"",he=C.model?.toLowerCase()??"";return M?re.includes(M)||he.includes(M):!0}).map(C=>({id:C.name,title:`${C.name}: ${C.model}`,subtitle:C.base_url??C.env_api_key??"",kind:"model",value:`/models ${C.name}`,meta:{provider:C}}));E("model"),z(h),Y(C=>h.length?Math.min(C,h.length-1):0);return}if(B.type==="context"){let U=[8e4,12e4,15e4,2e5].map(h=>({id:`${h}`,title:`${(h/1e3).toFixed(0)}k tokens`,subtitle:h===R?"Current":void 0,kind:"context",value:`/context ${(h/1e3).toFixed(0)}k`,meta:{contextValue:h}}));E("context"),z(U),Y(h=>U.length?Math.min(h,U.length-1):0);return}if(B.type==="slash"){let M=B.keyword.toLowerCase(),h=(M?Rn.filter(C=>C.matches?C.matches(M):C.name.startsWith(M)):Rn).map(C=>({id:C.name,title:`/${C.name}`,subtitle:C.description,kind:"slash",value:`/${C.name} `,meta:{slashCommand:C}}));E("slash"),z(h),Y(C=>h.length?Math.min(C,h.length-1):0);return}}catch{!$&&F===ge.current&&z([])}finally{!$&&F===ge.current&&xe(!1)}})(),()=>{$=!0}},[B,u,p,T,S,R]);let xt=Yr($=>{if($){if(I==="file"&&B?.type==="file"){let F=y.slice(0,B.tokenStart),M=y.slice(B.tokenStart+B.query.length),U=`${F}${$.value}${M}`;j.current=U,k(U),D(null),H(""),$.meta?.isDir||q();return}if(I==="history"){$.meta?.historyEntry&&m?.($.meta.historyEntry),j.current=$.value,k($.value),D(null),H(""),q();return}if(I==="model"&&$.meta?.provider){i?.($.meta.provider),j.current="",k(""),D(null),H(""),q();return}if(I==="slash"&&$.meta?.slashCommand){$.meta.slashCommand.run({setInputValue:M=>{j.current=M,k(M),D(null),H("")},closeSuggestions:q,clearScreen:()=>{o()},newSession:()=>{r?.()},exitApp:()=>{n()},showSystemMessage:(M,U)=>{a?.(M,U)},switchModel:M=>{i?.(M)},setContextLimit:M=>{l?.(M)},loadHistory:M=>{m?.(M)},data:{configPath:_,providerName:v,model:N,contextLimit:R,providers:S,mcpServers:w}});return}if(I==="context"&&$.meta?.contextValue){let F=$.meta.contextValue;l?.(F),a?.("Context",`Context limit set to ${(F/1e3).toFixed(0)}k tokens`),j.current="",k(""),D(null),H(""),q();return}}},[q,o,n,i,a,l,m,I,B,y,_,v,N,R,S,w]);yu(($,F)=>{if(F.ctrl&&$==="l"){j.current="",k(""),D(null),H(""),q(),o(),r?.();return}let M=I!=="none",U=M&&A.length>0;if(F.escape){let h=Date.now();if(h-ae.current<=Tu){ae.current=0,t?s():(j.current="",k(""),D(null),H(""),q());return}ae.current=h,M&&q();return}if(!t){if(F.upArrow){if(U){Y(re=>re<=0?A.length-1:re-1);return}if(!c.length)return;if(K===null){H(j.current);let re=c.length-1;D(re);let he=c[re]??"";j.current=he,k(he);return}let h=Math.max(0,K-1);D(h);let C=c[h]??"";j.current=C,k(C);return}if(F.downArrow){if(U){Y(re=>(re+1)%A.length);return}if(K===null)return;let h=K+1;if(h>=c.length){D(null),j.current=fe,k(fe),H("");return}D(h);let C=c[h]??"";j.current=C,k(C);return}if(F.tab&&U){xt(A[ie]);return}if(F.return){if(U){xt(A[ie]);return}if(F.shift){let C=j.current+`
|
|
84
|
+
`;j.current=C,k(C);return}let h=j.current.trim();h&&(e(h),j.current="",k(""),D(null),H(""),q(!1));return}if(F.backspace||F.delete){let h=j.current.slice(0,Math.max(0,j.current.length-1));j.current=h,k(h);return}if($){let h=j.current+$;j.current=h,k(h)}}});let et=y,St=t?" ":"\u258A",De=et.split(`
|
|
85
|
+
`),Ie=2,Kt=A.map(({value:$,meta:F,...M})=>M);return dt(Bt,{flexDirection:"column",gap:1,children:[dt(Bt,{flexDirection:"column",paddingY:1,children:[dt(Bt,{children:[Oe(Fe,{color:"gray",children:Gt}),t?Oe(Fe,{color:"gray",children:De[0]}):dt($u,{children:[Oe(Fe,{color:"white",children:De[0]}),De.length===1&&Oe(Fe,{color:"cyan",children:St})]})]}),De.slice(1).map(($,F)=>dt(Bt,{children:[Oe(Fe,{color:"gray",children:" ".repeat(Ie)}),Oe(Fe,{color:"white",children:$}),F===De.length-2&&Oe(Fe,{color:"cyan",children:St})]},`line-${F}`))]}),I!=="none"?Oe(jr,{items:Kt,activeIndex:ie,loading:Ce}):null]})}async function _u(t){let e=t.activeSessionFile?ft(t.activeSessionFile):null,r=(await wu(t.sessionsDir)).filter(l=>!e||ft(l.path)!==e).filter((l,c,u)=>u.findIndex(p=>ft(p.path)===ft(l.path))===c).sort((l,c)=>c.mtimeMs-l.mtimeMs),s=t.limit??10,i=t.keyword?.trim().toLowerCase(),a=[];for(let l of r){if(a.length>=s)break;let c=await xu(l.path,t.cwd,l.mtimeMs);if(c&&!(i&&!c.input.toLowerCase().includes(i))&&(a.push(c),a.length>=s))break}return a}async function xu(t,e,n){try{let o=await du(t,"utf8"),{firstPrompt:r,sessionCwd:s}=Su(o);if(!Cu(e,s))return null;let i=r?.trim()||vu(t);return{id:t,cwd:e,input:i,ts:n,sessionFile:t}}catch{return null}}function Su(t){let e=null,n=null;for(let o of t.split(`
|
|
86
|
+
`)){let r=o.trim();if(!r)continue;let s;try{s=JSON.parse(r)}catch{continue}if(!(!s||typeof s!="object")){if(s.type==="session_start"&&!n){let i=s.meta?.cwd;typeof i=="string"&&i.trim()&&(n=i);continue}if(s.type==="turn_start"&&!e){let i=typeof s.content=="string"?s.content.trim():"";i&&(e=i)}}}return{firstPrompt:e,sessionCwd:n}}function vu(t){return hu(t).replace(/\.jsonl$/i,"")}function Zr(t){let e=ft(t);return process.platform==="win32"?e.toLowerCase():e}function Cu(t,e){return e?Zr(t)===Zr(e):!1}async function wu(t){let e=async s=>{try{return await fu(s,{withFileTypes:!0})}catch{return[]}},n=(await e(t)).filter(s=>s.isDirectory()&&/^\d{4}$/.test(s.name)),o=[];for(let s of n){let i=jt(t,s.name),a=(await e(i)).filter(l=>l.isDirectory()&&/^\d{2}$/.test(l.name));for(let l of a){let c=jt(i,l.name),u=(await e(c)).filter(p=>p.isDirectory()&&/^\d{2}$/.test(p.name));for(let p of u){let T=jt(c,p.name),m=(await e(T)).filter(S=>S.isFile()&&S.name.endsWith(".jsonl"));for(let S of m)o.push(jt(T,S.name))}}}return(await Promise.all(o.map(async s=>{try{let i=await gu(s);return{path:s,mtimeMs:i.mtimeMs}}catch{return null}}))).filter(s=>!!s)}function Eu(t){let e=Mu(t);if(e)return e;let n=Au(t);if(n)return n;let o=Pu(t);if(o)return o;let r=ku(t);return r||bu(t)}function ku(t){let e=t.lastIndexOf("@");if(e===-1)return null;if(e>0){let o=t[e-1];if(o&&!/\s/.test(o))return null}let n=t.slice(e+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:e+1}}function bu(t){let e=t.trimStart(),n=t.length-e.length;if(e.length===0)return null;let o=e;if(o.startsWith("/")&&(o=o.slice(1)),!o.toLowerCase().startsWith("resume")||t.slice(0,n).trim().length>0)return null;let s=o.slice(6);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function Au(t){let e=t.trimStart();if(!e.startsWith("/models"))return null;let n=e.slice(7);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim()}}function Mu(t){let e=t.trimStart();if(!e.startsWith("/context"))return null;let n=e.slice(8);return n&&!n.startsWith(" ")?null:{type:"context"}}function Pu(t){let e=t.trimStart();if(!e.startsWith("/"))return null;let n=e.slice(1);return n.includes(" ")?null:/^[a-zA-Z]*$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:n.length===0?{type:"slash",keyword:""}:null}function Ru(t){return{id:t.id,title:t.input,subtitle:Iu(t.ts),kind:"history",badge:"HIS",value:t.input,meta:{historyEntry:t}}}function Iu(t){if(!t)return"";let e=new Date(t);if(Number.isNaN(e.getTime()))return"";let n=String(e.getFullYear()),o=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");return`${n}-${o}-${r} ${s}:${i}`}import{Box as gt,Text as Ln,useInput as Lu}from"ink";import{useState as Ou,useCallback as Nu}from"react";import{jsx as ht,jsxs as On}from"react/jsx-runtime";function Du(t){if(typeof t!="object"||t===null)return String(t);let e=Object.entries(t);if(e.length===0)return"";let[n,o]=e[0],r=typeof o=="string"?o:JSON.stringify(o);return`${r.slice(0,40)}${r.length>40?"...":""}`}function es({request:t,onDecision:e}){let n=[{label:"Allow once",decision:"once"},{label:"Allow all session",decision:"session"},{label:"Reject this time",decision:"deny"}],[o,r]=Ou(0);Lu(Nu((i,a)=>{a.upArrow?r(l=>l>0?l-1:n.length-1):a.downArrow?r(l=>l<n.length-1?l+1:0):a.return&&e(n[o].decision)},[o,e,n]));let s=Du(t.params);return On(gt,{borderStyle:"single",borderColor:"gray",paddingX:2,flexDirection:"column",children:[ht(gt,{children:ht(Ln,{bold:!0,children:"Tool Approval:"})}),ht(gt,{marginTop:1,children:On(Ln,{color:"cyan",children:[t.toolName,s?` (${s})`:""]})}),ht(gt,{flexDirection:"column",marginTop:1,children:n.map((i,a)=>ht(gt,{children:On(Ln,{color:o===a?"green":"gray",children:[o===a?"> ":" ",i.label]})},i.decision))})]})}import Hh from"string-width";function ns(t){if(!t)return"success";let e=t.toLowerCase();return e.includes("error")||e.includes("unknown")||e.includes("failed")?"error":"success"}var ts={"gpt-4o-mini":128e3,"gpt-4o":128e3,"gpt-4":8192,"gpt-3.5":16384,"claude-3":2e5,claude:2e5,"deepseek-coder":64e3,"deepseek-chat":64e3,deepseek:64e3,"kimi-k2":2e5,kimi:2e5,default:12e4};function Uu(t){let e=t.toLowerCase(),n=Object.entries(ts).filter(([o])=>o!=="default");for(let[o,r]of n.sort((s,i)=>i[0].length-s[0].length))if(e.includes(o))return r;return ts.default}function os(t,e){if(t==null)return 0;let n=typeof t=="number"?t:t.prompt??t.total??0;if(n<=0)return 0;let o=e&&e>0?e:Uu("");return Math.min(100,n/o*100)}function rs(t){return t?`${t.total} tokens`:""}function ss(t,e){let[n,...o]=t.trim().slice(1).split(/\s+/),r=(n??"").toLowerCase(),s=[8e4,12e4,15e4,2e5],i=a=>{if(!a)return null;let c=a.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!c)return null;let u=Number(c[1])*(c[2]?1e3:1);return Number.isFinite(u)?u:null};switch(r){case"exit":return{kind:"exit"};case"new":return{kind:"new"};case"help":return{kind:"message",title:"Help",content:Ft};case"config":return{kind:"message",title:"Config",content:`Config file: ${e.configPath}
|
|
87
|
+
Current provider: ${e.providerName}
|
|
88
|
+
Current model: ${e.model}`};case"resume":return{kind:"message",title:"Resume",content:'Type "resume" to filter and select from session history.'};case"context":{let p=i(o[0]),T=s.map(m=>`${m/1e3}k`).join(", ");return p===null?{kind:"message",title:"Context",content:`Current: ${(e.contextLimit/1e3).toFixed(0)}k
|
|
85
89
|
Usage: /context <length> (starts new session)
|
|
86
|
-
Choices: ${
|
|
87
|
-
${
|
|
88
|
-
`)}`};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${
|
|
89
|
-
Type /help for available commands.`}}}import{dirname as
|
|
90
|
-
`);
|
|
91
|
-
`);
|
|
90
|
+
Choices: ${T}`}:s.includes(p)?{kind:"set_context_limit",limit:p}:{kind:"message",title:"Context",content:`Unsupported length: ${p}. Pick one of: ${T}`}}case"init":return{kind:"init_agents_md"};case"$":{let p=o.join(" ").trim();return p?{kind:"shell_command",command:p}:{kind:"message",title:"Shell Command",content:"Usage: $ <command> (e.g. $ git status)"}}case"models":if(!e.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${e.configPath}`};let a=o.join(" ").trim(),l=e.providers.find(p=>p.name===a)??e.providers.find(p=>p.model===a);if(l)return{kind:"switch_model",provider:l};let c=e.providers.map(p=>{let T=p.base_url?` @ ${p.base_url}`:"";return`- ${p.name}: ${p.model}${T}`});return{kind:"message",title:"Models",content:`${a?`Not found: ${a}, `:""}Available models:
|
|
91
|
+
${c.join(`
|
|
92
|
+
`)}`};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${t}
|
|
93
|
+
Type /help for available commands.`}}}import{dirname as Wt,join as as,resolve as Hu}from"path";import{statSync as Fu,existsSync as ls,readFileSync as ju}from"fs";import{readFile as Bu}from"fs/promises";import{get as Wu}from"https";import{fileURLToPath as Vu}from"url";function is(t){let e=t.trim().replace(/^v/i,""),[n="",o]=e.split("-",2),r=n.split(".").map(s=>Number(s));return r.length<3||r.some(s=>!Number.isFinite(s))?null:{major:r[0]??0,minor:r[1]??0,patch:r[2]??0,prerelease:o??null}}function zu(t,e){let n=is(t),o=is(e);return!n||!o?!1:n.major!==o.major?n.major>o.major:n.minor!==o.minor?n.minor>o.minor:n.patch!==o.patch?n.patch>o.patch:n.prerelease&&!o.prerelease?!1:!n.prerelease&&o.prerelease?!0:n.prerelease&&o.prerelease?n.prerelease>o.prerelease:!1}function cs(){try{let e=Vu(import.meta.url);return Wt(e)}catch{}let t=Hu(process.argv[1]??process.cwd());try{return Fu(t).isFile()?Wt(t):t}catch{return process.cwd()}}async function Gu(t){let e=as(t,"package.json");if(!ls(e))return null;let n=await Bu(e,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}function Ku(t){let e=as(t,"package.json");if(!ls(e))return null;try{let n=ju(e,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}catch{return null}}async function qu(){let t=cs();for(;;){let e=await Gu(t);if(e&&e.name==="@memo-code/memo")return e;let n=Wt(t);if(n===t)break;t=n}return null}function Vt(){let t=cs();for(;;){let e=Ku(t);if(e&&e.name==="@memo-code/memo")return e;let n=Wt(t);if(n===t)break;t=n}return null}async function Xu(t,e=1500){let o=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(r=>{let s=Wu(o,{timeout:e},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),r(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));r(l.version??null)}catch{r(null)}})});s.on("timeout",()=>{s.destroy(),r(null)}),s.on("error",()=>r(null))})}async function us(){let t=await qu();if(!t)return null;let e=await Xu(t.name);return!e||!zu(e,t.version)?null:{current:t.version,latest:e}}import{Box as Qe,Text as ve,useInput as Ju}from"ink";import{useCallback as Nn,useMemo as Yu,useState as yt}from"react";import{jsx as Re,jsxs as je}from"react/jsx-runtime";var Ne=[{key:"name",label:"Provider name",hint:"Used in /model and config",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Memo reads this env var at runtime",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",hint:"Provider model ID",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",hint:"Leave default unless you have a custom endpoint",defaultValue:"https://api.deepseek.com"}];function ps({configPath:t,onComplete:e,onExit:n}){let[o,r]=yt(0),[s,i]=yt(""),[a,l]=yt({}),[c,u]=yt(!1),[p,T]=yt(null),m=Ne[o]??Ne[0],S=s||a[m.key]||"",_=Nn(async R=>{u(!0),T(null);try{let w=R.name||Ne[0].defaultValue,y=R.envKey||Ne[1].defaultValue,k=R.model||Ne[2].defaultValue,K=R.baseUrl||Ne[3].defaultValue;await Te(t,{current_provider:w,providers:[{name:w,env_api_key:y,model:k,base_url:K||void 0}]}),e()}catch(w){T(w.message),u(!1)}},[t,e]),v=Nn(async()=>{let w=s.trim()||m.defaultValue,y={...a,[m.key]:w};if(l(y),i(""),o<Ne.length-1){r(o+1);return}await _(y)},[m.defaultValue,m.key,o,s,a,_]);Ju(Nn((R,w)=>{if(!c){if(w.ctrl&&R==="c"){n();return}if(w.return){v();return}if(w.backspace||w.delete){i(y=>y.slice(0,-1));return}R&&i(y=>y+R)}},[v,n,c]));let N=Yu(()=>`Step ${o+1}/${Ne.length}`,[o]);return je(Qe,{flexDirection:"column",children:[je(Qe,{flexDirection:"column",marginBottom:1,children:[Re(ve,{bold:!0,children:"Memo setup"}),Re(ve,{color:"gray",children:"No provider config found. Create one to continue."}),je(ve,{color:"gray",children:["Config path: ",t]})]}),je(Qe,{flexDirection:"column",marginBottom:1,children:[Re(ve,{color:"cyan",children:N}),je(ve,{children:[m.label," (default: ",m.defaultValue,")"]}),m.hint?Re(ve,{color:"gray",children:m.hint}):null]}),je(Qe,{children:[Re(ve,{children:"> "}),Re(ve,{children:S})]}),Re(Qe,{marginTop:1,children:Re(ve,{color:"gray",children:"Press Enter to continue. Ctrl+C to exit."})}),p?Re(Qe,{marginTop:1,children:je(ve,{color:"red",children:["Failed to write config: ",p]})}):null]})}import{jsx as Be,jsxs as ip}from"react/jsx-runtime";var op=ep(Qu);function rp(t){return{index:t,userInput:"",steps:[]}}function ds({sessionOptions:t,providerName:e,model:n,configPath:o,mcpServers:r,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:u}=tp(),[p,T]=J(e),[m,S]=J(n),[_,v]=J(a),[N,R]=J({...t,providerName:e}),[w,y]=J(null),[k,K]=J([]),[D,fe]=J([]),[H,I]=J(!1),E=Tt(null),A=Tt(null),[z,ie]=J([]),[Y,Ce]=J(null),[xe,b]=J([]),[V,ge]=J(null),ae=Tt(null),[j,Gt]=J(null),B=Tt(0),[q,xt]=J(t.maxPromptTokens??12e4),[et,St]=J(c),[De,Ie]=J(0),Kt=Dn(()=>Vt(),[]),[$,F]=J(null),M=Tt(null),U=X(()=>(B.current+=1,B.current),[]),h=X((f,g)=>{let x=`${Date.now()}-${Math.random().toString(16).slice(2)}`,P=U();fe(O=>[...O,{id:x,title:f,content:g,sequence:P}])},[U]),C=X((f,g)=>{K(x=>{let P=[...x],O=P.findIndex(le=>le.index===f);O===-1&&(P.push(rp(f)),O=P.length-1);let W=P[O];return W&&(P[O]=g(W)),P})},[]),re=Dn(()=>({onAssistantStep:(f,g)=>{let x=E.current;x&&C(x,P=>{let O=P.steps.slice();for(;O.length<=g;)O.push({index:O.length,assistantText:""});let W=O[g];if(!W)return P;let le={...W,assistantText:W.assistantText+f};return O[g]=le,{...P,steps:O}})},requestApproval:l?void 0:f=>new Promise(g=>{F(f),M.current=g}),hooks:{onTurnStart:({turn:f,input:g,promptTokens:x})=>{E.current=f;let P=A.current;P&&(A.current=null);let O=P??g;x&&x>0&&Ie(x),C(f,W=>({...W,index:f,userInput:O,steps:[],startedAt:Date.now(),contextPromptTokens:x??W.contextPromptTokens}))},onAction:({turn:f,step:g,action:x,thinking:P,parallelActions:O})=>{C(f,W=>{let le=W.steps.slice();for(;le.length<=g;)le.push({index:le.length,assistantText:""});let vt=le[g];return vt?(le[g]={...vt,action:x,thinking:P,toolStatus:"executing",parallelActions:O&&O.length>1?O:void 0},{...W,steps:le}):W})},onObservation:({turn:f,step:g,observation:x})=>{C(f,P=>{let O=P.steps.slice();for(;O.length<=g;)O.push({index:O.length,assistantText:""});let W=O[g];return W?(O[g]={...W,observation:x,toolStatus:ns(x)},{...P,steps:O}):P})},onFinal:({turn:f,finalText:g,status:x,turnUsage:P,tokenUsage:O})=>{C(f,W=>{let le=W.startedAt??Date.now(),vt=Math.max(0,Date.now()-le),ks=O?.prompt??W.contextPromptTokens,bs=W.sequence??U();return{...W,finalText:g,status:x,tokenUsage:P,contextPromptTokens:ks,startedAt:le,durationMs:vt,sequence:bs}}),I(!1)}}}),[C,l,U]);zt(()=>{let f=!1;return(async()=>{if(et)return;let g=ae.current;g&&await g.close();let x=await lt(re,N);if(f){await x.close();return}ae.current=x,y(x),Ce(x.historyFilePath??null)})(),()=>{f=!0}},[re,N,et]),zt(()=>{let f=!1;return(async()=>{let g=await us();f||!g||h("Update",`Update available: v${g.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{f=!0}},[h]),zt(()=>()=>{ae.current&&ae.current.close()},[]);let he=X(async()=>{ae.current&&await ae.current.close(),Gt("Bye!"),setTimeout(()=>{u()},300)},[u]),Fn=X(()=>{K([]),fe([]),b([]),ge(null),Ie(0),B.current=0},[]),jn=X(async()=>{K([]),fe([]),b([]),ge(null),Ie(0),B.current=0;let f=_t(),g={...N,sessionId:f};ae.current&&await ae.current.close();let x=await lt(re,g);ae.current=x,y(x),Ce(x.historyFilePath??null),R(g),h("New Session","Started a new session with fresh context.")},[re,N,h]),Bn=X(async f=>{try{let g=await se(),x={...g.config,max_prompt_tokens:f};await Te(g.configPath,x)}catch(g){h("Failed to save config",`Failed to save context limit: ${g.message}`)}},[h]),qt=X(f=>{xt(f),Ie(0),R(g=>({...g,maxPromptTokens:f,sessionId:_t()})),h("Context length",`Context limit set to ${(f/1e3).toFixed(0)}k tokens (new session started)`),Bn(f)},[h,Bn]),Ts=X(async f=>{if(!f.sessionFile){h("History","This entry has no context file to load.");return}try{let g=await Zu(f.sessionFile,"utf8"),x=sp(g);b(x.turns),ge(x.messages),I(!1),K([]),y(null),Ce(null),Ie(0),E.current=null,B.current=Math.max(B.current,x.maxSequence),R(P=>({...P,sessionId:_t()})),h("History loaded",x.summary||f.input)}catch(g){h("Failed to load history",`Unable to read ${f.sessionFile}: ${g.message}`)}},[h]),Wn=X(async f=>{try{let g=await se(),x={...g.config,current_provider:f};await Te(g.configPath,x)}catch(g){h("Failed to save config",`Failed to save model selection: ${g.message}`)}},[h]),_s=X(()=>{H&&w?.cancelCurrentTurn?.()},[H,w]),Xt=X(async f=>{if(f.name===p&&f.model===m){h("Model switch",`Already using ${f.name} (${f.model})`);return}if(H){h("Model switch","Currently running. Press Esc Esc to cancel before switching models.");return}K([]),b([]),ge(null),Ie(0),E.current=null,y(null),Ce(null),T(f.name),S(f.model),R(g=>({...g,sessionId:_t(),providerName:f.name})),await Wn(f.name),h("Model switch",`Switched to ${f.name} (${f.model})`)},[h,H,m,p,Wn]),Jt=X(async f=>{if(!f.trim()){h("Shell Command","Usage: $ <command> (e.g. $ git status)");return}I(!0);try{let{stdout:g,stderr:x}=await op(f,{cwd:s,maxBuffer:5242880}),P=[g?.trim(),x?.trim()].filter(Boolean).join(`
|
|
94
|
+
`);h("Shell Result",P||"(no output)")}catch(g){let x=g,O=[x.stdout?.trim(),x.stderr?.trim(),x.message].filter(Boolean).join(`
|
|
95
|
+
`);h("Shell Error",O||"Command failed")}finally{I(!1)}},[h,s]),Vn=X(async f=>{let g=ss(f,{configPath:o,providerName:p,model:m,mcpServers:r,providers:_,contextLimit:q});if(g.kind==="exit"){await he();return}if(g.kind==="new"){await jn();return}if(g.kind==="switch_model"){await Xt(g.provider);return}if(g.kind==="set_context_limit"){qt(g.limit);return}if(g.kind==="init_agents_md"){h("Init","Analyzing project structure and generating AGENTS.md...");let x=`Please analyze the current project and create an AGENTS.md file at the project root.
|
|
92
96
|
|
|
93
97
|
The AGENTS.md should include:
|
|
94
98
|
1. Project name and brief description
|
|
@@ -99,15 +103,15 @@ The AGENTS.md should include:
|
|
|
99
103
|
6. Any project-specific notes for AI assistants
|
|
100
104
|
|
|
101
105
|
Steps:
|
|
102
|
-
1. First explore the project structure using
|
|
106
|
+
1. First explore the project structure using list_dir and exec_command tools
|
|
103
107
|
2. Read key configuration files (package.json, tsconfig.json, etc.)
|
|
104
108
|
3. Understand the tech stack and conventions
|
|
105
|
-
4. Create the AGENTS.md file using
|
|
109
|
+
4. Create the AGENTS.md file using apply_patch
|
|
106
110
|
|
|
107
|
-
Make the AGENTS.md concise but informative, following best practices for AI agent guidelines.`;if(
|
|
108
|
-
`);return
|
|
109
|
-
`).map(
|
|
110
|
-
`),messages:
|
|
111
|
+
Make the AGENTS.md concise but informative, following best practices for AI agent guidelines.`;if(ie(P=>[...P,"/init"]),!w){h("Error","Session not initialized");return}I(!0);try{A.current="/init (generate AGENTS.md)",await w.runTurn(x)}catch{I(!1)}return}if(g.kind==="shell_command"){await Jt(g.command);return}h(g.title,g.content)},[h,qt,o,Fn,he,Xt,r,m,p,q,_,Jt]),xs=X(async()=>{try{let f=await se(),g=Ue(f.config);v(f.config.providers),T(g.name),S(g.model),R(x=>({...x,sessionId:_t(),providerName:g.name})),St(!1),h("Setup",`Config saved to ${f.configPath}`)}catch(f){h("Setup",`Failed to reload config: ${f.message}`)}},[h]);zt(()=>{if(!w||!V?.length)return;let f=w.history[0];f&&(w.history.splice(0,w.history.length,f,...V),ge(null))},[V,w]);let Ss=X(async f=>{if(f.trim().toLowerCase()==="exit"){await he();return}if(!w||H)return;let g=f.trim();if(g.startsWith("$")){let x=g.slice(1).trim();ie(P=>[...P,f]),await Jt(x);return}if(f.startsWith("/")){await Vn(f);return}ie(x=>[...x,f]),I(!0);try{await w.runTurn(f)}catch{I(!1)}},[H,Vn,he,w]),vs=k[k.length-1],Sp=rs(vs?.tokenUsage),Cs=os(De,q),ws=Dn(()=>[...xe,...k],[xe,k]),Es=X(f=>{let g=M.current;g&&(g(f),M.current=null),F(null)},[]);if(j){let f=j.split(`
|
|
112
|
+
`);return Be(ms,{flexDirection:"column",children:f.map((g,x)=>Be(np,{color:"green",children:g},x))})}return et?Be(ps,{configPath:o,onComplete:xs,onExit:he}):ip(ms,{flexDirection:"column",children:[Be(Er,{systemMessages:D,turns:ws,headerInfo:{providerName:p,model:m,cwd:s,sessionId:N.sessionId??"unknown",mcpNames:Object.keys(r??{}).sort(),version:Kt?.version??"unknown"}}),Be(Qr,{disabled:!w||H||!!$,onSubmit:Ss,onExit:he,onClear:Fn,onNewSession:jn,onCancelRun:_s,onHistorySelect:Ts,onModelSelect:Xt,onSystemMessage:h,onSetContextLimit:f=>{qt(f)},history:z,cwd:s,sessionsDir:i,currentSessionFile:Y??void 0,providers:_,configPath:o,providerName:p,model:m,contextLimit:q,mcpServers:r}),$&&Be(es,{request:$,onDecision:Es}),Be(dr,{contextPercent:Cs})]})}function sp(t){let e=[],n=[],o=[],r=t.split(`
|
|
113
|
+
`).map(l=>l.trim()).filter(Boolean),s=null,i=0,a=0;for(let l of r){let c;try{c=JSON.parse(l)}catch{continue}if(!(!c||typeof c!="object")){if(c.type==="turn_start"){let u=typeof c.content=="string"?c.content:"";s={index:-(i+1),userInput:u,steps:[],status:"ok",sequence:a+=1},n.push(s),u&&(e.push({role:"user",content:u}),o.push(`User: ${u}`)),i+=1;continue}if(c.type==="assistant"){let u=typeof c.content=="string"?c.content:"";if(u&&(e.push({role:"assistant",content:u}),o.push(`Assistant: ${u}`),s)){let p={index:s.steps.length,assistantText:u};s.steps=[...s.steps,p],s.finalText=u}continue}if(c.type==="action"&&s){let u=c.meta;if(u&&typeof u=="object"){let p=typeof u.tool=="string"?u.tool:"",T=u.input,m=typeof u.thinking=="string"?u.thinking:"",_=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(N=>{let R=typeof N?.name=="string"?N.name:"";return R?{tool:R,input:N?.input}:null}).filter(Boolean),v=s.steps[s.steps.length-1];v&&(_.length>1?(v.action=_[0],v.parallelActions=_):p&&(v.action={tool:p,input:T}),m&&(v.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:o.join(`
|
|
114
|
+
`),messages:e,turns:n,maxSequence:a}}var ap=`
|
|
111
115
|
Usage:
|
|
112
116
|
memo mcp list [--json]
|
|
113
117
|
memo mcp get <name> [--json]
|
|
@@ -116,14 +120,14 @@ Usage:
|
|
|
116
120
|
memo mcp remove <name>
|
|
117
121
|
memo mcp login <name> [--scopes scope1,scope2]
|
|
118
122
|
memo mcp logout <name>
|
|
119
|
-
`;function
|
|
120
|
-
`)}function
|
|
121
|
-
`),{...
|
|
122
|
-
[approval required] ${
|
|
123
|
-
[tool] ${
|
|
124
|
-
`);let
|
|
125
|
-
${
|
|
126
|
-
[tokens] prompt=${
|
|
127
|
-
provider=${n.name} model=${n.model}`)}catch(
|
|
128
|
-
`)),await
|
|
123
|
+
`;function Un(){console.log(ap.trim())}function lp(t){let e=t.indexOf("=");if(e<=0)return null;let n=t.slice(0,e).trim(),o=t.slice(e+1);return n?{key:n,value:o}:null}function fs(t,e){let n=[];if(n.push(`${t}`),"url"in e){n.push(` type: ${e.type??"streamable_http"}`),n.push(` url: ${e.url}`),e.bearer_token_env_var&&n.push(` bearer_token_env_var: ${e.bearer_token_env_var}`);let o=e.http_headers??e.headers;o&&Object.keys(o).length>0&&n.push(` headers: ${Object.entries(o).map(([r,s])=>`${r}=${s}`).join(", ")}`)}else n.push(` type: ${e.type??"stdio"}`),n.push(` command: ${e.command}`),e.args&&e.args.length>0&&n.push(` args: ${e.args.join(" ")}`),e.env&&Object.keys(e.env).length>0&&n.push(` env: ${Object.entries(e.env).map(([o,r])=>`${o}=${r}`).join(", ")}`);return n.join(`
|
|
124
|
+
`)}function cp(t){let e=t.shift();if(!e)return{error:"Missing server name."};let n,o,r={},s=[];for(let i=0;i<t.length;i+=1){let a=t[i];if(a){if(a==="--"){s=t.slice(i+1);break}if(a==="--url"){let l=t[i+1];if(!l)return{error:"Missing value for --url."};n=l,i+=1;continue}if(a==="--bearer-token-env-var"){let l=t[i+1];if(!l)return{error:"Missing value for --bearer-token-env-var."};o=l,i+=1;continue}if(a==="--env"){let l=t[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=lp(l);if(!c)return{error:"Invalid --env format. Use KEY=VALUE."};r[c.key]=c.value,i+=1;continue}return a==="--help"||a==="-h"?{error:""}:{error:`Unknown option: ${a}`}}}return n?s.length>0?{error:"Use either --url or a stdio command, not both."}:Object.keys(r).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:e,url:n,bearerTokenEnvVar:o}}:o?{error:"--bearer-token-env-var is only supported with HTTP servers."}:s.length===0?{error:"Missing stdio command. Use `-- <command...>`."}:{options:{name:e,command:s[0],args:s.slice(1),env:Object.keys(r).length>0?r:void 0}}}function up(t){let[e,...n]=t;return!e||e==="--help"||e==="-h"||e==="help"?{command:"help",rest:[]}:{command:e,rest:n}}function Hn(t,e=[]){let n=new Set(e);for(let o=0;o<t.length;o+=1){let r=t[o];if(r){if(r.startsWith("--")){n.has(r)&&(o+=1);continue}return r}}return null}async function gs(t){let{command:e,rest:n}=up(t);if(e==="help"){Un();return}if(e==="list"){let o=n.includes("--json"),s=(await se()).config.mcp_servers??{};if(o){console.log(JSON.stringify(s,null,2));return}let i=Object.keys(s);if(i.length===0){console.log('No MCP servers configured. Add one with "memo mcp add".');return}console.log(`MCP servers (${i.length}):`);for(let a of i){let l=s[a];l&&console.log(fs(a,l))}return}if(e==="get"){let o=n.includes("--json"),r=Hn(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let i=(await se()).config.mcp_servers?.[r];if(!i){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(o){console.log(JSON.stringify(i,null,2));return}console.log(fs(r,i));return}if(e==="add"){let o=cp(n);if(o.error!==void 0){o.error&&(console.error(o.error),process.exitCode=1),Un();return}let r=o.options;if(!r)return;if(r.url)try{new URL(r.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await se(),i={...s.config.mcp_servers??{}};if(i[r.name]){console.error(`MCP server "${r.name}" already exists.`),process.exitCode=1;return}let a;r.url?a={type:"streamable_http",url:r.url,...r.bearerTokenEnvVar?{bearer_token_env_var:r.bearerTokenEnvVar}:{}}:a={command:r.command,args:r.args&&r.args.length>0?r.args:void 0,env:r.env},i[r.name]=a,await Te(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${r.name}".`);return}if(e==="remove"){let o=Hn(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let r=await se(),s={...r.config.mcp_servers??{}};if(!s[o]){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}delete s[o],await Te(r.configPath,{...r.config,mcp_servers:s}),console.log(`Removed MCP server "${o}".`);return}if(e==="login"||e==="logout"){let o=Hn(n,["--scopes"]);if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=(await se()).config.mcp_servers?.[o];if(!s){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth login/logout only applies to streamable HTTP servers."),process.exitCode=1;return}console.error("OAuth login/logout is not supported in memo yet. Configure a bearer token env var instead."),process.exitCode=1;return}console.error(`Unknown subcommand: ${e}`),Un(),process.exitCode=1}import{jsx as xp}from"react/jsx-runtime";function gp(t){let e={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let o=0;o<t.length;o++){let r=t[o];if(r!==void 0){if(r==="--version"||r==="-v"){e.showVersion=!0;continue}if(r==="--once"){e.removedOnceFlag=!0;continue}if(r==="--dangerous"||r==="-d"){e.dangerous=!0;continue}n.push(r)}}return{question:n.join(" "),options:e}}async function ys(t){let e=await se();if(!e.needsSetup)return e;let n=e.config.providers[0],r=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(a=>!!process.env[a]);if(n&&r)return await Te(e.configPath,e.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${e.configPath}`),{...e,needsSetup:!1};if(t==="tui")return e;let s=pp({input:mp,output:dp}),i=async(a,l)=>(await s.question(a)).trim()||l;try{console.log("No provider config found. Please answer the prompts:");let a=await i("Provider name [deepseek]: ","deepseek"),l=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),c=await i("Model name [deepseek-chat]: ","deepseek-chat"),u=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),p={current_provider:a,providers:[{name:a,env_api_key:l,model:c,base_url:u||void 0}]};return await Te(e.configPath,p),console.log(`Config written to ${e.configPath}
|
|
125
|
+
`),{...e,config:p,needsSetup:!1}}finally{s.close()}}async function hp(t){let e=await ys("plain"),n=Ue(e.config),r={sessionId:hs(),mode:"interactive",maxPromptTokens:e.config.max_prompt_tokens,dangerous:t.options.dangerous};t.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={requestApproval:t.options.dangerous?void 0:l=>(console.log(`
|
|
126
|
+
[approval required] ${l.toolName}: ${l.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:l})=>{console.log(`
|
|
127
|
+
[tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await lt(s,r),a=t.question;if(!a&&!process.stdin.isTTY&&(a=await _p()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
|
|
128
|
+
`);let l=await i.runTurn(a);console.log(`
|
|
129
|
+
${l.finalText}`),console.log(`
|
|
130
|
+
[tokens] prompt=${l.tokenUsage.prompt} completion=${l.tokenUsage.completion} total=${l.tokenUsage.total}`),console.log(`
|
|
131
|
+
provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function yp(t){let e=await ys("tui"),n=Ue(e.config),r={sessionId:hs(),mode:"interactive",maxPromptTokens:e.config.max_prompt_tokens,dangerous:t.options.dangerous},s=It(e,r);t.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
|
|
132
|
+
`)),await fp(xp(ds,{sessionOptions:r,providerName:n.name,model:n.model,configPath:e.configPath,mcpServers:e.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:s,providers:e.config.providers,dangerous:t.options.dangerous,needsSetup:e.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function Tp(){let t=process.argv.slice(2);if(t[0]==="mcp"||t[0]==="--"&&t[1]==="mcp"){let o=t[0]==="--"?2:1;await gs(t.slice(o));return}let e=gp(t);if(e.options.removedOnceFlag){console.error("`--once` has been removed. Use `memo` (interactive) or pipe input to `memo`."),process.exitCode=1;return}if(e.options.showVersion){let r=Vt()?.version??"unknown";console.log(r);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await hp(e);return}await yp(e)}Tp();async function _p(){return new Promise(t=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n}),process.stdin.on("end",()=>{t(e.trim())}),process.stdin.resume()})}
|
|
129
133
|
//# sourceMappingURL=index.js.map
|