mocode-ai 1.9.1 → 1.9.2

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.
@@ -5,7 +5,9 @@ import { createImageDescriber, relieveRequestBytes } from './request-governor.js
5
5
  import { countOversizedImagePlaceholders, countOversizedImages } from '../context/vision-window.js';
6
6
  import { getActiveSessionStore } from '../session/store.js';
7
7
  import { getCurrentSessionId } from '../session/state.js';
8
+ import { appendGlobalUsage } from '../session/global-usage.js';
8
9
  import { toUsageRecord } from '../session/usage-stats.js';
10
+ import { getWorkspaceRoot } from '../workspace/index.js';
9
11
  /**
10
12
  * 沿 cause 链(≤3 层)取第一个 errno,供 trace 取证。
11
13
  * undici 把底层 errno 挂在 cause 上(`TypeError: fetch failed` → cause `read ECONNRESET`),
@@ -471,6 +473,20 @@ export async function runModelTurn(input) {
471
473
  const sessionId = getCurrentSessionId();
472
474
  if (record && sessionId)
473
475
  getActiveSessionStore().appendUsage(sessionId, record);
476
+ // 全局跨工作空间账本(/usage 按天汇总);best-effort,见 global-usage.ts。
477
+ if (result.usage && sessionId) {
478
+ appendGlobalUsage({
479
+ workspace: getWorkspaceRoot(),
480
+ model: requestModel,
481
+ phase: 'main',
482
+ sessionId,
483
+ input: result.usage.promptTokens,
484
+ output: result.usage.completionTokens,
485
+ cached: result.usage.cachedTokens,
486
+ reasoning: result.usage.reasoningTokens,
487
+ cacheCreation: result.usage.cacheCreationTokens,
488
+ });
489
+ }
474
490
  if (result.usage) {
475
491
  cacheState.lastStepPromptTokens = result.usage.promptTokens;
476
492
  if (result.usage.cachedTokens > 0)
@@ -10,10 +10,12 @@ const zhCN = {
10
10
  'commands.context': '显示上下文用量条',
11
11
  'commands.skills': '列出已发现的 skill',
12
12
  'commands.compact': '压缩历史(可带焦点 /compact …)',
13
+ 'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
13
14
  'commands.session': '会话恢复与回滚',
14
15
  'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
15
16
  'commands.sessionBrowse': '浏览全部已保存会话',
16
17
  'commands.sessionRollback': '菜单选轮次回滚(↑↓·Enter)',
18
+ 'commands.sessionFork': '从当前会话分叉出独立新会话(不切换窗口)',
17
19
  'commands.memory': '记忆库、开关与反思',
18
20
  'commands.memoryOverview': '条目计数与近期索引',
19
21
  'commands.memoryToggle': '切换记忆子系统开关',
@@ -179,6 +181,26 @@ const zhCN = {
179
181
  'repl.noSessions': '(没有已保存的会话)',
180
182
  'repl.noValue': '(无)',
181
183
  'repl.historyCleared': '(历史已清空,保留系统提示)',
184
+ 'repl.forkUsage': '用法:/fork(无参数;从当前会话分叉)',
185
+ 'repl.forkEmpty': '(当前还没有对话,无可分叉内容)',
186
+ 'repl.forkFailed': '(分叉失败:{message})',
187
+ 'repl.forkMissing': '(当前会话尚未落盘,无法分叉)',
188
+ 'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
189
+ 'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
190
+ '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': '合计',
197
+ 'repl.usageByWorkspace': '按工作空间',
198
+ 'repl.usageByModel': '按模型',
199
+ 'repl.usageNone': '(无)',
200
+ 'repl.usageMore': '… 其余 {n} 项已省略',
201
+ 'repl.usageSessions': '{n} 个会话',
202
+ 'repl.usageBadArg': '用法:/usage [天数 1-366](默认 7)',
203
+ 'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积)',
182
204
  'repl.planAlready': '(已在 plan 模式)',
183
205
  'repl.planChanged': '(已切到 plan 模式:只读探查 + 产出计划,审批后切 auto 执行。/auto 或 Shift+Tab 切回)',
184
206
  'repl.autoAlready': '(已在 auto 模式)',
@@ -478,10 +500,12 @@ const en = {
478
500
  'commands.context': 'Show context usage',
479
501
  'commands.skills': 'List discovered skills',
480
502
  'commands.compact': 'Compact history (optional focus: /compact …)',
503
+ 'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
481
504
  'commands.session': 'Resume sessions and roll back turns',
482
505
  'commands.sessionResume': 'Resume one of the 10 latest saved sessions',
483
506
  'commands.sessionBrowse': 'Browse all saved sessions',
484
507
  'commands.sessionRollback': 'Choose a turn to roll back (↑↓·Enter)',
508
+ 'commands.sessionFork': 'Fork the current session into an independent new one (window stays)',
485
509
  'commands.memory': 'Memory store, controls, and reflection',
486
510
  'commands.memoryOverview': 'Show counts and recent entries',
487
511
  'commands.memoryToggle': 'Toggle the memory subsystem',
@@ -642,6 +666,26 @@ const en = {
642
666
  'repl.noSessions': '(no saved sessions)',
643
667
  'repl.noValue': '(none)',
644
668
  'repl.historyCleared': '(history cleared; system prompt kept)',
669
+ 'repl.forkUsage': 'Usage: /fork (no arguments; forks the current session)',
670
+ 'repl.forkEmpty': '(no conversation yet; nothing to fork)',
671
+ 'repl.forkFailed': '(fork failed: {message})',
672
+ 'repl.forkMissing': '(current session is not persisted yet; cannot fork)',
673
+ 'repl.forkDone': 'Forked new session {id} (inherits full context; independent from the original)',
674
+ 'repl.forkHint': 'This window stays on the original session; run mocode --resume {id} in a new terminal, or use /resume here',
675
+ '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',
682
+ 'repl.usageByWorkspace': 'By workspace',
683
+ 'repl.usageByModel': 'By model',
684
+ 'repl.usageNone': '(none)',
685
+ 'repl.usageMore': '… {n} more hidden',
686
+ 'repl.usageSessions': '{n} sessions',
687
+ '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)',
645
689
  'repl.planAlready': '(already in plan mode)',
646
690
  'repl.planChanged': '(switched to plan mode: read-only research and planning; approval returns to auto. Use /auto or Shift+Tab to switch back)',
647
691
  'repl.autoAlready': '(already in auto mode)',
@@ -44,6 +44,39 @@ export const sessionCommands = [
44
44
  layout.writeWelcomeBlock(ctx.welcomeLines()); // 回到空会话状态,欢迎引导重新出现
45
45
  return next();
46
46
  },
47
+ // /fork:把当前会话整个目录复制成一个新 id 会话(继承全部上下文),**不切换**窗口——
48
+ // 原会话继续在本窗口对话;分叉会话可用新终端 `mocode --resume <id>` 或本窗口 /resume 进入。
49
+ async (ctx) => {
50
+ if (ctx.line !== '/fork' && !ctx.line.startsWith('/fork '))
51
+ return unhandled();
52
+ const args = ctx.line.replace(/^\/fork\s*/, '').trim();
53
+ if (args) {
54
+ layout.contentWrite(`${ui.yellow}${t('repl.forkUsage')}${ui.reset}\n`);
55
+ return next();
56
+ }
57
+ const sourceId = ctx.state.currentSessionId;
58
+ if (!sourceId || ctx.history.length <= 1) {
59
+ layout.contentWrite(`${ui.dim}${t('repl.forkEmpty')}${ui.reset}\n`);
60
+ return next();
61
+ }
62
+ // 先落盘内存里的最新对话,分叉副本才能包含尚未自动保存的尾部;persistSnapshots 一并刷新。
63
+ ctx.runtime.session.save(ctx.history, sourceId, ctx.state.queryHistory, ctx.state.lastToolGroups);
64
+ let newId;
65
+ try {
66
+ newId = ctx.runtime.session.fork(sourceId);
67
+ }
68
+ catch (e) {
69
+ layout.contentWrite(`${ui.red}${t('repl.forkFailed', { message: e instanceof Error ? e.message : String(e) })}${ui.reset}\n`);
70
+ return next();
71
+ }
72
+ if (!newId) {
73
+ layout.contentWrite(`${ui.yellow}${t('repl.forkMissing')}${ui.reset}\n`);
74
+ return next();
75
+ }
76
+ layout.contentWrite(`${ui.accent}${t('repl.forkDone', { id: newId })}${ui.reset}\n`);
77
+ layout.contentWrite(`${ui.dim}${t('repl.forkHint', { id: newId })}${ui.reset}\n`);
78
+ return next();
79
+ },
47
80
  // /sessions:浏览全部已保存会话(慢路径,readdir+全量 JSON.parse,目录 N 大时会有可感知卡顿)。
