mocode-ai 1.8.7 → 1.8.9

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.
@@ -0,0 +1,16 @@
1
+ // 常见邮箱域名 → SMTP/IMAP 主机预设。
2
+ // 纯数据叶子:config 向导(src/commands/config.ts)与 /mail setup 斜杠命令共用,
3
+ // 避免在两个交互入口各维护一份域名表。
4
+ export const MAIL_PROVIDERS = [
5
+ { match: /@gmail\.com$/i, smtp: 'smtp.gmail.com', imap: 'imap.gmail.com' },
6
+ { match: /@(qq|foxmail)\.com$/i, smtp: 'smtp.qq.com', imap: 'imap.qq.com' },
7
+ { match: /@163\.com$/i, smtp: 'smtp.163.com', imap: 'imap.163.com' },
8
+ { match: /@126\.com$/i, smtp: 'smtp.126.com', imap: 'imap.126.com' },
9
+ { match: /@(outlook|hotmail|live)\.com$/i, smtp: 'smtp.office365.com', imap: 'outlook.office365.com' },
10
+ { match: /@(?:.*\.)?sina\.com$/i, smtp: 'smtp.sina.com', imap: 'imap.sina.com' },
11
+ ];
12
+ /** 按邮箱账号后缀猜 SMTP/IMAP 主机;未知域名返回 undefined,交给用户手填。 */
13
+ export function guessMailHosts(user) {
14
+ const hit = MAIL_PROVIDERS.find((p) => p.match.test(user));
15
+ return hit ? { smtp: hit.smtp, imap: hit.imap } : undefined;
16
+ }
@@ -1,8 +1,9 @@
1
1
  import { classifyProvider, classifyModel, resolveBaseURL } from './protocol.js';
2
+ import { fmtCompactTokens } from '../ui/render.js';
2
3
  function fmtK(n) {
3
4
  if (!n || n <= 0)
4
5
  return '-';
5
- return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
6
+ return fmtCompactTokens(n);
6
7
  }
7
8
  /** 该预设是否与当前生效配置一致(用于标 ★)。 */
