mocode-ai 1.8.6 → 1.8.8

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.
@@ -4,7 +4,7 @@
4
4
  // 行为与重构前的单文件 runAgent 完全一致——这是安全重构,实跑回归验证。
5
5
  import { ui } from '../ui/theme.js';
6
6
  import { Spinner } from '../ui/spinner.js';
7
- import { summarizeToolCall, summarizeToolResult, truncateDisplay, fmtElapsed } from '../ui/render.js';
7
+ import { summarizeToolCall, summarizeToolResult, truncateDisplay, fmtElapsed, fmtCompactTokens } from '../ui/render.js';
8
8
  import { renderFileChange, renderMultiFileChange } from '../ui/diff.js';
9
9
  import * as layout from '../ui/layout.js';
10
10
  import * as batch from '../ui/batch.js';
@@ -417,6 +417,10 @@ runtimeOrContext = defaultRuntime) {
417
417
  spinner.start(t('agent.generating', { tool: name }));
418
418
  },
419
419
  onStepStart: () => spinner.start(t('agent.thinking')),
420
+ // 压缩重建 history 是硬边界:收口压缩前仍未 flush 的工具批,
421
+ // 否则压缩后第一步的工具调用会因 currentBatchId 仍挂着而并进压缩前的「探索」集合,
422
+ // 形成跨压缩行的巨型批次。收口后压缩后的调用自然另起新批。
423
+ onHistoryRebuilt: () => flushToolBatch(),
420
424
  onChatDone: () => spinner.stop(),
421
425
  // 退避重试要在状态行可见:否则用户面对的是几十秒到几分钟的静止 spinner,与卡死无异。
422
426
  onModelRetry: (r) => spinner.start(t('agent.retrying', { seconds: Math.max(1, Math.round(r.waitMs / 1000)), attempt: r.attempt })),