48
81
  // 默认走 /resume(仅最近 10 条,瞬开);要翻历史续接更早的会话才用这条。
49
82
  // picker 走全显(cap=items.length,无 a 展开提示),靠 picker 自身开窗(以选中为中心分屏)。
@@ -1,14 +1,116 @@
1
1
  /**
2
- * 用量命令组:/stats(#token-efficiency P1)
2
+ * 用量命令组:/stats(当前会话诊断)· /usage(跨工作空间按天汇总)
3
3
  *
4
- * dialog-only:读取当前会话 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
5
- * 后端从未上报 cached 时命中率显示 n/a,不报错。
4
+ * /stats 读会话级 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
5
+ * /usage 读全局账本 ~/.mocode/usage-daily.jsonl(每次模型调用追加,含工作区/模型/
6
+ * 本地日期),输出最近 N 天的按天表、总计、工作区与模型排行。
6
7
  */
7
8
  import * as layout from '../../ui/layout.js';
9
+ import { ui } from '../../ui/theme.js';
10
+ import { fmtCompactTokens } from '../../ui/render.js';
11
+ import { t } from '../../i18n/index.js';
8
12
  import { getActiveSessionStore } from '../../session/store.js';
9
13
  import { formatUsageSummary, summarizeUsage } from '../../session/usage-stats.js';