8
9
  export function isPresetCurrent(p, cur) {
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { promptIntervention } from '../ui/intervention.js';
5
+ import { promptWithMail } from '../mail/index.js';
6
6
  import { config } from '../config/index.js';
7
7
  import { readConfigFile, updateConfigKey } from '../config/file.js';
8
8
  import { getSandboxRoot } from '../sandbox/index.js';
@@ -218,7 +218,10 @@ async function checkPermissionWithSessionGrants(runtimeConfig, runtimeSessionGra
218
218
  catch {
219
219
  // 标记读/写失败 → 视为未展示过:多提示一次无害,少提示也只是回归现状。
220
220
  }
221
- const result = await (options.prompt ?? promptIntervention)({
221
+ // 显式注入的 prompt(stdio host / bg job)优先;默认走邮件中介——本地按键或邮件回复均可放行,
222
+ // 邮件未配置时 promptWithMail 内部退化为纯本地面板。
223
+ const prompt = options.prompt ?? promptWithMail;
224
+ const result = await prompt({
222
225
  type: 'choice',
223
226
  title: dangerous
224
227
  ? t('permission.dangerTitle', { tool: tool.name })
@@ -0,0 +1,193 @@
1
+ /**
2
+ * 邮件远程介入命令组:/mail · /mail setup · /mail test · /mail on|off
3
+ *
4
+ * - /mail 查看配置与启用状态(不回显密码)
5
+ * - /mail setup 在 REPL 内交互式配置账号/应用密码/SMTP/IMAP(常见邮箱主机自动推导)
6
+ * - /mail test 发一封测试邮件 + IMAP 登录自检,验证 SMTP/IMAP 连通性
7
+ * - /mail on|off 启停邮件提醒;运行时立即生效并持久化到全局配置
8
+ *
9
+ * 与 `mocode config` 向导写同一份全局配置(~/.mocode/config),两条入口等价;
10
+ * 这里用介入面板的 input 模式逐项收集,无需退出 TUI。
11
+ */
12
+ import * as layout from '../../ui/layout.js';
13
+ import { ui } from '../../ui/theme.js';
14
+ import { t } from '../../i18n/index.js';
15
+ import { readConfigFile, writeConfigKeys, updateConfigKey } from '../../config/file.js';
16
+ import { getMailStatus, sendTestMail, resetMailConfigCache, getMailPollState, pendingInterventionCount, } from '../../mail/index.js';
17
+ import { guessMailHosts } from '../../mail/providers.js';
18
+ import { promptIntervention } from '../../ui/intervention.js';
19
+ import { unhandled, next } from './types.js';
20
+ function maskSecret(s) {
21
+ return s ? '••••••' : '';
22
+ }
23
+ /** 弹一个单行输入面板;取消返回 null,提交返回去空白文本(空串=接受默认的语义由调用方按 seed 判断)。 */
24
+ async function askInput(title, detail, seed = '') {
25
+ const res = await promptIntervention({ type: 'input', title, detail, seed });
26
+ if (res.action === 'cancelled')
27
+ return null;
28
+ return (res.value ?? '').trim();
29
+ }
30
+ /** /mail:配置与状态概览。 */
31
+ function renderStatus() {
32
+ resetMailConfigCache(); // 读最新 env/配置,不被本进程缓存钉住
33
+ const { cfg, enabled } = getMailStatus();
34
+ const lines = [];
35
+ if (!cfg) {
36
+ lines.push(`${ui.dim}${t('mail.notConfigured')}${ui.reset}`, `${ui.dim}${t('mail.howToConfigure')}${ui.reset}`);
37
+ return lines.join('\n') + '\n';
38
+ }
39
+ const state = enabled ? `${ui.green}${t('mail.stateOn')}${ui.reset}` : `${ui.yellow}${t('mail.stateOff')}${ui.reset}`;
40
+ lines.push(`${ui.accent}${t('mail.title')}${ui.reset} ${state}`);
41
+ lines.push(` ${t('mail.fieldAccount')}: ${cfg.user}`);
42
+ lines.push(` ${t('mail.fieldTo')}: ${cfg.to}`);
43
+ lines.push(` ${t('mail.fieldPassword')}: ${maskSecret(cfg.pass)}`);
44
+ lines.push(` SMTP: ${cfg.smtpHost}:${cfg.smtpPort}${cfg.smtpSecure ? ' (TLS)' : ''} IMAP: ${cfg.imapHost}:${cfg.imapPort}${cfg.imapSecure ? ' (TLS)' : ''}`);
45
+ lines.push(` ${t('mail.fieldTiming', { idle: Math.round(cfg.idleMs / 1000), poll: Math.round(cfg.pollMs / 1000) })}`);
46
+ // 轮询诊断:邮件提醒是否真的在收、收到后卡在哪一步(排障用,不含敏感信息)。
47
+ const ps = getMailPollState();
48
+ if (ps.at > 0) {
49
+ lines.push(` ${ui.dim}${t('mail.lastPoll', {
50
+ time: new Date(ps.at).toLocaleTimeString(),
51
+ highest: String(ps.highest),
52
+ candidates: String(ps.candidates),
53
+ handled: String(ps.handled),
54
+ pending: String(pendingInterventionCount()),
55
+ })}${ui.reset}`);
56
+ if (ps.skipped)
57
+ lines.push(` ${ui.dim}${t('mail.lastPollSkip', { reason: ps.skipped })}${ui.reset}`);
58
+ if (ps.error)
59
+ lines.push(` ${ui.yellow}${t('mail.lastPollError', { error: ps.error })}${ui.reset}`);
60
+ }
61
+ else {
62
+ lines.push(` ${ui.dim}${t('mail.lastPollNever')}${ui.reset}`);
63
+ }
64
+ lines.push('');
65
+ lines.push(`${ui.dim}/mail setup · /mail test · /mail on · /mail off${ui.reset}`);
66
+ return lines.join('\n') + '\n';
67
+ }
68
+ function isMailLine(line) {
69
+ return line === '/mail' || line.startsWith('/mail ');
70
+ }
71
+ export const mailCommands = [
72
+ // 组内更具体的子命令排在前:setup → test → on/off → 兜底状态。
73
+ async (ctx) => {
74
+ if (ctx.line !== '/mail setup' && ctx.line !== '/mail config')
75
+ return unhandled();
76
+ const cur = readConfigFile();
77
+ // 1) 账号(预填现值)
78
+ const user = await askInput(t('mail.setupAccount'), t('mail.setupAccountHint'), cur.MOCODE_MAIL_USER ?? '');
79
+ if (user === null) {
80
+ layout.contentWrite(`${ui.dim}${t('mail.setupCancelled')}${ui.reset}\n`);
81
+ return next();
82
+ }
83
+ if (!user) {
84
+ layout.contentWrite(`${ui.yellow}${t('mail.setupNeedAccount')}${ui.reset}\n`);
85
+ return next();
86
+ }
87
+ // 2) 应用密码(本地终端输入,会回显;预填值仅在保留时用,不展示明文)
88
+ const pass = await askInput(t('mail.setupPass'), t('mail.setupPassHint'), '');
89
+ if (pass === null) {
90
+ layout.contentWrite(`${ui.dim}${t('mail.setupCancelled')}${ui.reset}\n`);
91
+ return next();
92
+ }
93
+ const finalPass = pass || cur.MOCODE_MAIL_PASS || '';
94
+ if (!finalPass) {
95
+ layout.contentWrite(`${ui.yellow}${t('mail.setupNeedPass')}${ui.reset}\n`);
96
+ return next();
97
+ }
98
+ // 3) SMTP / IMAP:按账号后缀猜默认,允许覆盖
99
+ const guessed = guessMailHosts(user);
100
+ const smtpDefault = cur.MOCODE_SMTP_HOST ?? guessed?.smtp ?? '';
101
+ const imapDefault = cur.MOCODE_IMAP_HOST ?? guessed?.imap ?? '';
102
+ const smtpHost = (await askInput(t('mail.setupSmtp'), t('mail.setupHostHint'), smtpDefault)) ?? null;
103
+ if (smtpHost === null) {
104
+ layout.contentWrite(`${ui.dim}${t('mail.setupCancelled')}${ui.reset}\n`);
105
+ return next();
106
+ }
107
+ const finalSmtp = smtpHost || smtpDefault;
108
+ const imapHost = (await askInput(t('mail.setupImap'), t('mail.setupHostHint'), imapDefault)) ?? null;
109
+ if (imapHost === null) {
110
+ layout.contentWrite(`${ui.dim}${t('mail.setupCancelled')}${ui.reset}\n`);
111
+ return next();
112
+ }
113
+ const finalImap = imapHost || imapDefault;
114
+ if (!finalSmtp || !finalImap) {
115
+ layout.contentWrite(`${ui.yellow}${t('mail.setupNeedHosts')}${ui.reset}\n`);
116
+ return next();
117
+ }
118
+ // 4) 持久化(合并写,保留其它键)+ 写 env 让本会话立即生效。
119
+ writeConfigKeys({
120
+ MOCODE_MAIL_ENABLED: 'true',
121
+ MOCODE_MAIL_USER: user,
122
+ MOCODE_MAIL_PASS: finalPass,
123
+ MOCODE_MAIL_TO: cur.MOCODE_MAIL_TO ?? user,
124
+ MOCODE_SMTP_HOST: finalSmtp,
125
+ MOCODE_IMAP_HOST: finalImap,
126
+ MOCODE_SMTP_PORT: cur.MOCODE_SMTP_PORT ?? '465',
127
+ MOCODE_IMAP_PORT: cur.MOCODE_IMAP_PORT ?? '993',
128
+ });
129
+ Object.assign(process.env, {
130
+ MOCODE_MAIL_ENABLED: 'true',
131
+ MOCODE_MAIL_USER: user,
132
+ MOCODE_MAIL_PASS: finalPass,
133
+ MOCODE_MAIL_TO: process.env.MOCODE_MAIL_TO ?? user,
134
+ MOCODE_SMTP_HOST: finalSmtp,
135
+ MOCODE_IMAP_HOST: finalImap,
136
+ });
137
+ resetMailConfigCache();
138
+ layout.contentWrite(`${ui.green}${t('mail.setupSaved')}${ui.reset}\n`);
139
+ layout.contentWrite(`${ui.dim}${t('mail.setupTestHint')}${ui.reset}\n`);
140
+ return next();
141
+ },
142
+ (ctx) => {
143
+ if (ctx.line !== '/mail test')
144
+ return unhandled();
145
+ const { cfg } = getMailStatus();
146
+ if (!cfg) {
147
+ layout.contentWrite(`${ui.dim}${t('mail.notConfigured')} ${t('mail.howToConfigure')}${ui.reset}\n`);
148
+ return next();
149
+ }
150
+ layout.contentWrite(`${ui.dim}${t('mail.testing')}${ui.reset}\n`);
151
+ void sendTestMail().then((r) => {
152
+ if (r.smtp === 'ok' && r.imap === 'ok') {
153
+ layout.contentWrite(`${ui.green}${t('mail.testOk')}${ui.reset}\n`);
154
+ }
155
+ else {
156
+ const parts = [
157
+ `SMTP ${r.smtp === 'ok' ? 'OK' : 'FAIL'}`,
158
+ `IMAP ${r.imap === 'ok' ? 'OK' : r.imap === 'skipped' ? 'SKIP' : 'FAIL'}`,
159
+ ];
160
+ layout.contentWrite(`${ui.yellow}${t('mail.testFail', { parts: parts.join(' · ') })}${ui.reset}\n`);
161
+ if (r.error)
162
+ layout.contentWrite(`${ui.dim}${r.error}${ui.reset}\n`);
163
+ }
164
+ });
165
+ return next();
166
+ },
167
+ (ctx) => {
168
+ if (ctx.line !== '/mail on' && ctx.line !== '/mail off')
169
+ return unhandled();
170
+ const { cfg } = getMailStatus();
171
+ if (!cfg) {
172
+ layout.contentWrite(`${ui.dim}${t('mail.notConfigured')} ${t('mail.howToConfigure')}${ui.reset}\n`);
173
+ return next();
174
+ }
175
+ const enable = ctx.line === '/mail on';
176
+ // 运行时立即生效(下一个介入即采用):写 env + 清邮件模块缓存;并持久化到全局配置。
177
+ process.env.MOCODE_MAIL_ENABLED = enable ? 'true' : 'false';
178
+ resetMailConfigCache();
179
+ updateConfigKey('MOCODE_MAIL_ENABLED', enable ? 'true' : 'false');
180
+ layout.contentWrite(enable ? `${ui.green}${t('mail.enabledNow')}${ui.reset}\n` : `${ui.yellow}${t('mail.disabledNow')}${ui.reset}\n`);
181
+ return next();
182
+ },
183
+ (ctx) => {
184
+ if (!isMailLine(ctx.line))
185
+ return unhandled();
186
+ // /mail 或无法识别的子参数:都显示状态,并对未知子参数给一行用法提示。
187
+ if (ctx.line.trim() !== '/mail') {
188
+ layout.contentWrite(`${ui.dim}${t('mail.unknownSub')}${ui.reset}\n`);
189
+ }
190
+ layout.contentWrite(renderStatus());
191
+ return next();
192
+ },
193
+ ];
@@ -21,6 +21,7 @@ import { diffCommands } from './diff.js';
21
21
  import { scheduleCommands } from './schedule.js';
22
22
  import { botsCommands } from './bots.js';
23
23
  import { flowCommands } from './flow.js';
24
+ import { mailCommands } from './mail.js';
24
25
  /**
25
26
  * 命令注册表。顺序即匹配优先级 —— 更具体的分支放前面。
26
27
  * 组内顺序由各文件自己保证(见文件头注释);组间顺序互不影响(条件互斥)。
@@ -50,6 +51,7 @@ export const commandHandlers = [
50
51
  ...scheduleCommands,
51
52
  ...botsCommands,
52
53
  ...flowCommands,
54
+ ...mailCommands,
53
55
  ];
54
56
  /**
55
57
  * 依次询问 handler,返回第一个非 unhandled 的结果。
@@ -34,6 +34,17 @@ export function buildSlashCommands() {
34
34
  { name: '/jobs', desc: '后台任务列表(/jobs log/kill <id前缀>)' },
35
35
  { name: '/schedules', desc: '查看定时计划与调度守护状态' },
36
36
  { name: '/bots', desc: '查看具名 Bot 列表' },
37
+ {
38
+ name: '/mail',
39
+ desc: '人工介入超时邮件提醒与邮件回复(/mail setup|test|on|off)',
40
+ children: [
41
+ { name: 'setup', value: '/mail setup', desc: '在 REPL 内配置邮箱账号、应用密码与 SMTP/IMAP' },
42
+ { name: 'status', value: '/mail', desc: '查看邮件通知配置与启用状态' },
43
+ { name: 'test', value: '/mail test', desc: '发测试邮件并自检 SMTP/IMAP' },
44
+ { name: 'on', value: '/mail on', desc: '开启邮件提醒(本会话立即生效并持久化)' },
45
+ { name: 'off', value: '/mail off', desc: '关闭邮件提醒' },
46
+ ],
47
+ },
37
48
  {
38
49
  name: '/memory',
39
50
  desc: d('commands.memory'),
@@ -196,7 +207,19 @@ export const HELP_GROUPS = [
196
207
  { key: 'help.groupSession', names: ['/sessions', '/rollback', '/memory', '/skills', '/skill', '/init'] },
197
208
  {
198
209
  key: 'help.groupConfig',
199
- names: ['/mode', '/subagent', '/fe', '/mcp', '/router', '/theme', '/pet', '/image', '/language', '/upgrade'],
210
+ names: [
211
+ '/mode',
212
+ '/subagent',
213
+ '/fe',
214
+ '/mcp',
215
+ '/router',
216
+ '/mail',
217
+ '/theme',
218
+ '/pet',
219
+ '/image',
220
+ '/language',
221
+ '/upgrade',
222
+ ],
200
223
  },
201
224
  ];
202
225
  /**
@@ -14,7 +14,7 @@ let runningCursor = 0; // 缓冲内光标字符索引(0..len);运行态支持任
14
14
  let runningPlaceholder = '';
15
15
  let currentAbort = null;
16
16
  let listening = false; // onRunningKey 是否处于挂载期(start → stop 之间)
17
- let queuedTurns = [];
17
+ const queuedTurns = [];
18
18
  /** 运行态打开的输入面板(Ctrl+G);非 null = 面板仍开着。主循环进 INPUT 态前须等它关闭,否则两个 keypress 监听抢键。 */
19
19
  let composerPending = null;
20
20
  /** 粘贴多行时 \r\n 合一:刚吃了 \r,尾随的 \n 需吞掉(与 INPUT 态编辑器一致)。 */
@@ -22,7 +22,7 @@ import { initializeAllMcp, getMcpTools, closeAllMcp } from '../mcp/index.js';
22
22
  import { refreshChatTools, classifyChatError } from '../llm/index.js';
23
23
  import { renderChip } from '../attachments/image.js';
24
24
  import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index.js';
25
- import { effectiveSystemPrompt } from '../skills/index.js';
25
+ import { effectiveSystemPrompt, skillsChangedSinceLastObserve } from '../skills/index.js';
26
26
  import { clearSkillActivation } from '../skills/activation.js';
27
27
  import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, initPersona, gcMemories, kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, } from '../memory/index.js';
28
28
  import { collectQueryHistory } from '../session/query-history.js';
@@ -497,6 +497,11 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
497
497
  // 入口设定本轮初始模式(合成执行轮传 false→auto;用户轮传当前 mode)。
498
498
  // setAgentMode 触发 listener 重写 history[0];模式只由用户面切换,runAgent 每步读取当前值。
499
499
  setAgentMode(planMode ? 'plan' : 'auto');
500
+ // 会话中途新增/修改 skill 后,普通对话轮也刷新系统提示,使新 skill 立即可见于模型,
501
+ // 不必等切模式 / /cd / /clear / 重启。listSkills 内部按签名热重载,此处只触发重建。
502
+ if (!inheritedToolPolicy && skillsChangedSinceLastObserve()) {
503
+ applyMode(getAgentMode() === 'plan');
504
+ }
500
505
  // 仅真实用户轮清除上一轮 inline skill 激活态。plan 审批后的合成执行轮继承
501
506
  // 同一 controller 与 skill deny,避免审批边界意外扩权。
502
507
  if (!inheritedToolPolicy)
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { ui } from '../ui/theme.js';
4
+ import { fmtCompactTokens } from '../ui/render.js';
4
5
  import * as layout from '../ui/layout.js';
5
6
  import { t } from '../i18n/index.js';
6
7
  import { config, getActiveEffort } from '../config/index.js';
@@ -23,7 +24,7 @@ export function renderContextBar(history) {
23
24
  const W = 10;
24
25
  const filled = Math.round(pct * W);
25
26
  const bar = '█'.repeat(filled) + '░'.repeat(W - filled);
26
- const k = (n) => `${Math.round(n / 1000)}k`;
27
+ const k = fmtCompactTokens;
27
28
  // 标签必须描述**这个数字**是什么:本条 bar 恒为「对话内容」估算(dialog-only,不含
28
29
  // system prompt / 工具 schema),与底栏用量条、80% 压力线都不是同一个数。
29
30
  // 旧实现只要 lastUsage 存在就打「实测」,而显示的仍是估算值 —— 标签与数字对不上,
@@ -108,8 +109,8 @@ export function renderContextBarInline(history) {
108
109
  const W = 10;
109
110
  const filled = Math.round(pct * W);
110
111
  const bar = '█'.repeat(filled) + '░'.repeat(W - filled);
111
- // 与轮末 token 行 formatTurnTokens 同一格式:<10k 保留一位小数,锚点生效时两处逐字一致(5.2k)。
112
- const k = (n) => (n < 1000 ? `${Math.round(n)}` : `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k`);
112
+ // 与轮末 token 行 formatTurnTokens 同一格式(共用 fmtCompactTokens):<10k 保留一位小数,锚点生效时两处逐字一致(5.2k);≥100k 切 M。
113
+ const k = fmtCompactTokens;
113
114
  const pctCol = pct >= DEFAULT_BUDGET_POLICY.pressureTriggerRatio ? ui.yellow : ui.accent;
114
115
  return `${ui.gray}[${pctCol}${bar}${ui.reset}] ${pctCol}${Math.round(pct * 100)}%${ui.reset} ${ui.dim}${k(est)}/${k(win)}${ui.reset}`;
115
116
  }
@@ -4,6 +4,7 @@
4
4
  // Playwright 浏览器进程在正常路径 await close(),硬退出路径依赖 Playwright 自身的 exit 处理。
5
5
  // 两个入口都必须幂等:normal exit / SIGINT / uncaughtException 可能重复触发。
6
6
  import { stopAllDevServersSync } from './dev-server-manager.js';
7
+ import { stopMailPollerSync } from '../mail/index.js';
7
8
  let asyncDone = false;
8
9
  /** 正常退出路径:可 await,尽量优雅关闭。 */
9
10
  export async function shutdownRuntime() {
@@ -38,4 +39,5 @@ export async function shutdownRuntime() {
38
39
  /** 同步兜底(process exit / 信号 / 未捕获异常):只做同步树杀,不留孤儿 dev server。 */
39
40
  export function shutdownRuntimeSync() {
40
41
  stopAllDevServersSync();
42
+ stopMailPollerSync(); // 回收 IMAP 轮询定时器(已 unref,此处幂等保险)
41
43
  }
@@ -3,6 +3,7 @@ import { config } from '../config/index.js';
3
3
  import { COMPACT_USER_VERBATIM_MAX_TOKENS, COMPACT_USER_VERBATIM_WINDOW_RATIO, MAX_HISTORY_RESULT, MAX_MEMORY_RESULT, MAX_OLD_TOOL_STUB, MAX_SKILL_RESULT, SUMMARY_KEYFACTS_MAX_CHARS, SUMMARY_KEYFACTS_MIN_CHARS, SUMMARY_KEYFACTS_WINDOW_RATIO, SUMMARY_MSG_MAX_CHARS, SUMMARY_OUTPUT_MAX_CHARS, SUMMARY_TRANSCRIPT_WINDOW_RATIO, USER_DIRECTIVE_MAX_CHARS, USER_DIRECTIVE_MAX_CONSTRAINTS, } from '../tools/constants.js';
4
4
  import { ui } from '../ui/theme.js';
5
5
  import { Spinner } from '../ui/spinner.js';
6
+ import { fmtCompactTokens } from '../ui/render.js';
6
7
  import * as layout from '../ui/layout.js';
7
8
  import { defaultRollbackStore } from '../rollback/index.js';
8
9
  import { toText } from '../context/utils.js';
@@ -649,12 +650,12 @@ async function forkSummarize(prefix, instruction, signal, runtime, activeTools,
649
650
  function rawPromptTokens(history, activeTools) {
650
651
  return estimatePromptTokens(history, activeTools, 1);
651
652
  }
652
- /** 压缩行统一格式:`● 标签 205214 → 28614 tokens (80% → 11%)`。
653
+ /** 压缩行统一格式:`● 标签 205k → 29k tokens (80% → 11%)`(≥100k 用 0.x M)。
653
654
  * 百分比与数字同源(裸估算 / 窗口),让「凭什么这时压」在行内自证,不必回头翻代码。 */
654
655
  function compactionLogLine(label, before, after, window) {
655
656
  const pct = (n) => `${Math.round((n / Math.max(1, window)) * 100)}%`;
656
657
  return (` ${ui.bold}${ui.accent}●${ui.reset} ${ui.accent}${label}${ui.reset} ` +
657
- `${ui.dim}${before} → ${after} tokens (${pct(before)} → ${pct(after)})${ui.reset}\n`);
658
+ `${ui.dim}${fmtCompactTokens(before)} → ${fmtCompactTokens(after)} tokens (${pct(before)} → ${pct(after)})${ui.reset}\n`);
658
659
  }
659
660
  /**
660
661
  * 压缩 history(原地)。手动 /compact 与自动 maybeCompact 都走这里。
@@ -9,7 +9,6 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import os from 'node:os';
10
10
  import path from 'node:path';
11
11
  import { parseReasoningEffort } from '../llm/reasoning.js';
12
- import { builtinSkillNames } from './builtin-skills.js';
13
12
  /** 把开头的 ~/ 或 ~ 展开为 home 目录(Windows 与 POSIX 通用)。 */
14
13
  function expandHome(p) {
15
14
  if (p === '~')
@@ -207,12 +206,8 @@ export function discoverSkills() {
207
206
  // SKILLS_DIRS 自定义目录无法归类 project,统一按 user(免门禁)处理。
208
207
  const origin = dir === projDir ? 'project' : 'user';
209
208
  for (const name of entries) {
210
- // 跳过内置 skill 同名目录(项目级用户版可放在 ~/.mocode/skills/<name>/
211
- // 覆盖内置版;cwd/.mocode/skills/<name>/ 也算项目级覆盖)。discoverSkills 按
212
- // 优先级升序遍历、项目级 Map.set 后写覆盖先写,所以这里只是「不重复登记内置」,
213
- // 真实覆盖逻辑在 listSkills 的合并步骤。
214
- if (builtinSkillNames.has(name))
215
- continue;
209
+ // 不跳过与内置同名的目录:discoverSkills 按优先级升序遍历、listSkills 合并时
210
+ // 磁盘 skill 后写覆盖内置版,故 ~/.mocode/skills/codegraph/ 等可正常覆盖内置版。
216
211
  const skillDir = path.join(dir, name);
217
212
  const skillMdPath = path.join(skillDir, 'SKILL.md');
218
213
  try {
@@ -269,6 +264,23 @@ export function skillsScanSignature() {
269
264
  catch {
270
265
  parts.push('D' + dir + 'x');
271
266
  }
267
+ // 同时 stat 每个一级子目录:覆盖"先 mkdir 空子目录、会话中才写入 SKILL.md"的盲区——
268
+ // 写文件改的是子目录 mtime,skills 根目录 mtime 此时不变。
269
+ try {
270
+ for (const name of readdirSync(dir, { withFileTypes: true })) {
271
+ if (!name.isDirectory())
272
+ continue;
273
+ try {
274
+ parts.push('S' + path.join(dir, name.name) + statSync(path.join(dir, name.name)).mtimeMs);
275
+ }
276
+ catch {
277
+ parts.push('S' + path.join(dir, name.name) + 'x');
278
+ }
279
+ }
280
+ }
281
+ catch {
282
+ // 根目录不可读已在上面记 'x',这里无需再处理。
283
+ }
272
284
  }
273
285
  for (const p of lastKnownMdPaths) {
274
286
  try {
@@ -9,6 +9,23 @@ import { discoverSkills, parseFrontmatter, skillsScanSignature } from './discove
9
9
  import { builtinSkills } from './builtin-skills.js';
10
10
  let cache = null;
11
11
  let cacheKey = null;
12
+ /**
13
+ * 自上次调用以来磁盘上的 skill 集合/内容是否发生变化(增删目录、改 SKILL.md)。
14
+ * 供 REPL 每个真实用户轮入口探测:变了就重建 history[0],让会话中途新增的 skill
15
+ * 无需重启/切模式即可进入模型清单。首轮(尚未构建过系统提示)不算变化,避免多余重建。
16
+ */
17
+ let observedKey = null;
18
+ export function skillsChangedSinceLastObserve() {
19
+ const key = skillsScanSignature();
20
+ if (observedKey === null) {
21
+ observedKey = key;
22
+ return false;
23
+ }
24
+ if (key === observedKey)
25
+ return false;
26
+ observedKey = key;
27
+ return true;
28
+ }
12
29
  /** 当前扫描签名(各 skills 目录 + 各 SKILL.md 的 mtime 拼接);用于热重载失效判断。 */
13
30
  function currentKey() {
14
31
  return skillsScanSignature();
@@ -1,4 +1,4 @@
1
- import { promptIntervention } from '../../ui/intervention.js';
1
+ import { promptWithMail } from '../../mail/index.js';
2
2
  import { sendState } from '../../pet/bridge.js';
3
3
  import { t } from '../../i18n/index.js';
4
4
  /** 把单个选项元素安全地转成 {label, detail}。LLM 有时传对象而不是字符串,这里提取可读字段。 */
@@ -159,7 +159,7 @@ export const askHumanTool = {
159
159
  const options = coerceOptions(args.options);
160
160
  const context = args.context ? String(args.context) : undefined;
161
161
  sendState('waiting_human');
162
- const result = await promptIntervention({
162
+ const result = await promptWithMail({
163
163
  type: options.length > 0 ? 'choice' : 'input',
164
164
  title: question,
165
165
  options: options.length > 0 ? options : undefined,
@@ -21,6 +21,24 @@ export function promptIntervention(req) {
21
21
  return result;
22
22
  }
23
23
  let panelQueue = Promise.resolve();
24
+ /**
25
+ * 当前活跃面板的 finish 句柄。面板经 panelQueue 串行化,同一进程至多一个活跃面板。
26
+ * 供「外部通道应答」(邮件/远程审批)在用户未操作终端时编程式关闭面板:
27
+ * 由 dismissActiveIntervention 调用,等价于用户在面板上做出同一选择。
28
+ * 无活跃面板时为 null;cleanup() 负责清空。
29
+ */
30
+ let activeFinish = null;
31
+ /**
32
+ * 从外部(非键盘)结束当前活跃介入面板。返回是否有面板被关闭。
33
+ * 用于邮件回复到达时收起本地 TUI 面板;finish 自带 resolved 幂等守卫,重复调用安全。
34
+ */
35
+ export function dismissActiveIntervention(result) {
36
+ const finish = activeFinish;
37
+ if (!finish)
38
+ return false;
39
+ finish(result);
40
+ return true;
41
+ }
24
42
  async function promptInterventionInner(req) {
25
43
  // 非 TTY 降级:不阻塞,自动选默认。日志走 stderr(不污染 stdout 内容流)。
26
44
  if (!layout.isActive()) {
@@ -172,6 +190,11 @@ async function promptInterventionInner(req) {
172
190
  redraw();
173
191
  }
174
192
  function redraw() {
193
+ // 介入面板在 RUNNING 态弹出,最关键的命令/diff/ask_human 行恰好在内容区底部。
194
+ // 先按菜单行数预留内容区底部等宽行:正文整体重排到菜单上沿之上,菜单不再盖住决策依据;
195
+ // 菜单高度不变时 setMenuReserve 内部去重,↑↓ 导航不会整屏闪。
196
+ const menuLines = mode === 'choice' ? menuLinesChoice() : menuLinesInput();
197
+ layout.setMenuReserve(menuLines.length);
175
198
  if (mode === 'choice') {
176
199
  const hint = t('prompt.chooseConfirm');
177
200
  layout.paintInput({
@@ -179,7 +202,7 @@ async function promptInterventionInner(req) {
179
202
  lines: [hint],
180
203
  cursorLine: 0,
181
204
  cursorCol: displayWidth(hint),
182
- menu: { lines: menuLinesChoice() },
205
+ menu: { lines: menuLines },
183
206
  });
184
207
  }
185
208
  else {
@@ -188,7 +211,7 @@ async function promptInterventionInner(req) {
188
211
  lines: [text],
189
212
  cursorLine: 0,
190
213
  cursorCol: displayWidth(text.slice(0, cursor)),
191
- menu: { lines: menuLinesInput() },
214
+ menu: { lines: menuLines },
192
215
  });
193
216
  }
194
217
  }
@@ -199,14 +222,31 @@ async function promptInterventionInner(req) {
199
222
  cleanup();
200
223
  resolve(result);
201
224
  }
225
+ /** 终端尺寸变化:layout 先重设区域/钳预留(它也挂了 SIGWINCH),稍等再按新几何重算
226
+ * 菜单行数并重设预留 + 重画,否则窗口缩高后旧菜单会超出新预留带、选项被裁。 */
227
+ function onResize() {
228
+ setTimeout(() => {
229
+ if (resolved)
230
+ return;
231
+ redraw();
232
+ }, 60);
233
+ }
202
234
  /** 退出:摘自己的监听 + 恢复快照监听 + 擦菜单恢复内容区。不 setRawMode(false)/pause stdin(运行态由 repl 接管)。 */
203
235
  function cleanup() {
236
+ if (activeFinish === finish)
237
+ activeFinish = null;
204
238
  layout.setMouseEnabled(true); // 恢复鼠标框选(面板期间禁,防拖拽覆盖菜单)
205
239
  layout.setCursorChangeHandler(null); // 注销光标变更处理器
206
240
  emitter.removeListener('keypress', onKey);
207
241
  for (const l of savedListeners)
208
242
  emitter.on('keypress', l);
209
243
  savedListeners = [];
244
+ try {
245
+ process.removeListener('SIGWINCH', onResize);
246
+ }
247
+ catch {
248
+ // 忽略
249
+ }
210
250
  // 先 paintInput(dim,menu:null):擦菜单(用 lastMenuRows)+ 画 dim 占位底栏 + 复位 lastMenuRows=0;
211
251
  // 再处理滚动:面板内可能滚过滚轮(scrollOffset>0)→ resetScroll 回尾让 agent 后续输出可见;
212
252
  // 未滚则 repaintViewport 从 content 缓冲重画内容区(恢复被菜单覆盖的 ● ask_human 行)。
@@ -218,6 +258,10 @@ async function promptInterventionInner(req) {
218
258
  cursorCol: 0,
219
259
  menu: null,
220
260
  });
261
+ // 释放菜单预留行:正文恢复满内容区(setMenuReserve 内部重画被菜单占过的底部行)。
262
+ // 必须在 menu:null 擦菜单之后——先释放会让 repaintViewport 用正文覆盖尚未擦的菜单,
263
+ // 紧接着的 stale lastMenuRows 擦除又会把刚恢复的正文抹掉。
264
+ layout.setMenuReserve(0);
221
265
  if (layout.isScrolled())
222
266
  layout.resetScroll();
223
267
  else
@@ -352,6 +396,7 @@ async function promptInterventionInner(req) {
352
396
  }
353
397
  return new Promise((res, rej) => {
354
398
  resolve = res;
399
+ activeFinish = finish; // 暴露给外部通道(dismissActiveIntervention)编程式关闭
355
400
  try {
356
401
  // 进入面板:停 spinner(避免 onFrame 覆盖)+ 停走时计时器(避免 drawStatusBar 80ms 心跳
357
402
  // 把真光标拉到 runningCaretPos 覆盖 paintInput 的正确光标位)+ 禁鼠标框选(防拖拽 viewport 重画覆盖菜单)+ 回尾(若用户正滚动回看)
@@ -376,6 +421,12 @@ async function promptInterventionInner(req) {
376
421
  }
377
422
  stdin.resume();
378
423
  emitter.on('keypress', onKey);
424
+ try {
425
+ process.on('SIGWINCH', onResize);
426
+ }
427
+ catch {
428
+ // 不支持则放弃 resize 自适应,不阻断面板
429
+ }
379
430
  layout.setCursorChangeHandler(applyExternalCursor); // 鼠标左键单击输入框 → 移光标到点击位
380
431
  redraw();
381
432
  }
@@ -388,6 +439,12 @@ async function promptInterventionInner(req) {
388
439
  catch {
389
440
  // 忽略
390
441
  }
442
+ try {
443
+ process.removeListener('SIGWINCH', onResize);
444
+ }
445
+ catch {
446
+ // 忽略
447
+ }
391
448
  for (const l of savedListeners) {
392
449
  try {
393
450
  emitter.on('keypress', l);
@@ -397,6 +454,8 @@ async function promptInterventionInner(req) {
397
454
  }
398
455
  }
399
456
  savedListeners = [];
457
+ if (activeFinish === finish)
458
+ activeFinish = null;
400
459
  rej(e instanceof Error ? e : new Error(String(e)));
401
460
  }
402
461
  });