mocode-ai 1.9.2 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -175,8 +175,34 @@ export async function runModelTurn(input) {
175
175
  const remainingSteps = maxSteps - step;
176
176
  const ephemeralReminder = [
177
177
  runPolicy.reminder,
178
+ // 正文纪律:与 step 0 的 Opening analysis 互斥——两段永远不同框,不再需要白名单交叉引用。
179
+ // 原先这半句只挂在 step 0 的 Opening analysis 里,而本段是临时拼进本次请求、不写回 history
180
+ // 的(见下方 return),于是从每个用户轮的第 2 步起就彻底消失——长任务后半程等于裸奔
181
+ // (实测:同一结论换个措辞每步复述一遍,屏幕上像卡死循环)。
182
+ // step 0 由 Opening analysis 独自承担:那里既没有工具结果可复述,也没有"已说过的观点",
183
+ // 而"能直接答就直接答"的授权已写在 Answer-first 里,本段三条约束在 step 0 均无对象。
184
+ // 子 agent 静默执行、不写屏,沿用 suppressOpeningAnalysis 一并免注入。
185
+ !opts.suppressOpeningAnalysis && step > 0
186
+ ? '## Silent work\n' +
187
+ // 禁令范围收在「调用之间」,而不是「不要宣布你要做什么」:后者与 step 0 的
188
+ // Opening analysis(要求说明打算怎么入手)字面冲突,只能靠下面的白名单化解,
189
+ // 模型得读完清单才解开。开场分析发生在首次工具调用之前,天然不在本禁令范围内。
190
+ 'Prefer doing over narrating. Do not narrate between tool calls: no sentence announcing ' +
191
+ 'the next call, and no sentence restating what a result means — one such sentence per ' +
192
+ 'call is noise, and repeated variants of ' +
193
+ 'the same conclusion read to the user as a stuck loop. If something genuinely must be said ' +
194
+ 'mid-task (a blocking decision, or a finding that changes what happens next), say it in one ' +
195
+ 'short sentence and keep going. Never repeat a point already made in this turn. Text is for: ' +
196
+ "direct answers to the user's questions, blocking questions, " +
197
+ 'findings that change the next action, and the final report.'
198
+ : '',
199
+ // 仅 step 0:先说明思路。与上面的正文纪律互斥(step > 0),两段永不同框。
200
+ // 曾经的结尾是"then start tool calls"——每个用户轮的第一步都无条件命令模型动手,
201
+ // 而 "Answer first" 在 history[0] 尾部隔了几万 token,权重被压过。结果:追问一件
202
+ // 已完成工作的细节时,模型也能答却先跑去排一堆工具调用。改为显式指向 Answer-first,
203
+ // 让近处指令与远处规则同向,而不是删掉动手要求(那会在真该干活的轮次矫枉过正)。
178
204
  !opts.suppressOpeningAnalysis && step === 0
179
- ? '## Opening analysis\nStart your first response of this turn with a brief analysis of the request and approach (1-3 sentences, no filler), then start tool calls. This is the only expected pre-tool prose; afterwards work quietly, no narration between calls.'
205
+ ? '## Opening analysis\nStart your first response of this turn with a brief analysis of the request and approach (1-3 sentences, no filler). Then follow Answer-first: answer directly when the conversation above already contains what is needed, and start tool calls only when this turn actually needs work. Keep the analysis to 1-3 sentences.'
180
206
  : '',
181
207
  remainingSteps <= 3
182
208
  ? `## Step budget warning\nOnly ${remainingSteps} step(s) remain before the hard step limit (${maxSteps}). ` +
@@ -11,6 +11,7 @@ const zhCN = {
11
11
  'commands.skills': '列出已发现的 skill',
12
12
  'commands.compact': '压缩历史(可带焦点 /compact …)',
13
13
  'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
14
+ 'commands.usageImport': '回填各工作区历史会话的 token 用量(幂等)',
14
15
  'commands.session': '会话恢复与回滚',
15
16
  'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
16
17
  'commands.sessionBrowse': '浏览全部已保存会话',
@@ -188,19 +189,39 @@ const zhCN = {
188
189
  'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
189
190
  'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
190
191
  'repl.usageTitle': 'Token 用量(全局 · {from} ~ {to} · {days} 天)',
191
- 'repl.usageTotal': '总计 {total} tokens = in {input} + out {output} · {calls} 次请求 · {sessions} 个会话 · {workspaces} 个工作空间',
192
- 'repl.usageMetrics': '缓存命中 {hit} · 推理占输出 {reasoning} · 缓存写 {cacheWrite} · 日均 {daily}',
193
- 'repl.usageCompact': '其中压缩(compact):in {input} / out {output} / {calls} 次',
194
- 'repl.usageColDate': 'date',
195
- 'repl.usageEmptyDay': '(无用量)',
192
+ 'repl.usageKMetric': '指标',
193
+ 'repl.usageKValue': '数值',
194
+ 'repl.usageKTotal': '总用量',
195
+ 'repl.usageKInput': '输入 in',
196
+ 'repl.usageKOutput': '输出 out',
197
+ 'repl.usageKRequests': '请求数',
198
+ 'repl.usageKSessions': '会话数',
199
+ 'repl.usageKWorkspaces': '工作空间数',
200
+ 'repl.usageKCacheHit': '缓存命中率',
201
+ 'repl.usageKReasoningShare': '推理占输出',
202
+ 'repl.usageKCacheWrite': '缓存写入',
203
+ 'repl.usageKDailyAvg': '日均用量',
204
+ 'repl.usageKCompact': '其中压缩(compact)',
205
+ 'repl.usageColDate': '日期',
206
+ 'repl.usageColWorkspace': '工作空间',
207
+ 'repl.usageColModel': '模型',
208
+ 'repl.usageColIn': '输入',
209
+ 'repl.usageColOut': '输出',
210
+ 'repl.usageColCached': '缓存命中',
211
+ 'repl.usageColReason': '推理',
212
+ 'repl.usageColCalls': '请求数',
213
+ 'repl.usageColHit': '命中率',
214
+ 'repl.usageColSessions': '会话数',
215
+ 'repl.usageEmptyDay': '(无用量)',
196
216
  'repl.usageTotalRow': '合计',
197
217
  'repl.usageByWorkspace': '按工作空间',
198
218
  'repl.usageByModel': '按模型',
199
- 'repl.usageNone': '(无)',
200
219
  'repl.usageMore': '… 其余 {n} 项已省略',
201
- 'repl.usageSessions': '{n} 个会话',
202
220
  'repl.usageBadArg': '用法:/usage [天数 1-366](默认 7)',
203
- 'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积)',
221
+ 'repl.usageImportDone': '已回填 {records} 条历史记录({sessions} 个会话 · {workspaces} 个工作空间;跳过 {skipped} 条已实时统计的记录)',
222
+ 'repl.usageImportNothing': '没有可回填的历史记录({skipped} 条已实时统计,重复执行是幂等的)',
223
+ 'repl.usageImportZero': '没有找到可回填的历史会话用量(先在 mocode 里跑过任务的工作区才会产生 usage.jsonl)',
224
+ 'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积,或用 /usage import 回填历史)',
204
225
  'repl.planAlready': '(已在 plan 模式)',
205
226
  'repl.planChanged': '(已切到 plan 模式:只读探查 + 产出计划,审批后切 auto 执行。/auto 或 Shift+Tab 切回)',
206
227
  'repl.autoAlready': '(已在 auto 模式)',
@@ -501,6 +522,7 @@ const en = {
501
522
  'commands.skills': 'List discovered skills',
502
523
  'commands.compact': 'Compact history (optional focus: /compact …)',
503
524
  'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
525
+ 'commands.usageImport': 'Backfill token usage from historical sessions (idempotent)',
504
526
  'commands.session': 'Resume sessions and roll back turns',
505
527
  'commands.sessionResume': 'Resume one of the 10 latest saved sessions',
506
528
  'commands.sessionBrowse': 'Browse all saved sessions',
@@ -673,19 +695,39 @@ const en = {
673
695
  'repl.forkDone': 'Forked new session {id} (inherits full context; independent from the original)',
674
696
  'repl.forkHint': 'This window stays on the original session; run mocode --resume {id} in a new terminal, or use /resume here',
675
697
  'repl.usageTitle': 'Token usage (global · {from} ~ {to} · {days}d)',
676
- 'repl.usageTotal': 'Total {total} tokens = in {input} + out {output} · {calls} requests · {sessions} sessions · {workspaces} workspaces',
677
- 'repl.usageMetrics': 'Cache hit {hit} · reasoning share of output {reasoning} · cache write {cacheWrite} · daily avg {daily}',
678
- 'repl.usageCompact': 'of which compact: in {input} / out {output} / {calls} calls',
679
- 'repl.usageColDate': 'date',
698
+ 'repl.usageKMetric': 'Metric',
699
+ 'repl.usageKValue': 'Value',
700
+ 'repl.usageKTotal': 'Total tokens',
701
+ 'repl.usageKInput': 'Input',
702
+ 'repl.usageKOutput': 'Output',
703
+ 'repl.usageKRequests': 'Requests',
704
+ 'repl.usageKSessions': 'Sessions',
705
+ 'repl.usageKWorkspaces': 'Workspaces',
706
+ 'repl.usageKCacheHit': 'Cache hit rate',
707
+ 'repl.usageKReasoningShare': 'Reasoning share of output',
708
+ 'repl.usageKCacheWrite': 'Cache write',
709
+ 'repl.usageKDailyAvg': 'Daily average',
710
+ 'repl.usageKCompact': 'of which compact',
711
+ 'repl.usageColDate': 'Date',
712
+ 'repl.usageColWorkspace': 'Workspace',
713
+ 'repl.usageColModel': 'Model',
714
+ 'repl.usageColIn': 'Input',
715
+ 'repl.usageColOut': 'Output',
716
+ 'repl.usageColCached': 'Cached',
717
+ 'repl.usageColReason': 'Reasoning',
718
+ 'repl.usageColCalls': 'Requests',
719
+ 'repl.usageColHit': 'Hit rate',
720
+ 'repl.usageColSessions': 'Sessions',
680
721
  'repl.usageEmptyDay': '(no usage)',
681
722
  'repl.usageTotalRow': 'Total',
682
723
  'repl.usageByWorkspace': 'By workspace',
683
724
  'repl.usageByModel': 'By model',
684
- 'repl.usageNone': '(none)',
685
725
  'repl.usageMore': '… {n} more hidden',
686
- 'repl.usageSessions': '{n} sessions',
687
726
  'repl.usageBadArg': 'Usage: /usage [days 1-366] (default 7)',
688
- 'repl.usageNoData': '(No global usage data yet; collection starts from model calls after this feature is enabled)',
727
+ 'repl.usageImportDone': 'Backfilled {records} historical records ({sessions} sessions · {workspaces} workspaces; skipped {skipped} already-tracked records)',
728
+ 'repl.usageImportNothing': 'Nothing to backfill ({skipped} records were already tracked live; re-running is idempotent)',
729
+ 'repl.usageImportZero': 'No historical session usage found (a workspace only has usage.jsonl after tasks have run in mocode)',
730
+ 'repl.usageNoData': '(No global usage data yet; collection starts from model calls after this feature, or run /usage import to backfill history)',
689
731
  'repl.planAlready': '(already in plan mode)',
690
732
  'repl.planChanged': '(switched to plan mode: read-only research and planning; approval returns to auto. Use /auto or Shift+Tab to switch back)',
691
733
  'repl.autoAlready': '(already in auto mode)',
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * /stats 读会话级 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
5
5
  * /usage 读全局账本 ~/.mocode/usage-daily.jsonl(每次模型调用追加,含工作区/模型/
6
- * 本地日期),输出最近 N 天的按天表、总计、工作区与模型排行。
6
+ * 本地日期),以 GFM 表格输出最近 N 天的总览、按天、工作区与模型排行
7
+ * (经 contentWriteMdOnce 走 markdown 表格渲染,数字列右对齐)。
7
8
  */
8
9
  import * as layout from '../../ui/layout.js';
9
10
  import { ui } from '../../ui/theme.js';
@@ -12,6 +13,8 @@ import { t } from '../../i18n/index.js';
12
13
  import { getActiveSessionStore } from '../../session/store.js';
13
14
  import { formatUsageSummary, summarizeUsage } from '../../session/usage-stats.js';
14
15
  import { readGlobalUsage, summarizeGlobalUsage, } from '../../session/global-usage.js';
16
+ import { backfillGlobalUsage } from '../../session/backfill-usage.js';
17
+ import { getWorkspaceRoot } from '../../workspace/index.js';
15
18
  import { unhandled, next } from './types.js';
16
19
  /** 计数千分位(请求数/会话数等)。 */
17
20
  function n(v) {
@@ -21,74 +24,118 @@ function n(v) {
21
24
  function tok(v) {
22
25
  return fmtCompactTokens(v);
23
26
  }
24
- /** 固定宽右对齐(数字串无 ANSI)。 */
25
- function col(v, width) {
26
- const s = String(v);
27
- return s.length >= width ? s : ' '.repeat(width - s.length) + s;
28
- }
29
27
  function pct(part, whole) {
30
28
  return whole > 0 ? `${((part / whole) * 100).toFixed(1)}%` : 'n/a';
31
29
  }
32
- /** 工作区/模型排行:名称左截断(保留尾部,工作区尾部目录更有辨识度),数值右对齐。 */
33
- function groupTable(title, rows, nameWidth) {
34
- const lines = [`${ui.accent}${title}${ui.reset}`];
35
- if (rows.length === 0) {
36
- lines.push(` ${ui.dim}${t('repl.usageNone')}${ui.reset}`);
37
- return lines;
38
- }
39
- for (const r of rows.slice(0, 8)) {
40
- let name = r.key;
41
- if (name.length > nameWidth)
42
- name = `…${name.slice(name.length - nameWidth + 1)}`;
43
- lines.push(` ${ui.cyan}${name.padEnd(nameWidth)}${ui.reset} ${col(tok(r.input), 7)} in ${col(tok(r.output), 7)} out ${col(n(r.calls), 5)} calls ${ui.dim}${t('repl.usageSessions', { n: r.sessions })}${ui.reset}`);
44
- }
45
- if (rows.length > 8)
46
- lines.push(` ${ui.dim}${t('repl.usageMore', { n: rows.length - 8 })}${ui.reset}`);
47
- return lines;
48
- }
49
- function totalRow(b) {
50
- return `${t('repl.usageTotalRow')} ${col(tok(b.input), 7)} in · ${col(tok(b.output), 7)} out · ${col(tok(b.cached), 7)} cached · ${col(tok(b.reasoning), 7)} reasoning`;
30
+ /** 构造 GFM 表格:headers/rows 等宽;align 列 'l'(左,默认)或 'r'(右)。 */
31
+ function mdTable(headers, rows, align) {
32
+ const sep = align.map((a) => (a === 'r' ? '---:' : ':---')).join('|');
33
+ const lines = [`| ${headers.join(' | ')} |`, `|${sep}|`];
34
+ for (const row of rows)
35
+ lines.push(`| ${row.join(' | ')} |`);
36
+ return lines.join('\n');
51
37
  }
52
- function formatGlobal(s) {
53
- const lines = [];
38
+ /** 汇总指标键值表(两列)。 */
39
+ function overviewTable(s) {
54
40
  const b = s.total;
55
- const grandTotal = b.input + b.output;
56
- lines.push(`${ui.accent}${t('repl.usageTitle', { from: s.fromDay, to: s.toDay, days: s.days })}${ui.reset}`);
57
- lines.push(` ${t('repl.usageTotal', {
58
- total: tok(grandTotal),
59
- input: tok(b.input),
60
- output: tok(b.output),
61
- calls: n(b.calls),
62
- sessions: n(s.sessionCount),
63
- workspaces: n(s.workspaceCount),
64
- })}`);
65
- lines.push(` ${t('repl.usageMetrics', {
66
- hit: pct(b.cached, b.input),
67
- reasoning: pct(b.reasoning, b.output),
68
- cacheWrite: tok(b.cacheCreation),
69
- daily: tok(Math.round(grandTotal / s.days)),
70
- })}`);
41
+ const rows = [
42
+ [`${ui.bold}${t('repl.usageKTotal')}${ui.reset}`, `${ui.bold}${tok(b.input + b.output)}${ui.reset}`],
43
+ [t('repl.usageKInput'), tok(b.input)],
44
+ [t('repl.usageKOutput'), tok(b.output)],
45
+ [t('repl.usageKRequests'), n(b.calls)],
46
+ [t('repl.usageKSessions'), n(s.sessionCount)],
47
+ [t('repl.usageKWorkspaces'), n(s.workspaceCount)],
48
+ [t('repl.usageKCacheHit'), pct(b.cached, b.input)],
49
+ [t('repl.usageKReasoningShare'), pct(b.reasoning, b.output)],
50
+ [t('repl.usageKCacheWrite'), tok(b.cacheCreation)],
51
+ [t('repl.usageKDailyAvg'), tok(Math.round((b.input + b.output) / s.days))],
52
+ ];
71
53
  if (s.compact.calls > 0) {
72
- lines.push(` ${ui.dim}${t('repl.usageCompact', { input: tok(s.compact.input), output: tok(s.compact.output), calls: n(s.compact.calls) })}${ui.reset}`);
54
+ rows.push([
55
+ t('repl.usageKCompact'),
56
+ `${tok(s.compact.input)} in / ${tok(s.compact.output)} out / ${n(s.compact.calls)}`,
57
+ ]);
73
58
  }
74
- lines.push('');
75
- // 按天表(列宽固定,终端对齐;token 一律缩写)
76
- lines.push(` ${ui.dim}${t('repl.usageColDate').padEnd(10)} ${col('in', 7)} ${col('out', 7)} ${col('cached', 7)} ${col('reason', 7)} ${col('calls', 6)} hit${ui.reset}`);
77
- for (const d of s.byDay) {
59
+ return mdTable([t('repl.usageKMetric'), t('repl.usageKValue')], rows, ['l', 'r']);
60
+ }
61
+ function dayRows(byDay) {
62
+ return byDay.map((d) => {
78
63
  if (d.calls === 0) {
79
- lines.push(` ${ui.dim}${d.day} ${t('repl.usageEmptyDay')}${ui.reset}`);
80
- continue;
64
+ const dash = `${ui.dim}—${ui.reset}`;
65
+ return [
66
+ `${ui.dim}${d.day}${ui.reset}`,
67
+ dash,
68
+ dash,
69
+ dash,
70
+ dash,
71
+ dash,
72
+ `${ui.dim}${t('repl.usageEmptyDay')}${ui.reset}`,
73
+ ];
81
74
  }
82
- lines.push(` ${ui.cyan}${d.day}${ui.reset} ${col(tok(d.input), 7)} ${col(tok(d.output), 7)} ${col(tok(d.cached), 7)} ${col(tok(d.reasoning), 7)} ${col(n(d.calls), 6)} ${pct(d.cached, d.input)}`);
83
- }
84
- lines.push(` ${ui.bold}${totalRow(b)}${ui.reset}`);
85
- lines.push('');
86
- lines.push(...groupTable(t('repl.usageByWorkspace'), s.byWorkspace, 40));
87
- lines.push('');
88
- lines.push(...groupTable(t('repl.usageByModel'), s.byModel, 32));
89
- return lines.join('\n');
75
+ return [
76
+ `${ui.cyan}${d.day}${ui.reset}`,
77
+ tok(d.input),
78
+ tok(d.output),
79
+ tok(d.cached),
80
+ tok(d.reasoning),
81
+ n(d.calls),
82
+ pct(d.cached, d.input),
83
+ ];
84
+ });
85
+ }
86
+ /** 按天表:无用量日整行 dim,数字列右对齐,末行合计(每个着色单元格自带 reset 防串色)。 */
87
+ function dailyTable(s) {
88
+ const rows = dayRows(s.byDay);
89
+ const b = s.total;
90
+ const bold = (v) => `${ui.bold}${v}${ui.reset}`;
91
+ rows.push([
92
+ bold(t('repl.usageTotalRow')),
93
+ bold(tok(b.input)),
94
+ bold(tok(b.output)),
95
+ bold(tok(b.cached)),
96
+ bold(tok(b.reasoning)),
97
+ bold(n(b.calls)),
98
+ bold(pct(b.cached, b.input)),
99
+ ]);
100
+ return mdTable([
101
+ t('repl.usageColDate'),
102
+ t('repl.usageColIn'),
103
+ t('repl.usageColOut'),
104
+ t('repl.usageColCached'),
105
+ t('repl.usageColReason'),
106
+ t('repl.usageColCalls'),
107
+ t('repl.usageColHit'),
108
+ ], rows, ['l', 'r', 'r', 'r', 'r', 'r', 'r']);
109
+ }
110
+ /** 工作区/模型排行表(Top 8,按 input+output 降序已在聚合层排好)。 */
111
+ function groupTable(title, colName, rows) {
112
+ const body = rows.slice(0, 8).map((r) => [r.key, tok(r.input), tok(r.output), n(r.calls), n(r.sessions)]);
113
+ return (`${ui.accent}${title}${ui.reset}\n\n` +
114
+ mdTable([colName, t('repl.usageColIn'), t('repl.usageColOut'), t('repl.usageColCalls'), t('repl.usageColSessions')], body, ['l', 'r', 'r', 'r', 'r']) +
115
+ (rows.length > 8 ? `\n\n${ui.dim}${t('repl.usageMore', { n: rows.length - 8 })}${ui.reset}` : ''));
90
116
  }
91
117
  export const statsCommands = [
118
+ // /usage import:把各工作区旧会话的 usage.jsonl 回填进全局账本(幂等,可重复执行)。
119
+ (ctx) => {
120
+ if (ctx.line !== '/usage import' && ctx.line !== '/usage import ')
121
+ return unhandled();
122
+ const r = backfillGlobalUsage({ extraRoots: [getWorkspaceRoot()] });
123
+ if (r.records === 0 && r.skippedTracked > 0) {
124
+ layout.contentWrite(`${ui.dim}${t('repl.usageImportNothing', { skipped: n(r.skippedTracked) })}${ui.reset}\n`);
125
+ }
126
+ else if (r.records === 0) {
127
+ layout.contentWrite(`${ui.dim}${t('repl.usageImportZero')}${ui.reset}\n`);
128
+ }
129
+ else {
130
+ layout.contentWrite(`${ui.accent}${t('repl.usageImportDone', {
131
+ records: n(r.records),
132
+ sessions: n(r.sessions),
133
+ workspaces: n(r.workspaces),
134
+ skipped: n(r.skippedTracked),
135
+ })}${ui.reset}\n`);
136
+ }
137
+ return next();
138
+ },
92
139
  // /usage [days]:跨工作空间按天汇总。默认 7 天,可传天数(如 /usage 30);非法参数给用法提示。
93
140
  (ctx) => {
94
141
  if (ctx.line !== '/usage' && !ctx.line.startsWith('/usage '))
@@ -108,7 +155,17 @@ export const statsCommands = [
108
155
  layout.contentWrite(`${ui.dim}${t('repl.usageNoData')}${ui.reset}\n`);
109
156
  return next();
110
157
  }
111
- layout.contentWrite(` ${formatGlobal(summarizeGlobalUsage(records, days))}\n`);
158
+ const s = summarizeGlobalUsage(records, days);
159
+ // 标题与普通文案走裸通道;表格逐个走 md 通道(各自独立渲染,避免跨段识别问题)。
160
+ layout.contentWrite(`\n${ui.accent}${t('repl.usageTitle', { from: s.fromDay, to: s.toDay, days: s.days })}${ui.reset}\n\n`);
161
+ layout.contentWriteMdOnce(overviewTable(s));
162
+ layout.contentWrite('\n\n');
163
+ layout.contentWriteMdOnce(dailyTable(s));
164
+ layout.contentWrite('\n\n');
165
+ layout.contentWriteMdOnce(groupTable(t('repl.usageByWorkspace'), t('repl.usageColWorkspace'), s.byWorkspace));
166
+ layout.contentWrite('\n\n');
167
+ layout.contentWriteMdOnce(groupTable(t('repl.usageByModel'), t('repl.usageColModel'), s.byModel));
168
+ layout.contentWrite('\n');
112
169
  return next();
113
170
  },
114
171
  (ctx) => {
@@ -24,7 +24,11 @@ export function buildSlashCommands() {
24
24
  { name: '/skills', desc: d('commands.skills') },
25
25
  { name: '/skill', desc: '执行某个 skill(/skill <name> [args-json])' },
26
26
  { name: '/compact', desc: d('commands.compact') },
27
- { name: '/usage', desc: d('commands.usage') },
27
+ {
28
+ name: '/usage',
29
+ desc: d('commands.usage'),
30
+ children: [{ name: 'import', value: '/usage import', desc: d('commands.usageImport') }],
31
+ },
28
32
  { name: '/stats', desc: '查看本会话 token 用量与缓存命中率' },
29
33
  { name: '/effort', desc: '设置思考强度(/effort [low|medium|high|auto])' },
30
34
  { name: '/resume', desc: d('commands.sessionResume') },
@@ -8,6 +8,7 @@ import { defaultRuntime } from '../runtime/index.js';
8
8
  import { getAgentMode, setAgentMode, onModeChange } from '../agent/mode.js';
9
9
  import { sendState } from '../pet/bridge.js';
10
10
  import { setSandboxRoot } from '../sandbox/root.js';
11
+ import { registerWorkspace } from '../workspace/registry.js';
11
12
  import { ui, setTheme } from '../ui/theme.js';
12
13
  import { bannerLines } from '../ui/render.js';
13
14
  import * as layout from '../ui/layout.js';
@@ -233,6 +234,8 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
233
234
  // 沙箱根:文件操作边界。优先级 --sandbox-root > SANDBOX_ROOT env > process.cwd()。
234
235
  // 纯边界记录(不 chdir),jail.ts 内部 resolve。子 agent 同进程继承全局 root。
235
236
  setSandboxRoot(sandboxRootOverride ?? config.sandboxRoot ?? process.cwd());
237
+ // 全局工作区溯源登记:启动(新会话与 --resume 同路径都算)留一条轻量记录,供历史回填扫描。
238
+ registerWorkspace(sandboxRootOverride ?? config.sandboxRoot ?? process.cwd());
236
239
  const runtime = defaultRuntime;
237
240
  await runtime.start();
238
241
  const runtimeContext = runtime.context;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * 历史 token 用量回填。
3
+ *
4
+ * 全局账本(~/.mocode/usage-daily.jsonl)从实时记账功能上线起才有数据;本模块把各工作区
5
+ * 里**旧会话**的会话级 usage.jsonl 一次性补进全局账本,/usage 即可看到历史。
6
+ *
7
+ * 扫描来源:全局工作区注册表(~/.mocode/workspaces.jsonl,启动与 /cd 时登记)里的每个
8
+ * 工作区,读 `<root>/.mocode/sessions/<id>/usage.jsonl`。
9
+ *
10
+ * 去重(两层,共同保证任意顺序重复执行都不双算):
11
+ * 1. 行级 `trackedInGlobal`:实时记账上线后产生的 usage 行带此标记,回填直接跳过;
12
+ * 2. 文件级断点 `~/.mocode/usage-import-state.json`:记录每个 usage 文件已导入的行数,
13
+ * 重跑只导入新增的"未标记"行(覆盖"会话在升级前后都活跃"的时间窗口)。
14
+ *
15
+ * 历史记录缺真实时间戳/模型:日期与会话创建时间按 session 目录 id 的时间前缀推断
16
+ * (本地时区),模型取 session.json 的 model(会话最后保存时的模型)。回填行标 source=backfill。
17
+ */
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { appendGlobalUsage } from './global-usage.js';
22
+ import { readWorkspaceRegistry } from '../workspace/registry.js';
23
+ const DEFAULT_STATE_PATH = path.join(os.homedir(), '.mocode', 'usage-import-state.json');
24
+ function readState(statePath) {
25
+ try {
26
+ const s = JSON.parse(fs.readFileSync(statePath, 'utf8'));
27
+ return { files: s && typeof s.files === 'object' ? s.files : {} };
28
+ }
29
+ catch {
30
+ return { files: {} };
31
+ }
32
+ }
33
+ function writeState(statePath, state) {
34
+ try {
35
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
36
+ const tmp = `${statePath}.tmp`;
37
+ fs.writeFileSync(tmp, JSON.stringify(state), 'utf8');
38
+ fs.renameSync(tmp, statePath);
39
+ }
40
+ catch {
41
+ // 状态写失败不致命:最坏是下次重跑时多扫一遍(行级标记仍防双算,见文件头)。
42
+ }
43
+ }
44
+ /** session id 时间前缀 → 本地 ISO(无时区串,按机器本地时区)与本地日期;无法解析返回空。 */
45
+ function sessionIdTime(id) {
46
+ const m = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})(?:-(\d{3})-[a-f0-9]{8})?$/.exec(id);
47
+ if (!m)
48
+ return undefined;
49
+ const [, y, mo, d, h, mi, s, ms] = m;
50
+ const day = `${y}-${mo}-${d}`;
51
+ const isoLocal = `${day}T${h}:${mi}:${s}${ms ? `.${ms}` : ''}`;
52
+ return { isoLocal, day };
53
+ }
54
+ /** 列一个工作区的会话目录 id(与 SessionStore.list 的目录识别同规则)。 */
55
+ function listSessionIds(root) {
56
+ const dir = path.join(root, '.mocode', 'sessions');
57
+ try {
58
+ return fs
59
+ .readdirSync(dir, { withFileTypes: true })
60
+ .filter((e) => e.isDirectory() && /^\d{8}-\d{6}(?:-\d{3}-[a-f0-9]{8})?$/.test(e.name))
61
+ .map((e) => e.name);
62
+ }
63
+ catch {
64
+ return [];
65
+ }
66
+ }
67
+ function readSessionModel(root, id) {
68
+ try {
69
+ const rec = JSON.parse(fs.readFileSync(path.join(root, '.mocode', 'sessions', id, 'session.json'), 'utf8'));
70
+ return typeof rec.model === 'string' ? rec.model : '';
71
+ }
72
+ catch {
73
+ return '';
74
+ }
75
+ }
76
+ /**
77
+ * 执行历史回填。best-effort:单个工作区/会话失败不拖垮整体。
78
+ * @param extraRoots 注册表之外额外扫描的工作区根(如当前工作区)。
79
+ */
80
+ export function backfillGlobalUsage(opts = {}) {
81
+ const extraRoots = opts.extraRoots ?? [];
82
+ const statePath = opts.statePath ?? DEFAULT_STATE_PATH;
83
+ const roots = [
84
+ ...new Set([...readWorkspaceRegistry().map((e) => e.root), ...extraRoots.map((r) => path.resolve(r))]),
85
+ ];
86
+ const state = readState(statePath);
87
+ const result = { workspaces: 0, sessions: 0, records: 0, skippedTracked: 0 };
88
+ for (const root of roots) {
89
+ const ids = listSessionIds(root);
90
+ if (ids.length === 0)
91
+ continue;
92
+ result.workspaces++;
93
+ for (const id of ids) {
94
+ const file = path.join(root, '.mocode', 'sessions', id, 'usage.jsonl');
95
+ let rows;
96
+ try {
97
+ // 只保留非空行:游标按"已处理的记录行"计数,避开 split('\n') 末尾空串导致的错位。
98
+ rows = fs
99
+ .readFileSync(file, 'utf8')
100
+ .split('\n')
101
+ .filter((l) => l.trim() !== '');
102
+ }
103
+ catch {
104
+ continue; // 该会话无 usage 文件
105
+ }
106
+ const before = state.files[file] ?? 0;
107
+ // 断点只进不退:文件被截断重写(行数变少,轮转/手工)时从头来,否则只处理新增尾部。
108
+ const start = before <= rows.length ? before : 0;
109
+ const tinfo = sessionIdTime(id);
110
+ const model = readSessionModel(root, id) || '(unknown)';
111
+ let touchedSession = false;
112
+ for (let i = start; i < rows.length; i++) {
113
+ const line = rows[i].trim();
114
+ let row;
115
+ try {
116
+ row = JSON.parse(line);
117
+ }
118
+ catch {
119
+ continue; // 损坏行跳过
120
+ }
121
+ touchedSession = true;
122
+ // live 行已实时计入:只标记跳过,不重复导入。
123
+ if (row.trackedInGlobal) {
124
+ result.skippedTracked++;
125
+ continue;
126
+ }
127
+ if (typeof row.inputTokens !== 'number' || typeof row.outputTokens !== 'number')
128
+ continue;
129
+ appendGlobalUsage({
130
+ ts: tinfo?.isoLocal,
131
+ day: tinfo?.day,
132
+ workspace: root,
133
+ model,
134
+ phase: row.phase === 'compact' ? 'compact' : 'main',
135
+ sessionId: id,
136
+ source: 'backfill',
137
+ input: row.inputTokens,
138
+ output: row.outputTokens,
139
+ cached: row.cachedTokens ?? 0,
140
+ reasoning: row.reasoningTokens ?? 0,
141
+ cacheCreation: row.cacheCreationTokens ?? 0,
142
+ });
143
+ result.records++;
144
+ }
145
+ // 游标推进到已处理的记录行数(JSONL 只追加,新行总在尾部)。
146
+ if (rows.length !== before)
147
+ state.files[file] = rows.length;
148
+ if (touchedSession)
149
+ result.sessions++;
150
+ }
151
+ }
152
+ writeState(statePath, state);
153
+ return result;
154
+ }
@@ -12,8 +12,19 @@
12
12
  import fs from 'node:fs';
13
13
  import os from 'node:os';
14
14
  import path from 'node:path';
15
- /** 全局账本路径:跨工作空间,故放 ~/.mocode 而非项目目录。 */
15
+ /** 全局账本默认路径:跨工作空间,故放 ~/.mocode 而非项目目录。 */
16
16
  export const GLOBAL_USAGE_PATH = path.join(os.homedir(), '.mocode', 'usage-daily.jsonl');
17
+ /**
18
+ * 路径覆盖(仅测试用):让账本落到临时目录,避免污染真实 ~/.mocode。
19
+ * 模块在全量测试进程里可能被别的文件先静态 import 而绑定了真实 home,故不能靠改 env。
20
+ */
21
+ let globalUsagePathOverride;
22
+ export function __setGlobalUsagePath(p) {
23
+ globalUsagePathOverride = p;
24
+ }
25
+ export function getGlobalUsagePath() {
26
+ return globalUsagePathOverride ?? GLOBAL_USAGE_PATH;
27
+ }
17
28
  /** 本地日期 YYYY-MM-DD;不引时区库——运行机器本地时间即用户口径的"天"。 */
18
29
  export function localDay(d = new Date()) {
19
30
  const p = (n) => String(n).padStart(2, '0');
@@ -22,10 +33,11 @@ export function localDay(d = new Date()) {
22
33
  /** 追加一行全局用量。任何 I/O 失败静默——记账不能拖垮主流程。 */
23
34
  export function appendGlobalUsage(input) {
24
35
  try {
25
- const now = new Date();
36
+ const when = input.ts ? new Date(input.ts) : new Date();
37
+ const day = input.day ?? (Number.isNaN(when.getTime()) ? localDay() : localDay(when));
26
38
  const rec = {
27
- ts: now.toISOString(),
28
- day: localDay(now),
39
+ ts: Number.isNaN(when.getTime()) ? new Date().toISOString() : when.toISOString(),
40
+ day,
29
41
  input: input.input,
30
42
  output: input.output,
31
43
  cached: input.cached ?? 0,
@@ -35,9 +47,10 @@ export function appendGlobalUsage(input) {
35
47
  model: input.model,
36
48
  phase: input.phase,
37
49
  ...(input.sessionId ? { sessionId: input.sessionId } : {}),
50
+ ...(input.source === 'backfill' ? { source: 'backfill' } : {}),
38
51
  };
39
- fs.mkdirSync(path.dirname(GLOBAL_USAGE_PATH), { recursive: true });
40
- fs.appendFileSync(GLOBAL_USAGE_PATH, `${JSON.stringify(rec)}\n`, 'utf8');
52
+ fs.mkdirSync(path.dirname(getGlobalUsagePath()), { recursive: true });
53
+ fs.appendFileSync(getGlobalUsagePath(), `${JSON.stringify(rec)}\n`, 'utf8');
41
54
  }
42
55
  catch {
43
56
  // best-effort, see file header
@@ -47,7 +60,7 @@ export function appendGlobalUsage(input) {
47
60
  export function readGlobalUsage() {
48
61
  let raw;
49
62
  try {
50
- raw = fs.readFileSync(GLOBAL_USAGE_PATH, 'utf8');
63
+ raw = fs.readFileSync(getGlobalUsagePath(), 'utf8');
51
64
  }
52
65
  catch {
53
66
  return [];
@@ -1,5 +1,5 @@
1
1
  /** 从 ChatUsage 构造记录;usage 缺失返 null。 */
2
- export function toUsageRecord(step, phase, usage, estimatedTotal) {
2
+ export function toUsageRecord(step, phase, usage, estimatedTotal, trackedInGlobal = true) {
3
3
  if (!usage)
4
4
  return null;
5
5
  return {
@@ -11,6 +11,8 @@ export function toUsageRecord(step, phase, usage, estimatedTotal) {
11
11
  reasoningTokens: usage.reasoningTokens,
12
12
  ...(usage.cacheCreationTokens ? { cacheCreationTokens: usage.cacheCreationTokens } : {}),
13
13
  ...(estimatedTotal != null ? { estimatedTotal } : {}),
14
+ // 仅在 true 时落字段:旧记录形状保持最小(且 summarize 不读它)。
15
+ ...(trackedInGlobal ? { trackedInGlobal: true } : {}),
14
16
  };
15
17
  }
16
18
  function emptyTotals() {
@@ -21,6 +21,7 @@ import os from 'node:os';
21
21
  import path from 'node:path';
22
22
  import { config } from '../config/index.js';
23
23
  import { getSandboxRoot, setSandboxRoot } from '../sandbox/root.js';
24
+ import { registerWorkspace } from './registry.js';
24
25
  /** 当前工作区根(绝对路径)。沙箱根优先,未初始化回退 process.cwd()。 */
25
26
  export function getWorkspaceRoot() {
26
27
  return getSandboxRoot() ?? process.cwd();
@@ -85,5 +86,6 @@ export function switchWorkspaceRoot(root) {
85
86
  setSandboxRoot(abs);
86
87
  config.sessionDir = path.join(abs, '.mocode', 'sessions');
87
88
  previousRoot = previous;
89
+ registerWorkspace(abs); // 全局工作区溯源登记(best-effort,见 registry.ts)
88
90
  return { previous, root: abs };
89
91
  }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 全局工作区注册表(跨工作空间溯源)。
3
+ *
4
+ * mocode 每进入一个工作区工作(启动或 /cd),就在全局留一条**轻量**基础信息:
5
+ * 路径、首次/最近访问时间、目录名、历史会话数与总用量大小。存 `~/.mocode/workspaces.jsonl`,
6
+ * 供历史 token 回填扫描、以及后续工作区溯源/切换等功能使用。
7
+ *
8
+ * 形态选择:append-only JSONL(与全局 usage 账本同款),每次访问追加一行,
9
+ * 读取时按路径折叠保留最新一条——并发/崩溃安全(无读-改-写),单条 ~150 字节,
10
+ * 普通使用频率下年增不到 100KB,无需主动压缩。静态叶子模块(node:fs/os/path),
11
+ * 可在退出路径安全静态 import。
12
+ */
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ export const WORKSPACE_REGISTRY_PATH = path.join(os.homedir(), '.mocode', 'workspaces.jsonl');
17
+ /** 路径覆盖(仅测试用),原因同 global-usage 的 __setGlobalUsagePath。 */
18
+ let registryPathOverride;
19
+ export function __setWorkspaceRegistryPath(p) {
20
+ registryPathOverride = p;
21
+ }
22
+ export function getWorkspaceRegistryPath() {
23
+ return registryPathOverride ?? WORKSPACE_REGISTRY_PATH;
24
+ }
25
+ /** 本进程内的登记节流:避免短时间重复启动/切回同目录刷一堆行。 */
26
+ const lastAppendAt = new Map();
27
+ /** 读取时折叠结果内的 firstSeen 要持久,故进程内缓存已知 firstSeen。 */
28
+ const knownFirstSeen = new Map();
29
+ const APPEND_THROTTLE_MS = 60_000;
30
+ function sessionsDir(root) {
31
+ return path.join(root, '.mocode', 'sessions');
32
+ }
33
+ /** 统计会话目录数与总字节(best-effort,浅扫一层,任何异常返回 0)。 */
34
+ function scanSessions(root) {
35
+ const dir = sessionsDir(root);
36
+ let sessions = 0;
37
+ let sessionsBytes = 0;
38
+ try {
39
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
40
+ if (!e.isDirectory())
41
+ continue;
42
+ sessions++;
43
+ try {
44
+ sessionsBytes += dirSize(path.join(dir, e.name));
45
+ }
46
+ catch {
47
+ // 单个会话统计失败不影响其余
48
+ }
49
+ }
50
+ }
51
+ catch {
52
+ return { sessions: 0, sessionsBytes: 0 };
53
+ }
54
+ return { sessions, sessionsBytes };
55
+ }
56
+ /** 递归目录字节(best-effort);限制深度避免在巨型 sessions 上卡启动。 */
57
+ function dirSize(dir, depth = 0) {
58
+ if (depth > 4)
59
+ return 0;
60
+ let total = 0;
61
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
62
+ const full = path.join(dir, e.name);
63
+ try {
64
+ if (e.isDirectory())
65
+ total += dirSize(full, depth + 1);
66
+ else if (e.isFile())
67
+ total += fs.statSync(full).size;
68
+ }
69
+ catch {
70
+ // 忽略不可访问条目
71
+ }
72
+ }
73
+ return total;
74
+ }
75
+ /**
76
+ * 登记一次工作区访问。best-effort:任何 I/O 失败静默,绝不阻塞启动/切换。
77
+ * 同一路径 60s 内的重复登记跳过(进程级节流)。
78
+ */
79
+ export function registerWorkspace(root, now = new Date()) {
80
+ try {
81
+ const abs = path.resolve(root);
82
+ const key = abs.toLowerCase();
83
+ const nowMs = now.getTime();
84
+ // 节流以登记时刻为准(注入时间的调用方可控;生产传 new Date() 即时钟时间):
85
+ // 仅当本次时间晚于上次、且落在同一 60s 窗口内才视为重复访问跳过。
86
+ const prev = lastAppendAt.get(key);
87
+ if (prev != null && nowMs >= prev && nowMs - prev < APPEND_THROTTLE_MS)
88
+ return;
89
+ let firstSeen = knownFirstSeen.get(key);
90
+ if (!firstSeen) {
91
+ // 从注册表已有行恢复 firstSeen(进程刚启动、该目录此前登记过)。
92
+ firstSeen = readWorkspaceRegistry().find((e) => e.root.toLowerCase() === key)?.firstSeen ?? now.toISOString();
93
+ knownFirstSeen.set(key, firstSeen);
94
+ }
95
+ const { sessions, sessionsBytes } = scanSessions(abs);
96
+ const entry = {
97
+ root: abs,
98
+ name: path.basename(abs) || abs,
99
+ firstSeen,
100
+ lastSeen: now.toISOString(),
101
+ sessions,
102
+ sessionsBytes,
103
+ };
104
+ fs.mkdirSync(path.dirname(getWorkspaceRegistryPath()), { recursive: true });
105
+ fs.appendFileSync(getWorkspaceRegistryPath(), `${JSON.stringify(entry)}\n`, 'utf8');
106
+ lastAppendAt.set(key, nowMs);
107
+ }
108
+ catch {
109
+ // 注册表是增强能力,不能挡住进工作区
110
+ }
111
+ }
112
+ /**
113
+ * 读注册表并按 root 折叠(保留 lastSeen 最新的一条,firstSeen 取最早)。
114
+ * 按最近访问倒序。损坏行跳过,文件不存在返回空。
115
+ */
116
+ export function readWorkspaceRegistry() {
117
+ let raw;
118
+ try {
119
+ raw = fs.readFileSync(getWorkspaceRegistryPath(), 'utf8');
120
+ }
121
+ catch {
122
+ return [];
123
+ }
124
+ const byRoot = new Map();
125
+ for (const line of raw.split('\n')) {
126
+ const trimmed = line.trim();
127
+ if (!trimmed)
128
+ continue;
129
+ try {
130
+ const e = JSON.parse(trimmed);
131
+ if (typeof e.root !== 'string' || typeof e.lastSeen !== 'string')
132
+ continue;
133
+ const key = e.root.toLowerCase();
134
+ const existing = byRoot.get(key);
135
+ if (!existing || e.lastSeen > existing.lastSeen) {
136
+ const firstSeen = existing && existing.firstSeen < e.firstSeen ? existing.firstSeen : (e.firstSeen ?? e.lastSeen);
137
+ byRoot.set(key, { ...e, firstSeen });
138
+ }
139
+ }
140
+ catch {
141
+ // 跳过损坏行
142
+ }
143
+ }
144
+ return [...byRoot.values()].sort((a, b) => (a.lastSeen < b.lastSeen ? 1 : a.lastSeen > b.lastSeen ? -1 : 0));
145
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mocode-ai",
3
- "version": "1.9.2",
3
+ "version": "1.9.3",
4
4
  "description": "终端编码 agent:LLM + tool-call 循环 + 流式输出(含思考)+ 27 个工具,接任意 OpenAI 兼容后端。",
5
5
  "type": "module",
6
6
  "bin": {