mocode-ai 1.9.1 → 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.
- package/dist/agent/model-turn.js +43 -1
- package/dist/i18n/index.js +86 -0
- package/dist/repl/commands/session.js +33 -0
- package/dist/repl/commands/stats.js +162 -3
- package/dist/repl/commands.js +10 -1
- package/dist/repl/runtime.js +3 -0
- package/dist/runtime/runtime.js +13 -0
- package/dist/session/backfill-usage.js +154 -0
- package/dist/session/compact.js +16 -0
- package/dist/session/global-usage.js +186 -0
- package/dist/session/store.js +82 -1
- package/dist/session/usage-stats.js +3 -1
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/registry.js +145 -0
- package/package.json +1 -1
package/dist/agent/model-turn.js
CHANGED
|
@@ -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`),
|
|
@@ -173,8 +175,34 @@ export async function runModelTurn(input) {
|
|
|
173
175
|
const remainingSteps = maxSteps - step;
|
|
174
176
|
const ephemeralReminder = [
|
|
175
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
|
+
// 让近处指令与远处规则同向,而不是删掉动手要求(那会在真该干活的轮次矫枉过正)。
|
|
176
204
|
!opts.suppressOpeningAnalysis && step === 0
|
|
177
|
-
? '## Opening analysis\nStart your first response of this turn with a brief analysis of the request and approach (1-3 sentences, no filler)
|
|
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.'
|
|
178
206
|
: '',
|
|
179
207
|
remainingSteps <= 3
|
|
180
208
|
? `## Step budget warning\nOnly ${remainingSteps} step(s) remain before the hard step limit (${maxSteps}). ` +
|
|
@@ -471,6 +499,20 @@ export async function runModelTurn(input) {
|
|
|
471
499
|
const sessionId = getCurrentSessionId();
|
|
472
500
|
if (record && sessionId)
|
|
473
501
|
getActiveSessionStore().appendUsage(sessionId, record);
|
|
502
|
+
// 全局跨工作空间账本(/usage 按天汇总);best-effort,见 global-usage.ts。
|
|
503
|
+
if (result.usage && sessionId) {
|
|
504
|
+
appendGlobalUsage({
|
|
505
|
+
workspace: getWorkspaceRoot(),
|
|
506
|
+
model: requestModel,
|
|
507
|
+
phase: 'main',
|
|
508
|
+
sessionId,
|
|
509
|
+
input: result.usage.promptTokens,
|
|
510
|
+
output: result.usage.completionTokens,
|
|
511
|
+
cached: result.usage.cachedTokens,
|
|
512
|
+
reasoning: result.usage.reasoningTokens,
|
|
513
|
+
cacheCreation: result.usage.cacheCreationTokens,
|
|
514
|
+
});
|
|
515
|
+
}
|
|
474
516
|
if (result.usage) {
|
|
475
517
|
cacheState.lastStepPromptTokens = result.usage.promptTokens;
|
|
476
518
|
if (result.usage.cachedTokens > 0)
|
package/dist/i18n/index.js
CHANGED
|
@@ -10,10 +10,13 @@ const zhCN = {
|
|
|
10
10
|
'commands.context': '显示上下文用量条',
|
|
11
11
|
'commands.skills': '列出已发现的 skill',
|
|
12
12
|
'commands.compact': '压缩历史(可带焦点 /compact …)',
|
|
13
|
+
'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
|
|
14
|
+
'commands.usageImport': '回填各工作区历史会话的 token 用量(幂等)',
|
|
13
15
|
'commands.session': '会话恢复与回滚',
|
|
14
16
|
'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
|
|
15
17
|
'commands.sessionBrowse': '浏览全部已保存会话',
|
|
16
18
|
'commands.sessionRollback': '菜单选轮次回滚(↑↓·Enter)',
|
|
19
|
+
'commands.sessionFork': '从当前会话分叉出独立新会话(不切换窗口)',
|
|
17
20
|
'commands.memory': '记忆库、开关与反思',
|
|
18
21
|
'commands.memoryOverview': '条目计数与近期索引',
|
|
19
22
|
'commands.memoryToggle': '切换记忆子系统开关',
|
|
@@ -179,6 +182,46 @@ const zhCN = {
|
|
|
179
182
|
'repl.noSessions': '(没有已保存的会话)',
|
|
180
183
|
'repl.noValue': '(无)',
|
|
181
184
|
'repl.historyCleared': '(历史已清空,保留系统提示)',
|
|
185
|
+
'repl.forkUsage': '用法:/fork(无参数;从当前会话分叉)',
|
|
186
|
+
'repl.forkEmpty': '(当前还没有对话,无可分叉内容)',
|
|
187
|
+
'repl.forkFailed': '(分叉失败:{message})',
|
|
188
|
+
'repl.forkMissing': '(当前会话尚未落盘,无法分叉)',
|
|
189
|
+
'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
|
|
190
|
+
'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
|
|
191
|
+
'repl.usageTitle': 'Token 用量(全局 · {from} ~ {to} · {days} 天)',
|
|
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': '(无用量)',
|
|
216
|
+
'repl.usageTotalRow': '合计',
|
|
217
|
+
'repl.usageByWorkspace': '按工作空间',
|
|
218
|
+
'repl.usageByModel': '按模型',
|
|
219
|
+
'repl.usageMore': '… 其余 {n} 项已省略',
|
|
220
|
+
'repl.usageBadArg': '用法:/usage [天数 1-366](默认 7)',
|
|
221
|
+
'repl.usageImportDone': '已回填 {records} 条历史记录({sessions} 个会话 · {workspaces} 个工作空间;跳过 {skipped} 条已实时统计的记录)',
|
|
222
|
+
'repl.usageImportNothing': '没有可回填的历史记录({skipped} 条已实时统计,重复执行是幂等的)',
|
|
223
|
+
'repl.usageImportZero': '没有找到可回填的历史会话用量(先在 mocode 里跑过任务的工作区才会产生 usage.jsonl)',
|
|
224
|
+
'repl.usageNoData': '(全局账本暂无数据;统计从此功能启用后的模型调用开始累积,或用 /usage import 回填历史)',
|
|
182
225
|
'repl.planAlready': '(已在 plan 模式)',
|
|
183
226
|
'repl.planChanged': '(已切到 plan 模式:只读探查 + 产出计划,审批后切 auto 执行。/auto 或 Shift+Tab 切回)',
|
|
184
227
|
'repl.autoAlready': '(已在 auto 模式)',
|
|
@@ -478,10 +521,13 @@ const en = {
|
|
|
478
521
|
'commands.context': 'Show context usage',
|
|
479
522
|
'commands.skills': 'List discovered skills',
|
|
480
523
|
'commands.compact': 'Compact history (optional focus: /compact …)',
|
|
524
|
+
'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
|
|
525
|
+
'commands.usageImport': 'Backfill token usage from historical sessions (idempotent)',
|
|
481
526
|
'commands.session': 'Resume sessions and roll back turns',
|
|
482
527
|
'commands.sessionResume': 'Resume one of the 10 latest saved sessions',
|
|
483
528
|
'commands.sessionBrowse': 'Browse all saved sessions',
|
|
484
529
|
'commands.sessionRollback': 'Choose a turn to roll back (↑↓·Enter)',
|
|
530
|
+
'commands.sessionFork': 'Fork the current session into an independent new one (window stays)',
|
|
485
531
|
'commands.memory': 'Memory store, controls, and reflection',
|
|
486
532
|
'commands.memoryOverview': 'Show counts and recent entries',
|
|
487
533
|
'commands.memoryToggle': 'Toggle the memory subsystem',
|
|
@@ -642,6 +688,46 @@ const en = {
|
|
|
642
688
|
'repl.noSessions': '(no saved sessions)',
|
|
643
689
|
'repl.noValue': '(none)',
|
|
644
690
|
'repl.historyCleared': '(history cleared; system prompt kept)',
|
|
691
|
+
'repl.forkUsage': 'Usage: /fork (no arguments; forks the current session)',
|
|
692
|
+
'repl.forkEmpty': '(no conversation yet; nothing to fork)',
|
|
693
|
+
'repl.forkFailed': '(fork failed: {message})',
|
|
694
|
+
'repl.forkMissing': '(current session is not persisted yet; cannot fork)',
|
|
695
|
+
'repl.forkDone': 'Forked new session {id} (inherits full context; independent from the original)',
|
|
696
|
+
'repl.forkHint': 'This window stays on the original session; run mocode --resume {id} in a new terminal, or use /resume here',
|
|
697
|
+
'repl.usageTitle': 'Token usage (global · {from} ~ {to} · {days}d)',
|
|
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',
|
|
721
|
+
'repl.usageEmptyDay': '(no usage)',
|
|
722
|
+
'repl.usageTotalRow': 'Total',
|
|
723
|
+
'repl.usageByWorkspace': 'By workspace',
|
|
724
|
+
'repl.usageByModel': 'By model',
|
|
725
|
+
'repl.usageMore': '… {n} more hidden',
|
|
726
|
+
'repl.usageBadArg': 'Usage: /usage [days 1-366] (default 7)',
|
|
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)',
|
|
645
731
|
'repl.planAlready': '(already in plan mode)',
|
|
646
732
|
'repl.planChanged': '(switched to plan mode: read-only research and planning; approval returns to auto. Use /auto or Shift+Tab to switch back)',
|
|
647
733
|
'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,173 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 用量命令组:/stats(
|
|
2
|
+
* 用量命令组:/stats(当前会话诊断)· /usage(跨工作空间按天汇总)
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* /stats 读会话级 usage.jsonl,输出 cache 命中率 / 分层用量 / compact 次数。
|
|
5
|
+
* /usage 读全局账本 ~/.mocode/usage-daily.jsonl(每次模型调用追加,含工作区/模型/
|
|
6
|
+
* 本地日期),以 GFM 表格输出最近 N 天的总览、按天、工作区与模型排行
|
|
7
|
+
* (经 contentWriteMdOnce 走 markdown 表格渲染,数字列右对齐)。
|
|
6
8
|
*/
|
|
7
9
|
import * as layout from '../../ui/layout.js';
|
|
10
|
+
import { ui } from '../../ui/theme.js';
|
|
11
|
+
import { fmtCompactTokens } from '../../ui/render.js';
|
|
12
|
+
import { t } from '../../i18n/index.js';
|
|
8
13
|
import { getActiveSessionStore } from '../../session/store.js';
|
|
9
14
|
import { formatUsageSummary, summarizeUsage } from '../../session/usage-stats.js';
|
|
15
|
+
import { readGlobalUsage, summarizeGlobalUsage, } from '../../session/global-usage.js';
|
|
16
|
+
import { backfillGlobalUsage } from '../../session/backfill-usage.js';
|
|
17
|
+
import { getWorkspaceRoot } from '../../workspace/index.js';
|
|
10
18
|
import { unhandled, next } from './types.js';
|
|
19
|
+
/** 计数千分位(请求数/会话数等)。 */
|
|
20
|
+
function n(v) {
|
|
21
|
+
return v.toLocaleString('en-US');
|
|
22
|
+
}
|
|
23
|
+
/** token 统一缩写:<1k 整数,1k-1M 用 k,≥1M 用 M(复用全项目同口径)。 */
|
|
24
|
+
function tok(v) {
|
|
25
|
+
return fmtCompactTokens(v);
|
|
26
|
+
}
|
|
27
|
+
function pct(part, whole) {
|
|
28
|
+
return whole > 0 ? `${((part / whole) * 100).toFixed(1)}%` : 'n/a';
|
|
29
|
+
}
|
|
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');
|
|
37
|
+
}
|
|
38
|
+
/** 汇总指标键值表(两列)。 */
|
|
39
|
+
function overviewTable(s) {
|
|
40
|
+
const b = s.total;
|
|
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
|
+
];
|
|
53
|
+
if (s.compact.calls > 0) {
|
|
54
|
+
rows.push([
|
|
55
|
+
t('repl.usageKCompact'),
|
|
56
|
+
`${tok(s.compact.input)} in / ${tok(s.compact.output)} out / ${n(s.compact.calls)}`,
|
|
57
|
+
]);
|
|
58
|
+
}
|
|
59
|
+
return mdTable([t('repl.usageKMetric'), t('repl.usageKValue')], rows, ['l', 'r']);
|
|
60
|
+
}
|
|
61
|
+
function dayRows(byDay) {
|
|
62
|
+
return byDay.map((d) => {
|
|
63
|
+
if (d.calls === 0) {
|
|
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
|
+
];
|
|
74
|
+
}
|
|
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}` : ''));
|
|
116
|
+
}
|
|
11
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
|
+
},
|
|
139
|
+
// /usage [days]:跨工作空间按天汇总。默认 7 天,可传天数(如 /usage 30);非法参数给用法提示。
|
|
140
|
+
(ctx) => {
|
|
141
|
+
if (ctx.line !== '/usage' && !ctx.line.startsWith('/usage '))
|
|
142
|
+
return unhandled();
|
|
143
|
+
const arg = ctx.line.replace(/^\/usage\s*/, '').trim();
|
|
144
|
+
let days = 7;
|
|
145
|
+
if (arg) {
|
|
146
|
+
const parsed = Number(arg);
|
|
147
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 366) {
|
|
148
|
+
layout.contentWrite(`${ui.yellow}${t('repl.usageBadArg')}${ui.reset}\n`);
|
|
149
|
+
return next();
|
|
150
|
+
}
|
|
151
|
+
days = parsed;
|
|
152
|
+
}
|
|
153
|
+
const records = readGlobalUsage();
|
|
154
|
+
if (records.length === 0) {
|
|
155
|
+
layout.contentWrite(`${ui.dim}${t('repl.usageNoData')}${ui.reset}\n`);
|
|
156
|
+
return next();
|
|
157
|
+
}
|
|
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');
|
|
169
|
+
return next();
|
|
170
|
+
},
|
|
12
171
|
(ctx) => {
|
|
13
172
|
if (ctx.line !== '/stats')
|
|
14
173
|
return unhandled();
|
package/dist/repl/commands.js
CHANGED
|
@@ -24,9 +24,15 @@ 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
|
+
{
|
|
28
|
+
name: '/usage',
|
|
29
|
+
desc: d('commands.usage'),
|
|
30
|
+
children: [{ name: 'import', value: '/usage import', desc: d('commands.usageImport') }],
|
|
31
|
+
},
|
|
27
32
|
{ name: '/stats', desc: '查看本会话 token 用量与缓存命中率' },
|
|
28
33
|
{ name: '/effort', desc: '设置思考强度(/effort [low|medium|high|auto])' },
|
|
29
34
|
{ name: '/resume', desc: d('commands.sessionResume') },
|
|
35
|
+
{ name: '/fork', desc: d('commands.sessionFork') },
|
|
30
36
|
{ name: '/sessions', desc: d('commands.sessionBrowse') },
|
|
31
37
|
{ name: '/rollback', desc: d('commands.sessionRollback') },
|
|
32
38
|
{ name: '/diff', desc: '查看 agent 文件改动 diff(/diff [N]|all,快照 vs 工作区)' },
|
|
@@ -205,7 +211,10 @@ export const LLM_ERROR_HINT_KEYS = {
|
|
|
205
211
|
/** /help 的分组:按使用场景归组,组内保持菜单树顺序。未列入的顶层命令兜底进「其他」。 */
|
|
206
212
|
export const HELP_GROUPS = [
|
|
207
213
|
{ key: 'help.groupFrequent', names: ['/help', '/clear', '/cd', '/context', '/compact', '/resume', '/model'] },
|
|
208
|
-
{
|
|
214
|
+
{
|
|
215
|
+
key: 'help.groupSession',
|
|
216
|
+
names: ['/fork', '/sessions', '/rollback', '/usage', '/memory', '/skills', '/skill', '/init'],
|
|
217
|
+
},
|
|
209
218
|
{
|
|
210
219
|
key: 'help.groupConfig',
|
|
211
220
|
names: [
|
package/dist/repl/runtime.js
CHANGED
|
@@ -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;
|
package/dist/runtime/runtime.js
CHANGED
|
@@ -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 });
|
|
@@ -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
|
+
}
|
package/dist/session/compact.js
CHANGED
|
@@ -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,186 @@
|
|
|
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
|
+
/**
|
|
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
|
+
}
|
|
28
|
+
/** 本地日期 YYYY-MM-DD;不引时区库——运行机器本地时间即用户口径的"天"。 */
|
|
29
|
+
export function localDay(d = new Date()) {
|
|
30
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
31
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
|
32
|
+
}
|
|
33
|
+
/** 追加一行全局用量。任何 I/O 失败静默——记账不能拖垮主流程。 */
|
|
34
|
+
export function appendGlobalUsage(input) {
|
|
35
|
+
try {
|
|
36
|
+
const when = input.ts ? new Date(input.ts) : new Date();
|
|
37
|
+
const day = input.day ?? (Number.isNaN(when.getTime()) ? localDay() : localDay(when));
|
|
38
|
+
const rec = {
|
|
39
|
+
ts: Number.isNaN(when.getTime()) ? new Date().toISOString() : when.toISOString(),
|
|
40
|
+
day,
|
|
41
|
+
input: input.input,
|
|
42
|
+
output: input.output,
|
|
43
|
+
cached: input.cached ?? 0,
|
|
44
|
+
reasoning: input.reasoning ?? 0,
|
|
45
|
+
cacheCreation: input.cacheCreation ?? 0,
|
|
46
|
+
workspace: input.workspace,
|
|
47
|
+
model: input.model,
|
|
48
|
+
phase: input.phase,
|
|
49
|
+
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
50
|
+
...(input.source === 'backfill' ? { source: 'backfill' } : {}),
|
|
51
|
+
};
|
|
52
|
+
fs.mkdirSync(path.dirname(getGlobalUsagePath()), { recursive: true });
|
|
53
|
+
fs.appendFileSync(getGlobalUsagePath(), `${JSON.stringify(rec)}\n`, 'utf8');
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// best-effort, see file header
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** 读全部全局记录;文件不存在或损坏行跳过。 */
|
|
60
|
+
export function readGlobalUsage() {
|
|
61
|
+
let raw;
|
|
62
|
+
try {
|
|
63
|
+
raw = fs.readFileSync(getGlobalUsagePath(), 'utf8');
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const line of raw.split('\n')) {
|
|
70
|
+
const trimmed = line.trim();
|
|
71
|
+
if (!trimmed)
|
|
72
|
+
continue;
|
|
73
|
+
try {
|
|
74
|
+
const rec = JSON.parse(trimmed);
|
|
75
|
+
if (typeof rec.day === 'string' && typeof rec.input === 'number' && typeof rec.output === 'number') {
|
|
76
|
+
out.push(rec);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// 跳过损坏行
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
function emptyBucket() {
|
|
86
|
+
return { input: 0, output: 0, cached: 0, reasoning: 0, cacheCreation: 0, calls: 0 };
|
|
87
|
+
}
|
|
88
|
+
function addInto(b, r) {
|
|
89
|
+
b.input += r.input;
|
|
90
|
+
b.output += r.output;
|
|
91
|
+
b.cached += r.cached;
|
|
92
|
+
b.reasoning += r.reasoning;
|
|
93
|
+
b.cacheCreation += r.cacheCreation;
|
|
94
|
+
b.calls++;
|
|
95
|
+
}
|
|
96
|
+
/** 窗口起点:含今天在内往前 days 天。 */
|
|
97
|
+
export function windowStart(days, today = new Date()) {
|
|
98
|
+
const d = new Date(today);
|
|
99
|
+
d.setDate(d.getDate() - (Math.max(1, days) - 1));
|
|
100
|
+
return localDay(d);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* 聚合最近 days 天的全局用量:按天(补齐零天)、按工作区、按模型、按 phase;
|
|
104
|
+
* 另给 distinct session / workspace 计数。组数按总 token 降序。
|
|
105
|
+
*/
|
|
106
|
+
export function summarizeGlobalUsage(records, days) {
|
|
107
|
+
const toDay = localDay();
|
|
108
|
+
const fromDay = windowStart(days);
|
|
109
|
+
const inWindow = records.filter((r) => r.day >= fromDay && r.day <= toDay);
|
|
110
|
+
const total = emptyBucket();
|
|
111
|
+
const main = emptyBucket();
|
|
112
|
+
const compact = emptyBucket();
|
|
113
|
+
const dayMap = new Map();
|
|
114
|
+
const wsMap = new Map();
|
|
115
|
+
const modelMap = new Map();
|
|
116
|
+
const daySessions = new Map();
|
|
117
|
+
const groupSessions = (map, key) => {
|
|
118
|
+
let row = map.get(key);
|
|
119
|
+
if (!row) {
|
|
120
|
+
row = { key, ...emptyBucket(), sessions: 0 };
|
|
121
|
+
map.set(key, row);
|
|
122
|
+
}
|
|
123
|
+
return row;
|
|
124
|
+
};
|
|
125
|
+
const sessions = new Set();
|
|
126
|
+
for (const r of inWindow) {
|
|
127
|
+
addInto(total, r);
|
|
128
|
+
addInto(r.phase === 'compact' ? compact : main, r);
|
|
129
|
+
let dayRow = dayMap.get(r.day);
|
|
130
|
+
if (!dayRow) {
|
|
131
|
+
dayRow = { day: r.day, ...emptyBucket(), sessions: 0 };
|
|
132
|
+
dayMap.set(r.day, dayRow);
|
|
133
|
+
daySessions.set(r.day, new Set());
|
|
134
|
+
}
|
|
135
|
+
addInto(dayRow, r);
|
|
136
|
+
const wsRow = groupSessions(wsMap, r.workspace || '(unknown)');
|
|
137
|
+
addInto(wsRow, r);
|
|
138
|
+
const modelRow = groupSessions(modelMap, r.model || '(unknown)');
|
|
139
|
+
addInto(modelRow, r);
|
|
140
|
+
if (r.sessionId) {
|
|
141
|
+
sessions.add(`${r.workspace}::${r.sessionId}`);
|
|
142
|
+
daySessions.get(r.day)?.add(r.sessionId);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// distinct session 计数(按工作区/模型)
|
|
146
|
+
const wsSessionSets = new Map();
|
|
147
|
+
const modelSessionSets = new Map();
|
|
148
|
+
for (const r of inWindow) {
|
|
149
|
+
if (!r.sessionId)
|
|
150
|
+
continue;
|
|
151
|
+
if (!wsSessionSets.has(r.workspace || '(unknown)'))
|
|
152
|
+
wsSessionSets.set(r.workspace || '(unknown)', new Set());
|
|
153
|
+
wsSessionSets.get(r.workspace || '(unknown)').add(r.sessionId);
|
|
154
|
+
if (!modelSessionSets.has(r.model || '(unknown)'))
|
|
155
|
+
modelSessionSets.set(r.model || '(unknown)', new Set());
|
|
156
|
+
modelSessionSets.get(r.model || '(unknown)').add(r.sessionId);
|
|
157
|
+
}
|
|
158
|
+
for (const row of wsMap.values())
|
|
159
|
+
row.sessions = wsSessionSets.get(row.key)?.size ?? 0;
|
|
160
|
+
for (const row of modelMap.values())
|
|
161
|
+
row.sessions = modelSessionSets.get(row.key)?.size ?? 0;
|
|
162
|
+
for (const row of dayMap.values())
|
|
163
|
+
row.sessions = daySessions.get(row.day)?.size ?? 0;
|
|
164
|
+
// 补齐窗口内零用量日(从 fromDay 逐天 +1,本地日期)
|
|
165
|
+
const byDay = [];
|
|
166
|
+
const cursor = new Date(`${fromDay}T00:00:00`);
|
|
167
|
+
for (let i = 0; i < Math.max(1, days); i++) {
|
|
168
|
+
const key = localDay(cursor);
|
|
169
|
+
byDay.push(dayMap.get(key) ?? { day: key, ...emptyBucket(), sessions: 0 });
|
|
170
|
+
cursor.setDate(cursor.getDate() + 1);
|
|
171
|
+
}
|
|
172
|
+
const byTotal = (a, b) => b.input + b.output - (a.input + a.output);
|
|
173
|
+
return {
|
|
174
|
+
fromDay,
|
|
175
|
+
toDay,
|
|
176
|
+
days: byDay.length,
|
|
177
|
+
total,
|
|
178
|
+
byDay,
|
|
179
|
+
byWorkspace: [...wsMap.values()].sort(byTotal),
|
|
180
|
+
byModel: [...modelMap.values()].sort(byTotal),
|
|
181
|
+
main,
|
|
182
|
+
compact,
|
|
183
|
+
sessionCount: sessions.size,
|
|
184
|
+
workspaceCount: wsMap.size,
|
|
185
|
+
};
|
|
186
|
+
}
|
package/dist/session/store.js
CHANGED
|
@@ -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))
|
|
@@ -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() {
|
package/dist/workspace/index.js
CHANGED
|
@@ -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
|
+
}
|