@memo-code/memo 0.6.31 → 0.6.55
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 +16 -7
- package/README.zh.md +24 -16
- package/dist/index.js +113 -99
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -55,6 +55,9 @@ memo
|
|
|
55
55
|
- Plain mode (non-TTY): `echo "your prompt" | memo` (plain text output; useful for scripts).
|
|
56
56
|
- Dangerous mode: `memo --dangerous` or `memo -d` (skip tool approvals; use carefully).
|
|
57
57
|
- Version: `memo --version` or `memo -v`.
|
|
58
|
+
- Startup project guidance: if `AGENTS.md` exists in the startup root, Memo appends it to the system prompt automatically.
|
|
59
|
+
- MCP activation selection: when MCP servers are configured, startup shows a multi-select to activate servers for this run.
|
|
60
|
+
- Session titles: Memo generates a short title from the first user prompt and uses it in history/resume lists.
|
|
58
61
|
|
|
59
62
|
## Configuration
|
|
60
63
|
|
|
@@ -89,6 +92,10 @@ args = []
|
|
|
89
92
|
type = "streamable_http"
|
|
90
93
|
url = "https://your-mcp-server.com/mcp"
|
|
91
94
|
# headers = { Authorization = "Bearer xxx" }
|
|
95
|
+
|
|
96
|
+
# Optional: default active MCP servers at startup
|
|
97
|
+
active_mcp_servers = ["local_tools", "remote"]
|
|
98
|
+
# Optional: use [] to start with no MCP servers active
|
|
92
99
|
```
|
|
93
100
|
|
|
94
101
|
You can also manage MCP configs via CLI (aligned with Codex CLI style):
|
|
@@ -166,15 +173,16 @@ pnpm run build # generates dist/index.js
|
|
|
166
173
|
### Test
|
|
167
174
|
|
|
168
175
|
```bash
|
|
169
|
-
pnpm test
|
|
170
|
-
pnpm test
|
|
171
|
-
pnpm test
|
|
176
|
+
pnpm test # all tests
|
|
177
|
+
pnpm run test:core # core package
|
|
178
|
+
pnpm run test:tools # tools package
|
|
179
|
+
pnpm run test:tui # tui package
|
|
172
180
|
```
|
|
173
181
|
|
|
174
182
|
### Format
|
|
175
183
|
|
|
176
184
|
```bash
|
|
177
|
-
npm run format # format
|
|
185
|
+
npm run format # format source/config files
|
|
178
186
|
npm run format:check # check format (CI)
|
|
179
187
|
```
|
|
180
188
|
|
|
@@ -185,7 +193,7 @@ memo-cli/
|
|
|
185
193
|
├── packages/
|
|
186
194
|
│ ├── core/ # core logic: Session, tool routing, config
|
|
187
195
|
│ ├── tools/ # built-in tool implementations
|
|
188
|
-
│ └──
|
|
196
|
+
│ └── tui/ # terminal runtime (CLI entry, interactive TUI, slash, MCP command)
|
|
189
197
|
├── docs/ # technical docs
|
|
190
198
|
└── dist/ # build output
|
|
191
199
|
```
|
|
@@ -195,7 +203,7 @@ memo-cli/
|
|
|
195
203
|
- `/help`: show help and shortcut guide.
|
|
196
204
|
- `/models`: list available Provider/Model entries and switch with Enter; also supports direct selection like `/models deepseek`.
|
|
197
205
|
- `/context`: open 80k/120k/150k/200k options and apply immediately.
|
|
198
|
-
-
|
|
206
|
+
- `/mcp`: show configured MCP servers in current session.
|
|
199
207
|
- `resume` history: type `resume` to list and load past sessions for current directory.
|
|
200
208
|
- Exit and clear: `exit` / `/exit`, `Ctrl+L` for new session, `Esc Esc` to cancel current run or clear input.
|
|
201
209
|
- **Tool approval**: risky operations open an approval dialog with `once`/`session`/`deny`.
|
|
@@ -212,8 +220,9 @@ memo-cli/
|
|
|
212
220
|
|
|
213
221
|
## Related Docs
|
|
214
222
|
|
|
215
|
-
- [User Guide](./docs/
|
|
223
|
+
- [User Guide](./web/content/docs/README.md) - User-facing docs by module
|
|
216
224
|
- [Core Architecture](./docs/core.md) - Core implementation details
|
|
225
|
+
- [TUI Rewrite Design](./docs/tui-rewrite-design.md) - Codex-aligned TUI architecture and migration notes
|
|
217
226
|
- [CLI Adaptation History](./docs/cli-update.md) - Historical migration notes (Tool Use API)
|
|
218
227
|
- [Contributing](./CONTRIBUTING.md) - Contribution guide
|
|
219
228
|
- [Project Guidelines](./AGENTS.md) - Coding conventions and development process
|
package/README.zh.md
CHANGED
|
@@ -51,6 +51,9 @@ memo
|
|
|
51
51
|
- 非交互纯文本模式(非 TTY):`echo "你的问题" | memo`(适合脚本)。
|
|
52
52
|
- 危险模式:`memo --dangerous` 或 `memo -d`(跳过工具审批,谨慎使用)。
|
|
53
53
|
- 查看版本:`memo --version` 或 `memo -v`。
|
|
54
|
+
- 启动目录约定:若启动根目录存在 `AGENTS.md`,Memo 会自动将其拼接进系统提示词。
|
|
55
|
+
- MCP 启动选择:当配置了 MCP server 时,启动会弹出多选以决定本次会话激活哪些 server。
|
|
56
|
+
- 会话标题:Memo 会基于首条用户输入生成简短标题,并在历史/恢复列表中展示。
|
|
54
57
|
|
|
55
58
|
## 配置文件
|
|
56
59
|
|
|
@@ -85,6 +88,10 @@ args = []
|
|
|
85
88
|
type = "streamable_http"
|
|
86
89
|
url = "https://your-mcp-server.com/mcp"
|
|
87
90
|
# headers = { Authorization = "Bearer xxx" }
|
|
91
|
+
|
|
92
|
+
# 可选:启动时默认激活的 MCP server
|
|
93
|
+
active_mcp_servers = ["local_tools", "remote"]
|
|
94
|
+
# 可选:设为 [] 表示启动时不激活任何 MCP server
|
|
88
95
|
```
|
|
89
96
|
|
|
90
97
|
也可以通过 CLI 管理 MCP 配置(对齐 Codex CLI 风格):
|
|
@@ -106,15 +113,14 @@ memo mcp remove remote
|
|
|
106
113
|
|
|
107
114
|
## 内置工具
|
|
108
115
|
|
|
109
|
-
- `
|
|
110
|
-
- `
|
|
111
|
-
- `
|
|
112
|
-
- `
|
|
113
|
-
- `
|
|
114
|
-
- `grep`:搜索内容(正则匹配)
|
|
116
|
+
- `exec_command` / `write_stdin`:执行命令(默认执行工具族)
|
|
117
|
+
- `shell` / `shell_command`:兼容执行工具(按环境开关切换)
|
|
118
|
+
- `apply_patch`:结构化文件改动
|
|
119
|
+
- `read_file` / `list_dir` / `grep_files`:文件读取与检索
|
|
120
|
+
- `list_mcp_resources` / `list_mcp_resource_templates` / `read_mcp_resource`:MCP 资源访问
|
|
115
121
|
- `webfetch`:获取网页
|
|
116
|
-
- `
|
|
117
|
-
- `
|
|
122
|
+
- `update_plan`:更新当前会话内的计划状态
|
|
123
|
+
- `get_memory`:读取 `~/.memo/Agents.md`(或 `MEMO_HOME` 下)记忆内容
|
|
118
124
|
|
|
119
125
|
通过 MCP 协议可扩展更多工具。
|
|
120
126
|
|
|
@@ -122,8 +128,8 @@ memo mcp remove remote
|
|
|
122
128
|
|
|
123
129
|
新增工具审批机制,保护用户免受危险操作影响:
|
|
124
130
|
|
|
125
|
-
-
|
|
126
|
-
-
|
|
131
|
+
- **自动审批**:读类工具(如 `read_file`、`list_dir`、`grep_files`、`webfetch` 等)
|
|
132
|
+
- **手动审批**:高风险工具(如 `apply_patch`、`exec_command`、`write_stdin`)
|
|
127
133
|
- **审批选项**:
|
|
128
134
|
- `once`:仅批准当前操作
|
|
129
135
|
- `session`:批准本次会话中的所有同类操作
|
|
@@ -163,9 +169,10 @@ pnpm run build # 生成 dist/index.js
|
|
|
163
169
|
### 测试
|
|
164
170
|
|
|
165
171
|
```bash
|
|
166
|
-
pnpm test
|
|
167
|
-
pnpm test
|
|
168
|
-
pnpm test
|
|
172
|
+
pnpm test # 全量测试
|
|
173
|
+
pnpm run test:core # 测试 core 包
|
|
174
|
+
pnpm run test:tools # 测试 tools 包
|
|
175
|
+
pnpm run test:tui # 测试 tui 包
|
|
169
176
|
```
|
|
170
177
|
|
|
171
178
|
### 代码格式化
|
|
@@ -182,7 +189,7 @@ memo-cli/
|
|
|
182
189
|
├── packages/
|
|
183
190
|
│ ├── core/ # 核心逻辑:Session、工具路由、配置
|
|
184
191
|
│ ├── tools/ # 内置工具实现
|
|
185
|
-
│ └──
|
|
192
|
+
│ └── tui/ # 终端运行时(CLI 入口、交互 TUI、slash、MCP 子命令)
|
|
186
193
|
├── docs/ # 技术文档
|
|
187
194
|
└── dist/ # 构建输出
|
|
188
195
|
```
|
|
@@ -192,7 +199,7 @@ memo-cli/
|
|
|
192
199
|
- `/help`:显示帮助与快捷键说明。
|
|
193
200
|
- `/models`:列出现有 Provider/Model,回车切换;支持直接 `/models deepseek` 精确选择。
|
|
194
201
|
- `/context`:弹出 80k/120k/150k/200k 选项并立即设置上限。
|
|
195
|
-
-
|
|
202
|
+
- `/mcp`:查看当前会话加载的 MCP 服务器配置。
|
|
196
203
|
- `resume` 历史:输入 `resume` 查看并加载本目录的历史会话。
|
|
197
204
|
- 退出与清屏:`exit` / `/exit`,`Ctrl+L` 新会话,`Esc Esc` 取消运行或清空输入。
|
|
198
205
|
- **工具审批**:危险操作会弹出审批对话框,可选择 `once`/`session`/`deny`。
|
|
@@ -209,8 +216,9 @@ memo-cli/
|
|
|
209
216
|
|
|
210
217
|
## 相关文档
|
|
211
218
|
|
|
212
|
-
- [用户指南](./docs/
|
|
219
|
+
- [用户指南](./web/content/docs/README.md) - 面向使用者的分模块说明
|
|
213
220
|
- [Core 架构](./docs/core.md) - 核心实现详解
|
|
221
|
+
- [TUI 重构设计](./docs/tui-rewrite-design.md) - 对标 Codex 的 TUI 架构与迁移说明
|
|
214
222
|
- [CLI 适配更新](./docs/cli-update.md) - Tool Use API 迁移说明
|
|
215
223
|
- [开发指南](./CONTRIBUTING.md) - 贡献指南
|
|
216
224
|
- [项目约定](./AGENTS.md) - 代码规范和开发流程
|
package/dist/index.js
CHANGED
|
@@ -1,98 +1,115 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`)
|
|
8
|
-
|
|
9
|
-
`)?""
|
|
10
|
-
|
|
11
|
-
`)
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
14
|
-
|
|
15
|
-
`).
|
|
16
|
-
`)
|
|
2
|
+
var ws=Object.create;var jn=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var ks=Object.getOwnPropertyNames;var As=Object.getPrototypeOf,Ps=Object.prototype.hasOwnProperty;var Rs=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Is=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ks(t))!Ps.call(e,r)&&r!==n&&jn(e,r,{get:()=>t[r],enumerable:!(o=Ms(t,r))||o.enumerable});return e};var Os=(e,t,n)=>(n=e!=null?ws(As(e)):{},Is(t||!e||!e.__esModule?jn(n,"default",{value:e,enumerable:!0}):n,e));var mo=Rs((td,po)=>{"use strict";function ro(e){return Array.isArray(e)?e:[e]}var on="",so=" ",tn="\\",Mi=/^\s+$/,ki=/(?:[^\\]|^)\\$/,Ai=/^\\!/,Pi=/^\\#/,Ri=/\r?\n/g,Ii=/^\.*\/|^\.+$/,nn="/",lo="node-ignore";typeof Symbol<"u"&&(lo=Symbol.for("node-ignore"));var io=lo,Oi=(e,t,n)=>Object.defineProperty(e,t,{value:n}),Li=/([0-z])-([0-z])/g,co=()=>!1,$i=e=>e.replace(Li,(t,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?t:on),Ni=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Di=[[/^\uFEFF/,()=>on],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?so:on)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+so}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return t+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>tn],[/\\\\/g,()=>tn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,o,r)=>t===tn?`\\[${n}${Ni(o)}${r}`:r==="]"&&o.length%2===0?`[${$i(n)}${o}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],ao=Object.create(null),Ui=(e,t)=>{let n=ao[e];return n||(n=Di.reduce((o,[r,s])=>o.replace(r,s.bind(e)),e),ao[e]=n),t?new RegExp(n,"i"):new RegExp(n)},an=e=>typeof e=="string",Hi=e=>e&&an(e)&&!Mi.test(e)&&!ki.test(e)&&e.indexOf("#")!==0,Fi=e=>e.split(Ri),rn=class{constructor(t,n,o,r){this.origin=t,this.pattern=n,this.negative=o,this.regex=r}},ji=(e,t)=>{let n=e,o=!1;e.indexOf("!")===0&&(o=!0,e=e.substr(1)),e=e.replace(Ai,"!").replace(Pi,"#");let r=Ui(e,t);return new rn(n,e,o,r)},Bi=(e,t)=>{throw new t(e)},Ee=(e,t,n)=>an(e)?e?Ee.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),uo=e=>Ii.test(e);Ee.isNotRelative=uo;Ee.convert=e=>e;var sn=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:o=!1}={}){Oi(this,io,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(t){if(t&&t[io]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(Hi(t)){let n=ji(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,ro(an(t)?Fi(t):t).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(t){return this.add(t)}_testOne(t,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(t)&&(o=!i,r=i)}),{ignored:o,unignored:r}}_test(t,n,o,r){let s=t&&Ee.convert(t);return Ee(s,t,this._allowRelativePaths?co:Bi),this._t(s,n,o,r)}_t(t,n,o,r){if(t in n)return n[t];if(r||(r=t.split(nn)),r.pop(),!r.length)return n[t]=this._testOne(t,o);let s=this._t(r.join(nn)+nn,n,o,r);return n[t]=s.ignored?s:this._testOne(t,o)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return ro(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},_t=e=>new sn(e),Wi=e=>Ee(e&&Ee.convert(e),e,co);_t.isPathValid=Wi;_t.default=_t;po.exports=_t;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ee.convert=e;let t=/^[a-z]:\//i;Ee.isNotRelative=n=>t.test(n)||uo(n)}});import{randomUUID as us}from"crypto";import{createInterface as ap}from"readline/promises";import{stdin as lp,stdout as cp}from"process";import{render as up}from"ink";import Ls from"os";import{readFile as Bn}from"fs/promises";import{join as Wn,dirname as $s}from"path";import{fileURLToPath as Ns}from"url";var Ds=/{{\s*([\w.-]+)\s*}}/g;function Us(e,t){return e.replace(Ds,(n,o)=>t[o]??"")}function Hs(){try{return Ls.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}async function Fs(e){let t=Wn(e,"AGENTS.md");try{let n=await Bn(t,"utf-8");return n.trim()?{path:t,content:n}:null}catch{return null}}function js(e,t){return`${e}
|
|
3
|
+
|
|
4
|
+
## Project AGENTS.md (Startup Root)
|
|
5
|
+
Loaded from: ${t.path}
|
|
6
|
+
|
|
7
|
+
${t.content}`}async function zn(e={}){let t=e.cwd??process.cwd(),n=$s(Ns(import.meta.url)),o=Wn(n,"prompt.md"),r=await Bn(o,"utf-8"),s={date:new Date().toISOString(),user:Hs(),pwd:t},i=Us(r,s),a=await Fs(t);return a?js(i,a):i}import{appendFile as Bs,mkdir as Ws}from"fs/promises";import{dirname as zs}from"path";var St=class{constructor(t){this.filePath=t}ready=!1;async append(t){this.ready||(await Ws(zs(this.filePath),{recursive:!0}),this.ready=!0),await Bs(this.filePath,`${JSON.stringify(t)}
|
|
8
|
+
`,"utf8")}async flush(){return Promise.resolve()}};function qn(e){return{ts:new Date().toISOString(),sessionId:e.sessionId,turn:e.turn,step:e.step,type:e.type,content:e.content,role:e.role,meta:e.meta}}import{z as be}from"zod";function A(e){let{inputSchema:t,execute:n,...o}=e,r=t.toJSONSchema?.(),{$schema:s,...i}=r??{};return{...o,source:"native",inputSchema:i,validateInput:a=>{let l=t.safeParse(a);if(!l.success){let c=l.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${e.name} invalid input: ${c}`}}return{ok:!0,data:l.data}},execute:n}}function m(e,t=!1){return{content:[{type:"text",text:e}],isError:t}}import{spawn as pi}from"child_process";import{EventEmitter as di}from"events";import{resolve as mi}from"path";import{posix as qs}from"path";var Gn=220,Kn=4096,Gs=/^\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)$/i,Ks=/(?:^|[\s(])(?:\d?>>?|>>|>\||&>)\s*\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)(?:\s|$)/i,Vs=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),Xs=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function Vt(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Js(e){let t=e.replace(/\s+/g," ").trim();return t.length>Gn?`${t.slice(0,Gn)}\u2026`:t}function Vn(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return(t.split(/[\\/]/).at(-1)??t).toLowerCase()}function Ys(e){let t=null,n=!1;for(let o=0;o<e.length;o+=1){let r=e[o];if(n){n=!1;continue}if(r==="\\"&&t!=="'"){n=!0;continue}if(t){r===t&&(t=null);continue}if(r==='"'||r==="'"){t=r;continue}if(r==="#")return e.slice(0,o)}return e}function Zs(e){let t=[],n="",o=null,r=!1,s=()=>{let i=Ys(n).trim();i&&t.push(i),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(r){n+=a,r=!1;continue}if(a==="\\"&&o!=="'"){n+=a,r=!0;continue}if(o){n+=a,a===o&&(o=null);continue}if(a==='"'||a==="'"){o=a,n+=a;continue}if(a===";"||a===`
|
|
9
|
+
`){s();continue}if(a==="&"){e[i+1]==="&"&&(i+=1),s();continue}if(a==="|"){e[i+1]==="|"&&(i+=1),s();continue}n+=a}return s(),t}function Qs(e){let t=[],n="",o=null,r=!1,s=()=>{n&&t.push(n),n=""};for(let i=0;i<e.length;i+=1){let a=e[i];if(r){n+=a,r=!1;continue}if(a==="\\"&&o!=="'"){r=!0;continue}if(o){a===o?o=null:n+=a;continue}if(a==='"'||a==="'"){o=a;continue}if(/\s/.test(a)){s();continue}n+=a}return s(),t}function Xn(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function ei(e,t){let n=t;for(;n<e.length;){let o=Vn(e[n]??"");if(o==="sudo"){for(n+=1;n<e.length;){let r=e[n]??"";if(!r.startsWith("-"))break;n+=1,Vs.has(r)&&n<e.length&&(n+=1)}continue}if(o==="env"){for(n+=1;n<e.length;){let r=e[n]??"";if(r.startsWith("-")||Xn(r)){n+=1;continue}break}continue}if(o==="command"||o==="nohup"||o==="time"){n+=1;continue}break}return n}function ti(e){let t=Qs(e);if(t.length===0)return null;let n=0;for(;n<t.length&&Xn(t[n]??"");)n+=1;if(n=ei(t,n),n>=t.length)return null;let o=Vn(t[n]??"");return o?{raw:e,commandName:o,args:t.slice(n+1)}:null}function Xt(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return Gs.test(t)}function ni(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.toLowerCase();return n==="/"||n==="/*"||n==="/.*"||n==="~"||n==="~/"||n==="~/*"||n==="$home"||n==="$home/"||n==="$home/*"||n==="${home}"||n==="${home}/"||n==="${home}/*"?!0:t.startsWith("/")&&!/[*?[\]{}$]/.test(t)?qs.normalize(t)==="/":!1}function oi(e){return e.startsWith("-")&&e!=="-"}function ri(e){if(e.commandName!=="rm")return null;let t=!1,n=0;for(;n<e.args.length;){let r=e.args[n]??"";if(r==="--"){n+=1;break}if(!oi(r))break;if(r==="--recursive"){t=!0,n+=1;continue}if(r.startsWith("--")){n+=1;continue}let s=r.slice(1);(s.includes("r")||s.includes("R"))&&(t=!0),n+=1}if(!t)return null;let o=e.args.slice(n);for(let r of o)if(ni(r))return{ruleId:"rm_recursive_critical_target",matchedSegment:e.raw};return null}function si(e){return e.commandName==="mkfs"||e.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:e.raw}:null}function ii(e){if(e.commandName!=="dd")return null;for(let t=0;t<e.args.length;t+=1){let n=e.args[t]??"",o=n.indexOf("=");if(o<=0)continue;let r=n.slice(0,o).toLowerCase(),s=n.slice(o+1);if(r==="of"&&Xt(s))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}for(let t=0;t<e.args.length-1;t+=1){let n=(e.args[t]??"").toLowerCase(),o=e.args[t+1]??"";if(n==="of"&&Xt(o))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}return null}function ai(e){return!Xs.has(e.commandName)||!e.args.some(t=>Xt(t))?null:{ruleId:"disk_mutation_block_device",matchedSegment:e.raw}}function li(e){return Ks.test(e)?{ruleId:"redirect_block_device",matchedSegment:e}:null}function ci(e){for(let t of Zs(e)){let n=ti(t);if(n){let r=ri(n);if(r)return r;let s=si(n);if(s)return s;let i=ii(n);if(i)return i;let a=ai(n);if(a)return a}let o=li(t);if(o)return o}return null}function ui(e,t){let n=Js(e.command),o=typeof e.sessionId=="number"?` session_id="${e.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${Vt(e.toolName)}" reason="dangerous_command" policy="blacklist" rule="${Vt(t.ruleId)}"${o} command="${Vt(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function Jt(e){let t=ci(e.command);return t?{blocked:!0,xml:ui(e,t),match:t}:{blocked:!1}}function Jn(e){let n=e.replace(/\r\n/g,`
|
|
10
|
+
`).replace(/\r/g,`
|
|
11
|
+
`).split(`
|
|
12
|
+
`),o=n.pop()??"";return{completedLines:n,remainder:o}}function Yt(e){return e.length<=Kn?e:e.slice(-Kn)}var fi=1e4,gi=250,hi=2e3,Yn=64;function yi(e){return Math.ceil(e.length/4)}function Ti(){return Math.random().toString(16).slice(2)||String(Date.now())}function Si(e){let t=e.login,n=e.shell?.trim();if(process.platform==="win32"){let r=n||"powershell.exe";return r.toLowerCase().includes("powershell")?{file:r,args:["-NoProfile","-Command",e.cmd]}:{file:r,args:[t?"-lc":"-c",e.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[t?"-lc":"-c",e.cmd]}}function _i(e,t){let o=(typeof t=="number"&&t>0?Math.floor(t):hi)*4,r=yi(e);return e.length<=o?{output:e,originalTokenCount:r}:{output:e.slice(0,o),originalTokenCount:r}}function vi(e){let t=[];return t.push(`Chunk ID: ${e.chunkId}`),t.push(`Wall time: ${e.wallTimeSeconds.toFixed(4)} seconds`),e.exitCode!==null?t.push(`Process exited with code ${e.exitCode}`):t.push(`Process running with session ID ${e.sessionId}`),t.push(`Original token count: ${e.originalTokenCount}`),t.push("Output:"),t.push(e.output),t.join(`
|
|
13
|
+
`)}function Zn(e,t){return typeof e!="number"||Number.isNaN(e)?t:e<0?0:Math.floor(e)}async function Qn(e,t){t<=0||e.exited||await Promise.race([new Promise(n=>{let o=setTimeout(()=>{s(),n()},t),r=()=>{clearTimeout(o),s(),n()},s=()=>{e.eventBus.off("exit",r)};e.eventBus.on("exit",r)})])}var Zt=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Yn)return;let t=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,o)=>n.startedAtMs-o.startedAtMs);for(let n of t){if(this.sessions.size<=Yn)break;this.sessions.delete(n.id)}}async start(t){let n=t.cmd.trim();if(!n)throw new Error("cmd must not be empty");let o=Jt({toolName:t.source_tool??"exec_command",command:n});if(o.blocked)return o.xml;let r=this.nextId++,s=Date.now(),i=Si({cmd:n,shell:t.shell,login:t.login!==!1}),a=t.workdir?.trim()?mi(process.cwd(),t.workdir.trim()):process.cwd(),l=pi(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),c={id:r,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new di,proc:l},u=(d,h)=>{let S=typeof h=="string"?h:h.toString("utf8");c.output+=d?`${d}${S}`:S,c.eventBus.emit("output")};l.stdout?.on("data",d=>u("",d)),l.stderr?.on("data",d=>u("",d)),l.on("error",d=>{c.output+=`
|
|
14
|
+
[exec error] ${d.message}`,c.eventBus.emit("output")}),l.on("close",d=>{c.exited=!0,c.exitCode=typeof d=="number"?d:-1,c.eventBus.emit("exit")}),this.sessions.set(r,c),this.cleanupSessions();let p=Zn(t.yield_time_ms,fi);return await Qn(c,p),this.buildResponseText(c,t.max_output_tokens)}async write(t){let n=this.sessions.get(t.session_id);if(!n)throw new Error(`session_id ${t.session_id} not found`);if(!n.exited&&t.chars&&t.chars.length>0){let r=Yt(`${n.pendingStdinInput}${t.chars}`),{completedLines:s,remainder:i}=Jn(r);for(let a of s){if(!a.trim())continue;let l=Jt({toolName:t.source_tool??"write_stdin",command:a,sessionId:n.id});if(l.blocked)return n.pendingStdinInput="",l.xml}n.pendingStdinInput=Yt(i),n.proc.stdin?.write(t.chars)}let o=Zn(t.yield_time_ms,gi);return await Qn(n,o),this.buildResponseText(n,t.max_output_tokens)}buildResponseText(t,n){let o=t.output.slice(t.readOffset);t.readOffset=t.output.length;let r=_i(o,n),s={sessionId:t.id,chunkId:Ti(),wallTimeSeconds:(Date.now()-t.startedAtMs)/1e3,exitCode:t.exited?t.exitCode:null,output:r.output,originalTokenCount:r.originalTokenCount};return vi(s)}},eo=new Zt;async function Be(e){return eo.start(e)}async function to(e){return eo.write(e)}var xi=be.object({command:be.array(be.string().min(1)).min(1,"command cannot be empty"),workdir:be.string().optional(),timeout_ms:be.number().int().positive().optional(),sandbox_permissions:be.enum(["use_default","require_escalated"]).optional(),justification:be.string().optional(),prefix_rule:be.array(be.string().min(1)).optional()}).strict();function bi(e){return e.map(t=>/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)).join(" ")}var no=A({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:xi,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,timeout_ms:n})=>{try{let o=await Be({cmd:bi(e),workdir:t,login:!1,yield_time_ms:n,source_tool:"shell"});return m(o)}catch(o){return m(`shell failed: ${o.message}`,!0)}}});import{z as Ce}from"zod";var Ci=Ce.object({command:Ce.string().min(1,"command cannot be empty"),workdir:Ce.string().optional(),login:Ce.boolean().optional(),timeout_ms:Ce.number().int().positive().optional(),sandbox_permissions:Ce.enum(["use_default","require_escalated"]).optional(),justification:Ce.string().optional(),prefix_rule:Ce.array(Ce.string().min(1)).optional()}).strict(),oo=A({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:Ci,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,login:n,timeout_ms:o})=>{try{let r=await Be({cmd:e,workdir:t,login:n,yield_time_ms:o,source_tool:"shell_command"});return m(r)}catch(r){return m(`shell_command failed: ${r.message}`,!0)}}});import{z as ce}from"zod";var Ei=ce.object({cmd:ce.string().min(1,"cmd cannot be empty"),workdir:ce.string().optional(),shell:ce.string().optional(),login:ce.boolean().optional(),tty:ce.boolean().optional(),yield_time_ms:ce.number().int().nonnegative().optional(),max_output_tokens:ce.number().int().positive().optional(),sandbox_permissions:ce.enum(["use_default","require_escalated"]).optional(),justification:ce.string().optional(),prefix_rule:ce.array(ce.string().min(1)).optional()}).strict(),Qt=A({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:Ei,supportsParallelToolCalls:!0,isMutating:!0,execute:async e=>{try{let t=await Be({...e,source_tool:"exec_command"});return m(t)}catch(t){return m(`exec_command failed: ${t.message}`,!0)}}});import{z as tt}from"zod";var wi=tt.object({session_id:tt.number().int().positive(),chars:tt.string().optional(),yield_time_ms:tt.number().int().nonnegative().optional(),max_output_tokens:tt.number().int().positive().optional()}).strict(),en=A({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:wi,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{try{let t=await to({...e,source_tool:"write_stdin"});return m(t)}catch(t){return m(`write_stdin failed: ${t.message}`,!0)}}});import{mkdir as ho,readFile as ea,rm as yo,writeFile as ln}from"fs/promises";import{dirname as To}from"path";import{z as So}from"zod";var Ji=Os(mo(),1);import{normalize as zi,resolve as qi,dirname as od,join as Gi,relative as Ki,isAbsolute as Vi}from"path";import{homedir as Xi}from"os";import{existsSync as id,statSync as ad}from"fs";import{readFile as cd}from"fs/promises";function ue(e){return zi(qi(e))}function Yi(e,t){let n=Ki(t,e);return n===""||!n.startsWith("..")&&!Vi(n)}function Zi(){let e=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>ue(t)):[]}function fo(){let e=new Set;e.add(ue(process.cwd()));let t=process.env.MEMO_HOME?.trim()||Gi(Xi(),".memo");e.add(ue(t));for(let n of Zi())e.add(n);return Array.from(e)}function Qi(e){return fo().some(n=>Yi(e,n))}function go(e){if(Qi(e))return null;let t=fo();return`sandbox \u62D2\u7EDD\u5199\u5165: ${e} \u4E0D\u5728\u5141\u8BB8\u76EE\u5F55\u5185 (${t.join(", ")})`}var ta='Expected markers: "*** Add File:", "*** Update File:", "*** Delete File:", "*** End Patch".',na='Format hint: start with "*** Begin Patch", include one or more operations, and end with "*** End Patch". Update hunks use "@@" headers and body lines prefixed by " ", "+", or "-".',oa=2,ra=So.object({input:So.string().min(1,"patch input cannot be empty")}).strict();function ie(e){return`${e} ${na}`}function sa(e,t){if(/^@@\s*$/.test(e))return{header:e};let n=e.match(/^@@\s*-(\d+)(?:,\d+)?\s+\+\d+(?:,\d+)?\s*@@(?:\s.*)?$/);if(!n)throw new Error(ie(`Invalid hunk header at line ${t}: "${e}". Use "@@" or "@@ -start,count +start,count @@".`));return{header:e,sourceStart:Number(n[1])}}function ia(e){let t=e.replace(/\r/g,"").split(`
|
|
15
|
+
`);if(t[0]!=="*** Begin Patch")throw new Error(ie('patch must start with "*** Begin Patch".'));let n=[],o=1,r=!1;for(;o<t.length;){let s=t[o]??"";if(s==="*** End Patch"){r=!0;break}if(!s){o+=1;continue}if(s.startsWith("*** Add File: ")){let i=s.slice(14).trim();if(!i)throw new Error(ie(`Add File requires a path at line ${o+1}.`));o+=1;let a=[];for(;o<t.length;){let l=t[o];if(l===void 0||l.startsWith("*** "))break;if(!l.startsWith("+"))throw new Error(ie(`Invalid Add File content at line ${o+1}: each content line must start with "+".`));a.push(l.slice(1)),o+=1}n.push({type:"add",file:i,lines:a});continue}if(s.startsWith("*** Delete File: ")){let i=s.slice(17).trim();if(!i)throw new Error(ie(`Delete File requires a path at line ${o+1}.`));n.push({type:"delete",file:i}),o+=1;continue}if(s.startsWith("*** Update File: ")){let i=s.slice(17).trim();if(!i)throw new Error(ie(`Update File requires a path at line ${o+1}.`));o+=1;let a,l=t[o];l&&l.startsWith("*** Move to: ")&&(a=l.slice(13).trim(),o+=1);let c=[],u=null;for(;o<t.length;){let p=t[o];if(p===void 0||p.startsWith("*** "))break;if(p.startsWith("@@")){if(u){if(u.lines.length===0)throw new Error(ie(`Update File ${i} has an empty hunk at line ${o}.`));c.push(u)}u={...sa(p,o+1),lines:[]},o+=1;continue}if(p==="*** End of File"){o+=1;continue}if(p.startsWith("+")||p.startsWith("-")||p.startsWith(" ")){u||(u={header:"@@",lines:[]}),u.lines.push(p),o+=1;continue}throw new Error(ie(`Unexpected patch line at line ${o+1}: "${p}". Hunk lines must start with " ", "+", "-", or "@@".`))}if(u){if(u.lines.length===0)throw new Error(ie(`Update File ${i} has an empty hunk near line ${o}.`));c.push(u)}if(c.length===0)throw new Error(ie(`Update File ${i} has no hunks.`));n.push({type:"update",file:i,moveTo:a,hunks:c});continue}throw new Error(ie(`Unexpected patch marker at line ${o+1}: "${s}". ${ta}`))}if(!r)throw new Error(ie('patch is missing "*** End Patch".'));if(n.length===0)throw new Error(ie("patch contains no operations."));return n}function aa(e){let t=e.endsWith(`
|
|
16
|
+
`),n=t?e.slice(0,-1):e;return{lines:n.length>0?n.split(`
|
|
17
|
+
`):[],trailingNewline:t}}function _o(e,t){let n=e.join(`
|
|
18
|
+
`);return t&&n.length>0?`${n}
|
|
19
|
+
`:n}function la(e,t){if(t.length===0)return[];let n=e.length-t.length;if(n<0)return[];let o=[];for(let r=0;r<=n;r+=1){let s=!0;for(let i=0;i<t.length;i+=1)if(e[r+i]!==t[i]){s=!1;break}s&&o.push(r)}return o}function ca(e,t,n,o){if(e.length===0)throw new Error(`patch hunk context not found in ${n} (header: "${o}").`);if(t!==void 0){let r=Math.max(0,t-1),s=e.filter(i=>Math.abs(i-r)<=oa);if(s.length===1)return s[0];if(s.length>1)throw new Error(`patch hunk is ambiguous in ${n}: matched ${s.length} anchored locations near line ${t}. Add more context lines in this hunk.`)}if(e.length===1)return e[0];throw new Error(`patch hunk is ambiguous in ${n}: matched ${e.length} locations. Add more context lines or a more accurate @@ header.`)}function ua(e,t,n){let o=t.lines.filter(c=>c.startsWith(" ")||c.startsWith("-")).map(c=>c.slice(1)),r=t.lines.filter(c=>c.startsWith(" ")||c.startsWith("+")).map(c=>c.slice(1)),s=aa(e);if(o.length===0){if(r.length===0)return e;let c=t.sourceStart!==void 0?Math.max(0,t.sourceStart-1):s.lines.length,u=Math.min(c,s.lines.length),p=[...s.lines.slice(0,u),...r,...s.lines.slice(u)];return _o(p,s.trailingNewline)}let i=la(s.lines,o),a=ca(i,t.sourceStart,n,t.header),l=[...s.lines.slice(0,a),...r,...s.lines.slice(a+o.length)];return _o(l,s.trailingNewline)}function vt(e){let t=go(e);if(t)throw new Error(t)}var vo=A({name:"apply_patch",description:`Apply a structured patch.
|
|
20
|
+
|
|
21
|
+
Required envelope:
|
|
22
|
+
*** Begin Patch
|
|
23
|
+
...operations...
|
|
24
|
+
*** End Patch
|
|
25
|
+
|
|
26
|
+
Supported operations:
|
|
27
|
+
1) Add file
|
|
28
|
+
*** Add File: path/to/file.ts
|
|
29
|
+
+line 1
|
|
30
|
+
+line 2
|
|
31
|
+
|
|
32
|
+
2) Update file (with optional move)
|
|
33
|
+
*** Update File: path/to/file.ts
|
|
34
|
+
*** Move to: path/to/new-file.ts
|
|
35
|
+
@@ -3,2 +3,2 @@
|
|
36
|
+
-old line
|
|
37
|
+
+new line
|
|
38
|
+
|
|
39
|
+
3) Delete file
|
|
40
|
+
*** Delete File: path/to/file.ts
|
|
41
|
+
|
|
42
|
+
Update hunks may use "@@" or "@@ -start,count +start,count @@" headers.
|
|
43
|
+
Hunk body lines must start with " ", "+", or "-".`,inputSchema:ra,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{try{let t=ia(e.input);for(let n of t){if(n.type==="add"){let s=ue(n.file);vt(s),await ho(To(s),{recursive:!0}),await ln(s,n.lines.join(`
|
|
44
|
+
`),"utf8");continue}if(n.type==="delete"){let s=ue(n.file);vt(s),await yo(s);continue}let o=ue(n.file);vt(o);let r=await ea(o,"utf8");for(let s of n.hunks)r=ua(r,s,o);if(n.moveTo){let s=ue(n.moveTo);vt(s),await ho(To(s),{recursive:!0}),await ln(s,r,"utf8"),s!==o&&await yo(o)}else await ln(o,r,"utf8")}return m(`apply_patch succeeded (${t.length} operations)`)}catch(t){return m(`apply_patch failed: ${t.message}`,!0)}}});import{readFile as pa}from"fs/promises";import{z as ye}from"zod";var xo=500,bo=200,da=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 ma(e){return e.length<=xo?e:e.slice(0,xo)}function fa(e){let t=0;for(let n of e)if(n===" ")t+=1;else if(n===" ")t+=4;else break;return t}function ga(e){return e.split(/\r?\n/).map((n,o)=>({line:o+1,text:ma(n),indent:fa(n)}))}function ha(e){return e.map(t=>`L${t.line}: ${t.text}`).join(`
|
|
45
|
+
`)}function ya(e,t,n){let o=t-1;if(o>=e.length)throw new Error("offset exceeds file length");return e.slice(o,o+n)}function Ta(e,t){let n=t.offset??1,o=t.limit??bo,r=t.indentation,s=r?.anchor_line??n;if(s<=0||s>e.length)throw new Error("anchor_line exceeds file length");let i=e[s-1];if(!i)throw new Error("anchor_line exceeds file length");let a=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)),d=a===0?0:Math.max(0,i.indent-a*4),h=s-1,S=s-1;for(;h-1>=0;){let g=e[h-1];if(!g)break;let E=/^\s*(#|\/\/|--)/.test(g.text),_=g.text.trim().length===0;if(g.indent<d||!l&&g.indent===d&&!E&&!_||!c&&(E||_)&&g.indent<i.indent||(h-=1,S-h+1>=p))break}for(;S+1<e.length&&S-h+1<p;){let g=e[S+1];if(!g||g.indent<d||!l&&g.indent===d)break;S+=1}return e.slice(h,S+1)}var Co=A({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:da,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??1,n=e.limit??bo;if(t<=0)return m("offset must be a 1-indexed line number",!0);if(n<=0)return m("limit must be greater than zero",!0);let o=e.file_path.trim();if(!o.startsWith("/"))return m("file_path must be an absolute path",!0);let r=ue(o);try{let s=await pa(r,"utf8"),i=ga(s);if(i.length===0)return m("");let l=(e.mode??"slice")==="indentation"?Ta(i,e):ya(i,t,n);return m(ha(l))}catch(s){return m(`read_file failed: ${s.message}`,!0)}}});import{readdir as Sa,lstat as _a}from"fs/promises";import{join as va}from"path";import{z as nt}from"zod";var xa=1,ba=25,Ca=2,Ea=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 wa(e){let t=" ".repeat(e.displayDepth*2),n="";e.kind==="dir"&&(n="/"),e.kind==="symlink"&&(n="@"),e.kind==="other"&&(n="?");let o=e.path.split("/"),r=o[o.length-1]??e.path;return`${t}${r}${n}`}var Eo=A({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:Ea,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??xa,n=e.limit??ba,o=e.depth??Ca;if(t<=0)return m("offset must be a 1-indexed entry number",!0);if(n<=0)return m("limit must be greater than zero",!0);if(o<=0)return m("depth must be greater than zero",!0);let r=e.dir_path.trim();if(!r.startsWith("/"))return m("dir_path must be an absolute path",!0);let s=ue(r);try{let i=[{absPath:s,depth:o,displayDepth:0}],a=[];for(;i.length>0;){let p=i.shift();if(!p)continue;let d=await Sa(p.absPath);d.sort((h,S)=>h.localeCompare(S));for(let h of d){let S=va(p.absPath,h),g=await _a(S),E=g.isSymbolicLink()?"symlink":g.isDirectory()?"dir":g.isFile()?"file":"other";a.push({path:S,displayDepth:p.displayDepth,kind:E}),E==="dir"&&p.depth>1&&i.push({absPath:S,depth:p.depth-1,displayDepth:p.displayDepth+1})}}if(a.length===0)return m(`Absolute path: ${s}`);let l=t-1;if(l>=a.length)return m("offset exceeds directory entry count",!0);let c=a.slice(l,l+n),u=[`Absolute path: ${s}`,...c.map(wa)];return l+n<a.length&&u.push(`More than ${n} entries found`),m(u.join(`
|
|
46
|
+
`))}catch(i){return m(`list_dir failed: ${i.message}`,!0)}}});import{spawn as Ma}from"child_process";import{resolve as ka}from"path";import{z as ot}from"zod";var Aa=100,Pa=2e3,Ra=3e4,Ia=ot.object({pattern:ot.string().min(1),include:ot.string().optional(),path:ot.string().optional(),limit:ot.number().int().positive().optional()}).strict();function Oa(e){return new Promise((t,n)=>{let o=["--files-with-matches","--sortr=modified","--regexp",e.pattern,"--no-messages"];e.include?.trim()&&o.push("--glob",e.include.trim()),o.push("--",e.searchPath);let r=Ma("rg",o,{cwd:e.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),t({exitCode:typeof l=="number"?l:-1,stdout:s.join(""),stderr:i.join("")})})})}var wo=A({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:Ia,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.pattern.trim();if(!t)return m("pattern must not be empty",!0);let n=Math.min(e.limit??Aa,Pa),o=e.path?.trim()?ka(process.cwd(),e.path.trim()):process.cwd();try{let r=await Oa({pattern:t,include:e.include,searchPath:o,cwd:process.cwd(),limit:n});if(r.exitCode===1)return m("No matches found.");if(r.exitCode!==0)return m(`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?m("No matches found."):m(s.join(`
|
|
47
|
+
`))}catch(r){return m(`grep_files failed: ${r.message}`,!0)}}});import{z as we}from"zod";var Mo=null;function cn(e){Mo=e}function ko(){return Mo}var La=we.object({server:we.string().optional(),cursor:we.string().optional()}).strict(),$a=we.object({server:we.string().optional(),cursor:we.string().optional()}).strict(),Na=we.object({server:we.string().min(1),uri:we.string().min(1)}).strict();function un(){let e=ko();if(!e)throw new Error("MCP pool is not initialized");return e}var Ao=A({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:La,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=un();if(e?.trim()){let s=n.get(e.trim());if(!s)return m(`MCP server not found: ${e}`,!0);let i=await s.client.listResources(t?{cursor:t}:void 0);return m(JSON.stringify({server:s.name,resources:i.resources,nextCursor:i.nextCursor},null,2))}if(t)return m("cursor is only supported when server is specified",!0);let 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 m(JSON.stringify({resources:r},null,2))}catch(n){return m(`list_mcp_resources failed: ${n.message}`,!0)}}}),Po=A({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:$a,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=un();if(e?.trim()){let s=n.get(e.trim());if(!s)return m(`MCP server not found: ${e}`,!0);let i=await s.client.listResourceTemplates(t?{cursor:t}:void 0);return m(JSON.stringify({server:s.name,resourceTemplates:i.resourceTemplates,nextCursor:i.nextCursor},null,2))}if(t)return m("cursor is only supported when server is specified",!0);let 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 m(JSON.stringify({resourceTemplates:r},null,2))}catch(n){return m(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Ro=A({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:Na,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,uri:t})=>{try{let o=un().get(e);if(!o)return m(`MCP server not found: ${e}`,!0);let r=await o.client.readResource({uri:t});return m(JSON.stringify({server:e,uri:t,...r},null,2))}catch(n){return m(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as We}from"zod";var Da=We.object({step:We.string().min(1),status:We.enum(["pending","in_progress","completed"])}).strict(),Ua=We.object({explanation:We.string().optional(),plan:We.array(Da).min(1)}).strict(),Io=[],Oo=A({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:Ua,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:e,plan:t})=>t.filter(o=>o.status==="in_progress").length>1?m("At most one step can be in_progress at a time",!0):(Io=t,m(JSON.stringify({message:"Plan updated",explanation:e,plan:Io},null,2)))});import{readFile as Ha}from"fs/promises";import{homedir as Fa}from"os";import{join as Lo}from"path";import{z as $o}from"zod";var ja=$o.object({memory_id:$o.string().min(1)}).strict();function Ba(){let e=process.env.MEMO_HOME?.trim()||Lo(Fa(),".memo");return Lo(e,"Agents.md")}var No=A({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:ja,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:e})=>{try{let t=Ba(),n=await Ha(t,"utf8");return m(JSON.stringify({memory_id:e,memory_summary:n},null,2))}catch{return m(`memory not found for memory_id=${e}`,!0)}}});import{z as Do}from"zod";var Wa=Do.object({url:Do.string().min(1)}).strict(),Uo=1e4,rt=512e3,pn=4e3,za=new Set(["http:","https:","data:"]),qa=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Ga=/<\s*(br|hr)\s*\/?>/gi,Ka=/<\s*li[^>]*>/gi,Va=/<[^>]+>/g,Xa=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Ja=e=>e.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""}}),Ya=e=>{let o=e.replace(Xa," ").replace(Ka,"- ").replace(Ga,`
|
|
48
|
+
`).replace(qa,`
|
|
49
|
+
`).replace(Va," "),s=Ja(o).replace(/\r/g,"").split(`
|
|
17
50
|
`).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()},
|
|
19
|
-
...[truncated]`}function
|
|
20
|
-
${r}`),
|
|
21
|
-
|
|
22
|
-
`))}async function
|
|
23
|
-
`)}catch{}try{s.stdin?.end()}catch{}return o}var
|
|
24
|
-
`)}function
|
|
25
|
-
|
|
26
|
-
`);return{results:s,combinedObservation:a,hasRejection:i,executionMode:o,failurePolicy:r}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function
|
|
27
|
-
`)}formatToolDescription(
|
|
28
|
-
`)}groupByServer(
|
|
29
|
-
${
|
|
30
|
-
${t.
|
|
31
|
-
${
|
|
51
|
+
`).trim()},Za=e=>e.replace(/\s+/g," ").trim(),Ho=A({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:Wa,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t;try{t=new URL(e.url)}catch{return m(`Invalid URL: ${e.url}`,!0)}if(!za.has(t.protocol))return m(`Unsupported protocol: ${t.protocol}`,!0);let n=new AbortController,o=setTimeout(()=>n.abort(),Uo);try{let r=await globalThis.fetch(t,{signal:n.signal}),s=r.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>rt)return m(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(r.body&&r.body.getReader){let E=r.body.getReader(),_=[];for(;;){let{done:J,value:W}=await E.read();if(J)break;if(W){if(a+=W.byteLength,a>rt)return n.abort(),m(`Request aborted: response body exceeds ${rt} bytes`,!0);_.push(W)}}let T=new Uint8Array(a),D=0;for(let J of _)T.set(J,D),D+=J.byteLength;l=new TextDecoder().decode(T)}else if(l=await r.text(),a=new TextEncoder().encode(l).byteLength,a>rt)return m(`Request rejected: response body exceeds ${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?Ya(l):l.trim(),d=Za(p),h=d.length>pn?`${d.slice(0,pn)}...`:d,S=d.length>pn?" text_truncated=true":"",g=u?" source=html_stripped":"";return m(`status=${r.status} bytes=${a} text_chars=${d.length} text="${h}"${S}${g}`)}catch(r){return r.name==="AbortError"?m(`Request timeout or aborted (${Uo}ms)`,!0):m(`Request failed: ${r.message}`,!0)}finally{clearTimeout(o)}}});import{spawn as Qa}from"child_process";import{existsSync as el}from"fs";import{resolve as tl}from"path";import{z as Q}from"zod";var nl=3e4,ol=1e4,rl=3e5,Fo=4,sl=1500,jo=2e3,Ae=new Map,il=Q.object({message:Q.string().min(1),agent_type:Q.string().optional()}).strict(),al=Q.object({id:Q.string().min(1),message:Q.string().min(1),interrupt:Q.boolean().optional()}).strict(),ll=Q.object({id:Q.string().min(1)}).strict(),cl=Q.object({ids:Q.array(Q.string().min(1)).min(1),timeout_ms:Q.number().int().positive().optional()}).strict(),ul=Q.object({id:Q.string().min(1)}).strict();function ze(){return new Date().toISOString()}function dn(e){return m(`agent not found: ${e}`,!0)}function pl(){let e=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!e)return Fo;let t=Number(e);return!Number.isFinite(t)||t<=0?Fo:Math.floor(t)}function dl(){let e=0;for(let t of Ae.values())t.running&&(e+=1);return e}function ml(){let e=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(e)return e;let t=tl(process.cwd(),"dist/index.js");return el(t)?`node ${JSON.stringify(t)} --dangerous`:"memo --dangerous"}function fl(e){return e!=="running"}function gl(e){return new Promise(t=>{setTimeout(t,e)})}function hl(e){return e===void 0?nl:e<=0?null:Math.max(ol,Math.min(rl,e))}function yl(e){return e.length<=jo?e:`${e.slice(0,jo)}
|
|
52
|
+
...[truncated]`}function Tl(e,t){let n=[],o=e.trim(),r=t.trim();return o&&n.push(o),r&&n.push(`stderr:
|
|
53
|
+
${r}`),yl(n.join(`
|
|
54
|
+
|
|
55
|
+
`))}async function Bo(e){let t=e.running;if(!t)return;t.interrupted=!0;let n=t.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()}},sl);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function Sl(e){let t=Ae.get(e);return t?t.status:"not_found"}function _l(e){let t=Ae.get(e);return t?{status:t.status,last_message:t.lastMessage,last_output:t.lastOutput,last_error:t.lastError,last_submission_id:t.lastSubmissionId,updated_at:t.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function vl(e){return{agent_id:e.id,status:e.status,created_at:e.createdAt,updated_at:e.updatedAt,last_message:e.lastMessage,last_submission_id:e.lastSubmissionId,has_last_output:!!e.lastOutput,has_last_error:!!e.lastError}}function xl(e){let{record:t,submissionId:n,stdout:o,stderr:r,exitCode:s,interrupted:i}=e;if(!(!t.running||t.running.id!==n)&&(t.running=null,t.updatedAt=ze(),t.lastOutput=Tl(o,r)||null,t.lastError=null,t.status!=="closed")){if(i){t.status="errored",t.lastError="interrupted",t.statusBeforeClose="errored";return}if(s===0){t.status="completed",t.statusBeforeClose="completed";return}t.status="errored",t.lastError=`submission failed with exit code ${s}`,t.statusBeforeClose="errored"}}async function Wo(e,t){let n=pl();if(dl()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let o=crypto.randomUUID(),r=ml(),s=Qa(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}`)}),e.running={id:o,message:t,process:s,startedAt:ze(),interrupted:!1},e.status="running",e.lastMessage=t,e.lastSubmissionId=o,e.updatedAt=ze(),s.on("close",l=>{let c=typeof l=="number"?l:-1,u=!!(e.running?.id===o&&e.running.interrupted);xl({record:e,submissionId:o,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:u})});try{s.stdin?.write(`${t.trim()}
|
|
56
|
+
`)}catch{}try{s.stdin?.end()}catch{}return o}var zo=A({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:il,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:e})=>{let t=e.trim();if(!t)return m("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:t,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};Ae.set(n,r);try{let s=await Wo(r,t);return m(JSON.stringify({...vl(r),submission_id:s},null,2))}catch(s){return Ae.delete(n),m(`spawn_agent failed: ${s.message}`,!0)}}}),qo=A({name:"send_input",description:"Send a message to an existing agent.",inputSchema:al,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e,message:t,interrupt:n})=>{let o=Ae.get(e);if(!o)return dn(e);let r=t.trim();if(!r)return m("send_input failed: message must not be empty",!0);if(o.status==="closed")return m(`send_input failed: agent ${e} is closed; run resume_agent first`,!0);if(o.running){if(!n)return m(`send_input failed: agent ${e} is busy; set interrupt=true to cancel current submission`,!0);await Bo(o)}try{let s=await Wo(o,r);return m(JSON.stringify({agent_id:o.id,status:o.status,submission_id:s},null,2))}catch(s){return m(`send_input failed: ${s.message}`,!0)}}}),Go=A({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:ll,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=Ae.get(e);return t?(t.status==="closed"&&(t.status=t.statusBeforeClose,t.updatedAt=ze()),m(JSON.stringify({agent_id:e,status:t.status},null,2))):dn(e)}}),Ko=A({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:cl,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:e,timeout_ms:t})=>{let n=hl(t);if(n===null)return m("wait failed: timeout_ms must be greater than zero",!0);let o=()=>{let i={},a={};for(let l of e){let c=Sl(l);fl(c)&&(i[l]=c,a[l]=_l(l))}return{status:i,details:a}},r=o();if(Object.keys(r.status).length>0)return m(JSON.stringify({status:r.status,details:r.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await gl(100),r=o(),Object.keys(r.status).length>0)return m(JSON.stringify({status:r.status,details:r.details,timed_out:!1},null,2));return m(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),Vo=A({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:ul,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=Ae.get(e);return t?t.status==="closed"?m(JSON.stringify({agent_id:e,status:"closed"},null,2)):(t.statusBeforeClose=t.running?"completed":t.status,t.status="closed",t.updatedAt=ze(),await Bo(t),m(JSON.stringify({agent_id:e,status:"closed"},null,2))):dn(e)}});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"},Xo=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),xt={read:0,write:1,execute:2},Jo=["exec","run","shell","command","stdin"],Yo=["write","patch","create","delete","modify","update"],Zo=["read","get","fetch","search","list","find"],Qo=new Set(["write","execute"]);function gn(e){let t={...mn,...e?.customLevels};return{getRiskLevel(n){if(n in t)return t[n];let o=n.toLowerCase();return fn(o,Jo)?"execute":fn(o,Yo)?"write":fn(o,Zo)?"read":"write"},compareRisk(n,o){return xt[n]-xt[o]},needsApproval(n,o){return o==="strict"?!0:Qo.has(n)}}}function fn(e,t){return t.some(n=>e.includes(n))}import{createHash as bl}from"crypto";function bt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>bt(n)).join(",")+"]":`{${Object.entries(e).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${bt(o)}`).join(",")}}`}function hn(e,t){let n=bt(t),o=`${e}:${n}`;return bl("sha256").update(o).digest("hex").slice(0,16)}function Cl(e){return`Tool "${e}" requires approval.`}function yn(e){let{mode:t="auto",dangerous:n=!1,toolRiskLevels:o}=e||{},r=t==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=gn({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(Xo.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=hn(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:"This request was previously denied.",toolName:a,params:l}:{needApproval:!0,fingerprint:u,riskLevel:c,reason:Cl(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 er=12e3;function El(){let e=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!e)return er;let t=Number(e);return!Number.isFinite(t)||t<=0?er:Math.floor(t)}function wl(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ml(e){let t=0;for(let n of e.content??[]){if(n.type==="text"){t+=n.text.length;continue}try{t+=JSON.stringify(n).length}catch{t+=100}}return t}function kl(e,t,n){return`<system_hint type="tool_output_omitted" tool="${wl(e)}" reason="too_long" actual_chars="${t}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function Al(e,t){let n=El(),o=Ml(t);return o<=n?t:{content:[{type:"text",text:kl(e,o,n)}],isError:!1}}function Pl(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
|
|
57
|
+
`)}function Rl(e,t){let n=t;if(typeof t=="string"){let o=t.trim();if(o)try{n=JSON.parse(o)}catch{n=o}else n={}}return typeof n!="object"||n===null?{ok:!1,error:`${e.name} invalid input: expected object`}:typeof e.validateInput=="function"?e.validateInput(n):{ok:!0,data:n}}function Il(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("sandbox")||t.includes("permission denied")||t.includes("operation not permitted")||t.includes("eacces")?"sandbox_denied":"execution_failed"}var Tn=class{constructor(t){this.config=t;this.approvalManager=yn(t.approval)}approvalManager;async executeAction(t,n){let o=Date.now(),r=t.id??`${t.name}:${o}`,s=this.approvalManager.check(t.name,t.input);if(s.needApproval){let a={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(a);let l=n?.requestApproval?await n.requestApproval(a):"deny";if(this.approvalManager.recordDecision(s.fingerprint,l),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:l}),l==="deny")return{actionId:r,tool:t.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${t.name}`,durationMs:Date.now()-o,rejected:!0}}let i=this.config.tools[t.name];if(!i)return{actionId:r,tool:t.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${t.name}`,durationMs:Date.now()-o};try{let a=Rl(i,t.input);if(!a.ok)return{actionId:r,tool:t.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-o};let l=await i.execute(a.data),c=Al(t.name,l);return{actionId:r,tool:t.name,status:"success",success:!0,observation:Pl(c)||"(no tool output)",durationMs:Date.now()-o}}catch(a){let l=Il(a);return{actionId:r,tool:t.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-o}}}async executeActions(t,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(t.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 t){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(`
|
|
58
|
+
|
|
59
|
+
`);return{results:s,combinedObservation:a,hasRejection:i,executionMode:o,failurePolicy:r}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function tr(e){return new Tn(e)}var Ct=class{tools=new Map;register(t){this.tools.set(t.name,t)}registerMany(t){for(let n of t)this.register(n)}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,o]of this.tools)t[n]=o;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}};import{Client as Ol}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ll}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as $l}from"@modelcontextprotocol/sdk/client/stdio.js";function Nl(e){if(!e)return;let t={...process.env,...e},n=Object.entries(t).filter(o=>typeof o[1]=="string");return Object.fromEntries(n)}function nr(){return new Ol({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function Dl(e){if(!(!e||Object.keys(e).length===0))return{headers:e}}function Ul(e){let t={...e.http_headers??e.headers??{}};if(e.bearer_token_env_var){let n=process.env[e.bearer_token_env_var];n&&!t.Authorization&&(t.Authorization=`Bearer ${n}`)}return t}async function Hl(e){let t=new URL(e.url),n=Dl(Ul(e));try{let o=nr(),r=new Ll(t,{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 Fl(e){if("url"in e)return Hl(e);let t={command:e.command,args:e.args,env:Nl(e.env),stderr:e.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new $l(t),o=nr();return await o.connect(n),{client:o,transport:n}}var Et=class{connections=new Map;async connect(t,n){let o=this.connections.get(t);if(o)return o;let{client:r,transport:s}=await Fl(n),i=await r.listTools(),a={name:t,client:r,transport:s,tools:(i.tools||[]).map(l=>({name:`${t}_${l.name}`,description:l.description||`Tool from ${t}: ${l.name}`,source:"mcp",serverName:t,originalName:l.name,inputSchema:l.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(t,a),a}get(t){return this.connections.get(t)}getAll(){return Array.from(this.connections.values())}getAllTools(){let t=[];for(let n of this.connections.values())for(let o of n.tools)t.push({name:o.name,description:o.description,serverName:o.serverName,originalName:o.originalName,inputSchema:o.inputSchema,client:n.client});return t}async closeAll(){let t=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(t),this.connections.clear()}get size(){return this.connections.size}};var wt=class{pool;tools=new Map;shouldLog;constructor(){this.pool=new Et,cn(this.pool),this.shouldLog=process.env.MEMO_MCP_LOG==="1"||!(process.stdout.isTTY&&process.stdin.isTTY)}async loadServers(t){if(!t||Object.keys(t).length===0)return 0;let n=0;return await Promise.all(Object.entries(t).map(async([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(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,o]of this.tools)t[n]=o;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),cn(null)}getPool(){return this.pool}};var Mt=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new Ct,this.mcpRegistry=new wt}registerNativeTool(t){this.nativeRegistry.register(t)}registerNativeTools(t){for(let n of t)this.registerNativeTool(n)}async loadMcpServers(t){return this.mcpRegistry.loadServers(t)}getTool(t){return this.nativeRegistry.get(t)??this.mcpRegistry.get(t)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(t){return this.nativeRegistry.has(t)||this.mcpRegistry.has(t)}getToolCount(){let t=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:t,mcp:n,total:t+n}}async execute(t,n){let o=this.getTool(t);if(!o)throw new Error(`Tool '${t}' not found`);return o.execute(n)}generateToolDefinitions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let t=this.getAllTools();if(t.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let o=t.filter(s=>s.source==="native"),r=t.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(`
|
|
60
|
+
`)}formatToolDescription(t){let n=[];return n.push(`#### ${t.name}`),n.push(`- **Description**: ${t.description}`),t.inputSchema&&Object.keys(t.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(t.inputSchema)}`),n.join(`
|
|
61
|
+
`)}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()}};function jl(e){let t=process.env[e]?.trim();return t?new Set(t.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function Bl(){let e=[],t=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=jl("MEMO_EXPERIMENTAL_TOOLS"),o=n.size===0,r=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return t==="shell"?e.push(no):t==="shell_command"?e.push(oo):t==="unified_exec"?e.push(Qt,en):t!=="disabled"&&e.push(Qt,en),e.push(Ao,Po,Ro),e.push(Oo),e.push(vo),(o||n.has("grep_files"))&&e.push(wo),(o||n.has("read_file"))&&e.push(Co),(o||n.has("list_dir"))&&e.push(Eo),s&&e.push(No),e.push(Ho),r&&e.push(zo,qo,Go,Ko,Vo),e}function Wl(e){let t={};for(let n of e)t[n.name]=n;return t}var zl=Wl(Bl()),ql=Object.values(zl),or=ql;import ac from"openai";import{encoding_for_model as Gl,get_encoding as Kl}from"@dqbd/tiktoken";var rr="cl100k_base";function Vl(e){let t=e?.trim()||rr;try{let n=()=>Gl(t);return n().free(),{model:t,factory:n}}catch{let n=rr,o=()=>Kl(n);return o().free(),{model:n,factory:o}}}function Xl(e){if(e.role==="assistant"){let t=e.reasoning_content?`
|
|
62
|
+
${e.reasoning_content}`:"";return e.tool_calls?.length?`${e.content}${t}
|
|
63
|
+
${JSON.stringify(e.tool_calls)}`:`${e.content}${t}`}return e.role==="tool"?`${e.content}
|
|
64
|
+
${e.tool_call_id}
|
|
65
|
+
${e.name??""}`:e.content}function sr(e){let{model:t,factory:n}=Vl(e),o=n(),r=4,s=2,i=1,a=c=>c?o.encode(c).length:0;return{model:t,countText:a,countMessages:c=>{if(!c.length)return 0;let u=0;for(let p of c)u+=r,u+=a(Xl(p)),p.name&&(u+=i);return u+=s,u},dispose:()=>o.free()}}import{mkdir as Jl,writeFile as Yl,readFile as Zl,access as Ql}from"fs/promises";import{homedir as ir}from"os";import{dirname as ec,join as it}from"path";import{randomUUID as lf}from"crypto";import{parse as tc}from"toml";var nc=it(ir(),".memo"),oc="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 rc(e){return/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e)}function sc(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=[];for(let[n,o]of Object.entries(e)){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),t.push(i)}}return t}function ar(e){return e.startsWith("~")?it(ir(),e.slice(1)):e}function ic(e){let t=e.providers.map(s=>{let i=typeof s?.name=="string"?s.name:"";if(!i)return"";let l=[`[[providers.${rc(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(`
|
|
32
66
|
`)}).filter(Boolean).join(`
|
|
33
67
|
|
|
34
|
-
`),n="";
|
|
68
|
+
`),n="";e.mcp_servers&&Object.keys(e.mcp_servers).length>0&&(n=Object.entries(e.mcp_servers).map(([s,i])=>{if("url"in i){let h=[`[mcp_servers.${s}]`];h.push(`type = "${i.type??"streamable_http"}"`),h.push(`url = "${i.url}"`),i.bearer_token_env_var&&h.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 g=Object.entries(S).map(([_,T])=>`${JSON.stringify(_)} = ${JSON.stringify(T)}`).join(", "),E=i.http_headers?"http_headers":"headers";h.push(`${E} = { ${g} }`)}return h.join(`
|
|
35
69
|
`)}let a=i.args?`args = ${JSON.stringify(i.args)}`:"",l=i.type?`type = "${i.type}"
|
|
36
70
|
`:"",c=i.stderr?`stderr = "${i.stderr}"
|
|
37
71
|
`:"",u=`[mcp_servers.${s}]
|
|
38
72
|
${l}command = "${i.command}"
|
|
39
|
-
${c}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let
|
|
73
|
+
${c}${a}`.trimEnd(),p=i.env?Object.entries(i.env):[];if(p.length===0)return u;let d=p.map(([h,S])=>`${JSON.stringify(h)} = ${JSON.stringify(S)}`).join(`
|
|
40
74
|
`);return`${u}
|
|
41
75
|
|
|
42
76
|
[mcp_servers.${s}.env]
|
|
43
|
-
${
|
|
44
|
-
|
|
45
|
-
`));let o=[`current_provider = "${
|
|
46
|
-
`),
|
|
47
|
-
|
|
48
|
-
`)}async function
|
|
49
|
-
|
|
50
|
-
${
|
|
51
|
-
`),{thinkingParts:n,cleaned:o}=
|
|
52
|
-
|
|
53
|
-
`):o||void 0}import{randomUUID as
|
|
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,y=null,S=-1;for(let h=0;;h++){let P=this.tokenCounter.countMessages(this.history);if(P>a){let k=`Context tokens (${P}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:k}),u="prompt_limit",c=k,p=k,await this.emitEvent("final",{turn:o,step:h,content:k,role:"assistant",meta:{tokens:{prompt:P}}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:k,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.options.warnPromptTokens&&P>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${P}`);let C="",x=[],b,A;try{let k=await this.deps.callLLM(this.history,K=>this.deps.onAssistantStep?.(K,h),{signal:n.signal}),$=Hl(k);C=$.textContent,x=$.toolUseBlocks,A=$.stopReason,b=$.usage,C.trim().length>0&&(y=C,S=h)}catch(k){if(this.cancelling&&jl(k)){u="cancelled",c="",p="Turn cancelled",await this.emitEvent("final",{turn:o,step:h,content:"",role:"assistant",meta:{cancelled:!0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}let $=`LLM call failed: ${k.message}`;this.history.push({role:"assistant",content:$}),u="error",c=$,p=$,await this.emitEvent("final",{turn:o,content:$,role:"assistant"}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.deps.onAssistantStep?.(C,h);let M=x.length===0&&C?Wl(C,this.deps.tools):null,w,N=null;if(x.length>0){let k=x[0];if(k){let $=C?rr([C]):void 0;w={action:{tool:k.name,input:k.input},thinking:$},N={role:"assistant",content:C,tool_calls:Bl(x)}}else w={}}else C?(w={final:C},N={role:"assistant",content:C}):w={};let _e=this.tokenCounter.countText(C),U=b?.prompt??P,B=b?.completion??_e,re=b?.total??U+B,z={prompt:U,completion:B,total:re};if(lr(s,z),lr(this.sessionUsage,z),r.push({index:h,assistantText:C,parsed:w,tokenUsage:z}),await this.emitEvent("assistant",{turn:o,step:h,content:C,role:"assistant",meta:{tokens:z,protocol_violation:!!M,protocol_violation_count:M?T+1:T||void 0}}),M){T+=1;let k=`Model protocol error: returned plain-text tool JSON for "${M.tool}" ${T} times. Structured tool calls are required.`;u="error",c=k,p=k,this.history.push({role:"assistant",content:k}),await this.emitEvent("final",{turn:o,step:h,content:k,role:"assistant",meta:{error_type:"model_protocol_error",tool:M.tool,protocol_violation:!0,protocol_violation_count:T,tokens:z}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,errorMessage:p,tokenUsage:z,turnUsage:{...s},steps:r});break}if(N&&this.history.push(N),x.length>1){for(let E of x)this.maybeWarnRepeatedAction(E.name,E.input);await this.emitEvent("action",{turn:o,step:h,meta:{tools:x.map(E=>E.name),action_ids:x.map(E=>E.id),action_id:x[0]?.id,parallel:!0,phase:"dispatch",thinking:w.thinking,toolBlocks:x.map(E=>({id:E.id,name:E.name,input:E.input}))}});let k=x[0];k&&await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:h,action:{tool:k.name,input:k.input},parallelActions:x.map(E=>({tool:E.name,input:E.input})),thinking:w.thinking,history:Ge(this.history)});let $=x.every(E=>!!this.deps.tools[E.name]?.supportsParallelToolCalls),K=x.some(E=>!!this.deps.tools[E.name]?.isMutating),ue=$&&!K?"parallel":"sequential",pe=await this.toolOrchestrator.executeActions(x.map(E=>({id:E.id,name:E.name,input:E.input})),{...this.buildToolApprovalHooks(o,h),executionMode:ue,failurePolicy:"fail_fast"});for(let[E,F]of pe.results.entries())this.history.push({role:"tool",content:F.observation,tool_call_id:F.actionId,name:F.tool}),await this.emitEvent("observation",{turn:o,step:h,content:F.observation,meta:{tool:F.tool,index:E,action_id:F.actionId,phase:"result",status:F.status,error_type:F.errorType,duration_ms:F.durationMs,execution_mode:ue}});let xe=pe.combinedObservation,Ce=r[r.length-1];if(Ce&&(Ce.observation=xe),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:h,tool:x.map(E=>E.name).join(", "),observation:xe,history:Ge(this.history)}),pe.hasRejection){let E=pe.results.find(F=>F.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:h,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:E?.actionId,error_type:E?.errorType??"approval_denied",duration_ms:E?.durationMs}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,tokenUsage:z,turnUsage:{...s},steps:r});break}continue}else if(w.action){this.maybeWarnRepeatedAction(w.action.tool,w.action.input);let k=x[0]?.id??`${o}:${h}:single:${w.action.tool}`;await this.emitEvent("action",{turn:o,step:h,meta:{tool:w.action.tool,input:w.action.input,action_id:k,phase:"dispatch",thinking:w.thinking}}),await Z(this.hooks,"onAction",{sessionId:this.id,turn:o,step:h,action:w.action,thinking:w.thinking,history:Ge(this.history)});let $=await this.executeToolAction(k,w.action.tool,w.action.input,o,h);if($.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:h,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:$.actionId,error_type:$.errorType??"approval_denied",duration_ms:$.durationMs}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,tokenUsage:z,turnUsage:{...s},steps:r});break}let K=$.observation;this.history.push({role:"tool",content:K,tool_call_id:$.actionId,name:w.action.tool});let ue=r[r.length-1];ue&&(ue.observation=K),await this.emitEvent("observation",{turn:o,step:h,content:K,meta:{tool:w.action.tool,action_id:$.actionId,phase:"result",status:$.status,error_type:$.errorType,duration_ms:$.durationMs}}),await Z(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:h,tool:w.action.tool,observation:K,history:Ge(this.history)});continue}if(A==="end_turn"||w.final){this.resetActionRepetition();let k=A==="end_turn"&&!w.final&&C.trim().length===0&&!!y&&S===h-1;c=k?y??"":w.final||C,w.final&&(w.final=c),await this.emitEvent("final",{turn:o,step:h,content:c,role:"assistant",meta:{tokens:z,fallback_from_previous_text:k||void 0}}),await Z(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:h,finalText:c,status:u,tokenUsage:z,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 J,useEffect as zt,useMemo as Dn,useRef as Tt,useState as Y}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 ce}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 le}from"ink";import{memo as ic}from"react";import{Box as _n,Text as q}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(q,{bold:!0,children:Ae(t.tokens,e,`${n}-strong`)},n);case"em":return oe(q,{italic:!0,children:Ae(t.tokens,e,`${n}-em`)},n);case"codespan":return oe(q,{color:e.codeColor,backgroundColor:Zl,children:t.text},n);case"del":return oe(q,{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(q,{underline:!0,color:e.linkColor,children:[o,r]},n)}case"image":{let o=t.text||"image";return Ke(q,{color:e.linkColor,children:["[",o,"](",t.href,")"]},n)}case"br":return`
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
`):null}}var Cr=Sn(function({text:e,isThinking:n=!1}){let{content:o,thinking:r}=pc(()=>mc(e),[e]);return n?fe(ut,{flexDirection:"column",flexGrow:1,children:fe(qe,{text:e,tone:"muted"})}):Lt(ut,{flexDirection:"column",flexGrow:1,gap:1,children:[r&&fe(ut,{flexDirection:"column",paddingLeft:2,children:fe(qe,{text:r,tone:"muted"})}),fe(qe,{text:o,tone:"normal"})]})}),pg=Sn(function({text:e}){return fe(ut,{children:Lt(He,{color:"gray",children:["\u2022 ",e]})})}),mg=Sn(function({toolName:e,fileName:n}){return Lt(ut,{children:[fe(He,{color:"green",children:"\u25CF "}),fe(He,{color:"gray",children:"Used "}),fe(He,{color:"cyan",children:e}),n&&Lt(dc,{children:[fe(He,{color:"gray",children:" ("}),fe(He,{color:"cyan",children:n}),fe(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 Te}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 Te(Se,{flexDirection:"column",gap:0,children:[ee(Tc,{items:l,children:u=>{if(u.type==="header"&&u.data){let p=u.data;return Te(Se,{borderStyle:"round",borderColor:"blueBright",paddingX:2,paddingY:1,flexDirection:"column",gap:1,children:[ee(Se,{gap:1,alignItems:"center",children:Te(Se,{flexDirection:"column",children:[ee(ce,{bold:!0,children:"Welcome to Memo Code CLI!"}),ee(ce,{color:"gray",children:"Send /help for help information."})]})}),Te(Se,{flexDirection:"column",gap:0,children:[Te(Se,{children:[ee(ce,{color:"gray",children:"Directory: "}),ee(ce,{color:"cyan",children:Sc(p.cwd)})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"Session: "}),ee(ce,{color:"cyan",children:vc(p.sessionId)})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"Model: "}),ee(ce,{color:"cyan",children:p.model}),Te(ce,{color:"gray",children:[" ","(powered by ",p.providerName,")"]})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"Version: "}),Te(ce,{color:"cyan",children:["v",p.version]})]}),Te(Se,{children:[ee(ce,{color:"gray",children:"MCP: "}),ee(ce,{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 y=T.split("/").filter(Boolean),S=y.map(P=>P.toLowerCase()),h=c.isDirectory();if(o.push({path:T,pathLower:T.toLowerCase(),segments:y,segmentsLower:S,depth:a,isDir:h}),o.length>=r)break;h&&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:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
`),
|
|
66
|
-
${
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
Ctrl+C
|
|
77
|
-
|
|
78
|
-
|
|
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:y,providers:S,configPath:h,providerName:P,model:C,contextLimit:x,mcpServers:b}){let[A,M]=Le(""),[w,N]=Le(null),[_e,U]=Le(""),[B,re]=Le("none"),[z,k]=Le([]),[$,K]=Le(0),[ue,pe]=Le(!1),[xe,Ce]=Le(!1),E=$n(0),F=$n(0),W=$n(""),Gt="\u203A ";In(()=>{W.current=A,Ce(!1)},[A]);let V=mu(()=>xe||t?null:Eu(A),[t,xe,A]),X=Yr((L=!0)=>{L&&Ce(!0),re("none"),k([]),K(0),pe(!1)},[]);In(()=>{t&&X(!1)},[t,X]),In(()=>{if(!V){re("none"),k([]),K(0),pe(!1);return}let L=!1,j=++E.current;return pe(!0),(async()=>{try{if(V.type==="file"){let R=await Ur({cwd:u,query:V.query,limit:8});if(L||j!==E.current)return;let H=R.map(g=>{let v=g.isDir?`${g.path}/`:g.path;return{id:g.id,title:v,kind:"file",value:v,meta:{isDir:g.isDir}}});re("file"),k(H),K(g=>H.length?Math.min(g,H.length-1):0);return}if(V.type==="history"){let R=await _u({sessionsDir:p,cwd:u,keyword:V.keyword,activeSessionFile:T});if(L||j!==E.current)return;let H=R.map(Ru);re("history"),k(H),K(g=>H.length?Math.min(g,H.length-1):0);return}if(V.type==="models"){let R=V.keyword.toLowerCase(),g=(S??[]).filter(v=>{let se=v.name?.toLowerCase()??"",ge=v.model?.toLowerCase()??"";return R?se.includes(R)||ge.includes(R):!0}).map(v=>({id:v.name,title:`${v.name}: ${v.model}`,subtitle:v.base_url??v.env_api_key??"",kind:"model",value:`/models ${v.name}`,meta:{provider:v}}));re("model"),k(g),K(v=>g.length?Math.min(v,g.length-1):0);return}if(V.type==="context"){let H=[8e4,12e4,15e4,2e5].map(g=>({id:`${g}`,title:`${(g/1e3).toFixed(0)}k tokens`,subtitle:g===x?"Current":void 0,kind:"context",value:`/context ${(g/1e3).toFixed(0)}k`,meta:{contextValue:g}}));re("context"),k(H),K(g=>H.length?Math.min(g,H.length-1):0);return}if(V.type==="slash"){let R=V.keyword.toLowerCase(),g=(R?Rn.filter(v=>v.matches?v.matches(R):v.name.startsWith(R)):Rn).map(v=>({id:v.name,title:`/${v.name}`,subtitle:v.description,kind:"slash",value:`/${v.name} `,meta:{slashCommand:v}}));re("slash"),k(g),K(v=>g.length?Math.min(v,g.length-1):0);return}}catch{!L&&j===E.current&&k([])}finally{!L&&j===E.current&&pe(!1)}})(),()=>{L=!0}},[V,u,p,T,S,x]);let xt=Yr(L=>{if(L){if(B==="file"&&V?.type==="file"){let j=A.slice(0,V.tokenStart),R=A.slice(V.tokenStart+V.query.length),H=`${j}${L.value}${R}`;W.current=H,M(H),N(null),U(""),L.meta?.isDir||X();return}if(B==="history"){L.meta?.historyEntry&&y?.(L.meta.historyEntry),W.current=L.value,M(L.value),N(null),U(""),X();return}if(B==="model"&&L.meta?.provider){i?.(L.meta.provider),W.current="",M(""),N(null),U(""),X();return}if(B==="slash"&&L.meta?.slashCommand){L.meta.slashCommand.run({setInputValue:R=>{W.current=R,M(R),N(null),U("")},closeSuggestions:X,clearScreen:()=>{o()},newSession:()=>{r?.()},exitApp:()=>{n()},showSystemMessage:(R,H)=>{a?.(R,H)},switchModel:R=>{i?.(R)},setContextLimit:R=>{l?.(R)},loadHistory:R=>{y?.(R)},data:{configPath:h,providerName:P,model:C,contextLimit:x,providers:S,mcpServers:b}});return}if(B==="context"&&L.meta?.contextValue){let j=L.meta.contextValue;l?.(j),a?.("Context",`Context limit set to ${(j/1e3).toFixed(0)}k tokens`),W.current="",M(""),N(null),U(""),X();return}}},[X,o,n,i,a,l,y,B,V,A,h,P,C,x,S,b]);yu((L,j)=>{if(j.ctrl&&L==="l"){W.current="",M(""),N(null),U(""),X(),o(),r?.();return}let R=B!=="none",H=R&&z.length>0;if(j.escape){let g=Date.now();if(g-F.current<=Tu){F.current=0,t?s():(W.current="",M(""),N(null),U(""),X());return}F.current=g,R&&X();return}if(!t){if(j.upArrow){if(H){K(se=>se<=0?z.length-1:se-1);return}if(!c.length)return;if(w===null){U(W.current);let se=c.length-1;N(se);let ge=c[se]??"";W.current=ge,M(ge);return}let g=Math.max(0,w-1);N(g);let v=c[g]??"";W.current=v,M(v);return}if(j.downArrow){if(H){K(se=>(se+1)%z.length);return}if(w===null)return;let g=w+1;if(g>=c.length){N(null),W.current=_e,M(_e),U("");return}N(g);let v=c[g]??"";W.current=v,M(v);return}if(j.tab&&H){xt(z[$]);return}if(j.return){if(H){xt(z[$]);return}if(j.shift){let v=W.current+`
|
|
84
|
-
`;W.current=v,M(v);return}let g=W.current.trim();g&&(e(g),W.current="",M(""),N(null),U(""),X(!1));return}if(j.backspace||j.delete){let g=W.current.slice(0,Math.max(0,W.current.length-1));W.current=g,M(g);return}if(L){let g=W.current+L;W.current=g,M(g)}}});let et=A,St=t?" ":"\u258A",De=et.split(`
|
|
85
|
-
`),Ie=2,Kt=z.map(({value:L,meta:j,...R})=>R);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((L,j)=>dt(Bt,{children:[Oe(Fe,{color:"gray",children:" ".repeat(Ie)}),Oe(Fe,{color:"white",children:L}),j===De.length-2&&Oe(Fe,{color:"cyan",children:St})]},`line-${j}`))]}),B!=="none"?Oe(jr,{items:Kt,activeIndex:$,loading:ue}):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),y=(await e(T)).filter(S=>S.isFile()&&S.name.endsWith(".jsonl"));for(let S of y)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(y=>`${y/1e3}k`).join(", ");return p===null?{kind:"message",title:"Context",content:`Current: ${(e.contextLimit/1e3).toFixed(0)}k
|
|
89
|
-
Usage: /context <length> (starts new session)
|
|
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),y=Ne[o]??Ne[0],S=s||a[y.key]||"",h=Nn(async x=>{u(!0),T(null);try{let b=x.name||Ne[0].defaultValue,A=x.envKey||Ne[1].defaultValue,M=x.model||Ne[2].defaultValue,w=x.baseUrl||Ne[3].defaultValue;await ye(t,{current_provider:b,providers:[{name:b,env_api_key:A,model:M,base_url:w||void 0}]}),e()}catch(b){T(b.message),u(!1)}},[t,e]),P=Nn(async()=>{let b=s.trim()||y.defaultValue,A={...a,[y.key]:b};if(l(A),i(""),o<Ne.length-1){r(o+1);return}await h(A)},[y.defaultValue,y.key,o,s,a,h]);Ju(Nn((x,b)=>{if(!c){if(b.ctrl&&x==="c"){n();return}if(b.return){P();return}if(b.backspace||b.delete){i(A=>A.slice(0,-1));return}x&&i(A=>A+x)}},[P,n,c]));let C=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:C}),je(ve,{children:[y.label," (default: ",y.defaultValue,")"]}),y.hint?Re(ve,{color:"gray",children:y.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]=Y(e),[y,S]=Y(n),[h,P]=Y(a),[C,x]=Y({...t,providerName:e}),[b,A]=Y(null),[M,w]=Y([]),[N,_e]=Y([]),[U,B]=Y(!1),re=Tt(null),z=Tt(null),[k,$]=Y([]),[K,ue]=Y(null),[pe,xe]=Y([]),[Ce,E]=Y(null),F=Tt(null),[W,Gt]=Y(null),V=Tt(0),[X,xt]=Y(t.maxPromptTokens??12e4),[et,St]=Y(c),[De,Ie]=Y(0),Kt=Dn(()=>Vt(),[]),[L,j]=Y(null),R=Tt(null),H=J(()=>(V.current+=1,V.current),[]),g=J((d,f)=>{let _=`${Date.now()}-${Math.random().toString(16).slice(2)}`,I=H();_e(D=>[...D,{id:_,title:d,content:f,sequence:I}])},[H]),v=J((d,f)=>{w(_=>{let I=[..._],D=I.findIndex(ae=>ae.index===d);D===-1&&(I.push(rp(d)),D=I.length-1);let G=I[D];return G&&(I[D]=f(G)),I})},[]),se=Dn(()=>({onAssistantStep:(d,f)=>{let _=re.current;_&&v(_,I=>{let D=I.steps.slice();for(;D.length<=f;)D.push({index:D.length,assistantText:""});let G=D[f];if(!G)return I;let ae={...G,assistantText:G.assistantText+d};return D[f]=ae,{...I,steps:D}})},requestApproval:l?void 0:d=>new Promise(f=>{j(d),R.current=f}),hooks:{onTurnStart:({turn:d,input:f,promptTokens:_})=>{re.current=d;let I=z.current;I&&(z.current=null);let D=I??f;_&&_>0&&Ie(_),v(d,G=>({...G,index:d,userInput:D,steps:[],startedAt:Date.now(),contextPromptTokens:_??G.contextPromptTokens}))},onAction:({turn:d,step:f,action:_,thinking:I,parallelActions:D})=>{v(d,G=>{let ae=G.steps.slice();for(;ae.length<=f;)ae.push({index:ae.length,assistantText:""});let vt=ae[f];return vt?(ae[f]={...vt,action:_,thinking:I,toolStatus:"executing",parallelActions:D&&D.length>1?D:void 0},{...G,steps:ae}):G})},onObservation:({turn:d,step:f,observation:_})=>{v(d,I=>{let D=I.steps.slice();for(;D.length<=f;)D.push({index:D.length,assistantText:""});let G=D[f];return G?(D[f]={...G,observation:_,toolStatus:ns(_)},{...I,steps:D}):I})},onFinal:({turn:d,finalText:f,status:_,turnUsage:I,tokenUsage:D})=>{v(d,G=>{let ae=G.startedAt??Date.now(),vt=Math.max(0,Date.now()-ae),ks=D?.prompt??G.contextPromptTokens,bs=G.sequence??H();return{...G,finalText:f,status:_,tokenUsage:I,contextPromptTokens:ks,startedAt:ae,durationMs:vt,sequence:bs}}),B(!1)}}}),[v,l,H]);zt(()=>{let d=!1;return(async()=>{if(et)return;let f=F.current;f&&await f.close();let _=await lt(se,C);if(d){await _.close();return}F.current=_,A(_),ue(_.historyFilePath??null)})(),()=>{d=!0}},[se,C,et]),zt(()=>{let d=!1;return(async()=>{let f=await us();d||!f||g("Update",`Update available: v${f.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{d=!0}},[g]),zt(()=>()=>{F.current&&F.current.close()},[]);let ge=J(async()=>{F.current&&await F.current.close(),Gt("Bye!"),setTimeout(()=>{u()},300)},[u]),Fn=J(()=>{w([]),_e([]),xe([]),E(null),Ie(0),V.current=0},[]),jn=J(async()=>{w([]),_e([]),xe([]),E(null),Ie(0),V.current=0;let d=_t(),f={...C,sessionId:d};F.current&&await F.current.close();let _=await lt(se,f);F.current=_,A(_),ue(_.historyFilePath??null),x(f),g("New Session","Started a new session with fresh context.")},[se,C,g]),Bn=J(async d=>{try{let f=await ie(),_={...f.config,max_prompt_tokens:d};await ye(f.configPath,_)}catch(f){g("Failed to save config",`Failed to save context limit: ${f.message}`)}},[g]),qt=J(d=>{xt(d),Ie(0),x(f=>({...f,maxPromptTokens:d,sessionId:_t()})),g("Context length",`Context limit set to ${(d/1e3).toFixed(0)}k tokens (new session started)`),Bn(d)},[g,Bn]),Ts=J(async d=>{if(!d.sessionFile){g("History","This entry has no context file to load.");return}try{let f=await Zu(d.sessionFile,"utf8"),_=sp(f);xe(_.turns),E(_.messages),B(!1),w([]),A(null),ue(null),Ie(0),re.current=null,V.current=Math.max(V.current,_.maxSequence),x(I=>({...I,sessionId:_t()})),g("History loaded",_.summary||d.input)}catch(f){g("Failed to load history",`Unable to read ${d.sessionFile}: ${f.message}`)}},[g]),Wn=J(async d=>{try{let f=await ie(),_={...f.config,current_provider:d};await ye(f.configPath,_)}catch(f){g("Failed to save config",`Failed to save model selection: ${f.message}`)}},[g]),_s=J(()=>{U&&b?.cancelCurrentTurn?.()},[U,b]),Xt=J(async d=>{if(d.name===p&&d.model===y){g("Model switch",`Already using ${d.name} (${d.model})`);return}if(U){g("Model switch","Currently running. Press Esc Esc to cancel before switching models.");return}w([]),xe([]),E(null),Ie(0),re.current=null,A(null),ue(null),T(d.name),S(d.model),x(f=>({...f,sessionId:_t(),providerName:d.name})),await Wn(d.name),g("Model switch",`Switched to ${d.name} (${d.model})`)},[g,U,y,p,Wn]),Jt=J(async d=>{if(!d.trim()){g("Shell Command","Usage: $ <command> (e.g. $ git status)");return}B(!0);try{let{stdout:f,stderr:_}=await op(d,{cwd:s,maxBuffer:5242880}),I=[f?.trim(),_?.trim()].filter(Boolean).join(`
|
|
94
|
-
`);g("Shell Result",I||"(no output)")}catch(f){let _=f,D=[_.stdout?.trim(),_.stderr?.trim(),_.message].filter(Boolean).join(`
|
|
95
|
-
`);g("Shell Error",D||"Command failed")}finally{B(!1)}},[g,s]),Vn=J(async d=>{let f=ss(d,{configPath:o,providerName:p,model:y,mcpServers:r,providers:h,contextLimit:X});if(f.kind==="exit"){await ge();return}if(f.kind==="new"){await jn();return}if(f.kind==="switch_model"){await Xt(f.provider);return}if(f.kind==="set_context_limit"){qt(f.limit);return}if(f.kind==="init_agents_md"){g("Init","Analyzing project structure and generating AGENTS.md...");let _=`Please analyze the current project and create an AGENTS.md file at the project root.
|
|
77
|
+
${d}`}).join(`
|
|
78
|
+
|
|
79
|
+
`));let o=[`current_provider = "${e.current_provider}"`];return typeof e.max_prompt_tokens=="number"&&Number.isFinite(e.max_prompt_tokens)&&o.push(`max_prompt_tokens = ${Math.floor(e.max_prompt_tokens)}`),Array.isArray(e.active_mcp_servers)&&o.push(`active_mcp_servers = ${JSON.stringify(e.active_mcp_servers)}`),[o.join(`
|
|
80
|
+
`),t,n].filter(Boolean).join(`
|
|
81
|
+
|
|
82
|
+
`)}async function pe(e,t){await Jl(ec(e),{recursive:!0}),await Yl(e,ic(t),"utf-8")}async function ee(){let e=process.env.MEMO_HOME?ar(process.env.MEMO_HOME):nc,t=it(e,"config.toml");try{await Ql(t);let n=await Zl(t,"utf-8"),o=tc(n),r=sc(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=Array.isArray(o.active_mcp_servers)?o.active_mcp_servers.filter(c=>typeof c=="string"&&c.trim().length>0):void 0,a={current_provider:o.current_provider??st.current_provider,max_prompt_tokens:s??st.max_prompt_tokens,providers:r,mcp_servers:o.mcp_servers??{},active_mcp_servers:i},l=!a.providers.length;return{config:l?st:a,home:e,configPath:t,needsSetup:l}}catch{return{config:st,home:e,configPath:t,needsSetup:!0}}}function De(e,t){let n=t||e.current_provider,o=e.providers.find(r=>r.name===n);return o||(e.providers?.[0]??st.providers[0])}function kt(e,t){let n=t.historyDir??it(e.home,oc);return ar(n)}function lr(e,t){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}-${t}.jsonl`;return it(e,o,r,s,c)}function lc(e,t){if(!e||!t)return e;let n=new Set(t.map(r=>r.trim()).filter(Boolean));if(n.size===0)return{};let o={};for(let[r,s]of Object.entries(e))n.has(r)&&(o[r]=s);return o}function cc(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}function uc(e){if(e.role==="assistant"){let t={role:"assistant",content:e.content,tool_calls:e.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return e.reasoning_content&&(t.reasoning_content=e.reasoning_content),t}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:e.tool_call_id}:{role:e.role,content:e.content}}function pc(e){let t=e?.reasoning_content;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}async function cr(e,t,n){let o=await ee(),r=o.config,s=new Mt;if(s.registerNativeTools(or),await s.loadMcpServers(lc(r.mcp_servers,t.activeMcpServers)),e.tools)for(let[d,h]of Object.entries(e.tools))s.registerNativeTool({name:d,description:h.description,source:"native",inputSchema:{type:"object"},execute:h.execute});let i=s.toRegistry(),a=async()=>{let d=await(e.loadPrompt??zn)(),h=s.generateToolDescriptions();return h&&(d+=`
|
|
83
|
+
|
|
84
|
+
${h}`),d},l=s.generateToolDefinitions(),c=kt(o,t),u=lr(c,n),p=new St(u);return{tools:i,dispose:async()=>{e.dispose&&await e.dispose(),await s.dispose()},callLLM:e.callLLM??(async(d,h,S)=>{let g=De(r,t.providerName),E=process.env[g.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!E)throw new Error(`Missing env var ${g.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let _=new ac({apiKey:E,baseURL:g.base_url}),T=d.map(uc),D=S?.tools??l,J=D.length>0?D.map(C=>({type:"function",function:{name:C.name,description:C.description,parameters:C.input_schema}})):void 0,W=await _.chat.completions.create({model:g.model,messages:T,tools:J,tool_choice:J?"auto":void 0},{signal:S?.signal}),j=W.choices?.[0]?.message,x=pc(j);if(j?.tool_calls&&j.tool_calls.length>0){let C=[];j.content&&C.push({type:"text",text:j.content});for(let O of j.tool_calls)if(O.type==="function"){let me=cc(O.function.arguments);me.ok?C.push({type:"tool_use",id:O.id,name:O.function.name,input:me.data}):C.push({type:"text",text:`[tool_use parse error] ${me.error}; raw: ${me.raw}`})}let B=C.some(O=>O.type==="tool_use");return{content:C,reasoning_content:x,stop_reason:B?"tool_use":"end_turn",usage:{prompt:W.usage?.prompt_tokens??void 0,completion:W.usage?.completion_tokens??void 0,total:W.usage?.total_tokens??void 0}}}let N=j?.content;if(typeof N!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:N}],reasoning_content:x,stop_reason:"end_turn",usage:{prompt:W.usage?.prompt_tokens??void 0,completion:W.usage?.completion_tokens??void 0,total:W.usage?.total_tokens??void 0}}}),loadPrompt:a,historySinks:e.historySinks??[p],tokenCounter:e.tokenCounter??sr(t.tokenizerModel),historyFilePath:u}}function dc(e){let t=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,o=e.replace(n,(r,s,i)=>{let a=(i??"").trim();return a&&t.push(a),a});return{thinkingParts:t,cleaned:o.trim()}}function ur(e){if(e.length===0)return;let t=e.join(`
|
|
85
|
+
`),{thinkingParts:n,cleaned:o}=dc(t);return n.length>0?n.join(`
|
|
86
|
+
|
|
87
|
+
`):o||void 0}import{randomUUID as Sr}from"crypto";function mc(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function pr(e,t){t&&(t.onTurnStart&&e.onTurnStart.push(t.onTurnStart),t.onAction&&e.onAction.push(t.onAction),t.onObservation&&e.onObservation.push(t.onObservation),t.onFinal&&e.onFinal.push(t.onFinal),t.onApprovalRequest&&e.onApprovalRequest.push(t.onApprovalRequest),t.onApprovalResponse&&e.onApprovalResponse.push(t.onApprovalResponse),t.onTitleGenerated&&e.onTitleGenerated.push(t.onTitleGenerated))}function dr(e){let t=mc();if(pr(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)pr(t,n);return t}async function X(e,t,n){let o=e[t];if(o.length)for(let r of o)try{await r(n)}catch(s){console.warn(`Hook ${t} failed: ${s.message}`)}}function qe(e){return e.map(t=>t.role==="assistant"&&t.tool_calls?.length?{...t,tool_calls:t.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...t})}var _r="interactive",fc=12e4,mr="success",at="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.",gc=`Generate a concise session title based on the user's first prompt.
|
|
88
|
+
Requirements:
|
|
89
|
+
- 3 to 8 words when possible
|
|
90
|
+
- Keep it specific and descriptive
|
|
91
|
+
- Return title only, no quotes, no punctuation-only output
|
|
92
|
+
`,fr=60,hc="Skipped tool execution after previous rejection.",yc="Tool execution skipped: tools are disabled in current permission mode.";function Tc(e){if(e.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let t=e.dangerous??!1;return{mode:t?"full":"auto",toolsDisabled:!1,dangerous:t,approvalMode:"auto"}}function gr(){return{prompt:0,completion:0,total:0}}function hr(e,t){if(!t)return;let n=t.prompt??0,o=t.completion??0,r=t.total??n+o;e.prompt+=n,e.completion+=o,e.total+=r}function Sc(e){let t=e.content.filter(o=>o.type==="text"),n=e.content.filter(o=>o.type==="tool_use");return{textContent:t.map(o=>o.text).join(`
|
|
93
|
+
`),toolUseBlocks:n.map(o=>({id:o.id,name:o.name,input:o.input})),reasoningContent:typeof e.reasoning_content=="string"&&e.reasoning_content.trim().length>0?e.reasoning_content:void 0,stopReason:e.stop_reason,usage:e.usage}}async function _c(e,t){for(let n of t)try{await n.append(e)}catch(o){console.error(`Failed to write history event: ${o.message}`)}}function yr(e){return e instanceof Error&&e.name==="AbortError"}function lt(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(n=>lt(n)).join(",")}]`:`{${Object.entries(e).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${JSON.stringify(n)}:${lt(o)}`).join(",")}}`}function vc(e){return e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:lt(t.input)}}))}function xc(e,t){let n=e.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(t,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}function vr(e){return e.length<=fr?e:`${e.slice(0,fr-3).trimEnd()}...`}function bc(e){let t=e.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!t)return"";let n=t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?vr(n):""}function Cc(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"New Session";if(!t.includes(" "))return t.length<=20?t:`${t.slice(0,20).trimEnd()}...`;let o=t.split(" ").filter(Boolean).slice(0,8).join(" ");return vr(o||t)}function Tr(e){return{role:"tool",content:e.observation,tool_call_id:e.actionId,name:e.tool}}function Ec(e,t,n){let o=new Map(t.map(r=>[r.actionId,r]));return e.map(r=>{let s=o.get(r.id);return s||{actionId:r.id,tool:r.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${hc} ${r.name}`:`Tool result missing for ${r.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}var Sn=class{constructor(t,n,o,r,s){this.deps=t;this.options=n;this.id=n.sessionId||Sr(),this.mode=n.mode||_r,this.history=[{role:"system",content:o}],this.tokenCounter=r,this.sinks=t.historySinks??[],this.hooks=dr(t),this.historyFilePath=s;let i=Tc(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=tr({tools:t.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=gr();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(t,n){let o=`${t}:${lt(n)}`;if(this.lastActionSignature===o?this.repeatedActionCount+=1:(this.lastActionSignature=o,this.repeatedActionCount=1),this.repeatedActionCount===3){let r=lt(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${t}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${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(t,n){return{onApprovalRequest:async o=>{await X(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:t,step:n,request:o})},requestApproval:async o=>this.deps.requestApproval?this.deps.requestApproval(o):"deny",onApprovalResponse:async({fingerprint:o,decision:r})=>{await X(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:t,step:n,fingerprint:o,decision:r})}}}async executeToolAction(t,n,o,r,s){return this.toolOrchestrator.executeAction({id:t,name:n,input:o},this.buildToolApprovalHooks(r,s))}async maybeGenerateSessionTitle(t,n,o){if(t!==1||this.title)return;let r=Cc(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:gc},{role:"user",content:n}],void 0,{signal:o,tools:[]}),a=bc(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(r=a,s="llm")}catch(i){if(yr(i))return}this.title=r,await this.emitEvent("session_title",{turn:t,content:r,meta:{source:s,original_prompt:n}}),await X(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:t,title:r,originalPrompt:n})}async runTurn(t){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let o=this.turnIndex,r=[],s=gr(),i=Date.now(),a=this.options.maxPromptTokens??fc;if(!this.sessionStartEmitted){let l=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:l,role:l?"system":void 0,meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:t});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:o,content:t,meta:{tokens:{prompt:l}}}),await X(this.hooks,"onTurnStart",{sessionId:this.id,turn:o,input:t,promptTokens:l,history:qe(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(o,t,n.signal);let c="",u="ok",p,d=0,h=null,S=-1;for(let g=0;;g++){let E=this.tokenCounter.countMessages(this.history);if(E>a){let b=`Context tokens (${E}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:b}),u="prompt_limit",c=b,p=b,await this.emitEvent("final",{turn:o,step:g,content:b,role:"assistant",meta:{tokens:{prompt:E}}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:b,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.options.warnPromptTokens&&E>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${E}`);let _="",T=[],D,J,W;try{let b=await this.deps.callLLM(this.history,q=>this.deps.onAssistantStep?.(q,g),{signal:n.signal}),k=Sc(b);_=k.textContent,T=k.toolUseBlocks,J=k.stopReason,D=k.usage,W=k.reasoningContent,_.trim().length>0&&(h=_,S=g)}catch(b){if(this.cancelling&&yr(b)){u="cancelled",c="",p="Turn cancelled",await this.emitEvent("final",{turn:o,step:g,content:"",role:"assistant",meta:{cancelled:!0}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}let k=`LLM call failed: ${b.message}`;this.history.push({role:"assistant",content:k}),u="error",c=k,p=k,await this.emitEvent("final",{turn:o,content:k,role:"assistant"}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:c,status:u,errorMessage:p,turnUsage:{...s},steps:r});break}this.deps.onAssistantStep?.(_,g);let j=T.length===0&&_?xc(_,this.deps.tools):null,x,N=null;if(T.length>0){let b=T[0];if(b){let k=_?ur([_]):void 0;x={action:{tool:b.name,input:b.input},thinking:k},N={role:"assistant",content:_,reasoning_content:W,tool_calls:vc(T)}}else x={}}else _?(x={final:_},N={role:"assistant",content:_,reasoning_content:W}):x={};let C=this.tokenCounter.countText(_),B=D?.prompt??E,O=D?.completion??C,me=D?.total??B+O,U={prompt:B,completion:O,total:me};if(hr(s,U),hr(this.sessionUsage,U),r.push({index:g,assistantText:_,parsed:x,tokenUsage:U}),await this.emitEvent("assistant",{turn:o,step:g,content:_,role:"assistant",meta:{tokens:U,protocol_violation:!!j,protocol_violation_count:j?d+1:d||void 0}}),j){d+=1;let b=`Model protocol error: returned plain-text tool JSON for "${j.tool}" ${d} times. Structured tool calls are required.`;u="error",c=b,p=b,this.history.push({role:"assistant",content:b}),await this.emitEvent("final",{turn:o,step:g,content:b,role:"assistant",meta:{error_type:"model_protocol_error",tool:j.tool,protocol_violation:!0,protocol_violation_count:d,tokens:U}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:c,status:u,errorMessage:p,tokenUsage:U,turnUsage:{...s},steps:r});break}if(N&&this.history.push(N),T.length>0&&this.toolsDisabled){for(let b of T)this.history.push({role:"tool",content:yc,tool_call_id:b.id,name:b.name});u="error",c=at,p=at,this.history.push({role:"assistant",content:at}),await this.emitEvent("final",{turn:o,step:g,content:at,role:"assistant",meta:{error_type:"tool_disabled",tool_count:T.length,tools:T.map(b=>b.name).join(","),tokens:U}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:at,status:u,errorMessage:p,tokenUsage:U,turnUsage:{...s},steps:r});break}if(T.length>1){for(let v of T)this.maybeWarnRepeatedAction(v.name,v.input);await this.emitEvent("action",{turn:o,step:g,meta:{tools:T.map(v=>v.name),action_ids:T.map(v=>v.id),action_id:T[0]?.id,parallel:!0,phase:"dispatch",thinking:x.thinking,toolBlocks:T.map(v=>({id:v.id,name:v.name,input:v.input}))}});let b=T[0];b&&await X(this.hooks,"onAction",{sessionId:this.id,turn:o,step:g,action:{tool:b.name,input:b.input},parallelActions:T.map(v=>({tool:v.name,input:v.input})),thinking:x.thinking,history:qe(this.history)});let k=T.every(v=>!!this.deps.tools[v.name]?.supportsParallelToolCalls),q=T.some(v=>!!this.deps.tools[v.name]?.isMutating),oe=k&&!q?"parallel":"sequential",Se=await this.toolOrchestrator.executeActions(T.map(v=>({id:v.id,name:v.name,input:v.input})),{...this.buildToolApprovalHooks(o,g),executionMode:oe,failurePolicy:"fail_fast"}),fe=Ec(T,Se.results,Se.hasRejection);for(let[v,V]of fe.entries())this.history.push(Tr(V)),await this.emitEvent("observation",{turn:o,step:g,content:V.observation,meta:{tool:V.tool,index:v,action_id:V.actionId,phase:"result",status:V.status,error_type:V.errorType,duration_ms:V.durationMs,execution_mode:oe}});let je=fe.map(v=>`[${v.tool}]: ${v.observation}`).join(`
|
|
94
|
+
|
|
95
|
+
`),re=fe.map(v=>v.status),_e=re.find(v=>v!==mr)??mr,$e=r[r.length-1];if($e&&($e.observation=je),await X(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:g,tool:T.map(v=>v.name).join(", "),observation:je,resultStatus:_e,parallelResultStatuses:re,history:qe(this.history)}),Se.hasRejection){let v=fe.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:g,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:v?.actionId,error_type:v?.errorType??"approval_denied",duration_ms:v?.durationMs}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:c,status:u,tokenUsage:U,turnUsage:{...s},steps:r});break}continue}else if(x.action){this.maybeWarnRepeatedAction(x.action.tool,x.action.input);let b=T[0]?.id??`${o}:${g}:single:${x.action.tool}`;await this.emitEvent("action",{turn:o,step:g,meta:{tool:x.action.tool,input:x.action.input,action_id:b,phase:"dispatch",thinking:x.thinking}}),await X(this.hooks,"onAction",{sessionId:this.id,turn:o,step:g,action:x.action,thinking:x.thinking,history:qe(this.history)});let k=await this.executeToolAction(b,x.action.tool,x.action.input,o,g);if(k.rejected){this.history.push(Tr({...k,observation:k.observation||`User denied tool execution: ${x.action.tool}`})),u="cancelled",c="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:o,step:g,content:c,role:"assistant",meta:{rejected:!0,phase:"result",action_id:k.actionId,error_type:k.errorType??"approval_denied",duration_ms:k.durationMs}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:c,status:u,tokenUsage:U,turnUsage:{...s},steps:r});break}let q=k.observation;this.history.push({role:"tool",content:q,tool_call_id:k.actionId,name:x.action.tool});let oe=r[r.length-1];oe&&(oe.observation=q),await this.emitEvent("observation",{turn:o,step:g,content:q,meta:{tool:x.action.tool,action_id:k.actionId,phase:"result",status:k.status,error_type:k.errorType,duration_ms:k.durationMs}}),await X(this.hooks,"onObservation",{sessionId:this.id,turn:o,step:g,tool:x.action.tool,observation:q,resultStatus:k.status,history:qe(this.history)});continue}if(J==="end_turn"||x.final){this.resetActionRepetition();let b=J==="end_turn"&&!x.final&&_.trim().length===0&&!!h&&S===g-1;c=b?h??"":x.final||_,x.final&&(x.final=c),await this.emitEvent("final",{turn:o,step:g,content:c,role:"assistant",meta:{tokens:U,fallback_from_previous_text:b||void 0}}),await X(this.hooks,"onFinal",{sessionId:this.id,turn:o,step:g,finalText:c,status:u,tokenUsage:U,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 X(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:d||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(t,n){if(!this.sinks.length)return;let o=qn({sessionId:this.id,type:t,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await _c(o,this.sinks)}};async function At(e,t={}){let n=t.sessionId||Sr(),o=await cr(e,{...t,sessionId:n},n),r=await o.loadPrompt(),s=new Sn({...e,...o},{...t,sessionId:n,mode:t.mode??_r},r,o.tokenCounter,o.historyFilePath);return await s.init(),s}import{randomUUID as Fe}from"crypto";import{readFile as Ju}from"fs/promises";import{useCallback as K,useEffect as Tt,useMemo as zt,useReducer as Yu,useRef as qt,useState as Y}from"react";import{Box as is,Text as Zu,useApp as Qu}from"ink";import{memo as Rc,useMemo as Ic}from"react";import{Box as Rr,Static as Oc,Text as Pt}from"ink";import{Box as Re,Text as Z}from"ink";var Me={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import Ge from"path";var wc="success",ct=".";function _n(e){return e?e===wc?Me.SUCCESS:Me.ERROR:Me.SUCCESS}function xr(e){if(e?.length)return e.map(t=>_n(t))}function br(e,t){return!t||t<=0||!e||e<=0?0:Math.min(100,e/t*100)}function Cr(e){return e?`tokens: ${e.total} (prompt ${e.prompt} / completion ${e.completion})`:""}function ut(e,t=80){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function Er(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function vn(e,t){let n=e.trim();if(!n)return e;if(n===ct)return ct;if(Ge.isAbsolute(n)){let o=Ge.relative(Ge.resolve(t),n);return o?Ge.normalize(o):ct}if(n.startsWith("./")||n.startsWith("../")){let o=Ge.normalize(n);return!o||o==="."||o==="./"?ct:o}return n}function wr(e){return e?e===ct||Ge.isAbsolute(e)?!0:e.startsWith("./")||e.startsWith("../"):!1}import{Box as Ve,Text as Pe}from"ink";import{marked as Mc}from"marked";import{jsx as ke,jsxs as Ke}from"react/jsx-runtime";function kc(e){let t=[],n=Mc.lexer(e);for(let o of n)switch(o.type){case"heading":{let r=o;t.push({type:"heading",level:r.depth,content:r.text});break}case"paragraph":{let s=o.text;s.startsWith("> ")?t.push({type:"blockquote",content:s.slice(2)}):t.push({type:"paragraph",content:s});break}case"code":{let r=o;t.push({type:"code",language:r.lang,content:r.text});break}case"list":{let r=o,s=r.items.map(i=>i.text);t.push({type:"list",items:s,ordered:r.ordered});break}case"text":{let r=o;t.push({type:"text",content:r.text});break}}return t}function Mr({content:e}){if(!e)return null;let t=kc(e);return ke(Ve,{flexDirection:"column",children:t.map((n,o)=>ke(Ac,{node:n},o))})}function Ac({node:e}){switch(e.type){case"heading":{let t="#".repeat(e.level);return ke(Ve,{children:Ke(Pe,{bold:!0,color:"cyan",children:[t," ",e.content]})})}case"paragraph":case"text":return ke(Pe,{children:e.content});case"code":{let t=e.language?`[${e.language}] `:"";return Ke(Ve,{flexDirection:"column",marginY:1,children:[Ke(Pe,{color:"yellow",dimColor:!0,children:[t,"```"]}),ke(Pe,{color:"gray",children:e.content}),ke(Pe,{color:"yellow",dimColor:!0,children:"```"})]})}case"blockquote":return ke(Ve,{children:Ke(Pe,{color:"gray",dimColor:!0,children:["\u2502 ",e.content]})});case"list":return ke(Ve,{flexDirection:"column",children:e.items.map((t,n)=>Ke(Ve,{children:[ke(Pe,{color:"gray",children:e.ordered?`${n+1}.`:"\u2022"}),Ke(Pe,{children:[" ",t]})]},n))})}}import{jsx as ne,jsxs as de}from"react/jsx-runtime";function kr(e){return e===Me.ERROR?"red":e===Me.EXECUTING?"yellow":"green"}function Ar(e,t){if(e==null)return null;if(typeof e=="string"){let s=wr(e)?vn(e,t):e;return ut(s,70)}if(typeof e!="object"||Array.isArray(e))return ut(String(e),70);let n=e,o=["cmd","path","file_path","dir_path","query","pattern","url","content"],r=new Set(["path","file_path","dir_path"]);for(let s of o){let i=n[s];if(i==null||i==="")continue;let a=String(i),l=r.has(s)?vn(a,t):a;return ut(l,70)}return ut(Er(n),70)}function Pr({message:e}){let t=e.tone==="error"?"red":e.tone==="warning"?"yellow":"cyan";return de(Re,{flexDirection:"column",children:[de(Z,{color:t,children:["\u25CF ",e.title]}),ne(Z,{color:"gray",children:e.content})]})}function Pc({step:e,cwd:t}){let n=!!(e.parallelActions&&e.parallelActions.length>1),o=!n&&e.action?Ar(e.action.input,t):null;return de(Re,{flexDirection:"column",children:[e.thinking?de(Re,{children:[ne(Z,{color:"gray",children:"\u25CF "}),ne(Z,{color:"gray",children:e.thinking})]}):null,n?e.parallelActions?.map((r,s)=>{let i=Ar(r.input,t);return de(Re,{children:[de(Z,{color:kr(e.parallelToolStatuses?.[s]??e.toolStatus),children:["\u25CF"," "]}),ne(Z,{color:"gray",children:"Used "}),ne(Z,{color:"cyan",children:r.tool}),i?de(Z,{color:"gray",children:[" (",i,")"]}):null]},`${r.tool}-${s}`)}):null,!n&&e.action?de(Re,{children:[ne(Z,{color:kr(e.toolStatus),children:"\u25CF "}),ne(Z,{color:"gray",children:"Used "}),ne(Z,{color:"cyan",children:e.action.tool}),o?de(Z,{color:"gray",children:[" (",o,")"]}):null]}):null]})}function xn({turn:e,cwd:t}){return de(Re,{flexDirection:"column",children:[de(Re,{children:[ne(Z,{color:"gray",children:"\u203A "}),ne(Z,{children:e.userInput})]}),e.steps.map(n=>ne(Pc,{step:n,cwd:t},`${e.index}-${n.index}`)),e.finalText?ne(Re,{marginTop:0,children:ne(Mr,{content:e.finalText})}):null,e.status&&e.status!=="ok"?de(Z,{color:"red",children:["Status: ",e.status]}):null,e.errorMessage?ne(Z,{color:"red",children:e.errorMessage}):null]})}import{jsx as pt,jsxs as dt}from"react/jsx-runtime";var Ir=Rc(function({header:t,systemMessages:n,turns:o,historicalTurns:r}){let s=Ic(()=>[...r,...o],[r,o]),i=s.length>0?s[s.length-1]:void 0,a=i&&!!(i.finalText||i.status&&i.status!=="ok"),l=a?s:s.slice(0,-1),c=a?void 0:i,u=[{type:"header",data:t}],p=[...n.map(d=>({type:"system",sequence:d.sequence,data:d})),...l.map(d=>({type:"turn",sequence:d.sequence??0,data:d}))].sort((d,h)=>d.sequence-h.sequence);for(let d of p)u.push(d);return dt(Rr,{flexDirection:"column",children:[pt(Oc,{items:u,children:d=>d.type==="header"?dt(Rr,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[pt(Pt,{bold:!0,children:"Memo CLI"}),dt(Pt,{color:"gray",children:[d.data.providerName," / ",d.data.model," \u2022 v",d.data.version]}),dt(Pt,{color:"gray",children:["cwd: ",d.data.cwd]}),dt(Pt,{color:"gray",children:["mcp: ",d.data.mcpNames.join(", ")||"none"]})]},"header"):d.type==="system"?pt(Pr,{message:d.data},d.data.id):pt(xn,{turn:d.data,cwd:t.cwd},`turn-${d.data.index}`)}),c?pt(xn,{turn:c,cwd:t.cwd}):null]})});import{useCallback as Dt,useEffect as bn,useMemo as Br,useRef as Cn,useState as Ie}from"react";import{Box as Ut,Text as Je,useInput as uu}from"ink";var Xe=[8e4,12e4,15e4,2e5],Or=Xe[1],P={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",MODELS:"models",CONTEXT:"context",TOOLS:"tools",MCP:"mcp",INIT:"init"},I={NONE:"none",ONCE:"once",FULL:"full"};function ae(e){return`/${e}`}var Lr="exit";var Rt=[{name:P.HELP,description:"Show command and shortcut help"},{name:P.EXIT,description:"Exit current session"},{name:P.NEW,description:"Start a fresh session"},{name:P.RESUME,description:"List and load session history"},{name:P.MODELS,description:"List or switch configured models"},{name:P.CONTEXT,description:"Set context window (80k/120k/150k/200k)"},{name:P.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:P.MCP,description:"Show configured MCP servers"},{name:P.INIT,description:"Generate AGENTS.md with agent instructions"}],Lc={none:I.NONE,off:I.NONE,disabled:I.NONE,"no-tools":I.NONE,once:I.ONCE,ask:I.ONCE,single:I.ONCE,strict:I.ONCE,full:I.FULL,all:I.FULL,dangerous:I.FULL,"full-access":I.FULL};function $c(e){if(!e)return null;let t=e.trim().toLowerCase();return t?Lc[t]??null:null}function $r(e){return e===I.NONE?"none (no tools)":e===I.ONCE?"once (approval required)":"full (no approval)"}function Nc(){let e=Rt.reduce((n,o)=>Math.max(n,o.name.length),0);return["Available commands:",...Rt.map(n=>` ${ae(n.name).padEnd(e+3)} ${n.description}`)," exit Exit session (without slash)","","Shortcuts:"," Enter Send message"," Shift+Enter New line"," Up/Down Browse local input history"," Tab Accept active suggestion"," Ctrl+L Clear screen and start new session"," Esc Esc Interrupt running turn / clear input"].join(`
|
|
96
|
+
`)}function Dc(e){if(!e)return null;let n=e.toLowerCase().replace(/,/g,"").match(/^(\d+)(k)?$/);if(!n)return null;let o=Number(n[1]);return Number.isFinite(o)?o*(n[2]?1e3:1):null}function Nr(e,t){let[n,...o]=e.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case P.HELP:return{kind:"message",title:"Help",content:Nc()};case P.EXIT:return{kind:"exit"};case P.NEW:return{kind:"new"};case P.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case P.MODELS:{if(!t.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${t.configPath}`};let s=o.join(" ").trim(),i=t.providers.find(c=>c.name===s)??t.providers.find(c=>c.model===s);if(i)return{kind:"switch_model",provider:i};let a=t.providers.map(c=>{let u=c.name===t.providerName&&c.model===t.model?" (current)":"",p=c.base_url?` @ ${c.base_url}`:"";return`- ${c.name}: ${c.model}${p}${u}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
|
|
97
|
+
|
|
98
|
+
`:""}${a.join(`
|
|
99
|
+
`)}`}}case P.CONTEXT:{let s=Dc(o[0]),i=Xe.map(a=>`${Math.floor(a/1e3)}k`).join(", ");return s===null?{kind:"message",title:"Context",content:`Current: ${(t.contextLimit/1e3).toFixed(0)}k
|
|
100
|
+
Usage: ${ae(P.CONTEXT)} <length>
|
|
101
|
+
Choices: ${i}`}:Xe.includes(s)?{kind:"set_context_limit",limit:s}:{kind:"message",title:"Context",content:`Unsupported value: ${s}. Choose one of ${i}`}}case P.TOOLS:{let s=o.join(" ").trim(),i=$c(s),a=["none","once","full"].join(", ");return s?i?i===t.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${$r(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
|
|
102
|
+
Choose one of: ${a}`}:{kind:"message",title:"Tools",content:`Current: ${$r(t.toolPermissionMode)}
|
|
103
|
+
Usage: ${ae(P.TOOLS)} <mode>
|
|
104
|
+
Modes: ${a}`}}case P.MCP:{let s=Object.keys(t.mcpServers);if(!s.length)return{kind:"message",title:"MCP Servers",content:"No MCP servers configured in current config."};let i=[];i.push(`Total: ${s.length}`),i.push("");for(let[a,l]of Object.entries(t.mcpServers))i.push(`- ${a}`),"url"in l?(i.push(` type: ${l.type??"streamable_http"}`),i.push(` url: ${l.url}`),l.bearer_token_env_var&&i.push(` bearer: ${l.bearer_token_env_var}`)):(i.push(` type: ${l.type??"stdio"}`),i.push(` command: ${l.command}`),l.args?.length&&i.push(` args: ${l.args.join(" ")}`)),i.push("");return{kind:"message",title:"MCP Servers",content:i.join(`
|
|
105
|
+
`)}}case P.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${e}
|
|
106
|
+
Type ${ae(P.HELP)} for available commands.`}}}import{readdir as Uc}from"fs/promises";import{join as Hc,relative as Fc,sep as jc}from"path";var Bc=6,Wc=2500,Dr=25,zc=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),It=new Map;function qc(e){return e.split(jc).join("/")}function Gc(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):Bc,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):Wc,limit:typeof e.limit=="number"?Math.max(1,e.limit):Dr,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}function Kc(e,t){let n=e.split("/").filter(Boolean),o=n[n.length-1]??"";return n.some(r=>zc.has(r))||o.endsWith(".log")?!0:t.ignoreGlobs.length?t.ignoreGlobs.some(r=>{let s=r.replace(/\\/g,"/").trim();if(!s)return!1;if(s.endsWith("/**")){let i=s.slice(0,-3);return e.startsWith(i)}if(s.startsWith("*")){let i=s.slice(1);return e.endsWith(i)}return e.includes(s)}):!1}function Vc(e){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,ignoreGlobs:e.ignoreGlobs})}async function Xc(e,t){let n=[],o=async(r,s)=>{if(n.length>=t.maxEntries)return;let i;try{i=await Uc(r,{withFileTypes:!0})}catch{return}for(let a of i){if(n.length>=t.maxEntries)break;if(a.isSymbolicLink())continue;let l=Hc(r,a.name),c=Fc(e,l);if(!c)continue;let u=qc(c);if(Kc(u,t))continue;let p=u.split("/").filter(Boolean),d=a.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:p,segmentsLower:p.map(h=>h.toLowerCase()),depth:s,isDir:d}),d&&s<t.maxDepth&&await o(l,s+1)}};return await o(e,0),n.sort((r,s)=>r.path.localeCompare(s.path)),n}async function Jc(e,t){let n=Gc(t),o=Vc(n),r=It.get(e);if(r&&r.signature===o)return r.pending?r.pending:r.entries;let s=Xc(e,n).then(i=>(It.set(e,{entries:i,signature:o}),i)).catch(i=>{throw It.delete(e),i});return It.set(e,{entries:[],signature:o,pending:s}),s}function Yc(e,t){if(!t.length)return e.depth+(e.isDir?-.2:.2);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.2,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 e.isDir&&(n-=.5),n}function Zc(e,t,n){let r=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of e){let a=Yc(i,r);a!==null&&s.push({entry:i,score:a})}return s.sort((i,a)=>{let l=i.score-a.score;return l!==0?l:i.entry.path.localeCompare(a.entry.path)}),s.slice(0,n).map(({entry:i})=>({id:i.path,path:i.path,name:i.segments[i.segments.length-1]??i.path,parent:i.segments.length>1?i.segments.slice(0,-1).join("/"):void 0,isDir:i.isDir}))}async function Ur(e){let t=await Jc(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):Dr;return Zc(t,e.query,n)}import{readdir as Qc,readFile as eu,stat as tu}from"fs/promises";import{basename as nu,join as Ot,resolve as mt}from"path";function Hr(e){let t=mt(e);return process.platform==="win32"?t.toLowerCase():t}function ou(e,t){return t?Hr(e)===Hr(t):!1}function ru(e){return nu(e).replace(/\.jsonl$/i,"")}function su(e){let t=null,n=null,o=null;for(let r of e.split(`
|
|
107
|
+
`)){let s=r.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!(!i||typeof i!="object")){if(i.type==="session_start"&&!o){let a=i.meta?.cwd;typeof a=="string"&&a.trim()&&(o=a);continue}if(i.type==="turn_start"&&!t){let a=typeof i.content=="string"?i.content.trim():"";a&&(t=a)}if(i.type==="session_title"&&!n){let a=typeof i.content=="string"?i.content.trim():"";a&&(n=a)}}}return{firstPrompt:t,sessionTitle:n,sessionCwd:o}}async function iu(e,t,n){try{let o=await eu(e,"utf8"),{firstPrompt:r,sessionTitle:s,sessionCwd:i}=su(o);if(!ou(t,i))return null;let a=s?.trim()||r?.trim()||ru(e);return{id:e,cwd:t,input:a,ts:n,sessionFile:e}}catch{return null}}async function au(e){let t=async s=>{try{return await Qc(s,{withFileTypes:!0})}catch{return[]}},n=(await t(e)).filter(s=>s.isDirectory()&&/^\d{4}$/.test(s.name)),o=[];for(let s of n){let i=Ot(e,s.name),a=(await t(i)).filter(l=>l.isDirectory()&&/^\d{2}$/.test(l.name));for(let l of a){let c=Ot(i,l.name),u=(await t(c)).filter(p=>p.isDirectory()&&/^\d{2}$/.test(p.name));for(let p of u){let d=Ot(c,p.name),h=(await t(d)).filter(S=>S.isFile()&&S.name.endsWith(".jsonl"));for(let S of h)o.push(Ot(d,S.name))}}}return(await Promise.all(o.map(async s=>{try{let i=await tu(s);return{path:s,mtimeMs:i.mtimeMs}}catch{return null}}))).filter(s=>!!s)}async function Fr(e){let t=e.activeSessionFile?mt(e.activeSessionFile):null,o=(await au(e.sessionsDir)).filter(a=>!t||mt(a.path)!==t).filter((a,l,c)=>c.findIndex(u=>mt(u.path)===mt(a.path))===l).sort((a,l)=>l.mtimeMs-a.mtimeMs),r=e.keyword?.trim().toLowerCase(),s=e.limit??10,i=[];for(let a of o){if(i.length>=s)break;let l=await iu(a.path,e.cwd,a.mtimeMs);l&&(r&&!l.input.toLowerCase().includes(r)||i.push(l))}return i}import{Box as Lt,Text as $t}from"ink";import{jsx as Ue,jsxs as cu}from"react/jsx-runtime";var lu="#3a3a3a",Nt="#262626";function jr({items:e,activeIndex:t,loading:n}){return n?Ue(Lt,{paddingX:1,backgroundColor:Nt,children:Ue($t,{color:"gray",children:"Loading..."})}):e.length?Ue(Lt,{flexDirection:"column",backgroundColor:Nt,children:e.map((o,r)=>{let s=r===t;return cu(Lt,{paddingX:1,gap:2,backgroundColor:s?lu:Nt,children:[Ue($t,{color:s?"cyan":"white",bold:s,children:o.title}),o.subtitle?Ue($t,{color:"gray",children:o.subtitle}):null]},o.id)})}):Ue(Lt,{paddingX:1,backgroundColor:Nt,children:Ue($t,{color:"gray",children:"No matches"})})}import{jsx as He,jsxs as Ht}from"react/jsx-runtime";var pu=400,En=ae(P.MODELS),wn=ae(P.CONTEXT),Mn=ae(P.TOOLS),du=ae(P.INIT),mu=[{mode:I.NONE,description:"Disable all tool calls"},{mode:I.ONCE,description:"Require approval when needed"},{mode:I.FULL,description:"Run tools without approval"}];function fu(e){let t=e.lastIndexOf("@");if(t===-1)return null;if(t>0){let o=e[t-1];if(o&&!/\s/.test(o))return null}let n=e.slice(t+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:t+1}}function gu(e){let t=e.trimStart(),n=e.length-t.length;if(!t.length)return null;let o=t;if(o.startsWith("/")&&(o=o.slice(1)),!o.toLowerCase().startsWith(P.RESUME)||e.slice(0,n).trim().length>0)return null;let s=o.slice(P.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function hu(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1);return n.includes(" ")?null:n.length?/^[a-zA-Z-]+$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:null:{type:"slash",keyword:""}}function yu(e){let t=e.trimStart();if(!t.startsWith(En))return null;let n=t.slice(En.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function Tu(e){let t=e.trimStart();if(!t.startsWith(wn))return null;let n=t.slice(wn.length);return n&&!n.startsWith(" ")?null:{type:"context"}}function Su(e){let t=e.trimStart();if(!t.startsWith(Mn))return null;let n=t.slice(Mn.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function _u(e){return Su(e)??Tu(e)??yu(e)??hu(e)??fu(e)??gu(e)}function vu(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getFullYear()),o=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${r} ${s}:${i}`}function xu(e,t){return{mode:"model",items:e.filter(o=>{if(!t)return!0;let r=o.name.toLowerCase(),s=o.model.toLowerCase();return r.includes(t)||s.includes(t)}).map(o=>({id:o.name,title:`${o.name}: ${o.model}`,subtitle:o.base_url,kind:"model",value:`${En} ${o.name}`,meta:{type:"model",provider:o}}))}}function bu(e){return{mode:"context",items:Xe.map(n=>({id:`${n}`,title:`${Math.floor(n/1e3)}k tokens`,subtitle:n===e?"Current":void 0,kind:"context",value:`${wn} ${Math.floor(n/1e3)}k`,meta:{type:"context",value:n}}))}}function Cu(e){return{mode:"tools",items:mu.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===e?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${Mn} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function Eu(e){return{mode:"slash",items:Rt.filter(n=>n.name.startsWith(e)).map(n=>({id:n.name,title:`/${n.name}`,subtitle:n.description,kind:"slash",value:`/${n.name}`,meta:{type:"slash"}}))}}async function wu({trigger:e,cwd:t,sessionsDir:n,currentSessionFile:o,providers:r,contextLimit:s,toolPermissionMode:i}){switch(e.type){case"file":return{mode:"file",items:(await Ur({cwd:t,query:e.query,limit:8})).map(c=>({id:c.id,title:c.isDir?`${c.path}/`:c.path,kind:"file",value:c.isDir?`${c.path}/`:c.path,meta:{type:"file",isDir:c.isDir}}))};case"history":return{mode:"history",items:(await Fr({sessionsDir:n,cwd:t,keyword:e.keyword,activeSessionFile:o})).map(c=>({id:c.id,title:c.input,subtitle:vu(c.ts),kind:"history",value:c.input,meta:{type:"history",entry:c}}))};case"models":return xu(r,e.keyword);case"context":return bu(s);case"tools":return Cu(i);case"slash":return Eu(e.keyword)}}function Wr({disabled:e,busy:t,history:n,cwd:o,sessionsDir:r,currentSessionFile:s,providers:i,configPath:a,providerName:l,model:c,contextLimit:u,toolPermissionMode:p,mcpServers:d,onSubmit:h,onExit:S,onClear:g,onNewSession:E,onCancelRun:_,onHistorySelect:T,onModelSelect:D,onSetContextLimit:J,onSetToolPermission:W,onSystemMessage:j}){let[x,N]=Ie(""),C=Cn(""),[B,O]=Ie(null),[me,U]=Ie(""),[b,k]=Ie("none"),[q,oe]=Ie([]),[Se,fe]=Ie(0),[je,re]=Ie(!1),[_e,$e]=Ie(!1),v=Cn(0),V=Cn(0);bn(()=>{C.current=x,$e(!1)},[x]);let Gt=Br(()=>({configPath:a,providerName:l,model:c,mcpServers:d,providers:i,contextLimit:u,toolPermissionMode:p}),[a,l,c,d,i,u,p]),ge=Br(()=>e||_e?null:_u(x),[e,_e,x]),z=Dt((w=!0)=>{w&&$e(!0),k("none"),oe([]),fe(0),re(!1)},[]),xe=Dt(w=>{C.current=w,N(w),O(null),U("")},[]),G=Dt(()=>{xe("")},[xe]);bn(()=>{e&&z(!1)},[e,z]),bn(()=>{if(!ge){z(!1);return}let w=!1,H=++v.current;return re(!0),(async()=>{try{let{mode:te,items:se}=await wu({trigger:ge,cwd:o,sessionsDir:r,currentSessionFile:s,providers:i,contextLimit:u,toolPermissionMode:p});if(w||H!==v.current)return;k(te),oe(se),fe(L=>se.length?Math.min(L,se.length-1):0)}finally{!w&&H===v.current&&re(!1)}})(),()=>{w=!0}},[ge,o,r,s,i,u,p,z]);let Qe=Dt(w=>{if(w){if(b==="file"&&ge?.type==="file"){let H=x.slice(0,ge.tokenStart),te=x.slice(ge.tokenStart+ge.query.length),se=`${H}${w.value}${te}`;xe(se),w.meta?.type==="file"&&w.meta.isDir||z();return}switch(w.meta?.type){case"history":T(w.meta.entry),xe(w.value),z();return;case"model":D(w.meta.provider),G(),z();return;case"context":J(w.meta.value),G(),z();return;case"tools":W(w.meta.mode),G(),z();return;case"slash":xe(`${w.value} `),z(!1);return;default:xe(w.value),z()}}},[b,ge,x,z,xe,G,T,D,J,W]);uu((w,H)=>{if(H.ctrl&&w==="c"){S();return}if(H.ctrl&&w==="l"){C.current="",N(""),O(null),U(""),z(),g(),E();return}let te=b!=="none",se=te&&q.length>0;if(H.escape){let L=Date.now();if(L-V.current<=pu){V.current=0,t?_():(C.current="",N(""),O(null),U(""),z());return}V.current=L,te&&z();return}if(!e){if(H.upArrow){if(se){fe($=>$<=0?q.length-1:$-1);return}if(!n.length)return;if(B===null){U(C.current);let $=n.length-1;O($);let R=n[$]??"";C.current=R,N(R);return}let L=Math.max(0,B-1);O(L);let F=n[L]??"";C.current=F,N(F);return}if(H.downArrow){if(se){fe($=>($+1)%q.length);return}if(B===null)return;let L=B+1;if(L>=n.length){O(null),C.current=me,N(me),U("");return}O(L);let F=n[L]??"";C.current=F,N(F);return}if(H.tab&&se){Qe(q[Se]);return}if(H.return){if(se){Qe(q[Se]);return}if(H.shift){let F=`${C.current}
|
|
108
|
+
`;C.current=F,N(F);return}let L=C.current.trim();if(!L)return;if(L.startsWith("/")){let F=Nr(L,Gt);F.kind==="message"?j(F.title,F.content):F.kind==="new"?E():F.kind==="exit"?S():F.kind==="switch_model"?D(F.provider):F.kind==="set_context_limit"?J(F.limit):F.kind==="set_tool_permission"?W(F.mode):F.kind==="init_agents_md"&&h(du),C.current="",N(""),O(null),U(""),z(!1);return}h(L),C.current="",N(""),O(null),U(""),z(!1);return}if(H.backspace||H.delete){let L=C.current.slice(0,Math.max(0,C.current.length-1));C.current=L,N(L);return}if(w){let L=`${C.current}${w}`;C.current=L,N(L),w.includes(`
|
|
109
|
+
`)&&z(!1)}}});let he=x.split(`
|
|
110
|
+
`);return Ht(Ut,{flexDirection:"column",gap:1,children:[Ht(Ut,{flexDirection:"column",paddingY:1,children:[Ht(Ut,{children:[He(Je,{color:"gray",children:"\u203A "}),He(Je,{children:he[0]??""}),!e&&he.length===1?He(Je,{color:"cyan",children:"\u258A"}):null]}),he.slice(1).map((w,H)=>Ht(Ut,{children:[He(Je,{color:"gray",children:" "}),He(Je,{children:w}),H===he.length-2&&!e&&w===""?He(Je,{color:"cyan",children:"\u258A"}):null]},`line-${H}`))]}),b!=="none"?He(jr,{items:q.map(({value:w,meta:H,...te})=>te),activeIndex:Se,loading:je}):null]})}import{Box as Mu,Text as zr}from"ink";import{jsx as ku,jsxs as qr}from"react/jsx-runtime";function Gr({busy:e,contextPercent:t,tokenLine:n}){let o=`${t.toFixed(1)}%`;return qr(Mu,{justifyContent:"space-between",children:[ku(zr,{color:"gray",children:e?"Working... Esc Esc to interrupt":"Enter send \u2022 Shift+Enter newline \u2022 /help"}),qr(zr,{color:"gray",children:[n?`${n} \u2022 `:"","context: ",o]})]})}import{useState as Au}from"react";import{Box as Kr,Text as Ft,useInput as Pu}from"ink";import{jsx as kn,jsxs as An}from"react/jsx-runtime";var Ru=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function Iu(e){if(!e)return"";if(typeof e!="object")return String(e);let t=Object.entries(e);if(!t.length)return"";let[n,o]=t[0]??[];if(!n)return"";let r=typeof o=="string"?o:JSON.stringify(o);return`${n}=${r?.slice(0,60)??""}${r&&r.length>60?"...":""}`}function Vr({request:e,onDecision:t}){let[n,o]=Au(0),r=Ru;Pu((i,a)=>{if(a.upArrow){o(l=>l<=0?r.length-1:l-1);return}if(a.downArrow){o(l=>(l+1)%r.length);return}if(a.return){let l=r[n];l&&t(l.decision);return}(a.escape||a.ctrl&&i==="c")&&t("deny")});let s=Iu(e.params);return An(Kr,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[kn(Ft,{bold:!0,color:"yellow",children:"Tool Approval Required"}),An(Ft,{children:[e.toolName,s?` (${s})`:""]}),kn(Ft,{color:"gray",children:e.reason}),kn(Kr,{marginTop:1,flexDirection:"column",children:r.map((i,a)=>An(Ft,{color:n===a?"green":"gray",children:[n===a?"> ":" ",i.label]},i.decision))})]})}import{useMemo as Xr,useState as Pn}from"react";import{Box as Rn,Text as Ye,useInput as Ou}from"ink";import{jsx as jt,jsxs as ft}from"react/jsx-runtime";function Lu(e,t){let n=new Set(e);return t.filter(o=>n.has(o))}function Jr({serverNames:e,defaultSelected:t,onConfirm:n,onExit:o}){let r=Xr(()=>{let h=Lu(e,t);return t.length===0?[]:h.length>0?h:[...e]},[t,e]),[s,i]=Pn(r),[a,l]=Pn(0),[c,u]=Pn(!0),p=Xr(()=>new Set(s),[s]),d=s.length===e.length;return Ou((h,S)=>{if(S.ctrl&&h==="c"){o();return}if(S.upArrow){l(g=>g<=0?e.length-1:g-1);return}if(S.downArrow){l(g=>(g+1)%e.length);return}if(S.return){n(s,c);return}if(h===" "){let g=e[a];if(!g)return;i(E=>{let _=new Set(E);return _.has(g)?_.delete(g):_.add(g),e.filter(T=>_.has(T))});return}if(h.toLowerCase()==="a"){i([...e]);return}if(h.toLowerCase()==="n"){i([]);return}if(h.toLowerCase()==="p"){u(g=>!g);return}S.escape&&n(s,c)}),ft(Rn,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jt(Ye,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),jt(Ye,{color:"gray",children:"Select servers to load for this run."}),jt(Rn,{marginTop:1,flexDirection:"column",children:e.map((h,S)=>{let g=p.has(h);return ft(Ye,{color:S===a?"green":"gray",children:[S===a?"> ":" ","[",g?"x":" ","] ",h]},h)})}),ft(Rn,{marginTop:1,flexDirection:"column",children:[ft(Ye,{color:"gray",children:["Selected: ",s.length,"/",e.length,d?" (all)":""]}),ft(Ye,{color:"gray",children:["Persist as default: ",c?"yes":"no"]}),jt(Ye,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, A all, N none, P persist, Enter confirm"})]})]})}import{Box as gt,Text as Te,useInput as $u}from"ink";import{useCallback as Yr,useMemo as Nu,useState as ht}from"react";import{jsx as ve,jsxs as Ze}from"react/jsx-runtime";var Oe=[{key:"name",label:"Provider name",hint:"Used for /models switching",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Read at runtime from environment variables",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",defaultValue:"https://api.deepseek.com"}];function Zr({configPath:e,onComplete:t,onExit:n}){let[o,r]=ht(0),[s,i]=ht(""),[a,l]=ht({}),[c,u]=ht(!1),[p,d]=ht(null),h=Oe[o]??Oe[0],S=Yr(async _=>{u(!0),d(null);try{let T={current_provider:_.name,providers:[{name:_.name,env_api_key:_.envKey,model:_.model,base_url:_.baseUrl||void 0}]};await pe(e,T),t()}catch(T){d(T.message),u(!1)}},[e,t]),g=Yr(async()=>{if(!h)return;let _=s.trim()||h.defaultValue,T={...a,[h.key]:_};if(l(T),i(""),o<Oe.length-1){r(o+1);return}let D={name:T.name||Oe[0].defaultValue,envKey:T.envKey||Oe[1].defaultValue,model:T.model||Oe[2].defaultValue,baseUrl:T.baseUrl||Oe[3].defaultValue};await S(D)},[s,S,h,o,a]);$u((_,T)=>{if(!c){if(T.ctrl&&_==="c"){n();return}if(T.return){g();return}if(T.backspace||T.delete){i(D=>D.slice(0,-1));return}_&&i(D=>D+_)}});let E=Nu(()=>`Step ${o+1}/${Oe.length}`,[o]);return h?Ze(gt,{flexDirection:"column",children:[ve(Te,{bold:!0,children:"Memo setup"}),ve(Te,{color:"gray",children:"No provider config found. Complete setup to continue."}),Ze(Te,{color:"gray",children:["Config path: ",e]}),Ze(gt,{marginTop:1,flexDirection:"column",children:[ve(Te,{color:"cyan",children:E}),ve(Te,{children:h.label}),Ze(Te,{color:"gray",children:["Default: ",h.defaultValue]}),h.hint?ve(Te,{color:"gray",children:h.hint}):null]}),Ze(gt,{marginTop:1,children:[ve(Te,{children:"> "}),ve(Te,{children:s})]}),ve(gt,{marginTop:1,children:ve(Te,{color:"gray",children:"Enter to continue, Ctrl+C to exit."})}),p?ve(gt,{marginTop:1,children:Ze(Te,{color:"red",children:["Failed to save config: ",p]})}):null]}):null}function Qr(e){let t=[],n=[],o=[],r=e.split(`
|
|
111
|
+
`).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&&(t.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&&(t.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:"",d=u.input,h=typeof u.thinking=="string"?u.thinking:"",g=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(_=>{let T=typeof _?.name=="string"?_.name:"";return T?{tool:T,input:_?.input}:null}).filter(Boolean),E=s.steps[s.steps.length-1];E&&(g.length>1?(E.action=g[0],E.parallelActions=g):p&&(E.action={tool:p,input:d}),h&&(E.thinking=h))}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(`
|
|
112
|
+
`),messages:t,turns:n,maxSequence:a}}function On(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function Du(e,t){return{index:e,userInput:"",steps:[],sequence:t}}function In(e,t){let n=e.slice();for(;n.length<=t;)n.push({index:n.length,assistantText:""});return n}function yt(e,t,n){let o=e.turns.slice(),r=o.findIndex(i=>i.index===t);if(r===-1){let i=e.sequence+1;return o.push(n(Du(t,i))),{turns:o,sequence:i}}let s=o[r];return s?(o[r]=n(s),{turns:o,sequence:e.sequence}):{turns:o,sequence:e.sequence}}function Uu(e){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:e.title,content:e.content,tone:e.tone??"info",sequence:e.sequence}}function es(e,t){switch(t.type){case"append_system_message":{let n=e.sequence+1;return{...e,sequence:n,systemMessages:[...e.systemMessages,Uu({title:t.title,content:t.content,tone:t.tone,sequence:n})]}}case"turn_start":{let n=yt(e,t.turn,o=>({...o,index:t.turn,userInput:t.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:t.promptTokens??o.contextPromptTokens}));return{...e,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=yt(e,t.turn,o=>{let r=In(o.steps,t.step),s=r[t.step];return s?(r[t.step]={...s,assistantText:`${s.assistantText}${t.chunk}`},{...o,steps:r}):o});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=yt(e,t.turn,o=>{let r=In(o.steps,t.step),s=r[t.step];return s?(r[t.step]={...s,action:t.action,thinking:t.thinking,parallelActions:t.parallelActions&&t.parallelActions.length>1?t.parallelActions:void 0,toolStatus:Me.EXECUTING},{...o,steps:r}):o});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=yt(e,t.turn,o=>{let r=In(o.steps,t.step),s=r[t.step];return s?(r[t.step]={...s,observation:t.observation,toolStatus:t.toolStatus,parallelToolStatuses:t.parallelToolStatuses},{...o,steps:r}):o});return{...e,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=yt(e,t.turn,o=>{let r=o.startedAt??Date.now(),s=Math.max(0,Date.now()-r),i=t.tokenUsage?.prompt??o.contextPromptTokens;return{...o,finalText:t.finalText,status:t.status,errorMessage:t.errorMessage,tokenUsage:t.turnUsage,contextPromptTokens:i,startedAt:r,durationMs:s}});return{...e,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...e,historicalTurns:t.turns,sequence:Math.max(e.sequence,t.maxSequence)};case"clear_current_timeline":return{...e,turns:[],systemMessages:[]};case"reset_all":return On();default:return e}}import{dirname as Bt,join as ns,resolve as Hu}from"path";import{statSync as Fu,existsSync as os,readFileSync as ju}from"fs";import{readFile as Bu}from"fs/promises";import{get as Wu}from"https";import{fileURLToPath as zu}from"url";function ts(e){let t=e.trim().replace(/^v/i,""),[n="",o]=t.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 qu(e,t){let n=ts(e),o=ts(t);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 rs(){try{let t=zu(import.meta.url);return Bt(t)}catch{}let e=Hu(process.argv[1]??process.cwd());try{return Fu(e).isFile()?Bt(e):e}catch{return process.cwd()}}async function Gu(e){let t=ns(e,"package.json");if(!os(t))return null;let n=await Bu(t,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}function Ku(e){let t=ns(e,"package.json");if(!os(t))return null;try{let n=ju(t,"utf8"),o=JSON.parse(n);return!o.name||!o.version?null:{name:o.name,version:o.version}}catch{return null}}async function Vu(){let e=rs();for(;;){let t=await Gu(e);if(t&&t.name==="@memo-code/memo")return t;let n=Bt(e);if(n===e)break;e=n}return null}function Wt(){let e=rs();for(;;){let t=Ku(e);if(t&&t.name==="@memo-code/memo")return t;let n=Bt(e);if(n===e)break;e=n}return null}async function Xu(e,t=1500){let o=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(r=>{let s=Wu(o,{timeout:t},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 ss(){let e=await Vu();if(!e)return null;let t=await Xu(e.name);return!t||!qu(t,e.version)?null:{current:e.version,latest:t}}import{jsx as Le,jsxs as np}from"react/jsx-runtime";function ep(e,t){if(e.length===0)return[];if(t===void 0)return[...e];if(t.length===0)return[];let n=new Set(e),o=t.filter(r=>n.has(r));return o.length>0?o:[...e]}function tp(e,t){if(e.length===0)return[];if(t.length===0)return[];let n=new Set(e);return t.filter(o=>n.has(o))}function as({sessionOptions:e,providerName:t,model:n,configPath:o,mcpServers:r,cwd:s,sessionsDir:i,providers:a,dangerous:l=!1,needsSetup:c=!1}){let{exit:u}=Qu(),p=zt(()=>Object.keys(r??{}).sort(),[r]),d=zt(()=>ep(p,e.activeMcpServers),[p,e.activeMcpServers]),h=e.toolPermissionMode??(l?I.FULL:I.ONCE),[S,g]=Yu(es,void 0,On),[E,_]=Y(t),[T,D]=Y(n),[J,W]=Y(a),[j,x]=Y(h),[N,C]=Y({...e,providerName:t,dangerous:h===I.FULL,toolPermissionMode:h}),[B,O]=Y(!1),[me,U]=Y([]),[b,k]=Y(null),[q,oe]=Y(null),[Se,fe]=Y(e.maxPromptTokens??Or),[je,re]=Y(0),[_e,$e]=Y(c),[v,V]=Y(!c&&p.length>0),[Gt,ge]=Y(d),[z,xe]=Y(null),[G,Qe]=Y(null),he=qt(null),w=qt(null),H=qt(null),[te,se]=Y(null),L=qt(null),F=zt(()=>Wt(),[]),$=K(f=>{g(f)},[]);Tt(()=>{_e||(ge(d),V(p.length>0))},[_e,d,p.length]);let R=K((f,y,M="info")=>{$({type:"append_system_message",title:f,content:y,tone:M})},[$]),Nn=zt(()=>({onAssistantStep:(f,y)=>{let M=w.current;M&&$({type:"assistant_chunk",turn:M,step:y,chunk:f})},requestApproval:j===I.FULL||j===I.NONE?void 0:f=>new Promise(y=>{se(f),L.current=y}),hooks:{onTurnStart:({turn:f,input:y,promptTokens:M})=>{w.current=f;let le=H.current;le&&(H.current=null);let Ne=le??y;M&&M>0&&re(M),$({type:"turn_start",turn:f,input:Ne,promptTokens:M})},onAction:({turn:f,step:y,action:M,thinking:le,parallelActions:Ne})=>{$({type:"tool_action",turn:f,step:y,action:M,thinking:le,parallelActions:Ne})},onObservation:({turn:f,step:y,observation:M,resultStatus:le,parallelResultStatuses:Ne})=>{$({type:"tool_observation",turn:f,step:y,observation:M,toolStatus:_n(le),parallelToolStatuses:xr(Ne)})},onFinal:({turn:f,finalText:y,status:M,errorMessage:le,turnUsage:Ne,tokenUsage:Es})=>{$({type:"turn_final",turn:f,finalText:y,status:M,errorMessage:le,turnUsage:Ne,tokenUsage:Es}),O(!1)}}}),[$,j]);Tt(()=>{let f=!1;return(async()=>{if(_e||v)return;let y=he.current;y&&await y.close();let M=await At(Nn,N);if(f){await M.close();return}he.current=M,Qe(M),k(M.historyFilePath??null)})(),()=>{f=!0}},[Nn,v,N,_e]),Tt(()=>{let f=!1;return(async()=>{let y=await ss();f||!y||R("Update",`Update available: v${y.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{f=!0}},[R]),Tt(()=>()=>{he.current&&he.current.close()},[]);let et=K(async()=>{he.current&&await he.current.close(),xe("Bye!"),setTimeout(()=>u(),250)},[u]),ds=K(()=>{$({type:"clear_current_timeline"}),oe(null),re(0)},[$]),ms=K(()=>{$({type:"reset_all"}),oe(null),re(0),w.current=null,C(f=>({...f,sessionId:Fe()})),R("New Session","Started a fresh session.")},[R,$]),Dn=K(async f=>{try{let y=await ee();await pe(y.configPath,{...y.config,current_provider:f})}catch(y){R("Config",`Failed to persist provider: ${y.message}`,"warning")}},[R]),fs=K(async f=>{if(B){R("Model switch","Cancel current run before switching models.","warning");return}if(f.name===E&&f.model===T){R("Model switch",`Already using ${f.name} (${f.model}).`);return}$({type:"reset_all"}),re(0),w.current=null,_(f.name),D(f.model),C(y=>({...y,sessionId:Fe(),providerName:f.name})),await Dn(f.name),R("Model switch",`Switched to ${f.name} (${f.model}).`)},[R,B,T,E,$,Dn]),Un=K(async f=>{try{let y=await ee();await pe(y.configPath,{...y.config,max_prompt_tokens:f})}catch(y){R("Context",`Failed to persist context limit: ${y.message}`,"warning")}},[R]),gs=K(f=>{fe(f),re(0),C(y=>({...y,maxPromptTokens:f,sessionId:Fe()})),R("Context",`Context window set to ${Math.floor(f/1e3)}k.`),Un(f)},[R,Un]),Kt=K(f=>f===I.NONE?"none (no tools)":f===I.ONCE?"once (approval required)":"full (no approval)",[]),hs=K(f=>{if(B){R("Tools","Cancel current run before changing tool permission mode.","warning");return}if(te){R("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(f===j){R("Tools",`Already using ${Kt(f)}.`);return}x(f),C(y=>({...y,sessionId:Fe(),dangerous:f===I.FULL,toolPermissionMode:f})),R("Tools",`Tool permission set to ${Kt(f)}.`)},[R,B,te,Kt,j]),Hn=K(async f=>{try{let y=await ee();await pe(y.configPath,{...y.config,active_mcp_servers:f})}catch(y){R("MCP",`Failed to persist active MCP servers: ${y.message}`,"warning")}},[R]),ys=K((f,y)=>{let M=tp(p,f);ge(M),V(!1),C(le=>({...le,sessionId:Fe(),activeMcpServers:M})),y&&Hn(M)},[p,Hn]),Ts=K(async f=>{try{let y=await Ju(f.sessionFile,"utf8"),M=Qr(y);$({type:"clear_current_timeline"}),$({type:"replace_history",turns:M.turns,maxSequence:M.maxSequence}),oe(M.messages),O(!1),Qe(null),k(null),re(0),w.current=null,C(le=>({...le,sessionId:Fe()})),R("History",M.summary||f.input)}catch(y){R("History",`Failed to load ${f.sessionFile}: ${y.message}`,"error")}},[R,$]),Ss=K(()=>{B&&G?.cancelCurrentTurn?.()},[B,G]),Fn=K(async()=>{if(!G||B)return;let f=`Please analyze the current project and create an AGENTS.md file at the project root.
|
|
96
113
|
|
|
97
114
|
The AGENTS.md should include:
|
|
98
115
|
1. Project name and brief description
|
|
@@ -103,15 +120,12 @@ The AGENTS.md should include:
|
|
|
103
120
|
6. Any project-specific notes for AI assistants
|
|
104
121
|
|
|
105
122
|
Steps:
|
|
106
|
-
1.
|
|
107
|
-
2. Read key configuration files
|
|
108
|
-
3. Understand
|
|
109
|
-
4. Create
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
`);return Be(ms,{flexDirection:"column",children:d.map((f,_)=>Be(np,{color:"green",children:f},_))})}return et?Be(ps,{configPath:o,onComplete:xs,onExit:ge}):ip(ms,{flexDirection:"column",children:[Be(Er,{systemMessages:N,turns:ws,headerInfo:{providerName:p,model:y,cwd:s,sessionId:C.sessionId??"unknown",mcpNames:Object.keys(r??{}).sort(),version:Kt?.version??"unknown"}}),Be(Qr,{disabled:!b||U||!!L,onSubmit:Ss,onExit:ge,onClear:Fn,onNewSession:jn,onCancelRun:_s,onHistorySelect:Ts,onModelSelect:Xt,onSystemMessage:g,onSetContextLimit:d=>{qt(d)},history:k,cwd:s,sessionsDir:i,currentSessionFile:K??void 0,providers:h,configPath:o,providerName:p,model:y,contextLimit:X,mcpServers:r}),L&&Be(es,{request:L,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,y=typeof u.thinking=="string"?u.thinking:"",h=(Array.isArray(u.toolBlocks)?u.toolBlocks:[]).map(C=>{let x=typeof C?.name=="string"?C.name:"";return x?{tool:x,input:C?.input}:null}).filter(Boolean),P=s.steps[s.steps.length-1];P&&(h.length>1?(P.action=h[0],P.parallelActions=h):p&&(P.action={tool:p,input:T}),y&&(P.thinking=y))}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=`
|
|
123
|
+
1. Explore project structure using list_dir and exec_command tools
|
|
124
|
+
2. Read key configuration files
|
|
125
|
+
3. Understand stack and conventions
|
|
126
|
+
4. Create AGENTS.md using apply_patch
|
|
127
|
+
|
|
128
|
+
Keep the result concise and actionable.`,y=ae(P.INIT);U(M=>[...M,y]),O(!0);try{H.current=y,await G.runTurn(f)}catch{O(!1)}},[B,G]),_s=K(async f=>{let y=f.trim();if(y){if(y.toLowerCase()===Lr){await et();return}if(y===ae(P.INIT)){await Fn();return}if(!(!G||B)){U(M=>[...M,y]),O(!0);try{await G.runTurn(y)}catch{O(!1)}}}},[B,et,Fn,G]),vs=K(async()=>{try{let f=await ee(),y=De(f.config);W(f.config.providers),_(y.name),D(y.model),C(M=>({...M,sessionId:Fe(),providerName:y.name})),$e(!1),R("Setup",`Config saved to ${f.configPath}`)}catch(f){R("Setup",`Failed to reload config: ${f.message}`,"error")}},[R]);Tt(()=>{if(!G||!q?.length)return;let f=G.history[0];f&&(G.history.splice(0,G.history.length,f,...q),oe(null))},[q,G]);let xs=K(f=>{let y=L.current;y&&(y(f),L.current=null),se(null)},[]),bs=Cr(S.turns[S.turns.length-1]?.tokenUsage),Cs=br(je,Se);return z?Le(is,{children:Le(Zu,{color:"green",children:z})}):_e?Le(Zr,{configPath:o,onComplete:vs,onExit:et}):v?Le(Jr,{serverNames:p,defaultSelected:d,onConfirm:ys,onExit:()=>{et()}}):np(is,{flexDirection:"column",children:[Le(Ir,{header:{providerName:E,model:T,cwd:s,sessionId:N.sessionId??"unknown",mcpNames:Gt,version:F?.version??"unknown"},systemMessages:S.systemMessages,turns:S.turns,historicalTurns:S.historicalTurns}),Le(Wr,{disabled:!G||!!te,busy:B,history:me,cwd:s,sessionsDir:i,currentSessionFile:b??void 0,providers:J,configPath:o,providerName:E,model:T,contextLimit:Se,toolPermissionMode:j,mcpServers:r,onSubmit:f=>{_s(f)},onExit:()=>{et()},onClear:ds,onNewSession:ms,onCancelRun:Ss,onHistorySelect:f=>{Ts(f)},onModelSelect:f=>{fs(f)},onSetContextLimit:gs,onSetToolPermission:hs,onSystemMessage:R}),te?Le(Vr,{request:te,onDecision:xs}):null,Le(Gr,{busy:B,contextPercent:Cs,tokenLine:bs})]})}var op=`
|
|
115
129
|
Usage:
|
|
116
130
|
memo mcp list [--json]
|
|
117
131
|
memo mcp get <name> [--json]
|
|
@@ -120,14 +134,14 @@ Usage:
|
|
|
120
134
|
memo mcp remove <name>
|
|
121
135
|
memo mcp login <name> [--scopes scope1,scope2]
|
|
122
136
|
memo mcp logout <name>
|
|
123
|
-
`;function
|
|
124
|
-
`)}function
|
|
125
|
-
`),{...
|
|
137
|
+
`;function Ln(){console.log(op.trim())}function rp(e){let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),o=e.slice(t+1);return n?{key:n,value:o}:null}function ls(e,t){let n=[];if(n.push(`${e}`),"url"in t){n.push(` type: ${t.type??"streamable_http"}`),n.push(` url: ${t.url}`),t.bearer_token_env_var&&n.push(` bearer_token_env_var: ${t.bearer_token_env_var}`);let o=t.http_headers??t.headers;o&&Object.keys(o).length>0&&n.push(` headers: ${Object.entries(o).map(([r,s])=>`${r}=${s}`).join(", ")}`)}else n.push(` type: ${t.type??"stdio"}`),n.push(` command: ${t.command}`),t.args&&t.args.length>0&&n.push(` args: ${t.args.join(" ")}`),t.env&&Object.keys(t.env).length>0&&n.push(` env: ${Object.entries(t.env).map(([o,r])=>`${o}=${r}`).join(", ")}`);return n.join(`
|
|
138
|
+
`)}function sp(e){let t=e.shift();if(!t)return{error:"Missing server name."};let n,o,r={},s=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(a){if(a==="--"){s=e.slice(i+1);break}if(a==="--url"){let l=e[i+1];if(!l)return{error:"Missing value for --url."};n=l,i+=1;continue}if(a==="--bearer-token-env-var"){let l=e[i+1];if(!l)return{error:"Missing value for --bearer-token-env-var."};o=l,i+=1;continue}if(a==="--env"){let l=e[i+1];if(!l)return{error:"Missing value for --env (KEY=VALUE)."};let c=rp(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:t,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:t,command:s[0],args:s.slice(1),env:Object.keys(r).length>0?r:void 0}}}function ip(e){let[t,...n]=e;return!t||t==="--help"||t==="-h"||t==="help"?{command:"help",rest:[]}:{command:t,rest:n}}function $n(e,t=[]){let n=new Set(t);for(let o=0;o<e.length;o+=1){let r=e[o];if(r){if(r.startsWith("--")){n.has(r)&&(o+=1);continue}return r}}return null}async function cs(e){let{command:t,rest:n}=ip(e);if(t==="help"){Ln();return}if(t==="list"){let o=n.includes("--json"),s=(await ee()).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(ls(a,l))}return}if(t==="get"){let o=n.includes("--json"),r=$n(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let i=(await ee()).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(ls(r,i));return}if(t==="add"){let o=sp(n);if(o.error!==void 0){o.error&&(console.error(o.error),process.exitCode=1),Ln();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 ee(),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 pe(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${r.name}".`);return}if(t==="remove"){let o=$n(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let r=await ee(),s={...r.config.mcp_servers??{}};if(!s[o]){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}delete s[o],await pe(r.configPath,{...r.config,mcp_servers:s}),console.log(`Removed MCP server "${o}".`);return}if(t==="login"||t==="logout"){let o=$n(n,["--scopes"]);if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=(await ee()).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: ${t}`),Ln(),process.exitCode=1}import{jsx as hp}from"react/jsx-runtime";function pp(e){let t={dangerous:!1,showVersion:!1,removedOnceFlag:!1},n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r!==void 0){if(r==="--version"||r==="-v"){t.showVersion=!0;continue}if(r==="--once"){t.removedOnceFlag=!0;continue}if(r==="--dangerous"||r==="-d"){t.dangerous=!0;continue}n.push(r)}}return{question:n.join(" "),options:t}}async function ps(e){let t=await ee();if(!t.needsSetup)return t;let n=t.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 pe(t.configPath,t.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${t.configPath}`),{...t,needsSetup:!1};if(e==="tui")return t;let s=ap({input:lp,output:cp}),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 pe(t.configPath,p),console.log(`Config written to ${t.configPath}
|
|
139
|
+
`),{...t,config:p,needsSetup:!1}}finally{s.close()}}async function dp(e){let t=await ps("plain"),n=De(t.config),r={sessionId:us(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous};e.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let s={requestApproval:e.options.dangerous?void 0:l=>(console.log(`
|
|
126
140
|
[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
|
|
141
|
+
[tool] ${l.tool}`),l.input!==void 0&&console.log(`[input] ${JSON.stringify(l.input)}`)},onObservation:()=>{}}},i=await At(s,r),a=e.question;if(!a&&!process.stdin.isTTY&&(a=await gp()),!a){console.error("No input provided. Pass a question or use stdin."),await i.close();return}try{console.log(`User: ${a}
|
|
128
142
|
`);let l=await i.runTurn(a);console.log(`
|
|
129
143
|
${l.finalText}`),console.log(`
|
|
130
144
|
[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
|
|
132
|
-
`)),await
|
|
145
|
+
provider=${n.name} model=${n.model}`)}catch(l){console.error(`Run failed: ${l.message}`)}finally{await i.close()}}async function mp(e){let t=await ps("tui"),n=De(t.config),r={sessionId:us(),mode:"interactive",maxPromptTokens:t.config.max_prompt_tokens,activeMcpServers:t.config.active_mcp_servers,generateSessionTitle:!0,dangerous:e.options.dangerous},s=kt(t,r);e.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
|
|
146
|
+
`)),await up(hp(as,{sessionOptions:r,providerName:n.name,model:n.model,configPath:t.configPath,mcpServers:t.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:s,providers:t.config.providers,dangerous:e.options.dangerous,needsSetup:t.needsSetup}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function fp(){let e=process.argv.slice(2);if(e[0]==="mcp"||e[0]==="--"&&e[1]==="mcp"){let o=e[0]==="--"?2:1;await cs(e.slice(o));return}let t=pp(e);if(t.options.removedOnceFlag){console.error("`--once` has been removed. Use `memo` (interactive) or pipe input to `memo`."),process.exitCode=1;return}if(t.options.showVersion){let r=Wt()?.version??"unknown";console.log(r);return}if(!(process.stdin.isTTY&&process.stdout.isTTY)){await dp(t);return}await mp(t)}fp();async function gp(){return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim())}),process.stdin.resume()})}
|
|
133
147
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memo-code/memo",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.55",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "A lightweight coding agent that runs in your terminal",
|
|
@@ -41,18 +41,18 @@
|
|
|
41
41
|
"zod-to-json-schema": "^3.25.1"
|
|
42
42
|
},
|
|
43
43
|
"scripts": {
|
|
44
|
-
"start": "tsx packages/
|
|
44
|
+
"start": "tsx packages/tui/src/cli.tsx",
|
|
45
45
|
"build": "tsup",
|
|
46
46
|
"dev": "tsup --watch",
|
|
47
47
|
"web:dev": "pnpm --filter @memo-code/web dev",
|
|
48
48
|
"web:build": "pnpm --filter @memo-code/web build",
|
|
49
49
|
"web:start": "pnpm --filter @memo-code/web start",
|
|
50
|
-
"format": "prettier --write .",
|
|
51
|
-
"format:check": "prettier --check .",
|
|
50
|
+
"format": "prettier --write \"{packages,web}/**/*.{ts,tsx,js,jsx,mjs,cjs,json,css,mdx}\" \"{package.json,pnpm-workspace.yaml,tsconfig.json,tsup.config.ts,vitest.config.ts,vitest.setup.ts,.prettierrc}\"",
|
|
51
|
+
"format:check": "prettier --check \"{packages,web}/**/*.{ts,tsx,js,jsx,mjs,cjs,json,css,mdx}\" \"{package.json,pnpm-workspace.yaml,tsconfig.json,tsup.config.ts,vitest.config.ts,vitest.setup.ts,.prettierrc}\"",
|
|
52
52
|
"test": "vitest run",
|
|
53
53
|
"test:core": "vitest run packages/core",
|
|
54
54
|
"test:tools": "vitest run packages/tools",
|
|
55
|
-
"test:
|
|
55
|
+
"test:tui": "vitest run packages/tui",
|
|
56
56
|
"ci": "pnpm run format:check && pnpm run test:core && pnpm run test:tools && pnpm run build",
|
|
57
57
|
"release:patch": "npm version patch && npm publish",
|
|
58
58
|
"release:minor": "npm version minor && npm publish",
|