@@ -549,7 +553,7 @@ function formatTurnTokens(usage) {
549
553
  const total = usage.totalTokens;
550
554
  if (!total)
551
555
  return '';
552
- const fmt = (n) => (n < 1000 ? `${n}` : `${(n / 1000).toFixed(total >= 10000 ? 0 : 1)}k`);
556
+ const fmt = fmtCompactTokens;
553
557
  const cached = usage.cachedTokens;
554
558
  const cacheCreated = usage.cacheCreationTokens ?? 0;
555
559
  const reasoning = usage.reasoningTokens;
@@ -135,6 +135,7 @@ export async function runModelTurn(input) {
135
135
  rebuildHistoryIndexes();
136
136
  if (!opts.suppressSessionState)
137
137
  sessionStateText = ctx.buildSessionStateReminder();
138
+ hooks.onHistoryRebuilt?.();
138
139
  }
139
140
  hooks.onStepStart?.();
140
141
  const stream = { mode: 'idle', gotText: false, lastChar: '' };
@@ -422,6 +423,7 @@ export async function runModelTurn(input) {
422
423
  if (overflowResult.kind === 'rebuild') {
423
424
  historyRebuilt = true;
424
425
  rebuildHistoryIndexes();
426
+ hooks.onHistoryRebuilt?.();
425
427
  }
426
428
  requestHistory = buildRequestHistory();
427
429
  stepPromptEst = estimatePromptTokens(requestHistory, activeTools, runtimeContextState.correction);
@@ -22,11 +22,12 @@ export function inferModelFamily(model) {
22
22
  */
23
23
  const CORE_SECTION = `Use your judgment to choose the shortest reliable path from the request to a useful result.
24
24
 
25
- - Inspect only the code and context needed for the next decision.
25
+ - Answer directly when you already can: questions, explanations, advice, reviews, and read-only analysis that the conversation and known evidence already support get a direct answer with no tools, no extra investigation, and no validation. Reach for a tool only when the answer genuinely depends on information you do not have.
26
+ - Inspect only the code and context needed for the next decision; do not gather evidence "just in case".
26
27
  - Make the smallest coherent change and avoid unrelated refactors.
27
28
  - Preserve existing behavior and public API compatibility unless the task explicitly requires a change.
28
- - Decide whether validation is useful based on risk, scope, available commands, and the user's request. Validation is optional, not a completion gate.
29
- - When validation is useful, choose the smallest relevant check yourself; do not run broad test/build suites by default.
29
+ - Validation (typecheck/lint/build/test, or running the change) applies only to work that changes code or behavior. Decide whether it is useful based on risk, scope, available commands, and the user's request; it is never required for pure questions, explanations, or read-only analysis. It is optional, not a completion gate, and the user asking for an answer is not asking for verification.
30
+ - When validation is useful, choose the smallest relevant check yourself; do not run broad test/build suites by default. Trivial, self-evidently correct edits (comments, docs, typo fixes) need no check either.
30
31
  - Re-read or rerun only when evidence is stale or the next edit depends on exact current content.
31
32
  - On failure, diagnose before retrying; after repeated identical failures, change approach.
32
33
  - Report honestly what you changed, what you checked, and anything left uncertain.
@@ -1,5 +1,6 @@
1
1
  import * as readline from 'node:readline';
2
2
  import { CONFIG_PATH, readConfigFile, writeConfigKeys } from '../config/file.js';
3
+ import { guessMailHosts } from '../mail/providers.js';
3
4
  import { detectLanguage, setLanguage, t } from '../i18n/index.js';
4
5
  function ask(rl, q) {
5
6
  return new Promise((resolve) => {
@@ -34,12 +35,57 @@ export async function runConfigWizard() {
34
35
  }
35
36
  const modelIn = await ask(rl, `LLM_MODEL${cur.LLM_MODEL ? ` [${cur.LLM_MODEL}]` : ''}${t('config.modelDefault')}: `);
36
37
  const model = modelIn || cur.LLM_MODEL || 'gpt-4o-mini';
38
+ // ── 可选:人工介入超时邮件通知(SMTP 发提醒 + IMAP 收回复)。回车跳过即不启用。──
39
+ const mail = await collectMailConfig(rl, cur, ask);
37
40
  rl.close();
38
- // 合并:保留其它键,只覆盖三键。
41
+ // 合并:保留其它键,只覆盖向导管理的键。
39
42
  writeConfigKeys({
40
43
  LLM_BASE_URL: baseURL,
41
44
  LLM_API_KEY: apiKey,
42
45
  LLM_MODEL: model,
46
+ ...mail,
43
47
  });
44
48
  console.log(t('config.done', { path: CONFIG_PATH }));
45
49
  }
50
+ /** 常见邮箱主机由 mail/providers.ts 统一维护(向导与 /mail setup 共用)。 */
51
+ /**
52
+ * 询问邮件通知配置。返回待写入的键(值为 null 表示删除/不写)。
53
+ * 已配置时显示现状;首个问题回车(空)表示跳过,保留既有配置不变。
54
+ */
55
+ async function collectMailConfig(rl, cur, ask) {
56
+ const already = !!(cur.MOCODE_MAIL_USER && cur.MOCODE_SMTP_HOST && cur.MOCODE_IMAP_HOST);
57
+ const enableIn = await ask(rl, already ? `\n${t('config.mailEnabled')} ${t('config.mailEnablePrompt')}: ` : `\n${t('config.mailPrompt')}: `);
58
+ // 空回答:未配置→不启用(不写键);已配置→原样保留(不返回任何邮件键)。
59
+ if (!enableIn)
60
+ return {};
61
+ const enable = /^(y|yes|是|1|true|on)$/i.test(enableIn);
62
+ if (!enable) {
63
+ // 显式关闭:写 MOCODE_MAIL_ENABLED=false,其余凭据保留在文件里不删。
64
+ return { MOCODE_MAIL_ENABLED: 'false' };
65
+ }
66
+ const user = (await ask(rl, `${t('config.mailUser')}${cur.MOCODE_MAIL_USER ? ` [${cur.MOCODE_MAIL_USER}]` : ''}: `)) ||
67
+ cur.MOCODE_MAIL_USER ||
68
+ '';
69
+ const preset = guessMailHosts(user);
70
+ const defSmtp = cur.MOCODE_SMTP_HOST ?? preset?.smtp ?? '';
71
+ const defImap = cur.MOCODE_IMAP_HOST ?? preset?.imap ?? '';
72
+ const pass = (await ask(rl, `${t('config.mailPass')}${cur.MOCODE_MAIL_PASS ? t('config.keySet') : ''}: `)) ||
73
+ cur.MOCODE_MAIL_PASS ||
74
+ '';
75
+ const smtpHost = (await ask(rl, `${t('config.mailSmtp')}${defSmtp ? ` [${defSmtp}]` : ''}: `)) || defSmtp;
76
+ const imapHost = (await ask(rl, `${t('config.mailImap')}${defImap ? ` [${defImap}]` : ''}: `)) || defImap;
77
+ if (!user || !pass || !smtpHost || !imapHost) {
78
+ console.log(t('config.mailIncomplete'));
79
+ return {};
80
+ }
81
+ return {
82
+ MOCODE_MAIL_ENABLED: 'true',
83
+ MOCODE_MAIL_USER: user,
84
+ MOCODE_MAIL_PASS: pass,
85
+ MOCODE_MAIL_TO: cur.MOCODE_MAIL_TO ?? user,
86
+ MOCODE_SMTP_HOST: smtpHost,
87
+ MOCODE_IMAP_HOST: imapHost,
88
+ MOCODE_SMTP_PORT: cur.MOCODE_SMTP_PORT ?? '465',
89
+ MOCODE_IMAP_PORT: cur.MOCODE_IMAP_PORT ?? '993',
90
+ };
91
+ }
@@ -469,11 +469,12 @@ Complete programming tasks through an "analyze → call tool → observe result
469
469
  - PLAN: read-only design; no changes until the user approves and switches back.
470
470
 
471
471
  ## Workflow
472
+ - Answer first: if the request is a question, explanation, or read-only analysis you can already answer from context and known evidence, reply directly — no tools, no exploration, no verification ceremony. Tool calls and checks exist only to get information the answer actually needs.
472
473
  - Understand: use existing conversation and tool evidence before gathering more.
473
474
  - Plan: for tasks with 3+ steps or context-loss risk, record the plan with the \`plan_update\` tool (see Session state).
474
475
  - Delegate: when the \`sub-agent\` tool is exposed, prefer it for exploration-heavy work (unfamiliar subsystems, multi-file audits, open-ended "how does X work here" investigation) and for independent sub-tasks — emit several \`sub-agent\` calls in ONE message and they run concurrently. A worker returns only its summary, so its tool noise never floods the main context. Keep single known-path reads and trivial lookups inline.
475
476
  - Implement: edit against a fresh read (see Tool policy); change scope follows Engineering principles.
476
- - Verify: whether and what to run follows Engineering principles; use Validation commands for exact commands.
477
+ - Verify: only for work that changes code or behavior, and only when the risk is worth it — pure answers and read-only analysis need no verification. Whether and what to run follows Engineering principles; use Validation commands for exact commands.
477
478
  - Report: stop when done and give honest conclusions with path:line references (see Reporting).
478
479
  - Use web search only when freshness materially affects the answer.
479
480
  ${buildCodegraphSection()}
@@ -507,7 +508,7 @@ ${buildVoiceSection()}
507
508
  - **Do not stop prematurely during exploration**: if you started investigating but haven't gathered enough information to answer the user's question, keep calling tools. Only stop when you have sufficient evidence or hit a dead end.
508
509
  - **No flattery / no preamble in conclusions**: skip "Sure", "好的", "我已经完成了" and similar no-information prefixes — jump straight to substance.
509
510
  - Close with a brief explanation of what you did and why, not just a verdict, so the user doesn't have to re-read the tool trace: when files changed, group them by file or logical change — what changed and the behavior/fix it delivers, one or two lines each with "path:line" references, noting renames/deletions and skipping purely mechanical edits; for investigation or analysis, state the conclusion and the key evidence. Say success when successful, where you're stuck when failing, and anything skipped. Keep it concise.
510
- - Definition of done: never declare a multi-feature request finished just because the code exists. Each distinct user request listed in the plan must be actually verified (the relevant check run / observed result), not merely implemented; mark plan steps \`[x]\` only after that verification. If the user supplied an acceptance list, every item on it must pass. Leave unverified items explicitly listed as pending instead of collapsing them into "done".`;
511
+ - Definition of done (code/behavior changes only): never declare a multi-feature implementation finished just because the code exists. Each distinct implementation request listed in the plan must be actually verified where a check is warranted (the relevant check run / observed result), not merely implemented; mark plan steps \`[x]\` only after that verification. If the user supplied an acceptance list, every item on it must pass. Leave unverified items explicitly listed as pending instead of collapsing them into "done". This rule does not apply to questions, explanations, or read-only analysis — answer those directly with no verification.`;
511
512
  // 动态段(置于末尾):AGENTS.md 项目记忆 + notepad 索引/说明。工具簇特定指导由
512
513
  // ToolPolicyController.reminder() 按当前 turn 的 route 注入,避免旧全局 profile 与真实 schema 分裂。
513
514
  // 按需注入(#13):有内容的索引才拼对应标题,避免空标题噪声。
@@ -203,6 +203,64 @@ const zhCN = {
203
203
  'config.modelDefault': '(回车默认 gpt-4o-mini)',
204
204
  'config.required': '\n[config] {key} 不能为空,已取消。',
205
205
  'config.done': '\n已写入 {path}。现在运行 `mocode` 即可启动(任意目录、任意终端)。',
206
+ 'config.mailPrompt': '是否启用「人工介入超时邮件提醒 + 回复邮件继续执行」?(y/N,回车跳过)',
207
+ 'config.mailEnabled': '已检测到邮件配置。',
208
+ 'config.mailEnablePrompt': '重新配置邮件通知?(y=重新配置,n/回车=保持现状)',
209
+ 'config.mailUser': '邮箱账号(同时作为发件/收件/登录名)',
210
+ 'config.mailPass': '应用专用密码或授权码(多数邮箱不能用登录密码)',
211
+ 'config.mailSmtp': 'SMTP 主机',
212
+ 'config.mailImap': 'IMAP 主机(需在邮箱设置里开启 IMAP)',
213
+ 'config.mailIncomplete': '[config] 邮件配置不完整(账号/密码/SMTP/IMAP 缺一),已跳过邮件配置。',
214
+ 'mail.title': '邮件远程介入',
215
+ 'mail.stateOn': '已开启',
216
+ 'mail.stateOff': '已关闭',
217
+ 'mail.notConfigured': '邮件通知尚未配置。',
218
+ 'mail.howToConfigure': '在 REPL 内运行 `/mail setup` 配置(或退出后跑 `mocode config` 向导)。',
219
+ 'mail.setupAccount': '邮箱账号',
220
+ 'mail.setupAccountHint': '同时作为发件/收件/登录名,如 you@example.com。回车确认,Esc 取消。',
221
+ 'mail.setupPass': '应用专用密码 / 授权码',
222
+ 'mail.setupPassHint': '多数邮箱不能用登录密码,需在邮箱设置里生成应用专用密码并开启 IMAP。输入会显示在屏幕上,注意周围无人。',
223
+ 'mail.setupSmtp': 'SMTP 主机',
224
+ 'mail.setupImap': 'IMAP 主机',
225
+ 'mail.setupHostHint': '已按账号后缀给出默认值,直接回车采用,或输入自定义主机。',
226
+ 'mail.setupCancelled': '已取消邮件配置,未做改动。',
227
+ 'mail.setupNeedAccount': '邮箱账号不能为空,已取消。',
228
+ 'mail.setupNeedPass': '应用密码不能为空,已取消。',
229
+ 'mail.setupNeedHosts': 'SMTP/IMAP 主机不能为空,已取消。',
230
+ 'mail.setupSaved': '邮件配置已保存并在本会话立即生效。',
231
+ 'mail.setupTestHint': '可运行 /mail test 验证收发,再用 /mail off 临时关闭。',
232
+ 'mail.fieldAccount': '账号',
233
+ 'mail.fieldTo': '收件',
234
+ 'mail.fieldPassword': '密码',
235
+ 'mail.fieldTiming': '静默 {idle}s 后提醒 · 每 {poll}s 轮询收件箱',
236
+ // 提醒邮件正文(纯文本 + HTML 两版共用这些文案)
237
+ 'mail.subjectTag': '待你决定',
238
+ 'mail.bodyTitle': '人工介入 · 需要你的决定',
239
+ 'mail.bodyIntro': 'mocode 在终端暂停了 {idle} 秒,等待你的答复。直接回复本邮件即可让它继续执行。',
240
+ 'mail.bodyProblem': '问题',
241
+ 'mail.bodyBackground': '背景',
242
+ 'mail.bodyOptions': '选项(回复时只写编号)',
243
+ 'mail.bodyReply': '怎么回复',
244
+ 'mail.bodyReplyChoice': '回复本邮件,正文第一行只写数字,例如:\n {example}\n不要改动主题;若新建邮件,主题请保留 {marker}',
245
+ 'mail.bodyReplyInput': '回复本邮件,在正文写下你的答复(第一行就是 mocode 会采用的内容)。',
246
+ 'mail.bodyMeta': '其他信息',
247
+ 'mail.bodyMetaId': '介入编号',
248
+ 'mail.bodyMetaCwd': '工作目录',
249
+ 'mail.bodyMetaTime': '发送时间',
250
+ 'mail.bodyTrusted': '仅接受来自 {to} 的回复,其他地址的邮件会被忽略。',
251
+ 'mail.bodyFooter': '本邮件由 mocode 自动发送 · 回复即可继续任务',
252
+ 'mail.htmlTitle': '人工介入 · 需要你的决定',
253
+ 'mail.htmlReplyChoice': '回复本邮件,正文第一行只写编号(例如下方的高亮数字)。不要改动主题;若新建邮件,主题请保留 {marker}。',
254
+ 'mail.lastPoll': '上次轮询 {time} · 最高 UID {highest} · 候选 {candidates} · 命中 {handled} · 待决 {pending}',
255
+ 'mail.lastPollSkip': '最近一次跳过原因: {reason}(sender=发件人不受信, self=自发提醒, parse=解析失败, ambiguous=多待决无法归属)',
256
+ 'mail.lastPollError': '上次轮询出错: {error}',
257
+ 'mail.lastPollNever': '本会话尚未轮询(提醒邮件发出后才会开始轮询)。',
258
+ 'mail.testing': '正在发送测试邮件并自检 IMAP 登录…',
259
+ 'mail.testOk': '测试通过:SMTP 发送与 IMAP 登录均正常,请查收测试邮件。',
260
+ 'mail.testFail': '测试未完全通过({parts});见下方错误。',
261
+ 'mail.enabledNow': '邮件提醒已开启(本会话立即生效,已写入配置)。',
262
+ 'mail.disabledNow': '邮件提醒已关闭(本会话立即生效,已写入配置)。',
263
+ 'mail.unknownSub': '未知子命令,可用:/mail setup|test|on|off。',
206
264
  'cli.sandboxPath': '[cli] --sandbox-root 需要一个路径参数',
207
265
  'cli.noSessions': '(没有已保存的会话)',
208
266
  'cli.noValue': '(无)',
@@ -599,6 +657,63 @@ const en = {
599
657
  'config.modelDefault': ' (press Enter for gpt-4o-mini)',
600
658
  'config.required': '\n[config] {key} is required; cancelled.',
601
659
  'config.done': '\nSaved to {path}. Run `mocode` to start from any directory or terminal.',
660
+ 'config.mailPrompt': 'Enable email alerts when human intervention is idle, and resume by replying to the email? (y/N, Enter to skip)',
661
+ 'config.mailEnabled': 'Existing mail config detected.',
662
+ 'config.mailEnablePrompt': 'Reconfigure email notifications? (y=reconfigure, n/Enter=keep current)',
663
+ 'config.mailUser': 'Email account (used as sender/recipient/login)',
664
+ 'config.mailPass': 'App-specific password or authorization code (most providers reject the login password)',
665
+ 'config.mailSmtp': 'SMTP host',
666
+ 'config.mailImap': 'IMAP host (IMAP must be enabled in mailbox settings)',
667
+ 'config.mailIncomplete': '[config] Mail config incomplete (account/password/SMTP/IMAP missing); skipped.',
668
+ 'mail.title': 'Email remote intervention',
669
+ 'mail.stateOn': 'on',
670
+ 'mail.stateOff': 'off',
671
+ 'mail.notConfigured': 'Email notifications are not configured.',
672
+ 'mail.howToConfigure': 'Run `/mail setup` inside the REPL (or `mocode config` from a shell).',
673
+ 'mail.setupAccount': 'Email account',
674
+ 'mail.setupAccountHint': 'Used as sender/recipient/login, e.g. you@example.com. Enter to confirm, Esc to cancel.',
675
+ 'mail.setupPass': 'App-specific password / authorization code',
676
+ 'mail.setupPassHint': 'Most providers reject the login password; generate an app password and enable IMAP. Input is echoed on screen.',
677
+ 'mail.setupSmtp': 'SMTP host',
678
+ 'mail.setupImap': 'IMAP host',
679
+ 'mail.setupHostHint': 'A default guessed from your email domain is shown; press Enter to accept or type another host.',
680
+ 'mail.setupCancelled': 'Mail setup cancelled; nothing changed.',
681
+ 'mail.setupNeedAccount': 'Email account is required; cancelled.',
682
+ 'mail.setupNeedPass': 'App password is required; cancelled.',
683
+ 'mail.setupNeedHosts': 'Both SMTP and IMAP hosts are required; cancelled.',
684
+ 'mail.setupSaved': 'Mail config saved and active in this session.',
685
+ 'mail.setupTestHint': 'Run /mail test to verify, or /mail off to disable temporarily.',
686
+ 'mail.fieldAccount': 'account',
687
+ 'mail.fieldTo': 'to',
688
+ 'mail.fieldPassword': 'password',
689
+ 'mail.fieldTiming': 'alert after {idle}s idle · poll inbox every {poll}s',
690
+ 'mail.subjectTag': 'decision needed',
691
+ 'mail.bodyTitle': 'Intervention · your decision is needed',
692
+ 'mail.bodyIntro': 'mocode has been paused in the terminal for {idle}s waiting for your answer. Reply to this email to continue.',
693
+ 'mail.bodyProblem': 'Question',
694
+ 'mail.bodyBackground': 'Context',
695
+ 'mail.bodyOptions': 'Options (reply with the number only)',
696
+ 'mail.bodyReply': 'How to reply',
697
+ 'mail.bodyReplyChoice': 'Reply to this email with only the number on the first line, e.g.\n {example}\nDo not change the subject; if you compose a new email, keep {marker} in the subject.',
698
+ 'mail.bodyReplyInput': 'Reply to this email with your answer (the first line is what mocode will use).',
699
+ 'mail.bodyMeta': 'Details',
700
+ 'mail.bodyMetaId': 'Intervention ID',
701
+ 'mail.bodyMetaCwd': 'Working directory',
702
+ 'mail.bodyMetaTime': 'Sent at',
703
+ 'mail.bodyTrusted': 'Only replies from {to} are accepted; mail from other addresses is ignored.',
704
+ 'mail.bodyFooter': 'Sent automatically by mocode · reply to continue the task',
705
+ 'mail.htmlTitle': 'Intervention · your decision is needed',
706
+ 'mail.htmlReplyChoice': 'Reply to this email with only the option number on the first line (like the highlighted digit below). Do not change the subject; if you compose a new email, keep {marker} in the subject.',
707
+ 'mail.lastPoll': 'Last poll {time} · highest UID {highest} · candidates {candidates} · matched {handled} · pending {pending}',
708
+ 'mail.lastPollSkip': 'Last skip reason: {reason} (sender=untrusted sender, self=our own reminder, parse=parse failed, ambiguous=cannot attribute to a pending intervention)',
709
+ 'mail.lastPollError': 'Last poll error: {error}',
710
+ 'mail.lastPollNever': 'No poll yet in this session (starts after a reminder email is sent).',
711
+ 'mail.testing': 'Sending test email and checking IMAP login…',
712
+ 'mail.testOk': 'Test passed: SMTP send and IMAP login both work; check your inbox.',
713
+ 'mail.testFail': 'Test incomplete ({parts}); see error below.',
714
+ 'mail.enabledNow': 'Email notifications enabled (live this session; saved to config).',
715
+ 'mail.disabledNow': 'Email notifications disabled (live this session; saved to config).',
716
+ 'mail.unknownSub': 'Unknown subcommand; use /mail setup|test|on|off.',
602
717
  'cli.sandboxPath': '[cli] --sandbox-root requires a path',
603
718
  'cli.noSessions': '(no saved sessions)',
604
719
  'cli.noValue': '(none)',