mocode-ai 1.9.2 → 1.9.4

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 CHANGED
@@ -41,7 +41,7 @@ MoCode keeps code-level control light and leaves task strategy to the agent:
41
41
  - **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
42
42
  - **Bounded tool retries, explicit failures** — The runtime automatically retries only transient errors from tools explicitly marked `idempotent`, at most twice. `TIMEOUT`, permission denial, cancellation, and non-idempotent calls are not automatically retried. The resulting structured outcome is returned to the agent for any further recovery decision; see [Automatic retry](#automatic-retry-the-retryable-contract).
43
43
  - **`ask_human` for user-owned decisions** — The agent must ask before any decision the user has not made (multiple reasonable approaches) and before key modifications (public APIs, schemas, dependencies, file moves/deletes, architecture, security, large or irreversible changes). Only trivial, repository-precedent details are decided alone.
44
- - **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`) manage context pressure. Token estimation self-calibrates against provider usage.
44
+ - **Five independent context dials + token self-calibration** — `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` each manage one layer of context pressure. Triggering is a single threshold — request occupancy (raw or corrected, whichever is larger) at 80% of the window — not a per-zone quota: a zone being over its share never rewrites anything on its own. Token estimation self-calibrates against provider usage.
45
45
 
46
46
  ## Architecture
47
47
 
package/README.zh-CN.md CHANGED
@@ -93,7 +93,7 @@ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
93
93
  - **建议式工作纪律** — system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
94
94
  - **有界重试,明确报告失败** — runtime 仅对显式声明 `idempotent` 的工具瞬时错误自动重试,最多两次;`TIMEOUT`、权限拒绝、中断和非幂等调用不自动重试。最终结构化结果交给 agent,由其决定后续恢复方式,详见[自动重试](#自动重试retryable-契约)。
95
95
  - **ask_human 决策与关键修改先问** — 用户尚未做出的决策(存在多个合理方案)和关键修改(公共 API、schema、依赖、文件移动/删除、架构、安全、大范围或不可逆改动)必须先询问用户;只有符合仓库惯例的琐碎细节才由 agent 自行决定。
96
- - **五区上下文控制 + token 自校准** — 独立旋钮管理上下文压力,token 估算根据真实 provider 用量校准。
96
+ - **五个独立的上下文旋钮 + token 自校准** — `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` 各管一层上下文压力。触发条件是单一阈值:请求占用(裸估算与校正后取大者)到达窗口的 80%,不是分区配额——某个分区超配额本身不会改写任何内容。token 估算根据真实 provider 用量校准。
97
97
 
98
98
  ## 为什么用 mocode
99
99
 
@@ -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}). ` +
@@ -1,28 +1,17 @@
1
- // 五区 Context Budget accounting and the shared pressure threshold.
1
+ // Context Budget accounting and the shared pressure threshold.
2
2
  //
3
3
  // This module only estimates and reports. session/scheduler.ts owns the sole
4
4
  // automatic rewrite sequence and starts all pressure cleanup plus compact_history
5
5
  // when corrected or raw request occupancy reaches 80%.
6
- import { chatTools, estimateMessagesTokens, estimateToolSchemaTokens, messageTokens } from '../llm/index.js';
6
+ //
7
+ // 产出只有四个标量:total / rawTotal / window / hotBoundary(外加 systemCosts 拆分)。
8
+ // 曾经这里还有一套「五区分账」(system/history/toolRecent/toolOld/summary/reserve 各自的
9
+ // ratio 与 overBudget/overRatio),但它的全部产物只流向一个无人调用的 formatReport(),
10
+ // 调度器从头到尾只看总阈值 —— 留着会让后来的人以为改 ratios 能改变压缩行为,实际零影响。
11
+ // 2026-11 已删除,避免误判。
12
+ import { chatTools, estimateToolSchemaTokens, messageTokens } from '../llm/index.js';
7
13
  import { toText } from './utils.js';
8
- /** 五区分账(占比对齐 CONTEXT_WINDOW)。顺序固定,便于遍历。 */
9
- export const BUDGET_LAYERS = [
10
- 'system',
11
- 'history',
12
- 'toolRecent', // Hot Tool
13
- 'toolOld', // Cold Tool
14
- 'summary',
15
- 'reserve', // Reserve(不占内容,只占预算分配;5%)
16
- ];
17
14
  export const DEFAULT_BUDGET_POLICY = {
18
- ratios: {
19
- system: 0.15,
20
- history: 0.2,
21
- toolRecent: 0.25,
22
- toolOld: 0.25,
23
- summary: 0.1,
24
- reserve: 0.05,
25
- },
26
15
  hotTurnWindow: 4,
27
16
  // 压缩保留区:自动 15% / 强压 5%,且绝对上限 48k——摘要+最近几轮足够续工,
28
17
  // 旧 0.40 在大窗口下导致"160k 压到 100k"的无效压缩。
@@ -30,12 +19,8 @@ export const DEFAULT_BUDGET_POLICY = {
30
19
  compactForceKeepRatio: 0.05,
31
20
  compactKeepMaxTokens: 48000,
32
21
  pressureTriggerRatio: 0.8,
33
- schedulerTargetRatio: 0.8,
34
- estimateSafetyFactor: 1.05,
35
- compactHeadroomTokens: 1500,
36
22
  };
37
23
  /** 兼容既有调用方的只读别名;配置只在 DEFAULT_BUDGET_POLICY 中维护。 */
38
- export const BUDGET_RATIO = DEFAULT_BUDGET_POLICY.ratios;
39
24
  export const HOT_TURN_WINDOW = DEFAULT_BUDGET_POLICY.hotTurnWindow;
40
25
  function msgTokens(m) {
41
26
  // 与请求预估复用同一实现,避免角色结构开销、多模态和 tool_calls 在两个预算路径中漂移。
@@ -55,20 +40,17 @@ export function userTurnBoundary(history, window) {
55
40
  }
56
41
  return 1; // 没攒够 N 个 user 之前的全归 Cold(history[0] system 不动)
57
42
  }
58
- /** 评估当前 history 的五区预算(纯函数,改不动 history)。
43
+ /** 评估当前 history 的请求占用(纯函数,改不动 history)。
59
44
  * 传入 step 是当前所在 step 编号(agent 循环 step 变量),用于日志/调试。
60
45
  * correction:API 实测 / 估算的校正系数(默认 1);>1 表示粗估偏低,乘以系数后 actual 更接近真实值。
61
46
  * activeTools 必须与下一次 chat() 实际发送的工具集合一致,避免 plan/子 agent 误算 schema。
62
47
  * ephemeralTokens:本次请求会追加、但不在 history 里的尾部注入(会话状态提醒等)的裸 token,
63
48
  * 必须传入,否则压力线看不见这部分开销(见 SystemCostBreakdown.ephemeral)。 */
64
49
  export function evaluateBudget(history, window, step = 0, correction = 1, activeTools = chatTools, ephemeralTokens = 0) {
65
- const layers = {};
66
- for (const k of BUDGET_LAYERS) {
67
- const budget = Math.floor(BUDGET_RATIO[k] * window);
68
- layers[k] = { actual: 0, budget, overBudget: false, overRatio: 0 };
69
- }
70
50
  // 校正后的 token 数:raw * correction,最小 1(raw > 0 时)。
71
51
  const adj = (raw) => (raw > 0 ? Math.max(1, Math.round(raw * correction)) : 0);
52
+ // 校正后总量:逐段累加,不再先分桶再求和。
53
+ let total = 0;
72
54
  // 裸总量(不乘 correction):硬闸用它判断,防止 correction 折扣否决真实溢出。
73
55
  let rawTotal = 0;
74
56
  const sysMsg = history[0];
@@ -81,7 +63,7 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
81
63
  // 工具 schema、system prompt 与尾部 ephemeral 注入同属请求固定开销;
82
64
  // 必须计入总量才能可靠触发压缩(尾部注入不在 history 里,只能由调用方传入)。
83
65
  const systemRaw = systemCosts.prompt + systemCosts.toolSchemas + systemCosts.ephemeralInjection;
84
- layers.system.actual = adj(systemRaw);
66
+ total += adj(systemRaw);
85
67
  rawTotal += systemRaw;
86
68
  // Summary 检测:role:'system' 且不是 history[0] 的,视为摘要(compact.ts 摘要插 index 1)。
87
69
  // 简单启发:若 history[1]?.role === 'system' 且 content 含「# 会话摘要」特征串,计入 summary。
@@ -91,55 +73,31 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
91
73
  const c1 = toText(history[1].content);
92
74
  if (c1.startsWith('# 会话摘要') || c1.includes('会话摘要')) {
93
75
  const summaryRaw = msgTokens(history[1]);
94
- layers.summary.actual = adj(summaryRaw);
76
+ total += adj(summaryRaw);
95
77
  rawTotal += summaryRaw;
96
78
  summaryHit = true;
97
79
  }
98
80
  }
99
81
  // 划 Hot/Cold 边界
100
82
  const hotStart = userTurnBoundary(history, HOT_TURN_WINDOW);
101
- // history 区 = 减去 summary + tool 单算;tool 按 Hot/Cold 分。
83
+ // tool / user / assistant 一并计入总量(冷热区划分只用于决定改写范围,不影响总量)。
102
84
  for (let i = 1; i < history.length; i++) {
103
85
  const m = history[i];
104
86
  if (i === 1 && summaryHit)
105
87
  continue; // summary 已单独算过
88
+ if (m.role === 'system')
89
+ continue; // 其它 system(几乎不存在)跳过
106
90
  const raw = msgTokens(m);
107
- if (m.role === 'tool') {
108
- if (i >= hotStart)
109
- layers.toolRecent.actual += adj(raw);
110
- else
111
- layers.toolOld.actual += adj(raw);
112
- rawTotal += raw;
113
- }
114
- else if (m.role !== 'system') {
115
- // user / assistant 全部计入 history(对话轨迹)
116
- layers.history.actual += adj(raw);
117
- rawTotal += raw;
118
- }
119
- // 其它 system(几乎不存在)跳过
120
- }
121
- // 计算 overBudget + overRatio
122
- const triggers = [];
123
- for (const k of BUDGET_LAYERS) {
124
- const lb = layers[k];
125
- if (lb.actual > lb.budget) {
126
- lb.overBudget = true;
127
- lb.overRatio = (lb.actual - lb.budget) / Math.max(lb.budget, 1);
128
- triggers.push(k);
129
- }
91
+ total += adj(raw);
92
+ rawTotal += raw;
130
93
  }
131
- // 按 overRatio 降序
132
- triggers.sort((a, b) => layers[b].overRatio - layers[a].overRatio);
133
- const total = BUDGET_LAYERS.reduce((s, k) => s + (k === 'reserve' ? 0 : layers[k].actual), 0);
134
94
  const totalOver = total >= DEFAULT_BUDGET_POLICY.pressureTriggerRatio * window;
135
95
  return {
136
96
  step,
137
97
  total,
138
98
  rawTotal,
139
99
  window,
140
- layers,
141
100
  systemCosts,
142
- triggers,
143
101
  totalOver,
144
102
  hotBoundary: hotStart,
145
103
  correction,
@@ -147,7 +105,7 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
147
105
  }
148
106
  /** 根据 BudgetReport 生成可执行动作。
149
107
  * History compaction is the final fallback after pressure-only tool stages.
150
- * Per-layer overages are diagnostics, never independent rewrite triggers. */
108
+ * 唯一判定条件是总占用(裸估或校正后的较大者)过 80% 压力线。 */
151
109
  export function scheduleActions(report) {
152
110
  const actions = [];
153
111
  const pressureLine = DEFAULT_BUDGET_POLICY.pressureTriggerRatio * report.window;
@@ -156,23 +114,3 @@ export function scheduleActions(report) {
156
114
  }
157
115
  return actions;
158
116
  }
159
- /** 拍平成人类可读(供 /context 命令与 check-budget 脚本用)。 */
160
- export function formatReport(report) {
161
- const lines = [];
162
- lines.push(`step ${report.step} total ${report.total}/${report.window} (${((report.total / report.window) * 100).toFixed(1)}%) raw ${report.rawTotal}`);
163
- for (const k of BUDGET_LAYERS) {
164
- const lb = report.layers[k];
165
- const pct = lb.budget > 0 ? ((lb.actual / lb.budget) * 100).toFixed(0) : '-';
166
- const flag = lb.overBudget ? '⚠' : ' ';
167
- lines.push(` ${flag} ${k.padEnd(10)} ${String(lb.actual).padStart(6)} / ${String(lb.budget).padStart(6)} (${pct.padStart(3)}%)`);
168
- }
169
- if (report.triggers.length > 0) {
170
- lines.push(` triggers: ${report.triggers.join(' → ')}`);
171
- }
172
- return lines.join('\n');
173
- }
174
- /** 便捷:把 history 一把估成总 token 数(给 cap.js 等复用,避免重复实现)。
175
- * 注意:此处是粗估(只看 content 长度),不区分五区——只用于「系统层整体还剩多少」快查。 */
176
- export function quickEstimate(history) {
177
- return estimateMessagesTokens(history);
178
- }
@@ -6,4 +6,4 @@ export { classify, knownToolKinds } from './classifier.js';
6
6
  export { recordArtifact, invalidateArtifacts, rehydrateArtifacts, refreshArtifactFreshness, pruneStaleArtifacts, collectArtifactRefs, formatArtifactTokenSources, knownEditTargets, } from './artifacts.js';
7
7
  export { registerEncoder, registerAll, getEncoder, registeredKinds } from './registry.js';
8
8
  // ── Context Budget Scheduler ───────────────────────────────────────────────
9
- export { evaluateBudget, scheduleActions, formatReport, quickEstimate, userTurnBoundary, BUDGET_LAYERS, DEFAULT_BUDGET_POLICY, BUDGET_RATIO, HOT_TURN_WINDOW, } from './budget.js';
9
+ export { evaluateBudget, scheduleActions, userTurnBoundary, DEFAULT_BUDGET_POLICY, HOT_TURN_WINDOW } from './budget.js';
@@ -11,6 +11,8 @@ const zhCN = {
11
11
  'commands.skills': '列出已发现的 skill',
12
12
  'commands.compact': '压缩历史(可带焦点 /compact …)',
13
13
  'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
14
+ 'commands.usageOverview': '查看最近 7 天 token 用量(可 /usage 30 改天数)',
15
+ 'commands.usageImport': '回填各工作区历史会话的 token 用量(幂等)',
14
16
  'commands.session': '会话恢复与回滚',
15
17
  'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
16
18
  'commands.sessionBrowse': '浏览全部已保存会话',
@@ -188,19 +190,36 @@ const zhCN = {
188
190
  'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
189
191
  'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
190
192
  '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': '(无用量)',
196
- 'repl.usageTotalRow': '合计',
193
+ 'repl.usageBarsNote': '按天用量(对数刻度;柱高看相对趋势,精确值见高峰日与排行)',
194
+ 'repl.usageBarsBucket': '每柱聚合 {span} 天',
195
+ 'repl.usagePeaks': '高峰日:{days}',
196
+ 'repl.usageKMetric': '指标',
197
+ 'repl.usageKValue': '数值',
198
+ 'repl.usageKTotal': '总用量',
199
+ 'repl.usageKInput': '输入 in',
200
+ 'repl.usageKOutput': '输出 out',
201
+ 'repl.usageKRequests': '请求数',
202
+ 'repl.usageKSessions': '会话数',
203
+ 'repl.usageKWorkspaces': '工作空间数',
204
+ 'repl.usageKCacheHit': '缓存命中率',
205
+ 'repl.usageKReasoningShare': '推理占输出',
206
+ 'repl.usageKCacheWrite': '缓存写入',
207
+ 'repl.usageKDailyAvg': '日均用量',
208
+ 'repl.usageKCompact': '其中压缩(compact)',
209
+ 'repl.usageColWorkspace': '工作空间',
210
+ 'repl.usageColModel': '模型',
211
+ 'repl.usageColIn': '输入',
212
+ 'repl.usageColOut': '输出',
213
+ 'repl.usageColCalls': '请求数',
214
+ 'repl.usageColSessions': '会话数',
197
215
  'repl.usageByWorkspace': '按工作空间',
198
216
  'repl.usageByModel': '按模型',
199
- 'repl.usageNone': '(无)',
200
217
  'repl.usageMore': '… 其余 {n} 项已省略',
201
- 'repl.usageSessions': '{n} 个会话',
202
218
  'repl.usageBadArg': '用法:/usage [天数 1-366](默认 7)',
203
- 'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积)',
219
+ 'repl.usageImportDone': '已回填 {records} 条历史记录({sessions} 个会话 · {workspaces} 个工作空间;跳过 {skipped} 条已实时统计的记录)',
220
+ 'repl.usageImportNothing': '没有可回填的历史记录({skipped} 条已实时统计,重复执行是幂等的)',
221
+ 'repl.usageImportZero': '没有找到可回填的历史会话用量(先在 mocode 里跑过任务的工作区才会产生 usage.jsonl)',
222
+ 'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积,或用 /usage import 回填历史)',
204
223
  'repl.planAlready': '(已在 plan 模式)',
205
224
  'repl.planChanged': '(已切到 plan 模式:只读探查 + 产出计划,审批后切 auto 执行。/auto 或 Shift+Tab 切回)',
206
225
  'repl.autoAlready': '(已在 auto 模式)',
@@ -304,6 +323,7 @@ const zhCN = {
304
323
  'status.queued': '排队 ·',
305
324
  'status.queuedCount': '排队 ×{count} ·',
306
325
  'status.queuePlanTag': '(Plan)',
326
+ 'status.planMoreSteps': '还有 {count} 步',
307
327
  'status.measured': '实测',
308
328
  'status.estimated': '估算',
309
329
  'status.messages': '{count} 条消息',
@@ -501,6 +521,8 @@ const en = {
501
521
  'commands.skills': 'List discovered skills',
502
522
  'commands.compact': 'Compact history (optional focus: /compact …)',
503
523
  'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
524
+ 'commands.usageOverview': 'Show token usage for the last 7 days (try /usage 30)',
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,36 @@ 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',
680
- 'repl.usageEmptyDay': '(no usage)',
681
- 'repl.usageTotalRow': 'Total',
698
+ 'repl.usageBarsNote': 'Daily usage (log scale; bar height shows relative trend, see peaks and rankings for values)',
699
+ 'repl.usageBarsBucket': 'each bar aggregates {span} days',
700
+ 'repl.usagePeaks': 'Peak days: {days}',
701
+ 'repl.usageKMetric': 'Metric',
702
+ 'repl.usageKValue': 'Value',
703
+ 'repl.usageKTotal': 'Total tokens',
704
+ 'repl.usageKInput': 'Input',
705
+ 'repl.usageKOutput': 'Output',
706
+ 'repl.usageKRequests': 'Requests',
707
+ 'repl.usageKSessions': 'Sessions',
708
+ 'repl.usageKWorkspaces': 'Workspaces',
709
+ 'repl.usageKCacheHit': 'Cache hit rate',
710
+ 'repl.usageKReasoningShare': 'Reasoning share of output',
711
+ 'repl.usageKCacheWrite': 'Cache write',
712
+ 'repl.usageKDailyAvg': 'Daily average',
713
+ 'repl.usageKCompact': 'of which compact',
714
+ 'repl.usageColWorkspace': 'Workspace',
715
+ 'repl.usageColModel': 'Model',
716
+ 'repl.usageColIn': 'Input',
717
+ 'repl.usageColOut': 'Output',
718
+ 'repl.usageColCalls': 'Requests',
719
+ 'repl.usageColSessions': 'Sessions',
682
720
  'repl.usageByWorkspace': 'By workspace',
683
721
  'repl.usageByModel': 'By model',
684
- 'repl.usageNone': '(none)',
685
722
  'repl.usageMore': '… {n} more hidden',
686
- 'repl.usageSessions': '{n} sessions',
687
723
  '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)',
724
+ 'repl.usageImportDone': 'Backfilled {records} historical records ({sessions} sessions · {workspaces} workspaces; skipped {skipped} already-tracked records)',
725
+ 'repl.usageImportNothing': 'Nothing to backfill ({skipped} records were already tracked live; re-running is idempotent)',
726
+ 'repl.usageImportZero': 'No historical session usage found (a workspace only has usage.jsonl after tasks have run in mocode)',
727
+ 'repl.usageNoData': '(No global usage data yet; collection starts from model calls after this feature, or run /usage import to backfill history)',
689
728
  'repl.planAlready': '(already in plan mode)',
690
729
  'repl.planChanged': '(switched to plan mode: read-only research and planning; approval returns to auto. Use /auto or Shift+Tab to switch back)',
691
730
  'repl.autoAlready': '(already in auto mode)',
@@ -788,6 +827,7 @@ const en = {
788
827
  'status.queued': 'queued ·',
789
828
  'status.queuedCount': 'queued ×{count} ·',
790
829
  'status.queuePlanTag': ' (Plan)',
830
+ 'status.planMoreSteps': '{count} more step(s)',
791
831
  'status.measured': 'measured',
792
832
  'status.estimated': 'estimated',
793
833
  'status.messages': '{count} messages',
@@ -32,7 +32,7 @@ export const compactCommands = [
32
32
  }
33
33
  else if (rest)
34
34
  focus = rest;
35
- // 走调度器路径:与自动每步压缩完全一致——五区按 ROI 压(cold tools 优先 → history 摘要最后)。
35
+ // 走调度器路径:与自动每步压缩完全一致——先跑零成本清理(cold tools 优先),最后才 LLM 摘要。
36
36
  // focus 透传到 compact_history action 的 LLM 摘要 prompt。
37
37
  // 返回 SchedulerRunLog 给 UI 显示决策;退化路径(开关关时)在 manualCompact 内部走 compactHistory。
38
38
  const log = await (async () => {
@@ -1,9 +1,10 @@
1
1
  /**
2
- * 用量命令组:/stats(当前会话诊断)· /usage(跨工作空间按天汇总)
2
+ * 用量命令组:/stats(当前会话诊断)· /usage(跨工作空间用量)
3
3
  *
4
4
  * /stats 读会话级 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
5
- * /usage 读全局账本 ~/.mocode/usage-daily.jsonl(每次模型调用追加,含工作区/模型/
6
- * 本地日期),输出最近 N 天的按天表、总计、工作区与模型排行。
5
+ * /usage 读全局账本 ~/.mocode/usage-daily.jsonl:总览两行 + 固定高度柱状图(长区间
6
+ * 自动按周聚合,替代会撑出几百行的按天表格)+ 高峰日 Top5 + 工作区/模型 Top5 表。
7
+ * /usage import 回填历史会话 usage.jsonl(幂等)。
7
8
  */
8
9
  import * as layout from '../../ui/layout.js';
9
10
  import { ui } from '../../ui/theme.js';
@@ -12,6 +13,9 @@ 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 { bucketizeDays, renderUsageBars } from '../../session/usage-chart.js';
17
+ import { backfillGlobalUsage } from '../../session/backfill-usage.js';
18
+ import { getWorkspaceRoot } from '../../workspace/index.js';
15
19
  import { unhandled, next } from './types.js';
16
20
  /** 计数千分位(请求数/会话数等)。 */
17
21
  function n(v) {
@@ -21,75 +25,104 @@ function n(v) {
21
25
  function tok(v) {
22
26
  return fmtCompactTokens(v);
23
27
  }
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
28
  function pct(part, whole) {
30
29
  return whole > 0 ? `${((part / whole) * 100).toFixed(1)}%` : 'n/a';
31
30
  }
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;
31
+ /** 构造 GFM 表格:headers/rows 等宽;align 列 'l'(左,默认)或 'r'(右)。 */
32
+ function mdTable(headers, rows, align) {
33
+ const sep = align.map((a) => (a === 'r' ? '---:' : ':---')).join('|');
34
+ const lines = [`| ${headers.join(' | ')} |`, `|${sep}|`];
35
+ for (const row of rows)
36
+ lines.push(`| ${row.join(' | ')} |`);
37
+ return lines.join('\n');
48
38
  }
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`;
39
+ /** 工作区/模型排行表(Top 5)。 */
40
+ function groupTable(title, colName, rows) {
41
+ const body = rows.slice(0, 5).map((r) => [r.key, tok(r.input), tok(r.output), n(r.calls), n(r.sessions)]);
42
+ return (`${ui.accent}${title}${ui.reset}\n\n` +
43
+ mdTable([colName, t('repl.usageColIn'), t('repl.usageColOut'), t('repl.usageColCalls'), t('repl.usageColSessions')], body, ['l', 'r', 'r', 'r', 'r']) +
44
+ (rows.length > 5 ? `\n\n${ui.dim}${t('repl.usageMore', { n: rows.length - 5 })}${ui.reset}` : ''));
51
45
  }
52
- function formatGlobal(s) {
53
- const lines = [];
46
+ /** 汇总指标键值表(两列)。 */
47
+ function overviewTable(s) {
54
48
  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
- })}`);
49
+ const rows = [
50
+ [`${ui.bold}${t('repl.usageKTotal')}${ui.reset}`, `${ui.bold}${tok(b.input + b.output)}${ui.reset}`],
51
+ [t('repl.usageKInput'), tok(b.input)],
52
+ [t('repl.usageKOutput'), tok(b.output)],
53
+ [t('repl.usageKRequests'), n(b.calls)],
54
+ [t('repl.usageKSessions'), n(s.sessionCount)],
55
+ [t('repl.usageKWorkspaces'), n(s.workspaceCount)],
56
+ [t('repl.usageKCacheHit'), pct(b.cached, b.input)],
57
+ [t('repl.usageKReasoningShare'), pct(b.reasoning, b.output)],
58
+ [t('repl.usageKCacheWrite'), tok(b.cacheCreation)],
59
+ [t('repl.usageKDailyAvg'), tok(Math.round((b.input + b.output) / s.days))],
60
+ ];
71
61
  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}`);
62
+ rows.push([
63
+ t('repl.usageKCompact'),
64
+ `${tok(s.compact.input)} in / ${tok(s.compact.output)} out / ${n(s.compact.calls)}`,
65
+ ]);
73
66
  }
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) {
78
- if (d.calls === 0) {
79
- lines.push(` ${ui.dim}${d.day} ${t('repl.usageEmptyDay')}${ui.reset}`);
80
- continue;
67
+ return mdTable([t('repl.usageKMetric'), t('repl.usageKValue')], rows, ['l', 'r']);
68
+ }
69
+ /** 高峰日 Top5:一行紧凑文本(图给趋势,这里给精确值)。 */
70
+ function peaksLine(byDay) {
71
+ const top = byDay
72
+ .filter((d) => d.calls > 0)
73
+ .sort((a, b) => b.input + b.output - (a.input + a.output))
74
+ .slice(0, 5)
75
+ .map((d) => `${d.day.slice(5)} ${tok(d.input + d.output)}`);
76
+ return top.length ? `${ui.dim}${t('repl.usagePeaks', { days: top.join(' · ') })}${ui.reset}` : '';
77
+ }
78
+ /** 渲染 /usage 主体:总览表 → 柱状图 → 高峰日 → 排行两表。 */
79
+ function renderUsageReport(s) {
80
+ layout.contentWrite(`\n${ui.accent}${t('repl.usageTitle', { from: s.fromDay, to: s.toDay, days: s.days })}${ui.reset}\n\n`);
81
+ layout.contentWriteMdOnce(overviewTable(s));
82
+ layout.contentWrite('\n\n');
83
+ const buckets = bucketizeDays(s.byDay);
84
+ const bars = renderUsageBars(buckets, layout.getGeo().cols);
85
+ if (bars.length) {
86
+ for (const line of bars)
87
+ layout.contentWrite(` ${line}\n`);
88
+ layout.contentWrite(` ${ui.dim}${t('repl.usageBarsNote')}${ui.reset}\n`);
89
+ const span = buckets[buckets.length - 1]?.spanDays ?? 1;
90
+ if (span > 1) {
91
+ layout.contentWrite(` ${ui.dim}${t('repl.usageBarsBucket', { span })}${ui.reset}\n`);
81
92
  }
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)}`);
93
+ const peaks = peaksLine(s.byDay);
94
+ if (peaks)
95
+ layout.contentWrite(` ${peaks}\n`);
96
+ layout.contentWrite('\n');
83
97
  }
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');
98
+ layout.contentWriteMdOnce(groupTable(t('repl.usageByWorkspace'), t('repl.usageColWorkspace'), s.byWorkspace));
99
+ layout.contentWrite('\n\n');
100
+ layout.contentWriteMdOnce(groupTable(t('repl.usageByModel'), t('repl.usageColModel'), s.byModel));
101
+ layout.contentWrite('\n');
90
102
  }
91
103
  export const statsCommands = [
92
- // /usage [days]:跨工作空间按天汇总。默认 7 天,可传天数(如 /usage 30);非法参数给用法提示。
104
+ // /usage import:把各工作区旧会话的 usage.jsonl 回填进全局账本(幂等,可重复执行)。
105
+ (ctx) => {
106
+ if (ctx.line !== '/usage import' && ctx.line !== '/usage import ')
107
+ return unhandled();
108
+ const r = backfillGlobalUsage({ extraRoots: [getWorkspaceRoot()] });
109
+ if (r.records === 0 && r.skippedTracked > 0) {
110
+ layout.contentWrite(`${ui.dim}${t('repl.usageImportNothing', { skipped: n(r.skippedTracked) })}${ui.reset}\n`);
111
+ }
112
+ else if (r.records === 0) {
113
+ layout.contentWrite(`${ui.dim}${t('repl.usageImportZero')}${ui.reset}\n`);
114
+ }
115
+ else {
116
+ layout.contentWrite(`${ui.accent}${t('repl.usageImportDone', {
117
+ records: n(r.records),
118
+ sessions: n(r.sessions),
119
+ workspaces: n(r.workspaces),
120
+ skipped: n(r.skippedTracked),
121
+ })}${ui.reset}\n`);
122
+ }
123
+ return next();
124
+ },
125
+ // /usage [days]:跨工作空间用量。默认 7 天,可传天数(如 /usage 300);非法参数给用法提示。
93
126
  (ctx) => {
94
127
  if (ctx.line !== '/usage' && !ctx.line.startsWith('/usage '))
95
128
  return unhandled();
@@ -108,7 +141,7 @@ export const statsCommands = [
108
141
  layout.contentWrite(`${ui.dim}${t('repl.usageNoData')}${ui.reset}\n`);
109
142
  return next();
110
143
  }
111
- layout.contentWrite(` ${formatGlobal(summarizeGlobalUsage(records, days))}\n`);
144
+ renderUsageReport(summarizeGlobalUsage(records, days));
112
145
  return next();
113
146
  },
114
147
  (ctx) => {
@@ -24,7 +24,14 @@ 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: [
31
+ { name: 'overview', value: '/usage', desc: d('commands.usageOverview') },
32
+ { name: 'import', value: '/usage import', desc: d('commands.usageImport') },
33
+ ],
34
+ },
28
35
  { name: '/stats', desc: '查看本会话 token 用量与缓存命中率' },
29
36
  { name: '/effort', desc: '设置思考强度(/effort [low|medium|high|auto])' },
30
37
  { 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;