mocode-ai 0.1.4 → 0.1.5
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 +196 -188
- package/dist/agent/core.js +302 -0
- package/dist/agent/index.js +62 -249
- package/dist/agent/mode.js +46 -0
- package/dist/agent/spawn.js +123 -0
- package/dist/commands/config.js +8 -26
- package/dist/config/file.js +48 -0
- package/dist/config/index.js +73 -30
- package/dist/llm/index.js +11 -9
- package/dist/memory/index.js +2 -2
- package/dist/memory/reflect.js +11 -11
- package/dist/memory/store.js +4 -4
- package/dist/repl/index.js +264 -108
- package/dist/session/compact.js +1 -1
- package/dist/skills/index.js +2 -2
- package/dist/tools/builtins/ask-human.js +7 -7
- package/dist/tools/builtins/codegraph.js +113 -0
- package/dist/tools/builtins/edit-file.js +3 -3
- package/dist/tools/builtins/glob.js +3 -2
- package/dist/tools/builtins/grep.js +4 -3
- package/dist/tools/builtins/index.js +7 -1
- package/dist/tools/builtins/memory-forget.js +2 -2
- package/dist/tools/builtins/memory-list.js +2 -2
- package/dist/tools/builtins/memory-save.js +7 -7
- package/dist/tools/builtins/memory-search.js +4 -4
- package/dist/tools/builtins/memory-update.js +6 -6
- package/dist/tools/builtins/read-file.js +5 -4
- package/dist/tools/builtins/run-command.js +40 -7
- package/dist/tools/builtins/switch-mode.js +46 -0
- package/dist/tools/builtins/task.js +62 -0
- package/dist/tools/builtins/use-skill.js +2 -2
- package/dist/tools/builtins/web-fetch.js +16 -3
- package/dist/tools/builtins/web-search.js +6 -6
- package/dist/tools/builtins/write-file.js +3 -3
- package/dist/tools/constants.js +16 -0
- package/dist/tools/registry.js +11 -4
- package/dist/ui/content.js +25 -17
- package/dist/ui/diff.js +28 -26
- package/dist/ui/intervention.js +24 -3
- package/dist/ui/layout.js +295 -81
- package/dist/ui/markdown.js +607 -0
- package/dist/ui/mouse.js +93 -0
- package/dist/ui/prompt.js +259 -5
- package/dist/ui/render.js +1 -1
- package/dist/ui/theme.js +146 -13
- package/package.json +2 -2
package/dist/repl/index.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import readline from 'node:readline/promises';
|
|
2
2
|
import { emitKeypressEvents } from 'node:readline';
|
|
3
3
|
import { stdin, stdout } from 'node:process';
|
|
4
|
-
import { config } from '../config/index.js';
|
|
4
|
+
import { config, PLAN_MODE_SUFFIX } from '../config/index.js';
|
|
5
|
+
import { updateConfigKey } from '../config/file.js';
|
|
5
6
|
import { runAgent } from '../agent/index.js';
|
|
6
|
-
import {
|
|
7
|
+
import { getAgentMode, setAgentMode, onModeChange } from '../agent/mode.js';
|
|
8
|
+
import { ui, setTheme, getTheme, listThemes, themeExists } from '../ui/theme.js';
|
|
7
9
|
import { bannerString, displayWidth, padEndDisplay, summarizeToolCall, summarizeToolResult } from '../ui/render.js';
|
|
8
10
|
import * as layout from '../ui/layout.js';
|
|
9
|
-
import
|
|
11
|
+
import * as mouse from '../ui/mouse.js';
|
|
12
|
+
import { promptWithSlashMenu, promptTurnPicker, promptSessionPicker, promptThemePicker, promptRevertChoice, } from '../ui/prompt.js';
|
|
13
|
+
import { promptIntervention } from '../ui/intervention.js';
|
|
10
14
|
import { tools } from '../tools/registry.js';
|
|
11
15
|
import { estimateMessagesTokens, estimateToolSchemaTokens, } from '../llm/index.js';
|
|
12
16
|
import { compactHistory, contextState, newSessionId, saveSession, loadSession, listSessions, } from '../session/index.js';
|
|
@@ -26,40 +30,50 @@ const SLASH_COMMANDS = [
|
|
|
26
30
|
{ name: '/skills', desc: '列出已发现的 skill' },
|
|
27
31
|
{ name: '/compact', desc: '压缩历史(可带焦点 /compact …)' },
|
|
28
32
|
{ name: '/resume', desc: '续接已保存的会话' },
|
|
29
|
-
{ name: '/think', desc: '展开折叠思考段(/think N)' },
|
|
30
33
|
{ name: '/rollback', desc: '菜单选轮次回滚(↑↓·Enter)' },
|
|
31
34
|
{ name: '/memory', desc: '记忆库:条目计数与近期索引' },
|
|
32
35
|
{ name: '/reflect', desc: '手动触发后台记忆反思 pass' },
|
|
33
36
|
{ name: '/init', desc: '扫描项目生成 MOCODE.md 项目记忆' },
|
|
37
|
+
{ name: '/theme', desc: '切换颜色主题(↑↓·Enter)' },
|
|
38
|
+
{ name: '/plan', desc: '切到 plan 模式(只读探查+产出计划)' },
|
|
39
|
+
{ name: '/auto', desc: '切回 auto 模式(全工具执行)' },
|
|
34
40
|
];
|
|
41
|
+
/** 主题名 → 一句描述(供 /theme 菜单 / 列表显示)。新增主题时在 src/ui/theme.ts THEMES 加键后于此补一句。 */
|
|
42
|
+
const THEME_DESCRIPTIONS = {
|
|
43
|
+
default: '16 色原版(深底)',
|
|
44
|
+
light: '浅底终端',
|
|
45
|
+
solarized: 'Solarized 强调色',
|
|
46
|
+
gruvbox: 'Gruvbox 暖色',
|
|
47
|
+
nord: 'Nord 冷色',
|
|
48
|
+
};
|
|
35
49
|
/**
|
|
36
50
|
* /init 指令:发给 agent 扫描项目并生成 MOCODE.md(对标 Claude Code /init 生成 CLAUDE.md,
|
|
37
51
|
* 但 mocode 读 MOCODE.md)。已存在则让 agent 读后更新(不丢失事实)。写完供 memory 子系统下轮加载。
|
|
38
52
|
*/
|
|
39
|
-
const INIT_PROMPT = `分析当前项目(process.cwd()),生成 MOCODE.md 项目记忆文件,供 mocode 后续会话自动加载——目标是让后续会话无需重新摸索就能上手。
|
|
40
|
-
|
|
41
|
-
先探查(尽量少调用拿全貌):
|
|
42
|
-
-
|
|
43
|
-
-
|
|
44
|
-
-
|
|
45
|
-
- 若 MOCODE.md 已存在:read_file 读它,在其基础上更新(补缺、修正过时),不丢已有准确事实。
|
|
46
|
-
|
|
47
|
-
MOCODE.md 按以下结构写(每节简短,只写稳定、非显然的事实):
|
|
48
|
-
## 项目
|
|
49
|
-
一两句:是什么、技术栈、运行环境。
|
|
50
|
-
## 命令
|
|
51
|
-
install / dev / build / test / typecheck / lint 等——从 package.json scripts 提炼,写原样命令行(如 \`npm run typecheck\`);没有的注明"无测试"/"无 lint"。
|
|
52
|
-
## 目录结构
|
|
53
|
-
顶层各目录与子系统职责,一句话/个;不逐文件列。
|
|
54
|
-
## 约定
|
|
55
|
-
从代码与现有文档提炼的硬约定:模块系统(ESM?)、命名、错误处理、工具/函数契约、易踩坑点。只写非显然、会让人踩坑的;不写"保持简洁"这种正确废话。
|
|
56
|
-
## 扩展点
|
|
57
|
-
加工具/命令/provider/模块的接缝(改哪个文件、加在哪)。
|
|
58
|
-
|
|
59
|
-
硬要求:
|
|
60
|
-
- 从实际代码提炼,引用具体文件名/命令/符号;不编造、不泛泛。
|
|
61
|
-
- 总长 ≤ 1500 字;只写后续会话有用的稳定事实,不写易变项(当前 bug、临时文件、未决 TODO)。
|
|
62
|
-
- 用 write_file 写入项目根 MOCODE.md。
|
|
53
|
+
const INIT_PROMPT = `分析当前项目(process.cwd()),生成 MOCODE.md 项目记忆文件,供 mocode 后续会话自动加载——目标是让后续会话无需重新摸索就能上手。
|
|
54
|
+
|
|
55
|
+
先探查(尽量少调用拿全貌):
|
|
56
|
+
- 若有 .codegraph/:用 codegraph 工具(explore "<架构或入口符号>")一次拿相关源码+调用路径,别逐文件读!!!
|
|
57
|
+
- read_file package.json(或 Cargo.toml/pyproject.toml/go.mod 等):scripts、依赖、入口、模块类型。
|
|
58
|
+
- glob 顶层目录;read_file 入口文件 + 各子系统 index.ts/README。
|
|
59
|
+
- 若 MOCODE.md 已存在:read_file 读它,在其基础上更新(补缺、修正过时),不丢已有准确事实。
|
|
60
|
+
|
|
61
|
+
MOCODE.md 按以下结构写(每节简短,只写稳定、非显然的事实):
|
|
62
|
+
## 项目
|
|
63
|
+
一两句:是什么、技术栈、运行环境。
|
|
64
|
+
## 命令
|
|
65
|
+
install / dev / build / test / typecheck / lint 等——从 package.json scripts 提炼,写原样命令行(如 \`npm run typecheck\`);没有的注明"无测试"/"无 lint"。
|
|
66
|
+
## 目录结构
|
|
67
|
+
顶层各目录与子系统职责,一句话/个;不逐文件列。
|
|
68
|
+
## 约定
|
|
69
|
+
从代码与现有文档提炼的硬约定:模块系统(ESM?)、命名、错误处理、工具/函数契约、易踩坑点。只写非显然、会让人踩坑的;不写"保持简洁"这种正确废话。
|
|
70
|
+
## 扩展点
|
|
71
|
+
加工具/命令/provider/模块的接缝(改哪个文件、加在哪)。
|
|
72
|
+
|
|
73
|
+
硬要求:
|
|
74
|
+
- 从实际代码提炼,引用具体文件名/命令/符号;不编造、不泛泛。
|
|
75
|
+
- 总长 ≤ 1500 字;只写后续会话有用的稳定事实,不写易变项(当前 bug、临时文件、未决 TODO)。
|
|
76
|
+
- 用 write_file 写入项目根 MOCODE.md。
|
|
63
77
|
- 写完简述:写了哪几节 + 从代码里发现的 2-3 条非显然关键约定(供用户校验)。`;
|
|
64
78
|
/** 临时 readline 读一行(cooked,用于子提问;主输入走 promptWithSlashMenu)。 */
|
|
65
79
|
async function askLine(prompt) {
|
|
@@ -80,7 +94,7 @@ function renderContextBar(history) {
|
|
|
80
94
|
const pct = Math.min(1, est / win);
|
|
81
95
|
const W = 10;
|
|
82
96
|
const filled = Math.round(pct * W);
|
|
83
|
-
const bar = '█'.repeat(filled) + '░'.repeat(W - filled);
|
|
97
|
+
const bar = filled === 0 ? ' '.repeat(W) : '█'.repeat(filled) + '░'.repeat(W - filled);
|
|
84
98
|
const src = contextState.lastUsage ? '实测' : '估算';
|
|
85
99
|
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
86
100
|
const pctCol = pct >= config.compactThreshold ? ui.yellow : ui.cyan;
|
|
@@ -95,17 +109,18 @@ function renderContextBarInline(history) {
|
|
|
95
109
|
const pct = Math.min(1, est / win);
|
|
96
110
|
const W = 10;
|
|
97
111
|
const filled = Math.round(pct * W);
|
|
98
|
-
const bar = '█'.repeat(filled) + '░'.repeat(W - filled);
|
|
112
|
+
const bar = filled === 0 ? ' '.repeat(W) : '█'.repeat(filled) + '░'.repeat(W - filled);
|
|
99
113
|
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
100
114
|
const pctCol = pct >= config.compactThreshold ? ui.yellow : ui.cyan;
|
|
101
115
|
return `${ui.gray}[${pctCol}${bar}${ui.reset}] ${pctCol}${Math.round(pct * 100)}%${ui.reset} ${ui.dim}${k(est)}/${k(win)}${ui.reset}`;
|
|
102
116
|
}
|
|
103
|
-
/** 状态行基线:模型 / context / cwd
|
|
117
|
+
/** 状态行基线:模型 / context / cwd / 模式标识。repl 在轮次边界与切模式时调,刷新 context 用量与 mode chip。 */
|
|
104
118
|
function refreshStatusBase(history) {
|
|
105
119
|
layout.setStatusBase({
|
|
106
120
|
model: config.model,
|
|
107
121
|
contextBar: renderContextBarInline(history),
|
|
108
122
|
cwd: process.cwd(),
|
|
123
|
+
modeTag: getAgentMode() === 'plan' ? 'plan' : 'auto',
|
|
109
124
|
});
|
|
110
125
|
}
|
|
111
126
|
/** 命令 → 运行态状态文字 + 底栏 dim 占位。 */
|
|
@@ -119,12 +134,19 @@ function runningStateFor(cmd) {
|
|
|
119
134
|
return { status: '回滚', placeholder: '选择轮次…' };
|
|
120
135
|
case '/init':
|
|
121
136
|
return { status: '初始化', placeholder: '生成 MOCODE.md…' };
|
|
137
|
+
case '/plan':
|
|
138
|
+
return { status: '切 plan', placeholder: '…' };
|
|
139
|
+
case '/auto':
|
|
140
|
+
return { status: '切 auto', placeholder: '…' };
|
|
122
141
|
case '/clear':
|
|
123
142
|
return { status: '清空', placeholder: '…' };
|
|
143
|
+
case '/theme':
|
|
144
|
+
return { status: '切主题', placeholder: '选择主题…' };
|
|
124
145
|
default:
|
|
125
|
-
// 输入框留空(运行中可 typeahead 打字,dim 回显)
|
|
126
|
-
//
|
|
127
|
-
|
|
146
|
+
// 输入框留空(运行中可 typeahead 打字,dim 回显);运行状态由内联 spinner 承载(思考中/执行…),
|
|
147
|
+
// 状态行只显走时——故常态 status 留空,不塞「处理」这种与内联重复的泛标签。
|
|
148
|
+
// 不把「思考中… Ctrl+C 中断」塞进输入框占位——避免看起来像已有输入、妨碍正常输入。
|
|
149
|
+
return { status: '', placeholder: '' };
|
|
128
150
|
}
|
|
129
151
|
}
|
|
130
152
|
const emitter = stdin;
|
|
@@ -134,11 +156,20 @@ let runningInput = ''; // 运行中已打字缓冲(单行;agent 结束后预填
|
|
|
134
156
|
let runningPlaceholder = '';
|
|
135
157
|
let currentAbort = null;
|
|
136
158
|
let pendingPrefill = null; // /rollback 选中后预填的 user 输入(下轮 INPUT 态消费)
|
|
159
|
+
// agent 模式状态已提到 src/agent/mode.ts(共享叶子:switch_mode 工具可写、agent 每步读、repl 注册 onModeChange 监听器)。
|
|
137
160
|
/** 运行态按键:滚动优先,再 Ctrl+C 中断,再 typeahead 编辑(单行,Enter=无操作)。 */
|
|
138
161
|
function onRunningKey(_str, key) {
|
|
139
162
|
if (!key)
|
|
140
163
|
return;
|
|
141
|
-
//
|
|
164
|
+
// SGR 鼠标滚轮:readline 把 \x1B[<btn;col;rowM 拆成多 fragment,经 mouse.consumeMouse 重组;
|
|
165
|
+
// 滚轮 → scrollBy(±5)(不调 setUserActive——与键盘滚动一致;流式 flushTimer 在 scrollOffset>0 时不重画,安全)。
|
|
166
|
+
const _m = mouse.consumeMouse(key.sequence ?? '');
|
|
167
|
+
if (_m.suppress) {
|
|
168
|
+
if (_m.wheel)
|
|
169
|
+
layout.scrollBy(_m.wheel * 5);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
// 滚动回看键(优先;不触发回尾):PgUp/PgDn 翻页,↑/↓ 每次 5 行(键盘;鼠标滚轮已由上方守卫处理)。
|
|
142
173
|
// 运行态无输入光标,↑/↓ 无其他用途,直接作滚动。
|
|
143
174
|
if (key.name === 'pageup' ||
|
|
144
175
|
key.name === 'pagedown' ||
|
|
@@ -150,17 +181,27 @@ function onRunningKey(_str, key) {
|
|
|
150
181
|
else if (key.name === 'pagedown')
|
|
151
182
|
layout.scrollBy(-pageH);
|
|
152
183
|
else if (key.name === 'up')
|
|
153
|
-
layout.scrollBy(
|
|
184
|
+
layout.scrollBy(5);
|
|
154
185
|
else
|
|
155
|
-
layout.scrollBy(-
|
|
186
|
+
layout.scrollBy(-5);
|
|
156
187
|
return;
|
|
157
188
|
}
|
|
189
|
+
// 用户在交互(非滚动键)→ 暂停流式物理写,避免光标去 contentRow 扰动 IME 候选窗(停手后自动 flush)
|
|
190
|
+
layout.setUserActive();
|
|
158
191
|
// 其他键:若处于滚动回看,先回尾再处理(打字即回底)
|
|
159
192
|
if (layout.isScrolled())
|
|
160
193
|
layout.resetScroll();
|
|
161
|
-
// Ctrl+C
|
|
194
|
+
// Ctrl+C 4 层语义(RUNNING 态):有 typeahead → 清空(层 1,不中断);空 → abort(层 2,中断 agent)。
|
|
195
|
+
// 两次 Ctrl+C 才中断(先清 typeahead 再 abort),与 INPUT 态 onCtrlC 的 fish 式一致。
|
|
196
|
+
// raw 模式下 Ctrl+C 是按键不触发 SIGINT;signal 经 executeTool 串进工具,run_command/web_fetch 即时被杀。
|
|
162
197
|
if (key.ctrl && key.name === 'c') {
|
|
163
|
-
|
|
198
|
+
if (runningInput.length > 0) {
|
|
199
|
+
runningInput = '';
|
|
200
|
+
layout.paintRunningInputEcho(runningInput, runningPlaceholder);
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
currentAbort?.abort();
|
|
204
|
+
}
|
|
164
205
|
return;
|
|
165
206
|
}
|
|
166
207
|
const s = key.sequence ?? '';
|
|
@@ -214,6 +255,7 @@ function stopRunningListener() {
|
|
|
214
255
|
* 把用户消息格式化为带满宽背景色的文本(上滑时易辨认用户消息)。
|
|
215
256
|
* 每行用 padEndDisplay 填充到终端宽度(含 ❯ / 缩进),背景色 SGR 包裹整行 + 行末 reset。
|
|
216
257
|
* 满宽 pad 使终端背景色覆盖整行(含行尾空单元格),上滑滚动时用户消息呈连续色块、与 assistant 正文区分。
|
|
258
|
+
* 末尾多留一空行(\n\n 收尾):用户消息与后续(agent 流式输出 / 下条消息)之间空一行,仿 Claude Code。
|
|
217
259
|
*/
|
|
218
260
|
function formatUserMessage(lines) {
|
|
219
261
|
const cols = layout.getGeo().cols;
|
|
@@ -227,7 +269,7 @@ function formatUserMessage(lines) {
|
|
|
227
269
|
const padded = padEndDisplay(full, cols);
|
|
228
270
|
return `${userBg}${padded}${reset}`;
|
|
229
271
|
})
|
|
230
|
-
.join('\n') + '\n');
|
|
272
|
+
.join('\n') + '\n\n');
|
|
231
273
|
}
|
|
232
274
|
/** 把多行提交输入回显进内容区(❯ 首行,续行按 prompt 宽度缩进)。仅 TUI 态回显(非 TTY 由 readline 自带回显)。 */
|
|
233
275
|
function echoInput(lines) {
|
|
@@ -267,7 +309,7 @@ export function renderHistory(history) {
|
|
|
267
309
|
if (m.role === 'assistant') {
|
|
268
310
|
const text = textOf(m.content);
|
|
269
311
|
if (text) {
|
|
270
|
-
layout.
|
|
312
|
+
layout.contentWriteMdOnce(text);
|
|
271
313
|
if (!text.endsWith('\n'))
|
|
272
314
|
layout.contentWrite('\n');
|
|
273
315
|
}
|
|
@@ -300,16 +342,23 @@ export function renderHistory(history) {
|
|
|
300
342
|
* agent 只读取并追加(+ 经 session/ 压缩)。每轮成功结束后自动落盘,退出后可用 --resume / /resume 续接。
|
|
301
343
|
*/
|
|
302
344
|
export async function startRepl(initialHistory, sessionId, updateNotice = null) {
|
|
345
|
+
// 模式重置:agentMode 不落盘,每个 REPL 会话从 auto 开始(/resume / --resume 亦重置)。
|
|
346
|
+
setAgentMode('auto');
|
|
347
|
+
// 构造系统提示:auto 用 base;plan 在 config.systemPrompt 后追加 PLAN_MODE_SUFFIX。
|
|
348
|
+
// 切模式时 applyMode 重算 history[0](history[0] 恒 system,compaction 保它,不破坏)。
|
|
349
|
+
const buildSystemMessage = (planMode) => effectiveSystemPrompt(config.systemPrompt +
|
|
350
|
+
(planMode ? PLAN_MODE_SUFFIX : '') +
|
|
351
|
+
buildMemorySection() +
|
|
352
|
+
buildMemoryIndexSection());
|
|
303
353
|
// 有预加载(--resume)则用它,并把 history[0] 刷成当前 system prompt(config 可能已变);
|
|
304
|
-
// 否则新会话只塞 system
|
|
305
|
-
const systemPrompt = effectiveSystemPrompt(config.systemPrompt + buildMemorySection() + buildMemoryIndexSection());
|
|
354
|
+
// 否则新会话只塞 system 提示(默认 auto)。
|
|
306
355
|
const history = initialHistory && initialHistory.length
|
|
307
356
|
? initialHistory
|
|
308
|
-
: [{ role: 'system', content:
|
|
357
|
+
: [{ role: 'system', content: buildSystemMessage(false) }];
|
|
309
358
|
if (initialHistory &&
|
|
310
359
|
initialHistory.length &&
|
|
311
360
|
history[0]?.role === 'system') {
|
|
312
|
-
history[0] = { role: 'system', content:
|
|
361
|
+
history[0] = { role: 'system', content: buildSystemMessage(false) };
|
|
313
362
|
}
|
|
314
363
|
// --resume:读回该会话的轮次/快照;无文件则从 history 重建 turns(无快照→旧轮次文件改动不可撤销)
|
|
315
364
|
if (sessionId && initialHistory && initialHistory.length) {
|
|
@@ -319,8 +368,6 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
319
368
|
let currentSessionId = sessionId;
|
|
320
369
|
// 反思 cadence 计数:每 reflectEveryN 轮 fire-and-forget 一次后台反思 pass。
|
|
321
370
|
let turnCount = 0;
|
|
322
|
-
// 本会话累积的折叠思考段,供 /think N 重打原文。
|
|
323
|
-
const collapsedThinkings = [];
|
|
324
371
|
const toolsLine = tools.map((t) => t.name).join(' · ');
|
|
325
372
|
const banner = () => ({
|
|
326
373
|
model: config.model,
|
|
@@ -328,7 +375,9 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
328
375
|
cwd: process.cwd(),
|
|
329
376
|
tools: toolsLine,
|
|
330
377
|
});
|
|
331
|
-
//
|
|
378
|
+
// 开场:按 config.theme 切主题(横幅 / 状态行 / 后续渲染皆用新色),再进 alt screen + 状态基线 + 清内容区。
|
|
379
|
+
// --resume 有历史则渲染对话(仿 Claude Code),否则横幅。
|
|
380
|
+
setTheme(config.theme);
|
|
332
381
|
layout.enterAltScreen();
|
|
333
382
|
refreshStatusBase(history);
|
|
334
383
|
layout.clearContent();
|
|
@@ -343,10 +392,29 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
343
392
|
// 自更新提示:开场静态段(进 INPUT 态前),dim 一行,不与流式 / 输入争用。
|
|
344
393
|
layout.contentWrite(` ${ui.gray}↳ ${updateNotice}${ui.reset}\n`);
|
|
345
394
|
}
|
|
395
|
+
layout.contentWrite(`${ui.dim} /plan · /auto · Shift+Tab 切换模式(plan:只读探查 + 产出计划,审批后切 auto 执行)${ui.reset}\n`);
|
|
396
|
+
/**
|
|
397
|
+
* 切换 agent 模式(Shift+Tab 触发,经 prompt.ts 的 onCycleMode 回调)。
|
|
398
|
+
* cycleMode 翻 agentMode + applyMode 重写 history[0] + refreshStatusBase 设状态行 modeTag;
|
|
399
|
+
* 随后 prompt.ts 自调 redraw() 经 paintInput 把 chip 画出来(光标留输入框,不调 drawStatusBar)。
|
|
400
|
+
*/
|
|
401
|
+
const applyMode = (planMode) => {
|
|
402
|
+
history[0] = { role: 'system', content: buildSystemMessage(planMode) };
|
|
403
|
+
};
|
|
404
|
+
const cycleMode = () => {
|
|
405
|
+
setAgentMode(getAgentMode() === 'plan' ? 'auto' : 'plan'); // listener 接手 applyMode + refreshStatusBase
|
|
406
|
+
};
|
|
407
|
+
// 注册模式变更监听器:switch_mode 工具 / cycleMode / /plan / /auto / runTurn 调 setAgentMode 时同步触发,
|
|
408
|
+
// 重写 history[0] 系统提示(切 plan 追加 PLAN_MODE_SUFFIX)+ 刷状态行 modeTag。
|
|
409
|
+
// 不调 drawStatusBar:INPUT 态靠 prompt.ts redraw 画 chip;RUNNING 态(switch_mode 中途切)靠 200ms turnTimer 兜底。
|
|
410
|
+
onModeChange((m) => {
|
|
411
|
+
applyMode(m === 'plan');
|
|
412
|
+
refreshStatusBase(history);
|
|
413
|
+
});
|
|
346
414
|
/**
|
|
347
415
|
* 回滚子流程(由 /rollback 触发):菜单(↑/↓)选轮次 → 选中第 X 轮 = 删第 X 轮及之后 + 预填第 X 轮 user 输入
|
|
348
|
-
* (仿 Claude Code rewind,Enter 重新跑该轮)
|
|
349
|
-
*
|
|
416
|
+
* (仿 Claude Code rewind,Enter 重新跑该轮);被删轮次的文件改动走二选一菜单(promptRevertChoice:
|
|
417
|
+
* 撤销文件 / 只撤销消息)。选轮 + 方式菜单均走 raw mode。预填经 pendingPrefill 注入下轮 INPUT。
|
|
350
418
|
*/
|
|
351
419
|
const rollbackFlow = async () => {
|
|
352
420
|
const turnList = listTurns();
|
|
@@ -384,24 +452,25 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
384
452
|
dim: true,
|
|
385
453
|
});
|
|
386
454
|
const revertPaths = new Set();
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
455
|
+
// 文件撤销:二选一菜单(1=撤销文件改动 / 2=只撤销消息保留文件)
|
|
456
|
+
// 返回 true=撤销文件(把 changes 里所有可撤销的路径加入 revertPaths);
|
|
457
|
+
// false/null(取消/非 TTY/Ctrl+C)=只撤销消息,保留文件改动。
|
|
458
|
+
const changes = plan.changes;
|
|
459
|
+
const revertable = changes.filter((c) => c.snapshotAvailable);
|
|
460
|
+
let revertFiles = false;
|
|
461
|
+
if (changes.length > 0) {
|
|
390
462
|
try {
|
|
391
|
-
|
|
463
|
+
const choice = await promptRevertChoice(revertable.length);
|
|
464
|
+
revertFiles = choice === true;
|
|
392
465
|
}
|
|
393
466
|
catch {
|
|
394
|
-
|
|
395
|
-
}
|
|
396
|
-
if (ans.startsWith('u') || ans.startsWith('U')) {
|
|
397
|
-
if (c.snapshotAvailable) {
|
|
398
|
-
revertPaths.add(c.path);
|
|
399
|
-
}
|
|
400
|
-
else {
|
|
401
|
-
layout.contentWrite(`${ui.dim} (无快照,无法撤销——保留)${ui.reset}\n`);
|
|
402
|
-
}
|
|
467
|
+
revertFiles = false; // Ctrl+C(SIGINT)→ 保留文件,只撤销消息
|
|
403
468
|
}
|
|
404
469
|
}
|
|
470
|
+
if (revertFiles) {
|
|
471
|
+
for (const c of revertable)
|
|
472
|
+
revertPaths.add(c.path);
|
|
473
|
+
}
|
|
405
474
|
applyRollback(plan, history, revertPaths);
|
|
406
475
|
if (!currentSessionId)
|
|
407
476
|
currentSessionId = newSessionId();
|
|
@@ -417,6 +486,52 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
417
486
|
renderHistory(history);
|
|
418
487
|
pendingPrefill = prefillText.split('\n');
|
|
419
488
|
};
|
|
489
|
+
/**
|
|
490
|
+
* 跑一轮 agent(enterRunningMode 已由调用方完成):startRunningListener → runAgent → autosave / reflect。
|
|
491
|
+
* plan 模式传 planMode=true(runAgent 用 planChatTools 只读子集)。返 ok=正常结束(未中断 / 未抛错),
|
|
492
|
+
* 供调用方决定是否弹审批面板。execute 轮的合成输入也走这里。
|
|
493
|
+
*/
|
|
494
|
+
const runTurn = async (input, planMode, placeholder) => {
|
|
495
|
+
let ok = false;
|
|
496
|
+
try {
|
|
497
|
+
const signal = startRunningListener(placeholder);
|
|
498
|
+
// 入口设定本轮初始模式(合成执行轮传 false→auto;用户轮传当前 mode)。
|
|
499
|
+
// setAgentMode 触发 listener 重写 history[0];LLM 可在轮中调 switch_mode 切模式,runAgent 每步读实时值。
|
|
500
|
+
setAgentMode(planMode ? 'plan' : 'auto');
|
|
501
|
+
// 运行中每步 chat() 返回后刷新状态行 context 用量条(用 fresh lastUsage / 估算),
|
|
502
|
+
// 否则整轮冻结在轮首 refreshStatusBase 的值,「执行 grep」时 2k/1000k 不动。
|
|
503
|
+
await runAgent(history, input, signal, () => {
|
|
504
|
+
refreshStatusBase(history);
|
|
505
|
+
layout.drawStatusBar();
|
|
506
|
+
});
|
|
507
|
+
ok = !signal.aborted; // 中断(Ctrl+C)→ runAgent 已还原 history,ok=false 不弹审批
|
|
508
|
+
// 成功轮次自动落盘(崩溃也保住上一轮);新会话首轮分配 id
|
|
509
|
+
if (!currentSessionId)
|
|
510
|
+
currentSessionId = newSessionId();
|
|
511
|
+
try {
|
|
512
|
+
saveSession(history, currentSessionId);
|
|
513
|
+
}
|
|
514
|
+
catch {
|
|
515
|
+
// 落盘失败不阻断 REPL
|
|
516
|
+
}
|
|
517
|
+
persistSnapshots(currentSessionId); // 随会话落盘回滚快照(/resume 后仍可撤销)
|
|
518
|
+
// 后台反思:每 reflectEveryN 轮 fire-and-forget 一次(与下一轮 agent 并发,不阻塞)。
|
|
519
|
+
// 已有在飞任务 / autoReflect 关 → kickoff 内部自守卫。快照同步取(避免下一轮 mutate history 竞态)。
|
|
520
|
+
turnCount++;
|
|
521
|
+
if (turnCount % config.reflectEveryN === 0) {
|
|
522
|
+
kickoffReflection(snapshotTranscript(history, 20));
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
catch (e) {
|
|
526
|
+
ok = false;
|
|
527
|
+
layout.contentWrite(`${ui.red}[错误]${ui.reset} ${e instanceof Error ? e.message : String(e)}\n`);
|
|
528
|
+
}
|
|
529
|
+
finally {
|
|
530
|
+
stopRunningListener();
|
|
531
|
+
}
|
|
532
|
+
layout.contentWrite('\n'); // 轮次之间空行
|
|
533
|
+
return ok;
|
|
534
|
+
};
|
|
420
535
|
while (true) {
|
|
421
536
|
// INPUT 态:画底栏输入框 + 状态行,光标入输入框
|
|
422
537
|
refreshStatusBase(history);
|
|
@@ -433,6 +548,7 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
433
548
|
input = await promptWithSlashMenu({
|
|
434
549
|
prompt: PROMPT,
|
|
435
550
|
commands: SLASH_COMMANDS,
|
|
551
|
+
onCycleMode: cycleMode,
|
|
436
552
|
// /rollback 预填优先;否则上一轮运行中 typeahead 打的字 → 预填进输入框,用户可改可发
|
|
437
553
|
...(pendingPrefill
|
|
438
554
|
? { initialLines: pendingPrefill }
|
|
@@ -464,9 +580,30 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
464
580
|
// /init:把 init 指令当 user 输入发给 agent(扫描项目 + 生成 MOCODE.md),fall through 走 runAgent
|
|
465
581
|
joined = INIT_PROMPT;
|
|
466
582
|
}
|
|
583
|
+
if (line === '/plan') {
|
|
584
|
+
// /plan:切到 plan 模式(只读探查 + 产出计划)。Shift+Tab 的可靠后备——
|
|
585
|
+
// 中文 IME(微软拼音用 Shift 切中英)与部分终端会吞掉 Shift+Tab 的 \x1b[Z,命令不受影响。
|
|
586
|
+
if (getAgentMode() === 'plan') {
|
|
587
|
+
layout.contentWrite(`${ui.dim}(已在 plan 模式)${ui.reset}\n`);
|
|
588
|
+
}
|
|
589
|
+
else {
|
|
590
|
+
setAgentMode('plan'); // listener 接手 applyMode + refreshStatusBase
|
|
591
|
+
layout.contentWrite(`${ui.dim}(已切到 plan 模式:只读探查 + 产出计划,审批后切 auto 执行。/auto 或 Shift+Tab 切回)${ui.reset}\n`);
|
|
592
|
+
}
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
if (line === '/auto') {
|
|
596
|
+
if (getAgentMode() === 'auto') {
|
|
597
|
+
layout.contentWrite(`${ui.dim}(已在 auto 模式)${ui.reset}\n`);
|
|
598
|
+
}
|
|
599
|
+
else {
|
|
600
|
+
setAgentMode('auto'); // listener 接手 applyMode + refreshStatusBase
|
|
601
|
+
layout.contentWrite(`${ui.dim}(已切回 auto 模式:全工具执行)${ui.reset}\n`);
|
|
602
|
+
}
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
467
605
|
if (line === '/clear') {
|
|
468
606
|
history.length = 1; // 保留 system 提示
|
|
469
|
-
collapsedThinkings.length = 0; // 同步清空折叠的思考段
|
|
470
607
|
resetState(); // 同步清空回滚轮次/快照
|
|
471
608
|
currentSessionId = undefined; // 下轮起新会话文件
|
|
472
609
|
turnCount = 0; // 反思 cadence 重新计数
|
|
@@ -565,37 +702,70 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
565
702
|
continue;
|
|
566
703
|
}
|
|
567
704
|
if (loaded.history[0]?.role === 'system') {
|
|
568
|
-
loaded.history[0] = { role: 'system', content:
|
|
705
|
+
loaded.history[0] = { role: 'system', content: buildSystemMessage(false) };
|
|
569
706
|
}
|
|
570
707
|
history.length = 0;
|
|
571
708
|
history.push(...loaded.history);
|
|
709
|
+
setAgentMode('auto'); // /resume 重置为 auto(mode 不落盘;listener 重写 history[0] 回 auto,与 loaded 幂等)
|
|
572
710
|
currentSessionId = loaded.id;
|
|
573
711
|
// 读回该会话的轮次/快照;无文件则从 history 重建 turns(无快照→旧轮次文件改动不可撤销)
|
|
574
712
|
if (!loadSnapshots(loaded.id))
|
|
575
713
|
rebuildFromHistory(history);
|
|
576
714
|
contextState.lastUsage = undefined;
|
|
577
|
-
collapsedThinkings.length = 0;
|
|
578
715
|
layout.clearContent();
|
|
579
716
|
renderHistory(history);
|
|
580
717
|
layout.contentWrite(`${ui.dim}(已续接会话 ${loaded.id})${ui.reset}\n`);
|
|
581
718
|
continue;
|
|
582
719
|
}
|
|
583
|
-
if (line === '/
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
720
|
+
if (line === '/theme' || line.startsWith('/theme ')) {
|
|
721
|
+
// /theme:无参开菜单(↑↓ 选,Enter 切换,Esc 取消);/theme <name> 直切;/theme list 或未知名 → 列出。
|
|
722
|
+
const arg = line.startsWith('/theme ') ? line.slice('/theme '.length).trim() : '';
|
|
723
|
+
let name;
|
|
724
|
+
if (arg === '') {
|
|
725
|
+
// 无参:菜单选(仿 /resume /rollback 的 picker)
|
|
726
|
+
const items = listThemes().map((t) => ({
|
|
727
|
+
id: t,
|
|
728
|
+
title: t,
|
|
729
|
+
subtitle: THEME_DESCRIPTIONS[t] ?? '',
|
|
730
|
+
}));
|
|
731
|
+
let pick;
|
|
732
|
+
try {
|
|
733
|
+
pick = await promptThemePicker(items);
|
|
734
|
+
}
|
|
735
|
+
catch {
|
|
736
|
+
continue; // Ctrl+C(SIGINT)→ 取消
|
|
737
|
+
}
|
|
738
|
+
name = pick?.id ?? null;
|
|
588
739
|
}
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
740
|
+
else if (arg === 'list' || !themeExists(arg)) {
|
|
741
|
+
layout.contentWrite(`${ui.dim}可用主题:${ui.reset}\n`);
|
|
742
|
+
for (const t of listThemes()) {
|
|
743
|
+
layout.contentWrite(` ${ui.cyan}${t}${ui.reset} ${ui.dim}${THEME_DESCRIPTIONS[t] ?? ''}${ui.reset}\n`);
|
|
744
|
+
}
|
|
745
|
+
layout.contentWrite(`${ui.dim}(当前:${getTheme()};用 /theme <名称> 切换)${ui.reset}\n`);
|
|
592
746
|
continue;
|
|
593
747
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
if (
|
|
598
|
-
|
|
748
|
+
else {
|
|
749
|
+
name = arg;
|
|
750
|
+
}
|
|
751
|
+
if (name === null)
|
|
752
|
+
continue; // Esc / Ctrl+D 取消
|
|
753
|
+
// 切:setTheme → 重算状态行(新色)→ 清内容重绘(历史 / 横幅,镜像启动 + /resume)→ 确认 → 持久化。
|
|
754
|
+
// markdown MEMO 按 themeVersion 自动失效,故 renderHistory 取新色;状态栏 / 输入框由 continue 回 INPUT 态时读 getter 刷。
|
|
755
|
+
setTheme(name);
|
|
756
|
+
refreshStatusBase(history);
|
|
757
|
+
layout.clearContent();
|
|
758
|
+
if (history.some((m) => m.role === 'user')) {
|
|
759
|
+
renderHistory(history);
|
|
760
|
+
}
|
|
761
|
+
else {
|
|
762
|
+
layout.contentWrite(bannerString(banner()));
|
|
763
|
+
}
|
|
764
|
+
layout.contentWrite(`${ui.dim}(已切换主题 ${name})${ui.reset}\n`);
|
|
765
|
+
updateConfigKey('MOCODE_THEME', name);
|
|
766
|
+
if (config.themeFromShell) {
|
|
767
|
+
layout.contentWrite(`${ui.dim}(shell 环境变量 MOCODE_THEME 已设,文件写入下次启动被其覆盖;取消该 shell 设置后生效)${ui.reset}\n`);
|
|
768
|
+
}
|
|
599
769
|
continue;
|
|
600
770
|
}
|
|
601
771
|
if (line === '/rollback' || line.startsWith('/rollback ')) {
|
|
@@ -604,38 +774,24 @@ export async function startRepl(initialHistory, sessionId, updateNotice = null)
|
|
|
604
774
|
await rollbackFlow();
|
|
605
775
|
continue;
|
|
606
776
|
}
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
777
|
+
const initialPlan = getAgentMode() === 'plan'; // 轮首模式(在 runTurn 之前读)
|
|
778
|
+
const ok = await runTurn(joined, initialPlan, placeholder);
|
|
779
|
+
// plan 轮正常结束(未中断 / 未抛错)→ 看轮末模式决定:
|
|
780
|
+
// - 仍 plan:LLM 没自切(只产计划就 STOP)→ 弹审批面板(原行为)。
|
|
781
|
+
// - 已 auto:LLM 调了 switch_mode('auto') 在同轮自主执行了 → 跳过审批,不重复打扰。
|
|
782
|
+
if (initialPlan && ok && getAgentMode() === 'plan') {
|
|
783
|
+
const res = await promptIntervention({
|
|
784
|
+
type: 'choice',
|
|
785
|
+
title: '计划已就绪',
|
|
786
|
+
detail: '切换到 auto 模式按上述计划执行?(plan 模式只读探查,执行需切 auto)',
|
|
787
|
+
options: ['切 auto 执行', '留 plan 细化'],
|
|
614
788
|
});
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
saveSession(history, currentSessionId);
|
|
620
|
-
}
|
|
621
|
-
catch {
|
|
622
|
-
// 落盘失败不阻断 REPL
|
|
789
|
+
if (res.action === 'selected' && res.value === '切 auto 执行') {
|
|
790
|
+
// setAgentMode('auto') 由 runTurn 入口做(listener 重写 history[0] 回 auto);这里只切运行态 + 合成执行轮。
|
|
791
|
+
layout.enterRunningMode('执行', '按计划执行…');
|
|
792
|
+
await runTurn('请按上述计划执行。', false, '按计划执行…');
|
|
623
793
|
}
|
|
624
|
-
persistSnapshots(currentSessionId); // 随会话落盘回滚快照(/resume 后仍可撤销)
|
|
625
|
-
// 后台反思:每 reflectEveryN 轮 fire-and-forget 一次(与下一轮 agent 并发,不阻塞)。
|
|
626
|
-
// 已有在飞任务 / autoReflect 关 → kickoff 内部自守卫。快照同步取(避免下一轮 mutate history 竞态)。
|
|
627
|
-
turnCount++;
|
|
628
|
-
if (turnCount % config.reflectEveryN === 0) {
|
|
629
|
-
kickoffReflection(snapshotTranscript(history, 20));
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
catch (e) {
|
|
633
|
-
layout.contentWrite(`${ui.red}[错误]${ui.reset} ${e instanceof Error ? e.message : String(e)}\n`);
|
|
634
|
-
}
|
|
635
|
-
finally {
|
|
636
|
-
stopRunningListener();
|
|
637
794
|
}
|
|
638
|
-
layout.contentWrite('\n'); // 轮次之间空行
|
|
639
795
|
}
|
|
640
796
|
// 退出前等在飞反思收尾(Ctrl+C 走 SIGINT 直退不等;fire-and-forget 不承诺中断时完成)。
|
|
641
797
|
await drainMemoryBackground();
|
package/dist/session/compact.js
CHANGED
|
@@ -147,7 +147,7 @@ async function defaultSummarize(older, focus) {
|
|
|
147
147
|
}
|
|
148
148
|
const sysMsg = {
|
|
149
149
|
role: 'system',
|
|
150
|
-
content: '
|
|
150
|
+
content: 'You are a session summarizer. Output only the summary body, max 300 words, preserving: the user\'s core request; files read/written/modified and key changes; key commands run and their result highlights; decisions made; current task progress and next step; open questions. Do not recap every detail.',
|
|
151
151
|
};
|
|
152
152
|
const userMsg = {
|
|
153
153
|
role: 'user',
|
package/dist/skills/index.js
CHANGED
|
@@ -39,8 +39,8 @@ export function buildSkillsSection() {
|
|
|
39
39
|
return [
|
|
40
40
|
'',
|
|
41
41
|
'',
|
|
42
|
-
'## Skills(
|
|
43
|
-
'
|
|
42
|
+
'## Skills (load on demand)',
|
|
43
|
+
'The following skills are available. Call the use_skill tool (passing the skill name) only when relevant to the current task, to load its full instructions and act on them; do not load them all blindly.',
|
|
44
44
|
...lines,
|
|
45
45
|
].join('\n');
|
|
46
46
|
}
|
|
@@ -3,26 +3,26 @@ import { promptIntervention } from '../../ui/intervention.js';
|
|
|
3
3
|
export const askHumanTool = {
|
|
4
4
|
name: 'ask_human',
|
|
5
5
|
description: [
|
|
6
|
-
'
|
|
7
|
-
'
|
|
8
|
-
'
|
|
9
|
-
'
|
|
6
|
+
'Call this tool when you hit a decision point during a task that requires human input — it pops up a question panel in the terminal for the user to choose.',
|
|
7
|
+
'Use when: multiple implementation approaches need a user decision, user intent is unclear and needs clarification, or extra info is needed to proceed.',
|
|
8
|
+
'Blocks until the user responds; the user can pick a preset option or choose "custom input" to answer freely; the result is returned as the tool result.',
|
|
9
|
+
'Do not call frequently when the task is clear and you can decide yourself — it interrupts the user. When options is omitted or empty, it becomes free-text input instead.',
|
|
10
10
|
].join(''),
|
|
11
11
|
parameters: {
|
|
12
12
|
type: 'object',
|
|
13
13
|
properties: {
|
|
14
14
|
question: {
|
|
15
15
|
type: 'string',
|
|
16
|
-
description: '
|
|
16
|
+
description: 'The question to ask the user; keep it concise (shown as the panel title)',
|
|
17
17
|
},
|
|
18
18
|
options: {
|
|
19
19
|
type: 'array',
|
|
20
20
|
items: { type: 'string' },
|
|
21
|
-
description: '
|
|
21
|
+
description: 'Options for the user to choose from (2~6). May be omitted — when omitted or empty, it becomes free-text input instead',
|
|
22
22
|
},
|
|
23
23
|
context: {
|
|
24
24
|
type: 'string',
|
|
25
|
-
description: '
|
|
25
|
+
description: 'Background explanation for the question (optional; helps the user understand why their decision is needed; shown under the title, may be multiline)',
|
|
26
26
|
},
|
|
27
27
|
},
|
|
28
28
|
required: ['question'],
|