14
+ import { readGlobalUsage, summarizeGlobalUsage, } from '../../session/global-usage.js';
10
15
  import { unhandled, next } from './types.js';
16
+ /** 计数千分位(请求数/会话数等)。 */
17
+ function n(v) {
18
+ return v.toLocaleString('en-US');
19
+ }
20
+ /** token 统一缩写:<1k 整数,1k-1M 用 k,≥1M 用 M(复用全项目同口径)。 */
21
+ function tok(v) {
22
+ return fmtCompactTokens(v);
23
+ }
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
+ function pct(part, whole) {
30
+ return whole > 0 ? `${((part / whole) * 100).toFixed(1)}%` : 'n/a';
31
+ }
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`;
51
+ }
52
+ function formatGlobal(s) {
53
+ const lines = [];
54
+ 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
+ })}`);
71
+ 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}`);
73
+ }
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;
81
+ }
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');
90
+ }
11
91
  export const statsCommands = [
92
+ // /usage [days]:跨工作空间按天汇总。默认 7 天,可传天数(如 /usage 30);非法参数给用法提示。
93
+ (ctx) => {
94
+ if (ctx.line !== '/usage' && !ctx.line.startsWith('/usage '))
95
+ return unhandled();
96
+ const arg = ctx.line.replace(/^\/usage\s*/, '').trim();
97
+ let days = 7;
98
+ if (arg) {
99
+ const parsed = Number(arg);
100
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 366) {
101
+ layout.contentWrite(`${ui.yellow}${t('repl.usageBadArg')}${ui.reset}\n`);
102
+ return next();
103
+ }
104
+ days = parsed;
105
+ }
106
+ const records = readGlobalUsage();
107
+ if (records.length === 0) {
108
+ layout.contentWrite(`${ui.dim}${t('repl.usageNoData')}${ui.reset}\n`);
109
+ return next();
110
+ }
111
+ layout.contentWrite(` ${formatGlobal(summarizeGlobalUsage(records, days))}\n`);
112
+ return next();
113
+ },
12
114
  (ctx) => {
13
115
  if (ctx.line !== '/stats')
14
116
  return unhandled();
@@ -24,9 +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: '/stats', desc: '查看本会话 token 用量与缓存命中率' },
28
29
  { name: '/effort', desc: '设置思考强度(/effort [low|medium|high|auto])' },
29
30
  { name: '/resume', desc: d('commands.sessionResume') },
31
+ { name: '/fork', desc: d('commands.sessionFork') },
30
32
  { name: '/sessions', desc: d('commands.sessionBrowse') },
31
33
  { name: '/rollback', desc: d('commands.sessionRollback') },
32
34
  { name: '/diff', desc: '查看 agent 文件改动 diff(/diff [N]|all,快照 vs 工作区)' },
@@ -205,7 +207,10 @@ export const LLM_ERROR_HINT_KEYS = {
205
207
  /** /help 的分组:按使用场景归组,组内保持菜单树顺序。未列入的顶层命令兜底进「其他」。 */
206
208
  export const HELP_GROUPS = [
207
209
  { key: 'help.groupFrequent', names: ['/help', '/clear', '/cd', '/context', '/compact', '/resume', '/model'] },
208
- { key: 'help.groupSession', names: ['/sessions', '/rollback', '/memory', '/skills', '/skill', '/init'] },
210
+ {
211
+ key: 'help.groupSession',
212
+ names: ['/fork', '/sessions', '/rollback', '/usage', '/memory', '/skills', '/skill', '/init'],
213
+ },
209
214
  {
210
215
  key: 'help.groupConfig',
211
216
  names: [
@@ -54,6 +54,7 @@ export class Runtime {
54
54
  return this.context.sessionStore.list(limit);
55
55
  },
56
56
  clear: () => this.createSession(true),
57
+ fork: (sourceId) => this.forkSession(sourceId),
57
58
  gc: (async (opts = {}) => {
58
59
  this.assertIdle('gc sessions');
59
60
  const root = this.context.sessionStore.sessionsRoot;
@@ -272,6 +273,18 @@ export class Runtime {
272
273
  this.emit(cleared ? 'session.cleared' : 'session.created', { sessionId: id });
273
274
  return id;
274
275
  }
276
+ forkSession(sourceId) {
277
+ this.assertIdle('fork session');
278
+ const srcId = sourceId ?? this.context.sessionStore.getCurrentSessionId();
279
+ if (!srcId)
280
+ throw new Error('Cannot fork without an active session.');
281
+ const newId = this.context.sessionStore.forkSession(srcId);
282
+ if (!newId)
283
+ return null;
284
+ // 注意:不 setCurrentSessionId、不重置 rollback 状态——当前窗口继续原会话。
285
+ this.emit('session.forked', { sourceSessionId: srcId, sessionId: newId });
286
+ return newId;
287
+ }
275
288
  resumeSession(id) {
276
289
  this.assertIdle('resume session');
277
290
  const loaded = this.context.sessionStore.load(id, { restoreAssets: true });
@@ -13,7 +13,9 @@ import { collectArtifactRefs } from '../context/artifacts.js';
13
13
  import { writeCompactionSnapshot } from './notes.js';
14
14
  import { getActiveSessionStore } from './store.js';
15
15
  import { getCurrentSessionId } from './state.js';
16
+ import { appendGlobalUsage } from './global-usage.js';
16
17
  import { toUsageRecord } from './usage-stats.js';
18
+ import { getWorkspaceRoot } from '../workspace/index.js';
17
19
  /** 默认兼容依赖:旧调用方继续读取进程级 config/chat。 */
18
20
  export const defaultCompactionRuntime = {
19
21
  config,
@@ -655,6 +657,20 @@ async function forkSummarize(prefix, instruction, signal, runtime, activeTools,
655
657
  const sessionId = getCurrentSessionId();
656
658
  if (rec && sessionId)
657
659
  getActiveSessionStore().appendUsage(sessionId, rec);
660
+ // 全局跨工作空间账本:压缩调用单列 phase=compact(/usage 汇总区分主对话与压缩开销)。
661
+ if (r.usage && sessionId) {
662
+ appendGlobalUsage({
663
+ workspace: getWorkspaceRoot(),
664
+ model: config.model,
665
+ phase: 'compact',
666
+ sessionId,
667
+ input: r.usage.promptTokens,
668
+ output: r.usage.completionTokens,
669
+ cached: r.usage.cachedTokens,
670
+ reasoning: r.usage.reasoningTokens,
671
+ cacheCreation: r.usage.cacheCreationTokens,
672
+ });
673
+ }
658
674
  }
659
675
  // 同 legacy:幻觉 tool_calls 或空 content → 失败(调用方回落 microcompact)。
660
676
  if (r.toolCalls.length > 0 || !r.content)
@@ -0,0 +1,173 @@
1
+ /**
2
+ * 跨工作空间的全局 token 账本。
3
+ *
4
+ * 会话级 usage.jsonl 按 <workspace>/.mocode/sessions/<id>/ 分散存放,且不含
5
+ * 时间/工作区/模型字段,无法跨项目汇总。每次模型调用在写会话级 usage 之外,
6
+ * 再向全局账本 `~/.mocode/usage-daily.jsonl` 追加一行(含时间、本地日期、
7
+ * 工作区、模型、sessionId、phase),/usage 据此做按天/工作区/模型汇总。
8
+ *
9
+ * 与 SessionStore.appendUsage 同款策略:同步 append、失败静默(best-effort,
10
+ * 记账绝不阻塞模型调用)。只统计本功能上线后新产生的调用。
11
+ */
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ /** 全局账本路径:跨工作空间,故放 ~/.mocode 而非项目目录。 */
16
+ export const GLOBAL_USAGE_PATH = path.join(os.homedir(), '.mocode', 'usage-daily.jsonl');
17
+ /** 本地日期 YYYY-MM-DD;不引时区库——运行机器本地时间即用户口径的"天"。 */
18
+ export function localDay(d = new Date()) {
19
+ const p = (n) => String(n).padStart(2, '0');
20
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
21
+ }
22
+ /** 追加一行全局用量。任何 I/O 失败静默——记账不能拖垮主流程。 */
23
+ export function appendGlobalUsage(input) {
24
+ try {
25
+ const now = new Date();
26
+ const rec = {
27
+ ts: now.toISOString(),
28
+ day: localDay(now),
29
+ input: input.input,
30
+ output: input.output,
31
+ cached: input.cached ?? 0,
32
+ reasoning: input.reasoning ?? 0,
33
+ cacheCreation: input.cacheCreation ?? 0,
34
+ workspace: input.workspace,
35
+ model: input.model,
36
+ phase: input.phase,
37
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
38
+ };
39
+ fs.mkdirSync(path.dirname(GLOBAL_USAGE_PATH), { recursive: true });
40
+ fs.appendFileSync(GLOBAL_USAGE_PATH, `${JSON.stringify(rec)}\n`, 'utf8');
41
+ }
42
+ catch {
43
+ // best-effort, see file header
44
+ }
45
+ }
46
+ /** 读全部全局记录;文件不存在或损坏行跳过。 */
47
+ export function readGlobalUsage() {
48
+ let raw;
49
+ try {
50
+ raw = fs.readFileSync(GLOBAL_USAGE_PATH, 'utf8');
51
+ }
52
+ catch {
53
+ return [];
54
+ }
55
+ const out = [];
56
+ for (const line of raw.split('\n')) {
57
+ const trimmed = line.trim();
58
+ if (!trimmed)
59
+ continue;
60
+ try {
61
+ const rec = JSON.parse(trimmed);
62
+ if (typeof rec.day === 'string' && typeof rec.input === 'number' && typeof rec.output === 'number') {
63
+ out.push(rec);
64
+ }
65
+ }
66
+ catch {
67
+ // 跳过损坏行
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ function emptyBucket() {
73
+ return { input: 0, output: 0, cached: 0, reasoning: 0, cacheCreation: 0, calls: 0 };
74
+ }
75
+ function addInto(b, r) {
76
+ b.input += r.input;
77
+ b.output += r.output;
78
+ b.cached += r.cached;
79
+ b.reasoning += r.reasoning;
80
+ b.cacheCreation += r.cacheCreation;
81
+ b.calls++;
82
+ }
83
+ /** 窗口起点:含今天在内往前 days 天。 */
84
+ export function windowStart(days, today = new Date()) {
85
+ const d = new Date(today);
86
+ d.setDate(d.getDate() - (Math.max(1, days) - 1));
87
+ return localDay(d);
88
+ }
89
+ /**
90
+ * 聚合最近 days 天的全局用量:按天(补齐零天)、按工作区、按模型、按 phase;
91
+ * 另给 distinct session / workspace 计数。组数按总 token 降序。
92
+ */
93
+ export function summarizeGlobalUsage(records, days) {
94
+ const toDay = localDay();
95
+ const fromDay = windowStart(days);
96
+ const inWindow = records.filter((r) => r.day >= fromDay && r.day <= toDay);
97
+ const total = emptyBucket();
98
+ const main = emptyBucket();
99
+ const compact = emptyBucket();
100
+ const dayMap = new Map();
101
+ const wsMap = new Map();
102
+ const modelMap = new Map();
103
+ const daySessions = new Map();
104
+ const groupSessions = (map, key) => {
105
+ let row = map.get(key);
106
+ if (!row) {
107
+ row = { key, ...emptyBucket(), sessions: 0 };
108
+ map.set(key, row);
109
+ }
110
+ return row;
111
+ };
112
+ const sessions = new Set();
113
+ for (const r of inWindow) {
114
+ addInto(total, r);
115
+ addInto(r.phase === 'compact' ? compact : main, r);
116
+ let dayRow = dayMap.get(r.day);
117
+ if (!dayRow) {
118
+ dayRow = { day: r.day, ...emptyBucket(), sessions: 0 };
119
+ dayMap.set(r.day, dayRow);
120
+ daySessions.set(r.day, new Set());
121
+ }
122
+ addInto(dayRow, r);
123
+ const wsRow = groupSessions(wsMap, r.workspace || '(unknown)');
124
+ addInto(wsRow, r);
125
+ const modelRow = groupSessions(modelMap, r.model || '(unknown)');
126
+ addInto(modelRow, r);
127
+ if (r.sessionId) {
128
+ sessions.add(`${r.workspace}::${r.sessionId}`);
129
+ daySessions.get(r.day)?.add(r.sessionId);
130
+ }
131
+ }
132
+ // distinct session 计数(按工作区/模型)
133
+ const wsSessionSets = new Map();
134
+ const modelSessionSets = new Map();
135
+ for (const r of inWindow) {
136
+ if (!r.sessionId)
137
+ continue;
138
+ if (!wsSessionSets.has(r.workspace || '(unknown)'))
139
+ wsSessionSets.set(r.workspace || '(unknown)', new Set());
140
+ wsSessionSets.get(r.workspace || '(unknown)').add(r.sessionId);
141
+ if (!modelSessionSets.has(r.model || '(unknown)'))
142
+ modelSessionSets.set(r.model || '(unknown)', new Set());
143
+ modelSessionSets.get(r.model || '(unknown)').add(r.sessionId);
144
+ }
145
+ for (const row of wsMap.values())
146
+ row.sessions = wsSessionSets.get(row.key)?.size ?? 0;
147
+ for (const row of modelMap.values())
148
+ row.sessions = modelSessionSets.get(row.key)?.size ?? 0;
149
+ for (const row of dayMap.values())
150
+ row.sessions = daySessions.get(row.day)?.size ?? 0;
151
+ // 补齐窗口内零用量日(从 fromDay 逐天 +1,本地日期)
152
+ const byDay = [];
153
+ const cursor = new Date(`${fromDay}T00:00:00`);
154
+ for (let i = 0; i < Math.max(1, days); i++) {
155
+ const key = localDay(cursor);
156
+ byDay.push(dayMap.get(key) ?? { day: key, ...emptyBucket(), sessions: 0 });
157
+ cursor.setDate(cursor.getDate() + 1);
158
+ }
159
+ const byTotal = (a, b) => b.input + b.output - (a.input + a.output);
160
+ return {
161
+ fromDay,
162
+ toDay,
163
+ days: byDay.length,
164
+ total,
165
+ byDay,
166
+ byWorkspace: [...wsMap.values()].sort(byTotal),
167
+ byModel: [...modelMap.values()].sort(byTotal),
168
+ main,
169
+ compact,
170
+ sessionCount: sessions.size,
171
+ workspaceCount: wsMap.size,
172
+ };
173
+ }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
4
4
  import { gzipSync } from 'node:zlib';
5
5
  import path from 'node:path';
6
6
  import { MAX_TRACE_BYTES, MAX_TRACE_ROTATIONS, MAX_COMPACTED_ARCHIVE_BYTES } from '../tools/constants.js';
@@ -521,6 +521,87 @@ export class SessionStore {
521
521
  return null;
522
522
  }
523
523
  }
524
+ /**
525
+ * 分叉会话:把 `<sessionsRoot>/<sourceId>/` **整个目录**复制成一个新 id 会话
526
+ * (session.json/notes.md/snapshots.json/compacted/trace/usage 全带),
527
+ * 然后把副本里对旧会话的引用重写到新 id。原会话目录与当前 currentSessionId
528
+ * 均不动——fork 只在磁盘上产出一个独立副本,切不切过去由调用方决定。
529
+ *
530
+ * @returns 新会话 id;源会话目录不存在(如仅在归档 gz 中)时返回 null。
531
+ */
532
+ forkSession(sourceId) {
533
+ const srcDir = path.join(this.sessionsRoot, sourceId);
534
+ if (!existsSync(srcDir) || !statSync(srcDir).isDirectory())
535
+ return null;
536
+ const newId = createTimestampId();
537
+ const dstDir = path.join(this.sessionsRoot, newId);
538
+ // 时间前缀碰撞概率忽略不计,撞了直接报错也不覆盖任何东西。
539
+ if (existsSync(dstDir))
540
+ throw new Error(`Fork target session already exists: ${newId}`);
541
+ // filter 在 cp 过程中对每个条目回调:跳过 tmp(原子写残留)。整个目录递归复制。
542
+ cpSync(srcDir, dstDir, {
543
+ recursive: true,
544
+ errorOnExist: true,
545
+ force: false,
546
+ filter: (p) => !p.endsWith('.tmp'),
547
+ });
548
+ try {
549
+ this.rewriteForkedReferences(dstDir, sourceId, newId);
550
+ }
551
+ catch (error) {
552
+ // 不留下半成品会话目录(引用没改干净的副本比没有更危险)。
553
+ rmSync(dstDir, { recursive: true, force: true });
554
+ throw error;
555
+ }
556
+ return newId;
557
+ }
558
+ /**
559
+ * 重写分叉副本里的会话 id 引用:
560
+ * - 历史指针(.mocode/sessions/<old>/...)按路径前缀精确替换,避免裸 id 误匹配;
561
+ * - 跳过 .gz 二进制轮转;
562
+ * - session.json 单独结构化处理:id/createdAt 改成新会话,history 内指针同样替换。
563
+ */
564
+ rewriteForkedReferences(dir, oldId, newId) {
565
+ const oldPrefix = `.mocode/sessions/${oldId}/`;
566
+ const newPrefix = `.mocode/sessions/${newId}/`;
567
+ const rewriteFile = (file) => {
568
+ if (file.endsWith('.gz'))
569
+ return;
570
+ const original = readFileSync(file, 'utf8');
571
+ const updated = original.split(oldPrefix).join(newPrefix);
572
+ if (updated !== original)
573
+ writeFileSync(file, updated, 'utf8');
574
+ };
575
+ for (const entry of this.walkDirFiles(dir)) {
576
+ if (entry.endsWith('session.json'))
577
+ continue; // 下面结构化处理
578
+ rewriteFile(entry);
579
+ }
580
+ // session.json:id/createdAt 是新会话身份;history 里的 compacted/result blob
581
+ // 指针按同样的前缀替换。
582
+ const sessionJsonPath = path.join(dir, 'session.json');
583
+ if (existsSync(sessionJsonPath)) {
584
+ const rec = JSON.parse(readFileSync(sessionJsonPath, 'utf8'));
585
+ rec.id = newId;
586
+ rec.createdAt = idToIso(newId);
587
+ if (Array.isArray(rec.history)) {
588
+ rec.history = JSON.parse(JSON.stringify(rec.history).split(oldPrefix).join(newPrefix));
589
+ }
590
+ writeFileSync(sessionJsonPath, JSON.stringify(rec), 'utf8');
591
+ }
592
+ }
593
+ /** 递归列出目录下全部文件(绝对路径)。 */
594
+ *walkDirFiles(dir) {
595
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
596
+ const full = path.join(dir, entry.name);
597
+ if (entry.isDirectory()) {
598
+ yield* this.walkDirFiles(full);
599
+ }
600
+ else if (entry.isFile()) {
601
+ yield full;
602
+ }
603
+ }
604
+ }
524
605
  list(limit) {
525
606
  const root = this.sessionsRoot;
526
607
  if (!existsSync(root))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mocode-ai",
3
- "version": "1.9.1",
3
+ "version": "1.9.2",
4
4
  "description": "终端编码 agent:LLM + tool-call 循环 + 流式输出(含思考)+ 27 个工具,接任意 OpenAI 兼容后端。",
5
5
  "type": "module",
6
6
  "bin": {